diff --git a/.env.example b/.env.example index 591379c..19ca4a8 100644 --- a/.env.example +++ b/.env.example @@ -64,6 +64,11 @@ ADMIN_KEY= # ROOM_EMPTY_TTL_MS=60000 # sala sem ninguém espera isto e é destruída # # junto com o histórico (0 = na hora) +# Conversas privadas (Fase 3 da evolução). Também só em memória. +# MAX_DMS_PER_USER=20 # conversas privadas abertas por pessoa +# MAX_DMS=5000 # conversas privadas no servidor inteiro +# DM_HISTORY_SIZE=100 # mensagens guardadas por conversa privada + # Monitoramento (Fase 3). # METRICS_ENABLED=false # true expõe GET /metrics (JSON, sem dados pessoais) # METRICS_LOG_INTERVAL_MS=60000 # linha de log "metrics" periódica; 0 desliga diff --git a/README.md b/README.md index df4f8e5..340ff43 100644 --- a/README.md +++ b/README.md @@ -56,6 +56,7 @@ Cada item corresponde a código neste repositório. | Funcionalidade | Onde | | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | | **Salas criadas pelas pessoas**: quem cria vira anfitrião e recebe um código de convite `abc-defg-hij` (link `…/#/s/código`); quem tem o código entra. Sem sala pública. Uma identidade participa de até 10 salas ao mesmo tempo; cada sala tem participantes, histórico e moderação próprios e acaba (com o histórico) quando fica vazia | `backend/src/room/hub.js`, `backend/src/room/directory.js`, `backend/src/room/room.js` | +| **Conversas privadas no servidor**: entre duas identidades, abertas pelo `@` exato; cada pessoa é vista só pelo `@` (o id interno fica no servidor e só administradores o veem); só as duas leem e escrevem; bloqueio até o fim da sessão; acabam, com o histórico, quando uma das duas encerra, bloqueia ou sai | `backend/src/room/direct.js`, `backend/src/room/hub.js` | | Entrada com nome completo (até 60 caracteres) e nome de usuário único (`@username`), sem conta nem senha; botão Sair libera a identidade na hora | `frontend/src/ui/entry.js` | | Mensagens em tempo real para quem está na sala (até 1000 caracteres), nunca entregues fora dela | `backend/src/server.js`, `frontend/src/state/events.js` | | Últimas 50 mensagens da sala enviadas a quem entra nela | `backend/src/server.js` | @@ -72,7 +73,7 @@ Cada item corresponde a código neste repositório. | Confirmação de entrega: sua mensagem aparece como "enviando…" até o servidor confirmar; recusada ou sem confirmação, fica "não enviada" com o botão Tentar de novo (sem duplicar) | `frontend/src/main.js`, `frontend/src/state/store.js`, `backend/src/room/room.js` | | Proteções no servidor: payload máx. 16 KiB, limites de taxa separados para mensagens e digitação, teto de 500 conexões, allowlist de origem, validação de cada quadro recebido, heartbeat e desligamento gracioso | `backend/src/server.js` | | **Comandos no chat** (30): digite `/` para ver sugestões; `/help`, `/nick`, `/me`, `/roll`, `/flip`, `/afk`, `/users`, `/profile`, formatação (`/bold`, `/spoiler`…) e mais — ver [`docs/CHAT_COMMANDS.md`](./docs/CHAT_COMMANDS.md) | `backend/src/commands/`, `frontend/src/commands/` | -| Pessoas agrupadas (administradores, online, ausentes) com cartão de cada uma: ver perfil, copiar id e, para admins, silenciar, liberar e remover (com confirmação) — tudo por comandos verificados no servidor | `frontend/src/ui/people.js`, `frontend/src/ui/memberCard.js` | +| Pessoas agrupadas (administradores, online, ausentes) com cartão de cada uma: ver perfil, copiar o @ e, para quem modera a sala, silenciar, liberar e remover (com confirmação) — tudo por comandos verificados no servidor | `frontend/src/ui/people.js`, `frontend/src/ui/memberCard.js` | | Moderação por sala: o anfitrião (ou um administrador, pela chave `ADMIN_KEY`) usa `/clearall`, `/announce`, `/mute`, `/unmute`, `/kick` só naquela sala, com permissões verificadas no servidor | `backend/src/commands/handlers/admin.js`, `backend/src/room/policy.js` | | Reconexão sem avisos repetidos: queda e volta em até 10 s não geram "saiu"/"entrou" para os outros | `backend/src/room/room.js` | | Content-Security-Policy no HTML | `frontend/index.html` | @@ -82,8 +83,9 @@ Cada item corresponde a código neste repositório. O servidor mantém em memória, **por sala**, as últimas **200 mensagens** e envia as **50 mais recentes** para quem entra. Uma sala sem ninguém é destruída, com o histórico, depois de 60 s; uma identidade que cai e não volta em 2 min sai de -todas as salas. Nada é gravado em disco ou banco: **reiniciar o servidor apaga -tudo**. +todas as salas. Cada conversa privada guarda as últimas **100 mensagens** e é +destruída quando uma das duas pessoas a encerra, bloqueia a outra ou deixa de +existir. Nada é gravado em disco ou banco: **reiniciar o servidor apaga tudo**. ## O que não existe @@ -92,7 +94,7 @@ Nenhum destes itens está implementado. | Recurso | Situação | | ---------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | | Banimento e avisos de moderação | Não implementado: o chat é anônimo; `/kick` e `/mute` valem para a identidade atual naquela sala (quem abre outra aba entra como pessoa nova). | -| Mensagens privadas | Planejado (Fase 3 da evolução). | +| Interface das mensagens privadas | Planejado (Fases 4 e 5). O servidor já tem conversas privadas, busca por `@` e bloqueio; a interface atual ainda não as mostra. | | Navegar entre várias salas na interface | Planejado (Fases 4 e 5). O servidor já aceita várias salas por pessoa; a interface atual mostra uma por vez. | | Excluir, editar ou responder mensagens | Não implementado (só a limpeza da sala inteira por administrador). | | Fixar mensagens | Não implementado. `localStorage` guarda apenas o tema. | @@ -117,21 +119,50 @@ Versões exatas e estado das dependências em ## Arquitetura -Cliente-servidor sobre WebSocket, com mensagens JSON `{ type, payload }`. +Cliente-servidor sobre WebSocket, com mensagens JSON `{ type, payload }`. Eventos de +uma conversa levam também `conversationId`. ``` -Navegador Servidor (Node.js) -┌─────────────────────────────────────┐ ┌──────────────────────────────┐ -│ main.js (raiz de composição) │ │ backend/src/server.js │ -│ ├─ transport/ conexão, backoff, │ WebSocket│ HTTP 200 "ok" + WebSocket │ -│ │ fila — sem DOM │◄─────────►│ estado em memória: │ -│ ├─ state/ estado observável — │ JSON │ pessoas conectadas │ -│ │ sem transporte │ │ histórico (1000) │ -│ └─ ui/ DOM puro, sem │ │ rate limit, teto, Origin │ -│ innerHTML │ └──────────────────────────────┘ -└─────────────────────────────────────┘ +Navegador Servidor (Node.js, tudo em memória) +┌──────────────────────────────────┐ ┌───────────────────────────────────────────┐ +│ main.js (raiz de composição) │ │ transport/ HTTP, WebSocket, limites, Origin│ +│ ├─ transport/ conexão, backoff,│ WebSocket │ room/hub.js sessões e conversas │ +│ │ fila — sem DOM │◄─────────►│ room/sessions.js identidades, @, token │ +│ ├─ state/ estado observável│ JSON │ room/directory.js salas, códigos, limites │ +│ │ — sem transporte │ │ room/room.js regras de uma sala │ +│ └─ ui/ DOM puro, sem │ │ room/direct.js conversas privadas │ +│ innerHTML │ │ room/transcript.js histórico comum │ +└──────────────────────────────────┘ │ commands/ comandos e permissões │ + └───────────────────────────────────────────┘ ``` +### Identidade: o `@` é público, o id interno não + +- Cada pessoa entra com um nome e um `@username`, único entre quem está conectado. + É pelo `@` que as pessoas se veem, se procuram, abrem conversa privada, bloqueiam + e moderam. +- O servidor dá a cada identidade um **id interno**, usado só nele: índices de + conversas e bloqueios, e logs. Esse id não vai em nenhum evento, não é aceito em + nenhum pedido e não aparece na interface. +- Só **administradores** (chave `ADMIN_KEY`) veem o id interno, pelos comandos + `/users`, `/profile` e `/id`. +- Quando alguém sai, o `@` fica livre. Quem o pega depois é outra identidade: não + recupera conversas privadas, não herda bloqueios e não vê como "suas" as + mensagens antigas (a sessão informa quando a identidade nasceu). No histórico de + uma sala, porém, os outros participantes veem o mesmo `@` nas mensagens das duas + pessoas; a distinção de quem já saiu está planejada para a Fase 4 + ([plano](./docs/EVOLUCAO_FASE_4_PLANO.md)). + +### Quem pode o quê + +| Papel | Como se obtém | Pode | +| ------------- | ------------------------------ | ------------------------------------------------------------------------------------------- | +| Participante | Entrando com nome e `@` | Criar e entrar em salas, conversar, conversa privada, bloquear | +| Anfitrião | Criando a sala (ou herdando) | Moderar **a própria sala**, pelo `@`: `/mute`, `/unmute`, `/kick`, `/clearall`, `/announce` | +| Administrador | `/admin ` (`ADMIN_KEY`) | Moderar qualquer sala em que esteja e ver ids internos | + +Toda permissão é conferida no servidor, a cada operação. + Duas fronteiras do frontend são verificáveis por comando (ambos devem retornar vazio): ```bash @@ -175,7 +206,8 @@ web-chat/ │ │ ├── protocol.js contrato do protocolo (fonte no servidor) │ │ ├── validation.js normalização de nome, mensagem e token │ │ ├── rateLimiter.js balde de fichas -│ │ ├── room/ regras da sala e identidades (sem rede) +│ │ ├── room/ sessões, salas, conversas privadas e permissões (sem rede) +│ │ ├── commands/ comandos do chat: registro, executor e handlers │ │ └── transport/ HTTP, WebSocket, ciclo da conexão, heartbeat │ └── test/ │ ├── unit/ módulos isolados e contrato cliente ↔ servidor @@ -229,7 +261,7 @@ cp .env.example .env | Variável | Usada por | Para quê | Padrão | | ----------------- | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------ | ------------------------------- | | `VITE_SOCKET_URL` | Frontend (embutida no build) | Endereço do servidor WebSocket; precisa ser `ws://` ou `wss://` | `ws(s)://:8080` | -| `ALLOWED_ORIGINS` | Backend | Origens autorizadas a conectar, separadas por vírgula. **Configure em produção.** | vazio = qualquer origem | +| `ALLOWED_ORIGINS` | Backend | Origens autorizadas a conectar, separadas por vírgula. **Obrigatória em produção.** | vazio = qualquer origem (dev) | | `PORT` | Backend | Porta HTTP/WebSocket | `8080` | | `HEARTBEAT_MS` | Backend | Intervalo do ping que detecta conexões mortas (mínimo 50) | `30000` | | `ADMIN_KEY` | Backend | Chave secreta para `/admin` (16–200 caracteres, sem espaços). Vazia: administração desativada. Nunca use prefixo `VITE_` | vazio | @@ -242,7 +274,8 @@ no [`.env.example`](./.env.example): `MAX_CONNECTIONS`, `MAX_PAYLOAD_BYTES`, `RATE_SIGNALS_PER_SEC`, `HISTORY_SIZE`, `HISTORY_ON_JOIN`, `HEARTBEAT_MAX_MISSED`, `MAX_BUFFERED_BYTES`, `LOGIN_TIMEOUT_MS`, `METRICS_ENABLED`, `METRICS_LOG_INTERVAL_MS` e os limites de salas: `MAX_ROOMS`, `MAX_ROOMS_PER_USER`, `MAX_ROOMS_CREATED_PER_USER` -e `ROOM_EMPTY_TTL_MS`. +`ROOM_EMPTY_TTL_MS` e os das conversas privadas: `MAX_DMS_PER_USER`, `MAX_DMS` e +`DM_HISTORY_SIZE`. Comportamento previsível quando algo está errado: @@ -250,8 +283,10 @@ Comportamento previsível quando algo está errado: a explicação, em vez de gerar um bundle que nunca conecta. - `ALLOWED_ORIGINS` ou `PORT` inválidas impedem o servidor de subir, com uma linha de log `config_invalid` dizendo qual variável corrigir. -- Sem `ALLOWED_ORIGINS`, o servidor sobe e registra `allowed_origins_disabled` - (como aviso quando `NODE_ENV=production`). +- Em produção (`NODE_ENV=production`), `ALLOWED_ORIGINS` é **obrigatória**: sem + ela o servidor não sobe (`config_invalid`). Fora de produção, vazia aceita + qualquer origem e registra `allowed_origins_disabled`. Curinga (`*`) é recusado + sempre. - Só variáveis com prefixo `VITE_` chegam ao navegador; as do backend no mesmo arquivo nunca são expostas. @@ -264,11 +299,12 @@ Nunca versione arquivos `.env` (o `.gitignore` já os exclui). ### Administração -Para moderar a sala, defina `ADMIN_KEY` no `.env` da raiz e entregue a chave a quem -vai moderar. No chat, a pessoa digita `/admin ` e passa a poder usar -`/clearall`, `/announce`, `/mute`, `/unmute` e `/kick`. A chave nunca aparece em log -nem na tela; tentativas erradas são bloqueadas após 5 erros. Sem `ADMIN_KEY`, a -administração fica desativada. +Quem cria uma sala é o anfitrião dela e já pode moderá-la. Para ter um administrador +global, defina `ADMIN_KEY` no `.env` da raiz e entregue a chave a quem vai +administrar. No chat, a pessoa digita `/admin ` e passa a moderar qualquer +sala em que esteja e a ver os ids internos em `/users`, `/profile` e `/id`. A chave +nunca aparece em log nem na tela; tentativas erradas são bloqueadas após 5 erros. Sem +`ADMIN_KEY`, não há administrador. ## Executando localmente @@ -455,23 +491,27 @@ prevista no roadmap (F5-06). ## Documentação complementar -| Documento | Conteúdo | -| ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------ | -| [`docs/ANALISE_E_PLANO_DE_MELHORIAS.md`](./docs/ANALISE_E_PLANO_DE_MELHORIAS.md) | Diagnóstico técnico, problemas, melhorias e riscos | -| [`docs/ROADMAP_DE_IMPLEMENTACAO.md`](./docs/ROADMAP_DE_IMPLEMENTACAO.md) | 49 tarefas em 8 fases, estratégia e plano de testes | -| [`docs/INVENTARIO_TECNICO.md`](./docs/INVENTARIO_TECNICO.md) | Tecnologias, dependências, módulos, variáveis e scripts | -| [`docs/PROTOCOLO.md`](./docs/PROTOCOLO.md) | Contrato do WebSocket: eventos, erros, identidade, limites | -| [`docs/DEPLOY_RENDER.md`](./docs/DEPLOY_RENDER.md) | Deploy no Render: Blueprint, variáveis, origens, cabeçalhos | -| [`docs/FASE_1_RELATORIO_DE_IMPLEMENTACAO.md`](./docs/FASE_1_RELATORIO_DE_IMPLEMENTACAO.md) | Correções da Fase 1: decisões, testes e compatibilidade | -| [`docs/FASE_2_RELATORIO_DE_IMPLEMENTACAO.md`](./docs/FASE_2_RELATORIO_DE_IMPLEMENTACAO.md) | Fase 2: arquitetura modular do backend, testes e CI | -| [`docs/FASE_3_RELATORIO_DE_IMPLEMENTACAO.md`](./docs/FASE_3_RELATORIO_DE_IMPLEMENTACAO.md) | Fase 3: heartbeat, conexões, métricas, carga e otimizações medidas | -| [`docs/CHAT_COMMANDS.md`](./docs/CHAT_COMMANDS.md) | Comandos do chat: lista, permissões, respostas, como criar | -| [`docs/FASE_4_RELATORIO_DE_IMPLEMENTACAO.md`](./docs/FASE_4_RELATORIO_DE_IMPLEMENTACAO.md) | Fase 4: evolução funcional, comandos e administração | -| [`docs/FASE_5_RELATORIO_DE_IMPLEMENTACAO.md`](./docs/FASE_5_RELATORIO_DE_IMPLEMENTACAO.md) | Fase 5: redesign de UI/UX, componentes, testes e acessibilidade | -| [`docs/design-system.md`](./docs/design-system.md) | Design system v2: tokens, componentes, layout, contraste medido | -| [`docs/refactor-report.md`](./docs/refactor-report.md) | Antes → depois da refatoração do frontend | -| [`docs/security-report.md`](./docs/security-report.md) | Auditoria de segurança e riscos residuais | -| [`CONTRIBUTING.md`](./CONTRIBUTING.md) | Como contribuir | +| Documento | Conteúdo | +| -------------------------------------------------------------------------------------------- | ------------------------------------------------------------------- | +| [`docs/ANALISE_E_PLANO_DE_MELHORIAS.md`](./docs/ANALISE_E_PLANO_DE_MELHORIAS.md) | Diagnóstico técnico, problemas, melhorias e riscos | +| [`docs/ROADMAP_DE_IMPLEMENTACAO.md`](./docs/ROADMAP_DE_IMPLEMENTACAO.md) | 49 tarefas em 8 fases, estratégia e plano de testes | +| [`docs/INVENTARIO_TECNICO.md`](./docs/INVENTARIO_TECNICO.md) | Tecnologias, dependências, módulos, variáveis e scripts | +| [`docs/PROTOCOLO.md`](./docs/PROTOCOLO.md) | Contrato do WebSocket: eventos, erros, identidade, limites | +| [`docs/DEPLOY_RENDER.md`](./docs/DEPLOY_RENDER.md) | Deploy no Render: Blueprint, variáveis, origens, cabeçalhos | +| [`docs/PRODUCAO.md`](./docs/PRODUCAO.md) | Produção: pendências, checklist, publicação e rollback | +| [`docs/EVOLUCAO_FASE_2_SALAS.md`](./docs/EVOLUCAO_FASE_2_SALAS.md) | Evolução, Fase 2: várias salas e códigos de convite | +| [`docs/EVOLUCAO_FASE_3_CONVERSAS_PRIVADAS.md`](./docs/EVOLUCAO_FASE_3_CONVERSAS_PRIVADAS.md) | Evolução, Fase 3: conversas privadas e id interno fora do protocolo | +| [`docs/EVOLUCAO_FASE_4_PLANO.md`](./docs/EVOLUCAO_FASE_4_PLANO.md) | Evolução, Fase 4 (plano): frontend com várias conversas | +| [`docs/FASE_1_RELATORIO_DE_IMPLEMENTACAO.md`](./docs/FASE_1_RELATORIO_DE_IMPLEMENTACAO.md) | Correções da Fase 1: decisões, testes e compatibilidade | +| [`docs/FASE_2_RELATORIO_DE_IMPLEMENTACAO.md`](./docs/FASE_2_RELATORIO_DE_IMPLEMENTACAO.md) | Fase 2: arquitetura modular do backend, testes e CI | +| [`docs/FASE_3_RELATORIO_DE_IMPLEMENTACAO.md`](./docs/FASE_3_RELATORIO_DE_IMPLEMENTACAO.md) | Fase 3: heartbeat, conexões, métricas, carga e otimizações medidas | +| [`docs/CHAT_COMMANDS.md`](./docs/CHAT_COMMANDS.md) | Comandos do chat: lista, permissões, respostas, como criar | +| [`docs/FASE_4_RELATORIO_DE_IMPLEMENTACAO.md`](./docs/FASE_4_RELATORIO_DE_IMPLEMENTACAO.md) | Fase 4: evolução funcional, comandos e administração | +| [`docs/FASE_5_RELATORIO_DE_IMPLEMENTACAO.md`](./docs/FASE_5_RELATORIO_DE_IMPLEMENTACAO.md) | Fase 5: redesign de UI/UX, componentes, testes e acessibilidade | +| [`docs/design-system.md`](./docs/design-system.md) | Design system v2: tokens, componentes, layout, contraste medido | +| [`docs/refactor-report.md`](./docs/refactor-report.md) | Antes → depois da refatoração do frontend | +| [`docs/security-report.md`](./docs/security-report.md) | Auditoria de segurança e riscos residuais | +| [`CONTRIBUTING.md`](./CONTRIBUTING.md) | Como contribuir | ## Roadmap @@ -491,16 +531,22 @@ Resumo — detalhes, dependências e critérios de aceite em ## Status do projeto -**Em desenvolvimento ativo.** As Fases 1 a 4 do roadmap estão concluídas e a 5 está em curso: correções de -segurança, fundação modular, performance e monitoramento, e a **Fase 4**, que trouxe -28 comandos no chat com autocomplete, administração por chave do operador -(`ADMIN_KEY`), confirmação de entrega com "tentar de novo", presença, troca de nome e -reconexão sem avisos repetidos. A **Fase 5** refez a interface inteira (layout em -painéis, design system v2, gavetas em telas estreitas, cartão de pessoa, auditoria -de acessibilidade automática sem violações); o projeto tem 271 testes automatizados. -Próximo passo: concluir a Fase 5 (indicador de mensagens novas, contador no composer, -auditoria manual com leitores de tela). Antes de expor o chat publicamente, configure -`ALLOWED_ORIGINS` e, se quiser moderação, `ADMIN_KEY`. +**Em desenvolvimento ativo.** O roadmap original (Fases 1 a 5: segurança, fundação +modular, performance, comandos e redesign) está entregue. Em cima dele corre a +**evolução para salas e conversas privadas**: + +| Etapa | Situação | +| ---------------------------------------------------------------- | -------------------------------------------- | +| 1 · Barras laterais ajustáveis | Publicada | +| 2 · Várias salas com código de convite (servidor) | Publicada | +| 3 · Conversas privadas e id interno fora do protocolo (servidor) | Pronta, aguardando aprovação | +| 4 · Frontend com várias conversas e não lidas | [Planejada](./docs/EVOLUCAO_FASE_4_PLANO.md) | +| 5 · Interface: tela inicial, salas, convites, conversas privadas | A fazer | +| 6 · Revisão geral | A fazer | + +O projeto tem 463 testes automatizados (336 no servidor e 127 no cliente). Antes de +expor o chat publicamente, veja as pendências em +[`docs/PRODUCAO.md`](./docs/PRODUCAO.md): a principal é definir `ALLOWED_ORIGINS`. ## Contribuindo diff --git a/backend/src/commands/handlers/admin.js b/backend/src/commands/handlers/admin.js index 4aae989..e091d12 100644 --- a/backend/src/commands/handlers/admin.js +++ b/backend/src/commands/handlers/admin.js @@ -100,14 +100,14 @@ export const adminCommands = [ requiresRoom: true, description: "Impede alguém de enviar mensagens nesta sala, por um tempo (minutos) ou até /unmute.", - syntax: "/mute [minutos]", + syntax: "/mute <@ ou nome> [minutos]", examples: ["/mute @ana 10", "/mute Ana", '/mute "João Silva" 5'], params: [ - { name: "nome ou id", type: "word" }, + { name: "@ ou nome", type: "word" }, { name: "minutos", type: "int", optional: true, min: 1, max: 1440 }, ], run: (ctx) => { - const found = findModerationTarget(ctx, ctx.args["nome ou id"]); + const found = findModerationTarget(ctx, ctx.args["@ ou nome"]); if (!found.ok) return found.response; const minutes = ctx.args.minutos; ctx.room.setMuted( @@ -125,11 +125,11 @@ export const adminCommands = [ permission: PERMISSIONS.MODERATOR, requiresRoom: true, description: "Libera alguém silenciado nesta sala.", - syntax: "/unmute ", + syntax: "/unmute <@ ou nome>", examples: ["/unmute @ana", "/unmute Ana"], - params: [{ name: "nome ou id", type: "word" }], + params: [{ name: "@ ou nome", type: "word" }], run: (ctx) => { - const found = findModerationTarget(ctx, ctx.args["nome ou id"]); + const found = findModerationTarget(ctx, ctx.args["@ ou nome"]); if (!found.ok) return found.response; const { identity, membership } = found.target; if (membership.mutedUntil === null || membership.mutedUntil <= ctx.now()) { @@ -147,11 +147,11 @@ export const adminCommands = [ requiresRoom: true, description: "Remove alguém desta sala agora. A pessoa continua nas outras salas, mas não volta a esta.", - syntax: "/kick ", + syntax: "/kick <@ ou nome>", examples: ["/kick @ana", "/kick Ana", '/kick "João Silva"'], - params: [{ name: "nome ou id", type: "word" }], + params: [{ name: "@ ou nome", type: "word" }], run: (ctx) => { - const found = findModerationTarget(ctx, ctx.args["nome ou id"]); + const found = findModerationTarget(ctx, ctx.args["@ ou nome"]); if (!found.ok) return found.response; ctx.room.kick(ctx.identity, found.target.identity); return null; diff --git a/backend/src/commands/handlers/basic.js b/backend/src/commands/handlers/basic.js index 548e121..262a45f 100644 --- a/backend/src/commands/handlers/basic.js +++ b/backend/src/commands/handlers/basic.js @@ -1,6 +1,6 @@ /** Comandos básicos: ajuda, salas, conexão e informações do servidor. */ -import { isMuted } from "../../room/policy.js"; +import { isAdmin, isMuted } from "../../room/policy.js"; /** Regras da sala exibidas por /rules — fonte única. */ export const ROOM_RULES = [ @@ -45,13 +45,14 @@ export const basicCommands = [ name: "users", aliases: ["online", "who"], category: "basic", - description: "Lista quem está na sala agora, com o @username e o id curto de cada pessoa.", + description: "Lista quem está na sala agora, com o @username de cada pessoa.", syntax: "/users", examples: ["/users"], requiresRoom: true, run: (ctx) => { const time = ctx.now(); const people = ctx.room.listMembers(); + const seesIds = isAdmin(ctx.identity); const lines = people.map(({ identity, membership }) => { const tags = [ identity.id === ctx.identity.id ? "você" : null, @@ -60,7 +61,9 @@ export const basicCommands = [ identity.away !== null ? `ausente: ${identity.away}` : null, isMuted(membership, time) ? "silenciado" : null, ].filter(Boolean); - return `${identity.name} (@${identity.username}) · ${identity.id.slice(0, 8)}${tags.length ? ` · ${tags.join(" · ")}` : ""}`; + // O id interno só aparece para administradores. + const id = seesIds ? ` · id ${identity.id.slice(0, 8)}` : ""; + return `${identity.name} (@${identity.username})${id}${tags.length ? ` · ${tags.join(" · ")}` : ""}`; }); return ctx.reply.result( people.length === 1 ? "1 pessoa na sala" : `${people.length} pessoas na sala`, diff --git a/backend/src/commands/handlers/profile.js b/backend/src/commands/handlers/profile.js index a6b9b7f..4e39d49 100644 --- a/backend/src/commands/handlers/profile.js +++ b/backend/src/commands/handlers/profile.js @@ -1,7 +1,7 @@ /** Perfil e presença: nome, id, perfil público, ausência, ação. */ import { MESSAGE_KINDS } from "../../protocol.js"; -import { isMuted } from "../../room/policy.js"; +import { isAdmin, isMuted, PERMISSIONS } from "../../room/policy.js"; import { clock, findTarget, publishFor } from "./shared.js"; /** @type {import("../registry.js").CommandDefinition[]} */ @@ -10,7 +10,7 @@ export const profileCommands = [ name: "nick", aliases: ["nome"], category: "profile", - description: "Troca o seu nome de exibição. O seu id continua o mesmo.", + description: "Troca o seu nome de exibição. O seu @ continua o mesmo.", syntax: "/nick ", examples: ["/nick João Silva"], params: [{ name: "novo nome", type: "text" }], @@ -38,13 +38,13 @@ export const profileCommands = [ aliases: ["whois", "perfil"], category: "profile", description: "Mostra o perfil público de alguém da sala (ou o seu).", - syntax: "/profile [nome ou id]", + syntax: "/profile [@ ou nome]", examples: ["/profile", "/profile @ana", "/profile Ana"], - params: [{ name: "nome ou id", type: "text", optional: true }], + params: [{ name: "@ ou nome", type: "text", optional: true }], run: (ctx) => { let identity = ctx.identity; let membership = ctx.membership; - const query = ctx.args["nome ou id"]; + const query = ctx.args["@ ou nome"]; if (query) { // Procurar alguém só faz sentido dentro de uma sala: fora dela // não há como saber quem você "vê". @@ -71,7 +71,8 @@ export const profileCommands = [ title: "Perfil", lines: [ `Username: @${identity.username}`, - `Id: ${identity.id}`, + // O id interno só aparece para administradores. + ...(isAdmin(ctx.identity) ? [`Id interno: ${identity.id}`] : []), `Papel: ${role}`, `Status: ${identity.away !== null ? `ausente (${identity.away})` : "presente"}${muted}`, membership @@ -86,10 +87,11 @@ export const profileCommands = [ name: "id", aliases: [], category: "profile", - description: "Mostra o seu id completo, atribuído pelo servidor.", + permission: PERMISSIONS.ADMIN, + description: "Mostra o seu id interno. Só para administradores.", syntax: "/id", examples: ["/id"], - run: (ctx) => ctx.reply.result(`Seu id: ${ctx.identity.id}`), + run: (ctx) => ctx.reply.result(`Seu id interno: ${ctx.identity.id}`), }, { name: "me", diff --git a/backend/src/commands/handlers/shared.js b/backend/src/commands/handlers/shared.js index 4105aee..10f3081 100644 --- a/backend/src/commands/handlers/shared.js +++ b/backend/src/commands/handlers/shared.js @@ -6,7 +6,7 @@ */ import { ERROR_CODES } from "../../errors.js"; -import { canModerate } from "../../room/policy.js"; +import { canModerate, isAdmin } from "../../room/policy.js"; /** * Publica na sala em nome de quem executou o comando e traduz recusas. @@ -32,13 +32,14 @@ export const publishFor = (ctx, message) => { }; /** - * Encontra exatamente uma pessoa na sala por @username, nome ou id (prefixo 6+). + * Encontra exatamente uma pessoa na sala por @username ou nome. Só + * administradores também podem indicar alguém pelo id interno (prefixo 6+). * @param {any} ctx * @param {string} query * @returns {{ok: true, target: {identity: any, membership: any}} | {ok: false, response: any}} */ export const findTarget = (ctx, query) => { - const found = ctx.room.findMembers(query); + const found = ctx.room.findMembers(query, { allowIds: isAdmin(ctx.identity) }); if (found.length === 0) { return { ok: false, diff --git a/backend/src/config.js b/backend/src/config.js index d66d739..6ca6786 100644 --- a/backend/src/config.js +++ b/backend/src/config.js @@ -54,6 +54,9 @@ export const DEFAULTS = Object.freeze({ maxRoomsPerUser: 10, maxRoomsCreatedPerUser: 5, roomEmptyTtlMs: 60000, + maxDmsPerUser: 20, + maxDms: 5000, + dmHistorySize: 100, }); const isBlank = (raw) => raw === undefined || raw === ""; @@ -140,6 +143,9 @@ const readOrigins = (raw) => url !== null && (url.protocol === "http:" || url.protocol === "https:") && url.pathname === "/" && + // Curinga não existe: "https://*.x.com" seria aceito pelo + // parser como host literal e nunca casaria — melhor recusar. + !url.hostname.includes("*") && !url.search && !url.hash && !url.username && @@ -157,7 +163,7 @@ const readOrigins = (raw) => /** * @typedef {object} Config * @property {number} port - * @property {string[]} allowedOrigins vazio = qualquer origem + * @property {string[]} allowedOrigins vazio = qualquer origem (só fora de produção) * @property {number} heartbeatMs * @property {number} maxConnections * @property {number} maxPayloadBytes @@ -172,6 +178,7 @@ const readOrigins = (raw) => * @property {number} metricsLogIntervalMs 0 desliga o log periódico de métricas * @property {number} leaveGraceMs janela em que uma reconexão não gera avisos de saída/entrada * @property {{maxRooms: number, maxRoomsPerIdentity: number, maxCreatedPerIdentity: number, emptyTtlMs: number}} rooms + * @property {{maxPerIdentity: number, maxTotal: number, historySize: number}} dms * @property {string | null} adminKey chave secreta de administrador (null = administração desativada) * @property {boolean} production */ @@ -198,9 +205,24 @@ export const loadConfig = (env) => { ); } + const production = env.NODE_ENV === "production"; + const allowedOrigins = readOrigins(env.ALLOWED_ORIGINS); + // Em produção a lista é obrigatória: sem ela, qualquer site poderia abrir + // um WebSocket em nome de quem o visita (CSWSH). Sem a variável o servidor + // nem sobe — o Render mantém a versão anterior no ar e o erro aparece no + // log, em vez de um backend aberto passar despercebido. Curinga (`*`) não + // existe: não é uma origem válida e já é recusado acima. + if (production && allowedOrigins.length === 0) { + 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.", + ); + } + return { port: readInteger("PORT", env.PORT, { fallback: DEFAULTS.port, min: 0, max: 65535 }), - allowedOrigins: readOrigins(env.ALLOWED_ORIGINS), + allowedOrigins, heartbeatMs: readInteger("HEARTBEAT_MS", env.HEARTBEAT_MS, { fallback: DEFAULTS.heartbeatMs, min: 50, @@ -295,7 +317,26 @@ export const loadConfig = (env) => { unit: " ms", }), }, + dms: { + // Conversas privadas abertas por identidade ao mesmo tempo. + maxPerIdentity: readInteger("MAX_DMS_PER_USER", env.MAX_DMS_PER_USER, { + fallback: DEFAULTS.maxDmsPerUser, + min: 1, + max: 1000, + }), + // Conversas privadas no servidor inteiro: protege a memória. + maxTotal: readInteger("MAX_DMS", env.MAX_DMS, { + fallback: DEFAULTS.maxDms, + min: 1, + max: 1000000, + }), + historySize: readInteger("DM_HISTORY_SIZE", env.DM_HISTORY_SIZE, { + fallback: DEFAULTS.dmHistorySize, + min: 1, + max: 10000, + }), + }, adminKey: readAdminKey(env.ADMIN_KEY), - production: env.NODE_ENV === "production", + production, }; }; diff --git a/backend/src/errors.js b/backend/src/errors.js index 52a1adf..2a443e5 100644 --- a/backend/src/errors.js +++ b/backend/src/errors.js @@ -43,6 +43,15 @@ export const ERROR_CODES = Object.freeze({ ROOM_CREATE_LIMIT: "room_create_limit", ROOMS_FULL: "rooms_full", ROOM_JOIN_LOCKED: "room_join_locked", + // Conversas privadas (Fase 3 da evolução) + INVALID_USER: "invalid_user", + USER_UNAVAILABLE: "user_unavailable", + DM_SELF: "dm_self", + DM_LIMIT: "dm_limit", + DMS_FULL: "dms_full", + LOOKUP_LIMITED: "lookup_limited", + DM_OPEN_LIMITED: "dm_open_limited", + BLOCK_LIMIT: "block_limit", }); const { PROTOCOL, VALIDATION, AUTHORIZATION, RATE_LIMIT, INTERNAL } = ERROR_CATEGORIES; @@ -120,6 +129,40 @@ const CATALOG = Object.freeze({ category: RATE_LIMIT, message: "Tentativas demais com códigos inválidos. Aguarde um pouco para tentar de novo.", }, + [ERROR_CODES.INVALID_USER]: { + category: VALIDATION, + message: "Informe um @ válido.", + }, + // Mesmo texto para "não existe", "não está conectada" e "bloqueou você": + // a resposta não revela bloqueio nem confirma que alguém existe. + [ERROR_CODES.USER_UNAVAILABLE]: { + category: VALIDATION, + message: "Ninguém com esse @ está disponível para conversar agora.", + }, + [ERROR_CODES.DM_SELF]: { + category: VALIDATION, + message: "Você não pode abrir uma conversa privada com você mesmo.", + }, + [ERROR_CODES.DM_LIMIT]: { + category: AUTHORIZATION, + message: "Você já tem o número máximo de conversas privadas. Encerre uma para abrir outra.", + }, + [ERROR_CODES.DMS_FULL]: { + category: RATE_LIMIT, + message: "O servidor está no limite de conversas privadas. Tente de novo em instantes.", + }, + [ERROR_CODES.LOOKUP_LIMITED]: { + category: RATE_LIMIT, + message: "Buscas demais em pouco tempo. Aguarde um pouco para buscar de novo.", + }, + [ERROR_CODES.DM_OPEN_LIMITED]: { + category: RATE_LIMIT, + message: "Conversas novas demais em pouco tempo. Aguarde um pouco.", + }, + [ERROR_CODES.BLOCK_LIMIT]: { + category: AUTHORIZATION, + message: "Você já bloqueou o número máximo de pessoas nesta sessão.", + }, }); /** diff --git a/backend/src/metrics.js b/backend/src/metrics.js index 2f3711a..17d5ce3 100644 --- a/backend/src/metrics.js +++ b/backend/src/metrics.js @@ -43,6 +43,11 @@ export const createMetrics = ({ now = () => Date.now(), startedAt = Date.now() } roomsCreated: 0, roomJoins: 0, roomLeaves: 0, + // Conversas privadas (Fase 3 da evolução) + userLookups: 0, + dmsOpened: 0, + dmsClosed: 0, + blocks: 0, }; const buckets = new Array(PROCESSING_BUCKETS_MS.length + 1).fill(0); @@ -83,7 +88,7 @@ export const createMetrics = ({ now = () => Date.now(), startedAt = Date.now() } * Fotografia atual. `reset` zera as janelas (CPU, atraso do event * loop, máximo de processamento) — usado pelo log periódico, para que * cada linha descreva o intervalo desde a anterior. - * @param {{connections: number, users: number, identities: number, rooms?: number}} gauges + * @param {{connections: number, users: number, identities: number, rooms?: number, dms?: number}} gauges * @param {{reset?: boolean}} [options] */ snapshot(gauges, { reset = false } = {}) { diff --git a/backend/src/protocol.js b/backend/src/protocol.js index 6ae8d06..84f4b3b 100644 --- a/backend/src/protocol.js +++ b/backend/src/protocol.js @@ -13,6 +13,11 @@ * O `conversationId` é opaco e não é o código de convite: o código só é * entregue a quem está na sala e nunca vai para o log. * + * Pessoas: quem conversa se identifica pelo `@username` — é ele que vai em + * mensagens, listas, digitação e conversas privadas. O id interno de uma + * identidade NUNCA sai num evento: fica no servidor (índices, logs) e só + * administradores o veem, pelos comandos `/users`, `/profile` e `/id`. + * * O cliente tem o espelho deste contrato em `frontend/src/protocol.js`; um * teste (`test/unit/contract.test.js`) falha se os dois divergirem. Os dois * arquivos não são compartilhados por import porque o frontend precisa @@ -60,8 +65,18 @@ export const CLIENT_EVENTS = Object.freeze({ ROOM_JOIN: "room_join", /** Sair de uma sala (a identidade continua nas outras). */ ROOM_LEAVE: "room_leave", - /** Pedir a lista das salas de que a identidade participa. */ + /** Pedir a lista das conversas (salas e privadas) da identidade. */ ROOM_LIST: "room_list", + /** Procurar alguém conectado pelo @ exato (nunca lista ninguém). */ + USER_LOOKUP: "user_lookup", + /** Abrir (ou retomar) a conversa privada com alguém. */ + DM_OPEN: "dm_open", + /** Encerrar uma conversa privada: some para os dois, com o histórico. */ + DM_CLOSE: "dm_close", + /** Bloquear alguém até o fim da sessão (só afeta conversas privadas). */ + USER_BLOCK: "user_block", + /** Desfazer um bloqueio. */ + USER_UNBLOCK: "user_unblock", }); /** Eventos que o servidor envia. */ @@ -86,6 +101,16 @@ export const SERVER_EVENTS = Object.freeze({ ROOM_LIST: "room_list", /** O resumo de uma sala mudou (ex.: anfitrião novo). */ ROOM_UPDATED: "room_updated", + /** Resposta a `user_lookup`. */ + USER_LOOKUP: "user_lookup", + /** Você está numa conversa privada: resumo (seguido de histórico). */ + DM_OPENED: "dm_opened", + /** O resumo de uma conversa privada mudou (nome ou presença da outra pessoa). */ + DM_UPDATED: "dm_updated", + /** A conversa privada acabou, com o histórico. */ + DM_CLOSED: "dm_closed", + /** Quem você bloqueou nesta sessão (resposta a bloquear/desbloquear). */ + BLOCK_LIST: "block_list", }); /** @@ -117,6 +142,17 @@ export const PRESENCE = Object.freeze({ ONLINE: "online", AWAY: "away" }); */ export const ROLES = Object.freeze({ MEMBER: "member", ADMIN: "admin", HOST: "host" }); +/** Tipos de conversa: o prefixo do `conversationId` diz qual é. */ +export const CONVERSATION_KINDS = Object.freeze({ ROOM: "room", DM: "dm" }); + +/** Por que uma conversa privada acabou (`dm_closed`). */ +export const DM_CLOSED_REASONS = Object.freeze({ + /** Uma das duas pessoas a encerrou (ou bloqueou a outra). */ + CLOSED: "closed", + /** A identidade da outra pessoa acabou (saiu ou não voltou a tempo). */ + ENDED: "ended", +}); + /** Por que alguém deixou de estar numa sala (`room_left`). */ export const ROOM_LEFT_REASONS = Object.freeze({ /** A própria pessoa saiu. */ @@ -211,30 +247,40 @@ export const scoped = (conversationId, message) => ({ ...message, conversationId * @property {string} code código de convite (só para quem está na sala) * @property {string} name * @property {string} role papel de quem recebe NESTA sala - * @property {string | null} hostId + * @property {string | null} hostUsername @ de quem é anfitrião agora * @property {number} memberCount * @property {number} historyVersion */ +/** + * @typedef {object} DmSummary + * @property {string} conversationId + * @property {"dm"} kind + * @property {{name: string, username: string, online: boolean}} peer a outra pessoa + * @property {number} historyVersion + */ + export const serverMessage = Object.freeze({ /** * Sessão: quem a conexão é. Não diz nada sobre salas — cada sala chega * no seu próprio `room_joined`. `resumed` diz se a identidade anterior * foi retomada (e, com ela, as salas); sem isso, a identidade é nova e - * não está em sala nenhuma. - * @param {{id: string, name: string, username?: string, role?: string}} user + * não está em sala nenhuma. `since` é o instante em que ESTA identidade + * nasceu: mensagens anteriores com o mesmo @ são de outra pessoa, que + * usou o @ antes — o cliente não as mostra como "suas". + * @param {{name: string, username?: string, role?: string, joinedAt?: number}} user * @param {string} resumeToken * @param {boolean} [resumed] */ session: (user, resumeToken, resumed = false) => ({ type: SERVER_EVENTS.SESSION, payload: { - id: user.id, name: user.name, username: user.username ?? "", resumeToken, role: user.role === ROLES.ADMIN ? ROLES.ADMIN : ROLES.MEMBER, resumed, + since: new Date(user.joinedAt ?? 0).toISOString(), }, }), @@ -256,10 +302,59 @@ export const serverMessage = Object.freeze({ roomLeft: (conversationId, reason) => scoped(conversationId, { type: SERVER_EVENTS.ROOM_LEFT, payload: { reason } }), - /** @param {RoomSummary[]} rooms @param {string | null} [requestId] */ - roomList: (rooms, requestId = null) => ({ + /** + * As conversas da identidade: salas e conversas privadas. + * @param {RoomSummary[]} rooms + * @param {DmSummary[]} dms + * @param {string | null} [requestId] + */ + roomList: (rooms, dms, requestId = null) => ({ type: SERVER_EVENTS.ROOM_LIST, - payload: { rooms, ...(requestId ? { requestId } : {}) }, + payload: { rooms, dms, ...(requestId ? { requestId } : {}) }, + }), + + /** + * Resultado de uma busca por @: só nome e @ de quem foi achado. + * @param {{name: string, username: string} | null} user + * @param {string | null} [requestId] + */ + userLookup: (user, requestId = null) => ({ + type: SERVER_EVENTS.USER_LOOKUP, + payload: { + found: user !== null, + ...(user ? { user: { name: user.name, username: user.username } } : {}), + ...(requestId ? { requestId } : {}), + }, + }), + + /** + * @param {DmSummary} summary + * @param {{created?: boolean, resumed?: boolean}} [how] + */ + dmOpened: (summary, { created = false, resumed = false } = {}) => + scoped(summary.conversationId, { + type: SERVER_EVENTS.DM_OPENED, + payload: { ...summary, created, resumed }, + }), + + /** @param {DmSummary} summary */ + dmUpdated: (summary) => + scoped(summary.conversationId, { type: SERVER_EVENTS.DM_UPDATED, payload: summary }), + + /** @param {string} conversationId @param {string} reason um dos `DM_CLOSED_REASONS` */ + dmClosed: (conversationId, reason) => + scoped(conversationId, { type: SERVER_EVENTS.DM_CLOSED, payload: { reason } }), + + /** + * @param {{name: string, username: string}[]} people + * @param {string | null} [requestId] + */ + blockList: (people, requestId = null) => ({ + type: SERVER_EVENTS.BLOCK_LIST, + payload: { + blocked: people.map(({ name, username }) => ({ name, username })), + ...(requestId ? { requestId } : {}), + }, }), /** @param {unknown[]} entries mensagens de chat já no formato de envio */ @@ -269,7 +364,7 @@ export const serverMessage = Object.freeze({ * Mensagem de chat. `kind`, `format` e `clientMsgId` são aditivos: só * entram no payload quando presentes, e clientes antigos os ignoram. * @param {{ - * id: string, user: {id: string, name: string, username?: string}, + * id: string, user: {name: string, username?: string}, * content: string, timestamp: string, * kind?: string, format?: string | null, clientMsgId?: string | null, * }} message @@ -286,9 +381,8 @@ export const serverMessage = Object.freeze({ id, type: SERVER_EVENTS.CHAT_MESSAGE, payload: { - userId: user.id, userName: user.name, - ...(user.username ? { username: user.username } : {}), + username: user.username ?? "", content, timestamp, ...(kind !== MESSAGE_KINDS.TEXT ? { kind } : {}), @@ -297,32 +391,31 @@ export const serverMessage = Object.freeze({ }, }), - /** @param {string} userName @param {string} timestamp */ - joined: (userName, timestamp) => ({ + /** @param {{name: string, username?: string}} user @param {string} timestamp */ + joined: (user, timestamp) => ({ type: SERVER_EVENTS.USER_JOINED, - payload: { userName, timestamp }, + payload: { userName: user.name, username: user.username ?? "", timestamp }, }), /** - * @param {{id: string, name: string}} user + * @param {{name: string, username?: string}} user * @param {string} timestamp * @param {string} [reason] "left" (padrão) ou "removed" */ left: (user, timestamp, reason = "left") => ({ type: SERVER_EVENTS.USER_LEFT, - payload: { userId: user.id, userName: user.name, timestamp, reason }, + payload: { userName: user.name, username: user.username ?? "", timestamp, reason }, }), /** * `status` já existia ("online"); agora também "away". `role` e * `statusText` são aditivos. * `role` é o papel NA SALA: `admin` (global) prevalece sobre `host`. - * @param {{id: string, name: string, username?: string, role?: string, away?: string | null}[]} users + * @param {{name: string, username?: string, role?: string, away?: string | null}[]} users */ userList: (users) => ({ type: SERVER_EVENTS.USER_LIST, payload: users.map((user) => ({ - id: user.id, name: user.name, username: user.username ?? "", status: user.away === null || user.away === undefined ? PRESENCE.ONLINE : PRESENCE.AWAY, @@ -331,10 +424,10 @@ export const serverMessage = Object.freeze({ })), }), - /** @param {{id: string, name: string}} user @param {boolean} isTyping */ + /** @param {{name: string, username?: string}} user @param {boolean} isTyping */ typing: (user, isTyping) => ({ type: SERVER_EVENTS.USER_TYPING, - payload: { userId: user.id, userName: user.name, isTyping }, + payload: { userName: user.name, username: user.username ?? "", isTyping }, }), /** diff --git a/backend/src/room/direct.js b/backend/src/room/direct.js new file mode 100644 index 0000000..4cf332d --- /dev/null +++ b/backend/src/room/direct.js @@ -0,0 +1,355 @@ +/** + * Conversas privadas (Fase 3 da evolução): duas identidades, ninguém mais. + * + * Mesmo núcleo de histórico das salas (`transcript.js`), regras próprias: + * - só as duas participantes leem, escrevem ou recebem qualquer coisa + * (mensagem, digitação, presença) — não há como entrar numa conversa + * privada; ela é aberta pelo hub entre duas identidades; + * - a conversa é ligada aos IDS INTERNOS das duas identidades, nunca ao @: + * uma identidade nova que reutilize o mesmo @ não acha nada; + * - quem abre recebe a conversa na hora; a outra pessoa só fica sabendo + * dela com a primeira mensagem — abrir conversas não vira spam de avisos; + * - acaba quando uma das duas a encerra, bloqueia a outra ou deixa de + * existir; o histórico vai junto. Uma queda dentro da janela de retomada + * não encerra nada. + * + * Tudo em memória: reiniciar o servidor apaga todas. + */ + +import crypto from "node:crypto"; +import { ERROR_CODES } from "../errors.js"; +import { DM_CLOSED_REASONS, MESSAGE_KINDS, scoped, serverMessage } from "../protocol.js"; +import { readClientId, readContent } from "../validation.js"; +import { createTranscript } from "./transcript.js"; + +/** Limites padrão; configuráveis por variável de ambiente. */ +export const DM_DEFAULTS = Object.freeze({ + /** Conversas privadas abertas por identidade ao mesmo tempo. */ + maxPerIdentity: 20, + /** Conversas privadas no servidor inteiro. */ + maxTotal: 5000, + /** Mensagens guardadas por conversa privada. */ + historySize: 100, +}); + +/** Id opaco da conversa privada (o prefixo diz o tipo). */ +export const generateDmId = () => `d_${crypto.randomBytes(12).toString("base64url")}`; + +/** + * @typedef {import("./sessions.js").Identity} Identity + * @typedef {ReturnType} DirectConversation + */ + +/** + * @param {{ + * id: string, + * a: Identity, + * b: Identity, + * deliver: (holder: unknown, data: string) => void, + * log: (level: "info" | "warn" | "error", event: string, fields?: Record) => void, + * historySize: number, + * historyOnJoin: number, + * now?: () => Date, + * newMessageId?: () => string, + * onPresenceChange?: (identity: Identity) => void, + * }} options + */ +export const createDirectConversation = ({ + id, + a, + b, + deliver, + log, + historySize, + historyOnJoin, + now = () => new Date(), + newMessageId = () => crypto.randomUUID(), + onPresenceChange = () => {}, +}) => { + const participants = [a, b]; + const transcript = createTranscript({ id, historySize, now, newMessageId }); + /** Quem já sabe que a conversa existe (e por isso recebe os eventos dela). */ + const announced = new Set(); + let closed = false; + + /** @param {Identity} identity */ + const has = (identity) => identity === a || identity === b; + /** @param {Identity} identity */ + const peerOf = (identity) => (identity === a ? b : a); + + /** @param {Identity} identity @param {Record} message */ + const sendTo = (identity, message) => { + if (closed || identity.holder === null) return; + deliver(identity.holder, JSON.stringify(message)); + }; + + /** + * Resumo do ponto de vista de quem recebe: a outra pessoa e a presença dela. + * @param {Identity} identity + * @returns {import("../protocol.js").DmSummary} + */ + const summaryFor = (identity) => { + const peer = peerOf(identity); + return { + conversationId: id, + kind: "dm", + peer: { + name: peer.name, + username: peer.username, + online: peer.holder !== null, + }, + historyVersion: transcript.version, + }; + }; + + /** + * Resumo e histórico recente para uma das duas. + * @param {Identity} identity + * @param {{created?: boolean, resumed?: boolean}} how + */ + const sendState = (identity, how) => { + announced.add(identity); + sendTo(identity, serverMessage.dmOpened(summaryFor(identity), how)); + const recent = transcript.recent(historyOnJoin); + if (recent.length > 0) sendTo(identity, scoped(id, serverMessage.history(recent))); + }; + + /** A outra pessoa (se já sabe da conversa) recebe o resumo atualizado. @param {Identity} identity */ + const updatePeerOf = (identity) => { + const peer = peerOf(identity); + if (announced.has(peer)) sendTo(peer, serverMessage.dmUpdated(summaryFor(peer))); + }; + + /** + * Publica. Único caminho de escrita no histórico desta conversa. + * @param {Identity} identity + * @param {{content: string, kind?: string, format?: string | null, clientMsgId?: string | null}} input + * @returns {{ok: true, duplicate?: boolean} | {ok: false, code: string}} + */ + const publish = (identity, input) => { + if (closed || !has(identity)) + return { ok: false, code: ERROR_CODES.CONVERSATION_NOT_FOUND }; + const { message, duplicate } = transcript.append(identity, { + kind: MESSAGE_KINDS.TEXT, + ...input, + }); + const scopedMessage = scoped(id, message); + if (duplicate) { + sendTo(identity, scopedMessage); + return { ok: true, duplicate: true }; + } + sendTo(identity, scopedMessage); + const peer = peerOf(identity); + // Primeira mensagem: a outra pessoa descobre a conversa agora, já + // com esta mensagem no histórico. + if (announced.has(peer)) sendTo(peer, scopedMessage); + else sendState(peer, { created: true }); + + if (identity.away !== null) { + identity.away = null; + onPresenceChange(identity); + } + return { ok: true }; + }; + + return { + id, + kind: /** @type {const} */ ("dm"), + has, + peerOf, + summaryFor, + + /** Quem abre (ou reabre) recebe o estado; a outra pessoa, não. */ + open: sendState, + + /** + * Mensagem digitada. Autor é a identidade; `kind` e `format` do + * payload são ignorados. + * @param {Identity} identity + * @param {Record} payload + */ + post(identity, payload) { + if (closed || !has(identity)) + return { ok: false, code: ERROR_CODES.CONVERSATION_NOT_FOUND }; + const content = readContent(payload.content); + if (!content.ok) return content; + return publish(identity, { + content: content.content, + clientMsgId: readClientId(payload.clientMsgId), + }); + }, + + publish, + + /** + * Digitação, só para a outra pessoa — e só se ela já sabe da conversa. + * @param {Identity} identity + * @param {boolean} isTyping + */ + typing(identity, isTyping) { + if (closed || !has(identity)) return; + const peer = peerOf(identity); + if (announced.has(peer)) { + sendTo(peer, scoped(id, serverMessage.typing(identity, isTyping))); + } + }, + + /** A identidade voltou: recebe a conversa de novo; a outra vê "online". @param {Identity} identity */ + reconnect(identity) { + if (closed || !has(identity)) return; + if (announced.has(identity)) sendState(identity, { resumed: true }); + updatePeerOf(identity); + }, + + /** A conexão caiu (janela de retomada): a outra pessoa vê "offline". @param {Identity} identity */ + disconnect(identity) { + if (closed || !has(identity)) return; + updatePeerOf(identity); + }, + + /** Nome mudou: a outra pessoa recebe o resumo novo. @param {Identity} identity */ + refreshPeerOf: updatePeerOf, + + /** + * Fim da conversa, para as duas. Com `ended`, a identidade que deixou + * de existir não é avisada (não há mais a quem avisar). + * @param {{ended?: Identity | null, reason?: string}} [options] + */ + close({ + ended = null, + reason = ended ? DM_CLOSED_REASONS.ENDED : DM_CLOSED_REASONS.CLOSED, + } = {}) { + if (closed) return; + for (const identity of participants) { + if (identity !== ended && announced.has(identity)) { + sendTo(identity, serverMessage.dmClosed(id, reason)); + } + identity.dms.delete(id); + } + closed = true; + transcript.discard(participants); + announced.clear(); + log("info", "dm_closed", { conversation: id, reason }); + }, + + get closed() { + return closed; + }, + + get historyLength() { + return transcript.length; + }, + }; +}; + +/** + * Diretório das conversas privadas: no máximo uma por par de identidades. + * + * @param {{ + * makeConversation: (input: {id: string, a: Identity, b: Identity}) => DirectConversation, + * log: (level: "info" | "warn" | "error", event: string, fields?: Record) => void, + * limits?: Partial, + * newId?: () => string, + * }} options + */ +export const createDirectDirectory = ({ + makeConversation, + log, + limits = {}, + newId = generateDmId, +}) => { + const { maxPerIdentity, maxTotal } = { ...DM_DEFAULTS, ...limits }; + /** @type {Map} */ + const byId = new Map(); + /** par de ids internos (ordenados) → id da conversa @type {Map} */ + const byPair = new Map(); + + /** @param {Identity} x @param {Identity} y */ + const pairKey = (x, y) => [x.id, y.id].sort().join("|"); + + /** @param {DirectConversation} conversation @param {{ended?: Identity | null}} [options] */ + const close = (conversation, options = {}) => { + conversation.close(options); + const entry = byId.get(conversation.id); + byId.delete(conversation.id); + if (entry && byPair.get(entry.pair) === conversation.id) byPair.delete(entry.pair); + }; + + return { + /** + * A conversa entre as duas, existente ou nova. + * @param {Identity} from quem abre + * @param {Identity} to + * @returns {{ok: true, conversation: DirectConversation, created: boolean} | {ok: false, code: string}} + */ + open(from, to) { + const pair = pairKey(from, to); + const existing = byPair.get(pair); + const entry = existing === undefined ? undefined : byId.get(existing); + if (entry) return { ok: true, conversation: entry.conversation, created: false }; + if (from.dms.size >= maxPerIdentity) return { ok: false, code: ERROR_CODES.DM_LIMIT }; + // Do lado de quem recebe, "cheio" é igual a "indisponível": a + // resposta não diz nada sobre a outra pessoa. + if (to.dms.size >= maxPerIdentity) + return { ok: false, code: ERROR_CODES.USER_UNAVAILABLE }; + if (byId.size >= maxTotal) return { ok: false, code: ERROR_CODES.DMS_FULL }; + + let id = newId(); + while (byId.has(id)) id = newId(); + const conversation = makeConversation({ id, a: from, b: to }); + byId.set(id, { conversation, pair }); + byPair.set(pair, id); + from.dms.add(id); + to.dms.add(id); + log("info", "dm_opened", { conversation: id, user: from.id, peer: to.id }); + return { ok: true, conversation, created: true }; + }, + + /** + * A conversa, se a identidade participa dela; senão null ("não existe" + * e "não é sua" são a mesma resposta). + * @param {Identity} identity + * @param {string | null} conversationId + */ + forIdentity(identity, conversationId) { + if (conversationId === null || !identity.dms.has(conversationId)) return null; + const conversation = byId.get(conversationId)?.conversation ?? null; + return conversation && conversation.has(identity) ? conversation : null; + }, + + /** @param {Identity} x @param {Identity} y */ + between: (x, y) => { + const id = byPair.get(pairKey(x, y)); + return id === undefined ? null : (byId.get(id)?.conversation ?? null); + }, + + /** Conversas da identidade, na ordem em que foram abertas. @param {Identity} identity */ + of(identity) { + return [...identity.dms].flatMap((id) => { + const conversation = byId.get(id)?.conversation; + return conversation ? [conversation] : []; + }); + }, + + close, + + /** + * A identidade acabou: todas as conversas dela acabam, e a outra + * pessoa de cada uma é avisada. + * @param {Identity} identity + */ + dropIdentity(identity) { + for (const conversation of this.of(identity)) close(conversation, { ended: identity }); + identity.dms.clear(); + }, + + get size() { + return byId.size; + }, + + /** Desligamento: nada fica. */ + closeAll() { + for (const { conversation } of [...byId.values()]) close(conversation); + }, + }; +}; diff --git a/backend/src/room/hub.js b/backend/src/room/hub.js index 1c8a3e0..76fdae8 100644 --- a/backend/src/room/hub.js +++ b/backend/src/room/hub.js @@ -21,10 +21,16 @@ * * Também concentra o que é da IDENTIDADE e não de uma sala: nome, ausência * e papel de administrador, refletidos em todas as salas da pessoa. + * + * Conversas privadas (Fase 3 da evolução): busca por @ exato, abrir, + * encerrar e bloquear. Salas e conversas privadas são tipos distintos de + * conversa, com autorização própria, mas passam pelo mesmo caminho de + * mensagem e digitação (`resolveConversation`). */ import { ERROR_CODES } from "../errors.js"; import { LIMITS, ROLES, serverMessage } from "../protocol.js"; +import { createRateLimiter } from "../rateLimiter.js"; import { normalizeText, readConversationId, @@ -40,13 +46,40 @@ import { REMOVAL_REASONS, RENAME_COOLDOWN_MS } from "./room.js"; /** * @typedef {import("./sessions.js").Identity} Identity * @typedef {ReturnType} Room + * @typedef {import("./direct.js").DirectConversation} DirectConversation * @typedef {{ok: false, code: string}} Refusal */ +/** + * Limites contra abuso das conversas privadas, por identidade. + * - busca por @: 20 seguidas, depois 1 a cada 3 s — encontrar um conhecido + * é fácil; varrer @ às cegas, não; + * - conversas NOVAS: 10 seguidas, depois 1 a cada 30 s — reabrir uma + * conversa existente não conta; + * - bloqueios: até 100 por sessão. + * + * E no servidor inteiro (`global`): cada conexão nova pode criar uma + * identidade nova, com baldes cheios. Sem o teto global, abrir muitas + * conexões contornaria o limite por identidade e permitiria varrer quem + * está online. Esgotado o global, buscas e conversas novas são recusadas por + * um instante para todos — inclusive para quem acertaria o @. + */ +export const DM_GUARD_DEFAULTS = Object.freeze({ + lookup: Object.freeze({ capacity: 20, refillPerSecond: 1 / 3 }), + newConversation: Object.freeze({ capacity: 10, refillPerSecond: 1 / 30 }), + maxBlocked: 100, + global: Object.freeze({ + lookup: Object.freeze({ capacity: 100, refillPerSecond: 5 }), + newConversation: Object.freeze({ capacity: 60, refillPerSecond: 2 }), + }), +}); + /** * @param {{ * identities: ReturnType, * directory: ReturnType, + * directs: ReturnType, + * dmGuard?: Partial, * joinGuard: ReturnType, * deliver: (holder: unknown, data: string) => void, * log: (level: "info" | "warn" | "error", event: string, fields?: Record) => void, @@ -57,6 +90,8 @@ import { REMOVAL_REASONS, RENAME_COOLDOWN_MS } from "./room.js"; export const createHub = ({ identities, directory, + directs, + dmGuard = {}, joinGuard, deliver, log, @@ -72,6 +107,43 @@ export const createHub = ({ /** @param {unknown} member */ const entryOf = (member) => connections.get(member) ?? null; + const guard = { + ...DM_GUARD_DEFAULTS, + ...dmGuard, + global: { ...DM_GUARD_DEFAULTS.global, ...dmGuard.global }, + }; + /** Baldes por identidade; somem junto com ela. */ + const buckets = { + lookup: new WeakMap(), + newConversation: new WeakMap(), + }; + /** Baldes do servidor inteiro. */ + const shared = { + lookup: createRateLimiter({ ...guard.global.lookup, now }), + newConversation: createRateLimiter({ ...guard.global.newConversation, now }), + }; + /** + * Consome uma ficha do balde do servidor e uma do balde da identidade. + * O global vem primeiro: se ele está esgotado, a identidade não perde nada. + * @param {"lookup" | "newConversation"} kind + * @param {Identity} identity + */ + const consume = (kind, identity) => { + if (!shared[kind]()) { + log("warn", "dm_guard_global_limit", { kind }); + return false; + } + let take = buckets[kind].get(identity); + if (!take) { + take = createRateLimiter({ ...guard[kind], now }); + buckets[kind].set(identity, take); + } + return take(); + }; + + /** Alguém bloqueou alguém (em qualquer direção)? @param {Identity} x @param {Identity} y */ + const blockedBetween = (x, y) => x.blocked.has(y.id) || y.blocked.has(x.id); + /** * Identidade da conexão e a sala pedida, se ela participa. * @param {unknown} member @@ -86,6 +158,46 @@ export const createHub = ({ return { ok: true, identity: entry.identity, room }; }; + /** + * Identidade da conexão e a conversa pedida — sala OU privada —, se ela + * participa. As duas têm `post`, `publish` e `typing`. + * @param {unknown} member + * @param {unknown} rawConversationId + * @returns {{ok: true, identity: Identity, conversation: Room | DirectConversation} | Refusal} + */ + const resolveConversation = (member, rawConversationId) => { + const entry = connections.get(member); + if (!entry) return { ok: false, code: ERROR_CODES.NOT_LOGGED_IN }; + const id = readConversationId(rawConversationId); + const conversation = + directory.roomFor(entry.identity, id) ?? directs.forIdentity(entry.identity, id); + if (!conversation) return { ok: false, code: ERROR_CODES.CONVERSATION_NOT_FOUND }; + return { ok: true, identity: entry.identity, conversation }; + }; + + /** + * Pessoa indicada pelo `@` exato no payload, entre as identidades vivas + * (conectadas ou na janela de retomada). O id interno nunca vem do + * cliente nem volta para ele. A busca conta no limite, a menos que as + * duas já tenham uma conversa privada (aí não revela nada de novo). + * @param {Identity} identity quem procura + * @param {Record} payload `{ username }` + * @returns {{ok: true, target: Identity | null} | Refusal} + */ + const findTarget = (identity, payload) => { + const read = readUsername(payload.username); + if (!read.ok || !read.username) return { ok: false, code: ERROR_CODES.INVALID_USER }; + const target = identities.findByUsername(read.username); + const known = target !== null && directs.between(identity, target) !== null; + if (!known && !consume("lookup", identity)) { + return { ok: false, code: ERROR_CODES.LOOKUP_LIMITED }; + } + return { ok: true, target }; + }; + + /** Bloqueados da identidade, para `block_list`. @param {Identity} identity */ + const blockedOf = (identity) => [...identity.blocked.values()]; + /** * Fim da identidade (chamado pelo armazenamento): sai de todas as salas. * @param {Identity} identity @@ -95,6 +207,9 @@ export const createHub = ({ directory.leave(identity, room.id, REMOVAL_REASONS.ENDED); } identity.rooms.clear(); + // Conversas privadas acabam junto, com o histórico; a outra pessoa é avisada. + directs.dropIdentity(identity); + identity.blocked.clear(); identity.recent.clear(); log("info", "identity_ended", { user: identity.id }); }; @@ -105,6 +220,12 @@ export const createHub = ({ onCapabilitiesChange(identity); }; + /** Salas e conversas privadas da identidade. @param {Identity} identity */ + const conversationsOf = (identity) => ({ + rooms: directory.roomsOf(identity).map((room) => room.summaryFor(identity)), + dms: directs.of(identity).map((conversation) => conversation.summaryFor(identity)), + }); + return { forget, refreshEverywhere, @@ -157,6 +278,7 @@ export const createHub = ({ // para reconhecer as próprias mensagens nos históricos. sendTo(member, serverMessage.session(identity, resumeToken, resumed)); for (const room of directory.roomsOf(identity)) room.reconnect(identity); + for (const conversation of directs.of(identity)) conversation.reconnect(identity); return { ok: true, user: { id: identity.id, name: identity.name }, @@ -179,6 +301,8 @@ export const createHub = ({ if (identity.holder !== member) return true; // já substituída por outra conexão for (const room of directory.roomsOf(identity)) room.disconnect(identity); identities.release(identity, member); + // Depois de liberar: a outra pessoa de cada conversa vê "offline". + for (const conversation of directs.of(identity)) conversation.disconnect(identity); log("info", "session_paused", { connection: entry.label, user: identity.id }); return true; }, @@ -268,16 +392,152 @@ export const createHub = ({ return directory.roomsOf(entry.identity).map((room) => room.summaryFor(entry.identity)); }, + /** + * Salas e conversas privadas da conexão (`room_list`). + * @param {unknown} member + */ + conversationsOf(member) { + const entry = connections.get(member); + return entry ? conversationsOf(entry.identity) : null; + }, + resolve, + resolveConversation, /** + * Mensagem numa conversa — sala ou privada. * @param {unknown} member * @param {Record} payload `{ conversationId, content, clientMsgId? }` */ post(member, payload) { - const found = resolve(member, payload.conversationId); + const found = resolveConversation(member, payload.conversationId); if (!found.ok) return found; - return found.room.post(found.identity, payload); + return found.conversation.post(found.identity, payload); + }, + + /** + * Procura alguém conectado pelo @ EXATO. Nunca lista, completa ou + * sugere: sem o @ certo, nada aparece. Quem bloqueou você também não + * aparece (a resposta não diz por quê). + * @param {unknown} member + * @param {Record} payload `{ username }` + * @returns {{ok: true, user: Identity | null} | Refusal} + */ + lookup(member, payload) { + const entry = connections.get(member); + if (!entry) return { ok: false, code: ERROR_CODES.NOT_LOGGED_IN }; + const { identity } = entry; + const read = readUsername(payload.username); + if (!read.ok || !read.username) return { ok: false, code: ERROR_CODES.INVALID_USER }; + if (!consume("lookup", identity)) + return { ok: false, code: ERROR_CODES.LOOKUP_LIMITED }; + const found = identities.findConnected(read.username); + const visible = found && !found.blocked.has(identity.id) ? found : null; + return { ok: true, user: visible }; + }, + + /** + * Abre (ou retoma) a conversa privada com alguém, pelo `@` exato (o + * de uma busca, de uma lista de sala ou de um perfil). Conversa nova + * exige a outra pessoa conectada; uma existente é devolvida mesmo com + * ela na janela de retomada. + * @param {unknown} member + * @param {Record} payload `{ username }` + * @returns {{ok: true, conversation: DirectConversation, created: boolean} | Refusal} + */ + openDm(member, payload) { + const entry = connections.get(member); + if (!entry) return { ok: false, code: ERROR_CODES.NOT_LOGGED_IN }; + const { identity } = entry; + const found = findTarget(identity, payload); + if (!found.ok) return found; + const { target } = found; + // "Não existe", "não está aqui" e "bloqueou você" são a mesma resposta. + if (!target || blockedBetween(identity, target)) { + return { ok: false, code: ERROR_CODES.USER_UNAVAILABLE }; + } + if (target === identity) return { ok: false, code: ERROR_CODES.DM_SELF }; + const existing = directs.between(identity, target); + if (!existing) { + if (target.holder === null) + return { ok: false, code: ERROR_CODES.USER_UNAVAILABLE }; + if (!consume("newConversation", identity)) { + return { ok: false, code: ERROR_CODES.DM_OPEN_LIMITED }; + } + } + const result = existing + ? { ok: true, conversation: existing, created: false } + : directs.open(identity, target); + if (!result.ok) return result; + result.conversation.open(identity, { created: result.created }); + return result; + }, + + /** + * Encerra uma conversa privada para as duas pessoas, com o histórico. + * @param {unknown} member + * @param {Record} payload `{ conversationId }` + * @returns {{ok: true} | Refusal} + */ + closeDm(member, payload) { + const entry = connections.get(member); + if (!entry) return { ok: false, code: ERROR_CODES.NOT_LOGGED_IN }; + const conversation = directs.forIdentity( + entry.identity, + readConversationId(payload.conversationId), + ); + if (!conversation) return { ok: false, code: ERROR_CODES.CONVERSATION_NOT_FOUND }; + directs.close(conversation); + return { ok: true }; + }, + + /** + * Bloqueia alguém até o fim da sessão: a conversa privada entre as + * duas acaba, e nenhuma nova pode ser aberta em nenhuma direção. Quem + * foi bloqueado não é avisado do bloqueio (só vê a conversa encerrada). + * Vale só para conversas privadas: salas têm moderação própria. + * @param {unknown} member + * @param {Record} payload `{ username }` + * @returns {{ok: true, blocked: {name: string, username: string}[]} | Refusal} + */ + block(member, payload) { + const entry = connections.get(member); + if (!entry) return { ok: false, code: ERROR_CODES.NOT_LOGGED_IN }; + const { identity } = entry; + const found = findTarget(identity, payload); + if (!found.ok) return found; + const { target } = found; + if (target === identity) return { ok: false, code: ERROR_CODES.INVALID_USER }; + if (!target) return { ok: false, code: ERROR_CODES.USER_UNAVAILABLE }; + if (!identity.blocked.has(target.id)) { + if (identity.blocked.size >= guard.maxBlocked) { + return { ok: false, code: ERROR_CODES.BLOCK_LIMIT }; + } + // A chave é o id interno: se a pessoa sair e outra pegar o + // mesmo @, a nova não herda o bloqueio. + identity.blocked.set(target.id, { name: target.name, username: target.username }); + const conversation = directs.between(identity, target); + if (conversation) directs.close(conversation); + log("info", "user_blocked", { user: identity.id }); + } + return { ok: true, blocked: blockedOf(identity) }; + }, + + /** + * Desfaz o bloqueio de quem tinha esse `@` quando foi bloqueado. + * @param {unknown} member + * @param {Record} payload `{ username }` + * @returns {{ok: true, blocked: {name: string, username: string}[]} | Refusal} + */ + unblock(member, payload) { + const entry = connections.get(member); + if (!entry) return { ok: false, code: ERROR_CODES.NOT_LOGGED_IN }; + const read = readUsername(payload.username); + if (!read.ok || !read.username) return { ok: false, code: ERROR_CODES.INVALID_USER }; + for (const [id, person] of entry.identity.blocked) { + if (person.username === read.username) entry.identity.blocked.delete(id); + } + return { ok: true, blocked: blockedOf(entry.identity) }; }, /** @@ -287,8 +547,8 @@ export const createHub = ({ * @param {boolean} isTyping */ typing(member, payload, isTyping) { - const found = resolve(member, payload.conversationId); - if (found.ok) found.room.typing(found.identity, isTyping); + const found = resolveConversation(member, payload.conversationId); + if (found.ok) found.conversation.typing(found.identity, isTyping); }, /** @@ -314,6 +574,7 @@ export const createHub = ({ identity.lastRenameAt = now(); log("info", "user_renamed", { user: identity.id }); for (const room of directory.roomsOf(identity)) room.announceRename(identity, previous); + for (const conversation of directs.of(identity)) conversation.refreshPeerOf(identity); return { ok: true, changed: true, name: identity.name }; }, @@ -371,14 +632,19 @@ export const createHub = ({ return directory.size; }, + get dmCount() { + return directs.size; + }, + /** Desligamento: nenhuma sala anuncia saídas nem deixa timer pendente. */ silence() { for (const room of directory.all()) room.silence(); }, - /** Fim do processo: salas e históricos descartados. */ + /** Fim do processo: salas, conversas privadas e históricos descartados. */ closeAll() { directory.closeAll(); + directs.closeAll(); }, }; }; diff --git a/backend/src/room/room.js b/backend/src/room/room.js index 5e8e216..b764e1a 100644 --- a/backend/src/room/room.js +++ b/backend/src/room/room.js @@ -38,12 +38,12 @@ import { } from "../protocol.js"; import { readClientId, readContent } from "../validation.js"; import { isMuted } from "./policy.js"; +import { createTranscript } from "./transcript.js"; /** Intervalo mínimo entre duas trocas de nome da mesma pessoa. */ export const RENAME_COOLDOWN_MS = 10_000; -/** Mensagens recentes guardadas por identidade para ignorar reenvios. */ -export const RECENT_MESSAGES_PER_IDENTITY = 20; +export { RECENT_MESSAGES_PER_IDENTITY } from "./transcript.js"; /** * Por que uma participação termina. @@ -110,16 +110,14 @@ export const createRoom = ({ * @type {Map} */ const members = new Map(); - /** Mensagens de chat já no formato de envio, da mais antiga à mais nova. */ - const history = []; - /** Muda a cada limpeza da sala; o cliente a usa para descartar o que viu antes. */ - let historyVersion = 0; + /** O que foi dito (núcleo comum a salas e conversas privadas). */ + const transcript = createTranscript({ id, historySize, now, newMessageId }); /** Em desligamento: saídas não são anunciadas. */ let quiet = false; /** Ids removidos por moderação: não voltam enquanto a sala existir. */ const banned = new Set(); - /** @type {string | null} */ - let hostId = null; + /** Quem é anfitrião agora. @type {Identity | null} */ + let host = null; const timestamp = () => now().toISOString(); const nowMs = () => now().getTime(); @@ -150,7 +148,6 @@ export const createRoom = ({ broadcast( serverMessage.userList( present().map(([identity, membership]) => ({ - id: identity.id, name: identity.name, username: identity.username, away: identity.away, @@ -204,9 +201,9 @@ export const createRoom = ({ code, name, role: members.get(identity)?.role ?? ROLES.MEMBER, - hostId, + hostUsername: host?.username ?? null, memberCount: members.size, - historyVersion, + historyVersion: transcript.version, }); /** @@ -221,8 +218,9 @@ export const createRoom = ({ identity.holder, JSON.stringify(serverMessage.roomJoined(summaryFor(identity), how)), ); - if (history.length > 0 && historyOnJoin > 0) { - sendTo(identity, serverMessage.history(history.slice(-historyOnJoin))); + const recent = transcript.recent(historyOnJoin); + if (recent.length > 0) { + sendTo(identity, serverMessage.history(recent)); } }; @@ -248,12 +246,12 @@ export const createRoom = ({ const next = candidates.find(([, membership]) => membership.connected) ?? candidates[0] ?? null; if (!next) { - hostId = null; + host = null; return; } const [identity, membership] = next; membership.role = ROLES.HOST; - hostId = identity.id; + host = identity; log("info", "room_host_transferred", { conversation: id, user: identity.id }); notice(TONES.INFO, `${identity.name} agora é anfitrião da sala`); broadcastSummary(); @@ -276,35 +274,17 @@ export const createRoom = ({ if (!membership) return { ok: false, code: ERROR_CODES.CONVERSATION_NOT_FOUND }; if (isMuted(membership, nowMs())) return { ok: false, code: ERROR_CODES.MUTED }; - // Reenvio da mesma mensagem (retentativa do cliente): devolve a - // original só para quem enviou, sem duplicar na sala. A chave inclui - // a sala: o mesmo id de correlação em outra sala é outra mensagem. - const recentKey = clientMsgId ? `${id}:${clientMsgId}` : null; - if (recentKey) { - const original = identity.recent.get(recentKey); - if (original) { - sendTo(identity, /** @type {Record} */ (original)); - return { ok: true, duplicate: true }; - } - } - - const message = serverMessage.chat({ - id: newMessageId(), - user: identity, + // Reenvio da mesma mensagem (retentativa do cliente): a original volta + // só para quem enviou, sem duplicar na sala. + const { message, duplicate } = transcript.append(identity, { content, - timestamp: timestamp(), kind, format, clientMsgId, }); - history.push(message); - if (history.length > historySize) history.shift(); - identity.messageCount += 1; - if (recentKey) { - identity.recent.set(recentKey, message); - if (identity.recent.size > RECENT_MESSAGES_PER_IDENTITY) { - identity.recent.delete(identity.recent.keys().next().value); - } + if (duplicate) { + sendTo(identity, message); + return { ok: true, duplicate: true }; } broadcast(message); @@ -360,24 +340,28 @@ export const createRoom = ({ * @param {{host?: boolean, created?: boolean}} [options] * @returns {{ok: true, already: boolean} | {ok: false, code: string}} */ - add(identity, { host = false, created = false } = {}) { + add(identity, { host: asHost = false, created = false } = {}) { if (banned.has(identity.id)) return { ok: false, code: ERROR_CODES.REMOVED_FROM_ROOM }; if (members.has(identity)) { sendState(identity, { resumed: true }); return { ok: true, already: true }; } members.set(identity, { - role: host ? ROLES.HOST : ROLES.MEMBER, + role: asHost ? ROLES.HOST : ROLES.MEMBER, mutedUntil: null, joinedAt: nowMs(), connected: identity.holder !== null, pendingLeave: null, }); identity.rooms.add(id); - if (host) hostId = identity.id; - log("info", "room_member_joined", { conversation: id, user: identity.id, host }); + if (asHost) host = identity; + log("info", "room_member_joined", { + conversation: id, + user: identity.id, + host: asHost, + }); sendState(identity, { created }); - broadcast(serverMessage.joined(identity.name, timestamp()), identity); + broadcast(serverMessage.joined(identity, timestamp()), identity); broadcastUserList(); return { ok: true, already: false }; }, @@ -419,8 +403,7 @@ export const createRoom = ({ membership.connected = true; const silentReturn = wasConnected || cancelPendingLeave(membership); sendState(identity, { resumed: true }); - if (!silentReturn) - broadcast(serverMessage.joined(identity.name, timestamp()), identity); + if (!silentReturn) broadcast(serverMessage.joined(identity, timestamp()), identity); broadcastUserList(); }, @@ -484,23 +467,15 @@ export const createRoom = ({ * @param {Identity} actor */ clearHistory(actor) { - const removed = history.length; - history.length = 0; - historyVersion += 1; - const prefix = `${id}:`; - for (const identity of members.keys()) { - for (const key of identity.recent.keys()) { - if (key.startsWith(prefix)) identity.recent.delete(key); - } - } + const removed = transcript.clear(members.keys()); log("warn", "moderation_action", { action: "clear_history", conversation: id, actor: actor.id, removed, - historyVersion, + historyVersion: transcript.version, }); - broadcast(serverMessage.chatCleared(actor.name, timestamp(), historyVersion)); + broadcast(serverMessage.chatCleared(actor.name, timestamp(), transcript.version)); return true; }, @@ -571,20 +546,24 @@ export const createRoom = ({ /** * Localiza pessoas conectadas na sala por `@username` (exato e - * único), por id (ou prefixo de id com 6+ caracteres) ou por nome - * (sem diferenciar maiúsculas; pode haver mais de uma pessoa). + * único) ou por nome (sem diferenciar maiúsculas; pode haver mais + * de uma pessoa). Com `allowIds` (administradores), também por id + * interno ou prefixo dele com 6+ caracteres. * @param {string} query + * @param {{allowIds?: boolean}} [options] */ - findMembers(query) { + findMembers(query, { allowIds = false } = {}) { const wanted = query.trim().toLowerCase(); if (!wanted) return []; const all = present().map(([identity, membership]) => ({ identity, membership })); if (wanted.startsWith("@")) { return all.filter(({ identity }) => identity.username === wanted.slice(1)); } - const byId = /^[0-9a-f-]{6,36}$/.test(wanted) - ? all.filter(({ identity }) => identity.id.startsWith(wanted)) - : []; + // Por id interno: só para administradores (quem chama decide). + const byId = + allowIds && /^[0-9a-f-]{6,36}$/.test(wanted) + ? all.filter(({ identity }) => identity.id.startsWith(wanted)) + : []; if (byId.length > 0) return byId; const byName = all.filter(({ identity }) => identity.name.toLowerCase() === wanted); if (byName.length > 0) return byName; @@ -602,15 +581,16 @@ export const createRoom = ({ }, get historyVersion() { - return historyVersion; + return transcript.version; }, get historyLength() { - return history.length; + return transcript.length; }, + /** Id interno do anfitrião: só para o servidor (testes, diagnóstico). */ get hostId() { - return hostId; + return host?.id ?? null; }, /** @@ -632,11 +612,11 @@ export const createRoom = ({ */ destroy() { this.silence(); + transcript.discard(members.keys()); for (const identity of members.keys()) identity.rooms.delete(id); members.clear(); - history.length = 0; banned.clear(); - hostId = null; + host = null; log("info", "room_destroyed", { conversation: id }); }, }; diff --git a/backend/src/room/sessions.js b/backend/src/room/sessions.js index fc282ea..1c636b7 100644 --- a/backend/src/room/sessions.js +++ b/backend/src/room/sessions.js @@ -43,6 +43,9 @@ export const MAX_RELEASED_IDENTITIES = 2000; * @property {"member" | "admin"} role papel global: `admin` vale em todas as salas * @property {string | null} away texto de ausência, ou null se presente * @property {Set} rooms conversas (salas) de que participa + * @property {Set} dms conversas privadas de que participa + * @property {Map} blocked + * quem esta identidade bloqueou nesta sessão (chave: id interno, que não sai daqui) * @property {number} joinedAt * @property {number} messageCount * @property {number} lastRenameAt @@ -123,6 +126,8 @@ export const createIdentityStore = ({ role: "member", away: null, rooms: new Set(), + dms: new Set(), + blocked: new Map(), joinedAt: now(), messageCount: 0, lastRenameAt: -Infinity, @@ -133,6 +138,33 @@ export const createIdentityStore = ({ return identity; }, + /** + * Identidade viva com o username exato (conectada ou na janela de + * retomada), ou null. Expirada é encerrada aqui mesmo. + * @param {string} username já normalizado (sem @, minúsculo) + * @returns {Identity | null} + */ + findByUsername(username) { + const identity = usernames.get(username); + if (!identity) return null; + if (expired(identity, now())) { + retire(identity); + return null; + } + return identity; + }, + + /** + * Identidade CONECTADA agora com o username exato, ou null. Quem está + * só na janela de retomada não aparece: só se acha quem está aqui. + * @param {string} username já normalizado (sem @, minúsculo) + * @returns {Identity | null} + */ + findConnected(username) { + const identity = usernames.get(username); + return identity && identity.holder !== null ? identity : null; + }, + /** * O username está com alguma identidade viva? Uma identidade * desconectada além do prazo de retomada é encerrada aqui mesmo, sem diff --git a/backend/src/room/transcript.js b/backend/src/room/transcript.js new file mode 100644 index 0000000..eb2e928 --- /dev/null +++ b/backend/src/room/transcript.js @@ -0,0 +1,120 @@ +/** + * O que foi dito numa conversa — sala ou conversa privada. + * + * Núcleo comum aos dois tipos de conversa: histórico limitado, versão do + * histórico (muda a cada limpeza) e anti-duplicação por `clientMsgId`. Quem + * decide QUEM pode publicar é a conversa (`room.js`, `direct.js`); aqui só + * se registra o que foi publicado. Tudo em memória. + */ + +import crypto from "node:crypto"; +import { MESSAGE_KINDS, serverMessage } from "../protocol.js"; + +/** Mensagens recentes guardadas por identidade para ignorar reenvios. */ +export const RECENT_MESSAGES_PER_IDENTITY = 20; + +/** + * @typedef {import("./sessions.js").Identity} Identity + * @typedef {ReturnType} ChatMessage + */ + +/** + * @param {{ + * id: string, + * historySize: number, + * now?: () => Date, + * newMessageId?: () => string, + * }} options + */ +export const createTranscript = ({ + id, + historySize, + now = () => new Date(), + newMessageId = () => crypto.randomUUID(), +}) => { + /** Mensagens no formato de envio, da mais antiga à mais nova. @type {ChatMessage[]} */ + const history = []; + let version = 0; + /** A chave inclui a conversa: o mesmo id de correlação em outra conversa é outra mensagem. */ + const prefix = `${id}:`; + + return { + /** + * Registra uma mensagem. Reenvio com o mesmo `clientMsgId` devolve a + * original em `duplicate`, sem registrar de novo. + * @param {Identity} identity + * @param {{content: string, kind?: string, format?: string | null, clientMsgId?: string | null}} message + * @returns {{message: ChatMessage, duplicate: boolean}} + */ + append( + identity, + { content, kind = MESSAGE_KINDS.TEXT, format = null, clientMsgId = null }, + ) { + const recentKey = clientMsgId ? prefix + clientMsgId : null; + if (recentKey) { + const original = /** @type {ChatMessage | undefined} */ ( + identity.recent.get(recentKey) + ); + if (original) return { message: original, duplicate: true }; + } + const message = serverMessage.chat({ + id: newMessageId(), + user: identity, + content, + timestamp: now().toISOString(), + kind, + format, + clientMsgId, + }); + history.push(message); + if (history.length > historySize) history.shift(); + identity.messageCount += 1; + if (recentKey) { + identity.recent.set(recentKey, message); + if (identity.recent.size > RECENT_MESSAGES_PER_IDENTITY) { + identity.recent.delete(identity.recent.keys().next().value); + } + } + return { message, duplicate: false }; + }, + + /** As `count` mais recentes. @param {number} count */ + recent: (count) => (count > 0 ? history.slice(-count) : []), + + /** + * Apaga o histórico e muda a versão. A anti-duplicação desta conversa + * também é esquecida por quem participa. + * @param {Iterable} participants + * @returns {number} quantas mensagens foram apagadas + */ + clear(participants) { + const removed = history.length; + history.length = 0; + version += 1; + for (const identity of participants) { + for (const key of identity.recent.keys()) { + if (key.startsWith(prefix)) identity.recent.delete(key); + } + } + return removed; + }, + + /** Fim da conversa: nada fica. @param {Iterable} participants */ + discard(participants) { + history.length = 0; + for (const identity of participants) { + for (const key of identity.recent.keys()) { + if (key.startsWith(prefix)) identity.recent.delete(key); + } + } + }, + + get version() { + return version; + }, + + get length() { + return history.length; + }, + }; +}; diff --git a/backend/src/server.js b/backend/src/server.js index de7a3e7..fd88300 100644 --- a/backend/src/server.js +++ b/backend/src/server.js @@ -38,11 +38,11 @@ try { process.exit(1); } -// Sem allowlist o servidor aceita qualquer origem — comportamento histórico, -// preservado porque o domínio de produção não está definido (V03). Fica -// registrado em toda inicialização; em produção, como aviso. +// Sem allowlist (só possível fora de produção: lá a configuração recusa) o +// servidor aceita qualquer origem, para o desenvolvimento local. Fica +// registrado em toda inicialização. if (config.allowedOrigins.length === 0) { - log(config.production ? "warn" : "info", "allowed_origins_disabled", { + log("info", "allowed_origins_disabled", { message: "ALLOWED_ORIGINS vazia: conexões de qualquer origem serão aceitas.", }); } diff --git a/backend/src/transport/chatServer.js b/backend/src/transport/chatServer.js index dd7f889..a5b1d6c 100644 --- a/backend/src/transport/chatServer.js +++ b/backend/src/transport/chatServer.js @@ -14,6 +14,7 @@ import { createDefaultRegistry } from "../commands/index.js"; import { createAdminAuth } from "../commands/adminAuth.js"; import { createCommandExecutor } from "../commands/executor.js"; import { createMetrics } from "../metrics.js"; +import { createDirectConversation, createDirectDirectory } from "../room/direct.js"; import { createRoomDirectory } from "../room/directory.js"; import { createHub } from "../room/hub.js"; import { createJoinGuard } from "../room/joinGuard.js"; @@ -39,9 +40,16 @@ export const USER_LIST_COALESCE_MS = 50; * log: (level: "info" | "warn" | "error", event: string, fields?: Record) => void, * version?: string, * joinGuard?: Parameters[0], + * dmGuard?: Parameters[0]["dmGuard"], * }} options */ -export const createChatServer = ({ config, log, version = "desconhecida", joinGuard = {} }) => { +export const createChatServer = ({ + config, + log, + version = "desconhecida", + joinGuard = {}, + dmGuard = {}, +}) => { const metrics = createMetrics(); /** Agendador com timers reais; cancelável e sem nada pendurado no desligamento. */ @@ -80,9 +88,27 @@ export const createChatServer = ({ config, log, version = "desconhecida", joinGu }), }); + const directs = createDirectDirectory({ + log, + limits: config.dms, + makeConversation: ({ id, a, b }) => + createDirectConversation({ + id, + a, + b, + log, + historySize: config.dms.historySize, + historyOnJoin: config.historyOnJoin, + deliver: (holder, data) => deliver(holder, data), + onPresenceChange: (identity) => hub?.refreshEverywhere(identity), + }), + }); + hub = createHub({ identities, directory, + directs, + dmGuard, joinGuard: createJoinGuard(joinGuard), log, deliver: (member, data) => deliver(member, data), @@ -139,6 +165,7 @@ export const createChatServer = ({ config, log, version = "desconhecida", joinGu users: sessions.sessionCount, identities: identities.size, rooms: sessions.roomCount, + dms: sessions.dmCount, }); const httpServer = http.createServer( diff --git a/backend/src/transport/connection.js b/backend/src/transport/connection.js index 08ff269..44f85b5 100644 --- a/backend/src/transport/connection.js +++ b/backend/src/transport/connection.js @@ -39,6 +39,8 @@ const NOTIFY_WHEN_LIMITED = new Set([ CLIENT_EVENTS.COMMAND, CLIENT_EVENTS.ROOM_CREATE, CLIENT_EVENTS.ROOM_JOIN, + CLIENT_EVENTS.USER_LOOKUP, + CLIENT_EVENTS.DM_OPEN, ]); /** Métricas no-op: o handler funciona sem instrumentação (testes de unidade). */ @@ -195,15 +197,63 @@ export const createConnectionHandler = ({ metrics.count("roomLeaves"); }, [CLIENT_EVENTS.ROOM_LIST]: (payload) => { - const rooms = hub.roomsOf(ws); - if (rooms === null) { + const conversations = hub.conversationsOf(ws); + if (conversations === null) { return reject( CLIENT_EVENTS.ROOM_LIST, ERROR_CODES.NOT_LOGGED_IN, requestIdOf(payload), ); } - send(serverMessage.roomList(rooms, requestIdOf(payload))); + send( + serverMessage.roomList( + conversations.rooms, + conversations.dms, + requestIdOf(payload), + ), + ); + }, + [CLIENT_EVENTS.USER_LOOKUP]: (payload) => { + const result = hub.lookup(ws, payload); + if (!result.ok) { + return reject(CLIENT_EVENTS.USER_LOOKUP, result.code, requestIdOf(payload)); + } + metrics.count("userLookups"); + send(serverMessage.userLookup(result.user, requestIdOf(payload))); + }, + [CLIENT_EVENTS.DM_OPEN]: (payload) => { + const result = hub.openDm(ws, payload); + if (!result.ok) { + return reject(CLIENT_EVENTS.DM_OPEN, result.code, requestIdOf(payload)); + } + if (result.created) metrics.count("dmsOpened"); + }, + [CLIENT_EVENTS.DM_CLOSE]: (payload) => { + const result = hub.closeDm(ws, payload); + if (!result.ok) { + return reject( + CLIENT_EVENTS.DM_CLOSE, + result.code, + requestIdOf(payload), + readConversationId(payload.conversationId), + ); + } + metrics.count("dmsClosed"); + }, + [CLIENT_EVENTS.USER_BLOCK]: (payload) => { + const result = hub.block(ws, payload); + if (!result.ok) { + return reject(CLIENT_EVENTS.USER_BLOCK, result.code, requestIdOf(payload)); + } + metrics.count("blocks"); + send(serverMessage.blockList(result.blocked, requestIdOf(payload))); + }, + [CLIENT_EVENTS.USER_UNBLOCK]: (payload) => { + const result = hub.unblock(ws, payload); + if (!result.ok) { + return reject(CLIENT_EVENTS.USER_UNBLOCK, result.code, requestIdOf(payload)); + } + send(serverMessage.blockList(result.blocked, requestIdOf(payload))); }, }; diff --git a/backend/test/integration/commands.test.js b/backend/test/integration/commands.test.js index 3fec650..ae9c55a 100644 --- a/backend/test/integration/commands.test.js +++ b/backend/test/integration/commands.test.js @@ -133,17 +133,17 @@ describe("comandos", () => { userName: "Falso", role: "admin", isAdmin: true, - userId: admin.session.id, + userId: admin.session.username, }); assert.equal(forged.session.role, "member"); - assert.notEqual(forged.session.id, admin.session.id); + assert.notEqual(forged.session.username, admin.session.username); // Comando com papel e id no payload: ignorados. forged.client.send("command", { requestId: "forjado", text: "/kick AdmReal", role: "admin", isAdmin: true, - userId: admin.session.id, + userId: admin.session.username, }); const result = await forged.client.take((m) => m.type === "command_result"); assert.equal(result.payload.code, "forbidden"); @@ -213,9 +213,9 @@ describe("comandos", () => { const list = await b.client.take( (m) => m.type === "user_list" && - m.payload.some((p) => p.id === a.session.id && p.status === "away"), + m.payload.some((p) => p.username === a.session.username && p.status === "away"), ); - const me = list.payload.find((p) => p.id === a.session.id); + const me = list.payload.find((p) => p.username === a.session.username); assert.equal(me.name, "Depois Silva"); assert.equal(me.statusText, "almoçando"); a.client.close(); @@ -230,8 +230,9 @@ describe("comandos", () => { ); const profile = await run(a.client, "/profile Silencioso"); assert.equal(profile.lines[0], `Username: @${b.session.username}`); - assert.ok(profile.lines.some((line) => line.includes(b.session.id))); - assert.ok((await run(a.client, "/id")).text.includes(a.session.id)); + // Quem não é administrador não vê id interno em lugar nenhum. + assert.ok(!profile.lines.some((line) => line.startsWith("Id"))); + assert.equal((await run(a.client, "/id")).code, "forbidden"); assert.equal((await run(a.client, "/ping")).text, "pong"); assert.ok((await run(a.client, "/rules")).lines.length >= 3); assert.match((await run(a.client, "/version")).text, /1\.0\.0/); @@ -298,7 +299,7 @@ describe("moderação", () => { for (const c of [admin, witness, target]) c.client.close(); }); - test("hierarquia: não modera a si mesmo nem outro administrador; alvo ambíguo pede id", async () => { + test("hierarquia: não modera a si mesmo nem outro administrador; alvo ambíguo pede o @", async () => { const a = await join(server.url, { userName: "Adm1" }); const b = await join(server.url, { userName: "Adm2" }); const x1 = await join(server.url, { userName: "Repetido" }); @@ -309,8 +310,15 @@ describe("moderação", () => { assert.equal((await run(a.client, "/kick Adm2")).code, "cannot_moderate"); assert.equal((await run(a.client, "/mute Repetido")).code, "ambiguous_target"); assert.equal((await run(a.client, "/mute Ninguem")).code, "not_found"); - const viaId = await run(a.client, `/mute ${x2.session.id.slice(0, 8)} 1`); - assert.equal(viaId.code, undefined); + const viaHandle = await run(a.client, `/mute @${x2.session.username} 1`); + assert.equal(viaHandle.code, undefined); + // Administrador vê o id interno em /users e pode usá-lo como alvo. + const users = await run(a.client, "/users"); + const line = users.lines.find((l) => l.includes(`@${x1.session.username}`)); + const shortId = / id ([0-9a-f]{8})/.exec(line)?.[1]; + assert.ok(shortId, line); + assert.equal((await run(a.client, `/mute ${shortId} 1`)).code, undefined); + assert.ok((await run(a.client, "/id")).text.includes("-")); for (const c of [a, b, x1, x2]) c.client.close(); }); }); @@ -363,7 +371,7 @@ describe("entrega e reconexão", () => { userName: "Instável", resumeToken: flaky.session.resumeToken, }); - assert.equal(back.session.id, flaky.session.id); + assert.equal(back.session.username, flaky.session.username); await new Promise((resolve) => setTimeout(resolve, 1800)); await barrier(back.client, watcher.client); assert.equal(watcher.client.count("user_left"), 0); diff --git a/backend/test/integration/config.test.js b/backend/test/integration/config.test.js index ce67437..4ad130c 100644 --- a/backend/test/integration/config.test.js +++ b/backend/test/integration/config.test.js @@ -147,14 +147,43 @@ describe("validação da configuração", () => { }); } - test("sem ALLOWED_ORIGINS o servidor sobe e avisa que aceita qualquer origem", async () => { - const server = await startServer({ ALLOWED_ORIGINS: "", NODE_ENV: "production" }); - const warning = await server.waitForLog( + test("em produção, sem ALLOWED_ORIGINS o servidor não sobe", async () => { + const server = await startServer( + { ALLOWED_ORIGINS: "", NODE_ENV: "production" }, + { waitListening: false }, + ); + assert.equal(await server.exited, 1); + const entry = server.entries().find((item) => item.event === "config_invalid"); + assert.equal(entry?.variable, "ALLOWED_ORIGINS"); + assert.equal( + server.entries().some((item) => item.event === "server_listening"), + false, + "nunca chegou a escutar", + ); + }); + + test("em produção, com a lista: só a origem listada entra; sem Origin, não", async () => { + const server = await startServer({ + ALLOWED_ORIGINS: "https://chat.example", + NODE_ENV: "production", + }); + const client = await connect(server.url, { origin: "https://chat.example" }); + client.close(); + for (const origin of ["https://qualquer.example", "http://chat.example", undefined]) { + await assert.rejects( + connect(server.url, origin === undefined ? {} : { origin }), + String(origin), + ); + } + await server.stop(); + }); + + test("fora de produção, sem ALLOWED_ORIGINS sobe e registra que aceita qualquer origem", async () => { + const server = await startServer({ ALLOWED_ORIGINS: "", NODE_ENV: "development" }); + const notice = await server.waitForLog( (entry) => entry.event === "allowed_origins_disabled", ); - assert.equal(warning.level, "warn"); - const listening = await server.waitForLog((entry) => entry.event === "server_listening"); - assert.deepEqual(listening.allowedOrigins, []); + assert.equal(notice.level, "info"); const client = await connect(server.url, { origin: "https://qualquer.example" }); client.close(); await server.stop(); diff --git a/backend/test/integration/connections.test.js b/backend/test/integration/connections.test.js index ec7cc8e..0068ed8 100644 --- a/backend/test/integration/connections.test.js +++ b/backend/test/integration/connections.test.js @@ -27,7 +27,9 @@ describe("ciclo de vida da conexão", () => { assert.equal(joined.payload.userName, "Segunda"); const list = await first.client.take( - (m) => m.type === "user_list" && m.payload.some((p) => p.id === session.payload.id), + (m) => + m.type === "user_list" && + m.payload.some((p) => p.username === session.payload.username), ); assert.deepEqual(list.payload.map((p) => p.name).sort(), ["Primeira", "Segunda"]); // Quem entra não recebe o próprio "entrou na sala". @@ -77,9 +79,11 @@ describe("ciclo de vida da conexão", () => { ); assert.equal(left.payload.userName, "Sai"); const list = await stay.client.take( - (m) => m.type === "user_list" && !m.payload.some((p) => p.id === leave.session.id), + (m) => + m.type === "user_list" && + !m.payload.some((p) => p.username === leave.session.username), ); - assert.ok(list.payload.some((p) => p.id === stay.session.id)); + assert.ok(list.payload.some((p) => p.username === stay.session.username)); stay.client.close(); }); @@ -93,7 +97,7 @@ describe("ciclo de vida da conexão", () => { userName: "Volta", resumeToken: original.session.resumeToken, }); - assert.equal(back.session.id, original.session.id); + assert.equal(back.session.username, original.session.username); assert.equal(back.session.name, "Volta"); assert.notEqual( back.session.resumeToken, @@ -102,16 +106,21 @@ describe("ciclo de vida da conexão", () => { ); const list = await observer.client.take( - (m) => m.type === "user_list" && m.payload.some((p) => p.id === original.session.id), + (m) => + m.type === "user_list" && + m.payload.some((p) => p.username === original.session.username), + ); + assert.equal( + list.payload.filter((p) => p.username === original.session.username).length, + 1, ); - assert.equal(list.payload.filter((p) => p.id === original.session.id).length, 1); // O token antigo deixou de valer depois da rotação. const replay = await join(server.url, { userName: "Replay", resumeToken: original.session.resumeToken, }); - assert.notEqual(replay.session.id, original.session.id); + assert.notEqual(replay.session.username, original.session.username); observer.client.close(); back.client.close(); @@ -129,15 +138,15 @@ describe("ciclo de vida da conexão", () => { userName: "Zumbi", resumeToken: stale.session.resumeToken, }); - assert.equal(fresh.session.id, stale.session.id); + assert.equal(fresh.session.username, stale.session.username); await stale.client.waitClose(); const list = await observer.client.take( (m) => m.type === "user_list" && - m.payload.filter((p) => p.id === stale.session.id).length === 1, + m.payload.filter((p) => p.username === stale.session.username).length === 1, ); - assert.ok(list.payload.some((p) => p.id === observer.session.id)); + assert.ok(list.payload.some((p) => p.username === observer.session.username)); // Para os outros a pessoa nunca saiu: nem "saiu" nem um novo "entrou". await barrier(fresh.client, observer.client); const zumbi = (m) => m.payload?.userName === "Zumbi"; @@ -185,7 +194,9 @@ describe("heartbeat", () => { const left = await observer.client.take("user_left", 3000); assert.equal(left.payload.userName, "Fantasma"); const list = await observer.client.take( - (m) => m.type === "user_list" && !m.payload.some((p) => p.id === ghost.session.id), + (m) => + m.type === "user_list" && + !m.payload.some((p) => p.username === ghost.session.username), ); assert.equal(list.payload.length, 1); // Quem responde ao ping continua conectado. diff --git a/backend/test/integration/direct.test.js b/backend/test/integration/direct.test.js new file mode 100644 index 0000000..c3c8a73 --- /dev/null +++ b/backend/test/integration/direct.test.js @@ -0,0 +1,324 @@ +// Conversas privadas com o servidor real (processo filho e clientes `ws`): +// busca por @, abrir, isolamento, bloqueio, encerramento, retomada, limites +// e reinício do servidor. + +import { test, describe, before, after } from "node:test"; +import assert from "node:assert/strict"; +import { connect, join, startServer } from "./helpers.js"; + +let seq = 0; +/** Conecta e começa a sessão com um @ único, sem entrar em sala. */ +const person = async (url, userName) => { + seq += 1; + const username = `${userName.toLowerCase()}_${seq}`; + const { client, session } = await join(url, { userName, username }, undefined, { room: false }); + return { client, me: session, username }; +}; + +/** Abre a conversa privada e devolve `dm_opened` ou o erro. */ +const openDm = async (client, payload) => { + client.send("dm_open", payload); + return client.take((m) => m.type === "dm_opened" || m.type === "error"); +}; + +/** Barreira: `/ping` volta depois de tudo o que o servidor já tinha a entregar. */ +const settle = async (client) => { + const requestId = `sync-${++seq}`; + client.send("command", { requestId, text: "/ping", conversationId: undefined }); + await client.take((m) => m.type === "command_result" && m.payload.requestId === requestId); +}; + +describe("conversas privadas", () => { + let server; + before(async () => { + server = await startServer(); + }); + after(() => server.stop()); + + test("busca pelo @ exato; prefixo, inexistente e desconectado não aparecem", async () => { + const ana = await person(server.url, "Ana"); + const bia = await person(server.url, "Bia"); + ana.client.send("user_lookup", { + username: `@${bia.username.toUpperCase()}`, + requestId: "b1", + }); + const found = (await ana.client.take("user_lookup")).payload; + assert.deepEqual(found, { + found: true, + user: { name: "Bia", username: bia.username }, + requestId: "b1", + }); + for (const username of [bia.username.slice(0, 4), "ninguem_aqui"]) { + ana.client.send("user_lookup", { username }); + assert.deepEqual((await ana.client.take("user_lookup")).payload, { found: false }); + } + ana.client.send("user_lookup", { username: "a b" }); + assert.equal((await ana.client.take("error")).payload.code, "invalid_user"); + // Espera o servidor perceber a queda de Bia (mais uma sessão pausada no log). + const paused = () => server.entries().filter((e) => e.event === "session_paused").length; + const before = paused(); + bia.client.ws.terminate(); + await server.waitForLog(() => paused() > before); + ana.client.send("user_lookup", { username: bia.username }); + assert.equal((await ana.client.take("user_lookup")).payload.found, false); + ana.client.close(); + }); + + test("abrir, conversar nos dois sentidos, e ninguém mais recebe nada", async () => { + const ana = await person(server.url, "Ana"); + const bia = await person(server.url, "Bia"); + const caio = await person(server.url, "Caio"); + const opened = await openDm(ana.client, { username: bia.username }); + assert.equal(opened.type, "dm_opened"); + const id = opened.conversationId; + assert.match(id, /^d_/); + assert.deepEqual(opened.payload.peer, { + name: "Bia", + username: bia.username, + online: true, + }); + await settle(bia.client); + assert.equal(bia.client.count("dm_opened"), 0, "abrir não avisa a outra pessoa"); + + ana.client.send("chat_message", { + conversationId: id, + content: "oi Bia", + clientMsgId: "p1", + }); + const theirs = await bia.client.take("dm_opened"); + assert.equal(theirs.conversationId, id); + assert.equal(theirs.payload.peer.username, ana.username); + const history = await bia.client.take("message_history"); + assert.equal(history.conversationId, id); + assert.equal(history.payload[0].payload.content, "oi Bia"); + + bia.client.send("chat_message", { conversationId: id, content: "oi Ana" }); + const reply = await ana.client.take( + (m) => m.type === "chat_message" && m.payload.content === "oi Ana", + ); + assert.equal(reply.conversationId, id); + assert.equal(reply.payload.username, bia.username); + assert.equal("userId" in reply.payload, false); + bia.client.send("typing_start", { conversationId: id }); + assert.equal((await ana.client.take("user_typing")).conversationId, id); + + // Caio sabe o id e mesmo assim não lê, não escreve e não encerra. + caio.client.send("chat_message", { + conversationId: id, + content: "entrei?", + clientMsgId: "x1", + }); + const refused = await caio.client.take("error"); + assert.equal(refused.payload.code, "conversation_not_found"); + assert.equal(refused.payload.ref, "x1"); + caio.client.send("dm_close", { conversationId: id }); + assert.equal((await caio.client.take("error")).payload.code, "conversation_not_found"); + caio.client.send("typing_start", { conversationId: id }); + await settle(caio.client); + await settle(ana.client); + assert.deepEqual( + caio.client.inbox.filter((m) => m.conversationId === id && m.type !== "error"), + [], + ); + assert.equal( + ana.client.count((m) => m.payload?.content === "entrei?"), + 0, + ); + + ana.client.send("room_list", {}); + const list = (await ana.client.take("room_list")).payload; + assert.deepEqual( + list.dms.map((d) => [d.conversationId, d.peer.username]), + [[id, bia.username]], + ); + for (const p of [ana, bia, caio]) p.client.close(); + }); + + test("encerrar apaga para as duas; abrir de novo começa vazio", async () => { + const ana = await person(server.url, "Ana"); + const bia = await person(server.url, "Bia"); + const { conversationId } = await openDm(ana.client, { username: bia.username }); + ana.client.send("chat_message", { conversationId, content: "vai sumir" }); + await bia.client.take("message_history"); + bia.client.send("dm_close", { conversationId }); + for (const p of [ana, bia]) { + const closed = await p.client.take("dm_closed"); + assert.equal(closed.conversationId, conversationId); + assert.equal(closed.payload.reason, "closed"); + } + ana.client.send("chat_message", { conversationId, content: "ainda?" }); + assert.equal((await ana.client.take("error")).payload.code, "conversation_not_found"); + const again = await openDm(ana.client, { username: bia.username }); + assert.notEqual(again.conversationId, conversationId); + await settle(ana.client); + assert.equal( + ana.client.count( + (m) => m.type === "message_history" && m.conversationId === again.conversationId, + ), + 0, + ); + ana.client.close(); + bia.client.close(); + }); + + test("bloqueio: encerra a conversa e impede mensagens, busca e conversa nova", async () => { + const ana = await person(server.url, "Ana"); + const bia = await person(server.url, "Bia"); + const { conversationId } = await openDm(ana.client, { username: bia.username }); + ana.client.send("chat_message", { conversationId, content: "insistente" }); + await bia.client.take("message_history"); + + bia.client.send("user_block", { username: ana.username, requestId: "bl" }); + const blocked = (await bia.client.take("block_list")).payload; + assert.deepEqual(blocked, { + blocked: [{ name: "Ana", username: ana.username }], + requestId: "bl", + }); + assert.equal((await ana.client.take("dm_closed")).payload.reason, "closed"); + + ana.client.send("chat_message", { conversationId, content: "de novo" }); + assert.equal((await ana.client.take("error")).payload.code, "conversation_not_found"); + assert.equal( + (await openDm(ana.client, { username: bia.username })).payload.code, + "user_unavailable", + ); + ana.client.send("user_lookup", { username: bia.username }); + assert.equal((await ana.client.take("user_lookup")).payload.found, false); + await settle(bia.client); + assert.equal( + bia.client.count((m) => m.payload?.content === "de novo"), + 0, + ); + + bia.client.send("user_unblock", { username: ana.username }); + assert.deepEqual((await bia.client.take("block_list")).payload, { blocked: [] }); + assert.equal((await openDm(ana.client, { username: bia.username })).type, "dm_opened"); + ana.client.close(); + bia.client.close(); + }); + + test("queda e retomada preservam a conversa; sair de vez a destrói", async () => { + const ana = await person(server.url, "Ana"); + const bia = await person(server.url, "Bia"); + const { conversationId } = await openDm(ana.client, { username: bia.username }); + ana.client.send("chat_message", { conversationId, content: "primeira" }); + await bia.client.take("message_history"); + + bia.client.ws.terminate(); + const offline = await ana.client.take("dm_updated"); + assert.equal(offline.payload.peer.online, false); + ana.client.send("chat_message", { conversationId, content: "enquanto você caiu" }); + + const back = await connect(server.url); + back.send("user_login", { userName: "Bia", resumeToken: bia.me.resumeToken }); + const session = (await back.take("session")).payload; + assert.equal(session.resumed, true); + const resumed = await back.take("dm_opened"); + assert.equal(resumed.conversationId, conversationId); + assert.equal(resumed.payload.resumed, true); + assert.deepEqual( + (await back.take("message_history")).payload.map((m) => m.payload.content), + ["primeira", "enquanto você caiu"], + ); + assert.equal((await ana.client.take("dm_updated")).payload.peer.online, true); + + // Sair de vez: a conversa acaba para quem ficou. + back.send("user_logout", {}); + const ended = await ana.client.take("dm_closed"); + assert.equal(ended.payload.reason, "ended"); + + // Outra pessoa com o mesmo @ não recupera nada. + const impostor = await connect(server.url); + impostor.send("user_login", { userName: "Outra", username: bia.username }); + const fresh = (await impostor.take("session")).payload; + assert.equal(fresh.resumed, false); + impostor.send("chat_message", { conversationId, content: "sou a Bia?" }); + assert.equal((await impostor.take("error")).payload.code, "conversation_not_found"); + const reopened = await openDm(impostor, { username: ana.username }); + assert.notEqual(reopened.conversationId, conversationId); + await settle(impostor); + assert.equal(impostor.count("message_history"), 0); + ana.client.close(); + impostor.close(); + }); + + test("buscas demais em pouco tempo são limitadas", async () => { + const { client } = await person(server.url, "Varre"); + for (let i = 0; i < 25; i += 1) client.send("user_lookup", { username: `alvo${i}` }); + const limited = await client.take( + (m) => m.type === "error" && m.payload.code === "lookup_limited", + ); + assert.equal(limited.payload.code, "lookup_limited"); + assert.equal(client.count("user_lookup"), 20); + client.close(); + }); + + test("sem sessão, nada funciona; logs não trazem @, nome nem conteúdo", async () => { + const lurker = await connect(server.url); + for (const [type, payload] of [ + ["user_lookup", { username: "alguem" }], + ["dm_open", { username: "alguem" }], + ["dm_close", { conversationId: "d_aaaaaaaaaaaaaaaa" }], + ["user_block", { username: "alguem" }], + ]) { + lurker.send(type, payload); + assert.equal((await lurker.take("error")).payload.code, "not_logged_in", type); + } + lurker.close(); + + const ana = await person(server.url, "NomeSecreto"); + const bia = await person(server.url, "Bia"); + const { conversationId } = await openDm(ana.client, { username: bia.username }); + ana.client.send("chat_message", { conversationId, content: "conteudo-privado-xyz" }); + await bia.client.take("message_history"); + await server.waitForLog((e) => e.event === "dm_opened"); + const all = server.lines.join("\n"); + assert.ok(!all.includes("conteudo-privado-xyz")); + assert.ok(!all.includes("NomeSecreto")); + assert.ok(!all.includes(bia.username)); + ana.client.close(); + bia.client.close(); + }); +}); + +describe("limites por ambiente e reinício", () => { + test("MAX_DMS_PER_USER é aplicado", async () => { + const server = await startServer({ MAX_DMS_PER_USER: "1" }); + const ana = await person(server.url, "Ana"); + const bia = await person(server.url, "Bia"); + const caio = await person(server.url, "Caio"); + assert.equal((await openDm(ana.client, { username: bia.username })).type, "dm_opened"); + assert.equal( + (await openDm(ana.client, { username: caio.username })).payload.code, + "dm_limit", + ); + for (const p of [ana, bia, caio]) p.client.close(); + await server.stop(); + }); + + test("reinício do servidor: nenhuma conversa privada sobrevive", async () => { + const first = await startServer(); + const ana = await person(first.url, "Ana"); + const bia = await person(first.url, "Bia"); + const { conversationId } = await openDm(ana.client, { username: bia.username }); + ana.client.send("chat_message", { conversationId, content: "não fica" }); + await bia.client.take("message_history"); + await first.stop(); + + const second = await startServer(); + const back = await connect(second.url); + back.send("user_login", { + userName: "Ana", + username: ana.username, + resumeToken: ana.me.resumeToken, + }); + const session = (await back.take("session")).payload; + assert.equal(session.resumed, false); + back.send("room_list", {}); + assert.deepEqual((await back.take("room_list")).payload, { rooms: [], dms: [] }); + back.send("chat_message", { conversationId, content: "ainda existe?" }); + assert.equal((await back.take("error")).payload.code, "conversation_not_found"); + back.close(); + await second.stop(); + }); +}); diff --git a/backend/test/integration/identity.test.js b/backend/test/integration/identity.test.js index 92ac973..33603c2 100644 --- a/backend/test/integration/identity.test.js +++ b/backend/test/integration/identity.test.js @@ -13,13 +13,14 @@ describe("identidade temporária: nome completo + username", () => { }); after(() => server.stop()); - test("sessão, lista e mensagens carregam o username; o id vem do servidor", async () => { + test("sessão, lista e mensagens carregam o username; o id interno nunca é enviado", async () => { const { client, session } = await join(server.url, { userId: "escolhido", userName: "Ana Carolina Souza", username: "@AnaCarolina", }); - assert.notEqual(session.id, "escolhido"); + assert.equal("id" in session, false); + assert.ok(!JSON.stringify(session).includes("escolhido")); assert.equal(session.name, "Ana Carolina Souza"); assert.equal(session.username, "anacarolina"); const list = await client.take("user_list"); @@ -53,7 +54,7 @@ describe("identidade temporária: nome completo + username", () => { client.close(); }); - test("queda abrupta: username fica reservado e a retomada devolve id e username", async () => { + test("queda abrupta: username fica reservado e a retomada devolve a mesma identidade", async () => { const { client, session } = await join(server.url, { userName: "Davi", username: "davi" }); client.close(); await client.waitClose(); @@ -62,7 +63,7 @@ describe("identidade temporária: nome completo + username", () => { assert.equal((await other.take("error")).payload.code, "username_taken"); other.close(); const back = await join(server.url, { userName: "Davi", resumeToken: session.resumeToken }); - assert.equal(back.session.id, session.id); + assert.equal(back.session.resumed, true); assert.equal(back.session.username, "davi"); back.client.close(); }); @@ -109,7 +110,7 @@ describe("sair (user_logout)", () => { // Com username, entra — como identidade nova, com o mesmo @ já livre. again.send("user_login", { userName: "Fábio", username: "fabio" }); const fresh = await again.take("session"); - assert.notEqual(fresh.payload.id, session.id); + assert.equal(fresh.payload.resumed, false); assert.equal(fresh.payload.username, "fabio"); again.close(); }); @@ -186,7 +187,7 @@ describe("allowlist de origem: clientes automatizados e reconexão", () => { { userName: "Helena", resumeToken: session.resumeToken }, { origin: ALLOWED }, ); - assert.equal(back.session.id, session.id); + assert.equal(back.session.resumed, true); back.client.close(); }); }); diff --git a/backend/test/integration/logs.test.js b/backend/test/integration/logs.test.js index 3ac56f3..2673260 100644 --- a/backend/test/integration/logs.test.js +++ b/backend/test/integration/logs.test.js @@ -66,9 +66,7 @@ describe("logs do servidor", () => { client.send("chat_message", { content: "conteudo-privado-123" }); await client.take("chat_message"); client.close(); - await server.waitForLog( - (entry) => entry.event === "session_paused" && entry.user === session.id, - ); + await server.waitForLog((entry) => entry.event === "session_paused"); const all = server.lines.join("\n"); assert.ok(!all.includes("conteudo-privado-123")); diff --git a/backend/test/integration/messages.test.js b/backend/test/integration/messages.test.js index c1a8a07..05cac0d 100644 --- a/backend/test/integration/messages.test.js +++ b/backend/test/integration/messages.test.js @@ -22,7 +22,7 @@ describe("mensagens", () => { (m) => m.type === "chat_message" && m.payload.content === "olá, sala", ); assert.match(message.id, /^[0-9a-f-]{36}$/); - assert.equal(message.payload.userId, a.session.id); + assert.equal(message.payload.username, a.session.username); assert.equal(message.payload.userName, "Ana"); assert.ok(!Number.isNaN(Date.parse(message.payload.timestamp))); } @@ -95,7 +95,7 @@ describe("mensagens", () => { const delivered = await observer.client.take( (m) => m.type === "chat_message" && m.payload.content === "mensagem importante", ); - assert.equal(delivered.payload.userId, typist.session.id); + assert.equal(delivered.payload.username, typist.session.username); assert.equal( typist.client.count((m) => m.type === "error"), 0, diff --git a/backend/test/integration/rooms.test.js b/backend/test/integration/rooms.test.js index 70f3082..77e72bd 100644 --- a/backend/test/integration/rooms.test.js +++ b/backend/test/integration/rooms.test.js @@ -35,7 +35,7 @@ describe("várias salas", () => { const { client } = await session(server.url, "Solitária"); client.send("room_list", { requestId: "lista" }); const list = await client.take("room_list"); - assert.deepEqual(list.payload, { rooms: [], requestId: "lista" }); + assert.deepEqual(list.payload, { rooms: [], dms: [], requestId: "lista" }); client.send("chat_message", { content: "alguém?" }); assert.equal((await client.take("error")).payload.code, "conversation_not_found"); client.close(); @@ -193,7 +193,6 @@ describe("reinício do servidor", () => { const fresh = await connect(second.url); fresh.send("user_login", { userName: "Antes", resumeToken: me.resumeToken }); const next = (await fresh.take("session")).payload; - assert.notEqual(next.id, me.id, "o token não vale num processo novo"); assert.equal(next.resumed, false); assert.equal((await joinRoom(fresh, room.payload.code)).payload.code, "room_not_found"); fresh.close(); diff --git a/backend/test/integration/security.test.js b/backend/test/integration/security.test.js index 5e558b8..01524b1 100644 --- a/backend/test/integration/security.test.js +++ b/backend/test/integration/security.test.js @@ -12,41 +12,51 @@ describe("identidade atribuída pelo servidor", () => { }); after(() => server.stop()); - test("o servidor ignora o userId enviado e atribui um id próprio", async () => { + test("o servidor ignora o userId enviado; o id interno fica só nele", async () => { const { client, session } = await join(server.url, { userId: "id-escolhido-pelo-cliente", userName: "Ana", }); - assert.notEqual(session.id, "id-escolhido-pelo-cliente"); - assert.match(session.id, /^[0-9a-f-]{36}$/); + assert.equal("id" in session, false, "a sessão não traz id"); + const started = await server.waitForLog( + (entry) => entry.event === "session_started" && /^[0-9a-f-]{36}$/.test(entry.user), + ); + assert.notEqual(started.user, "id-escolhido-pelo-cliente"); + assert.ok(!JSON.stringify(client.inbox).includes(started.user)); assert.equal(session.name, "Ana"); assert.equal(typeof session.resumeToken, "string"); assert.ok(session.resumeToken.length >= 32); client.close(); }); - test("tentativa de personificação: copiar o id de outra pessoa não funciona", async () => { + test("tentativa de personificação: dizer que é outra pessoa não funciona", async () => { const victim = await join(server.url, { userName: "Vítima" }); const attacker = await join(server.url, { - userId: victim.session.id, + userId: victim.session.username, userName: "Vítima", }); - assert.notEqual(attacker.session.id, victim.session.id); + assert.notEqual(attacker.session.username, victim.session.username); + // O @ é a identidade visível: enquanto a vítima existe, ninguém o pega. + const thief = await connect(server.url); + thief.send("user_login", { userName: "Vítima", username: victim.session.username }); + assert.equal((await thief.take("error")).payload.code, "username_taken"); + thief.close(); attacker.client.send("chat_message", { content: "sou eu, a vítima" }); const seen = await victim.client.take( (m) => m.type === "chat_message" && m.payload.content === "sou eu, a vítima", ); - // O cliente marca como "Você" quando userId === seu id: aqui não pode. - assert.equal(seen.payload.userId, attacker.session.id); - assert.notEqual(seen.payload.userId, victim.session.id); + // O cliente marca como "Você" pelo @ da mensagem: aqui é o do atacante. + assert.equal(seen.payload.username, attacker.session.username); + assert.notEqual(seen.payload.username, victim.session.username); const list = await victim.client.take( (m) => m.type === "user_list" && m.payload.length >= 2, ); - const ids = list.payload.map((person) => person.id); - assert.equal(new Set(ids).size, ids.length, "lista sem ids duplicados"); + const handles = list.payload.map((person) => person.username); + assert.equal(new Set(handles).size, handles.length, "lista sem @ duplicado"); + assert.ok(list.payload.every((person) => !("id" in person))); victim.client.close(); attacker.client.close(); @@ -56,7 +66,7 @@ describe("identidade atribuída pelo servidor", () => { const observer = await join(server.url, { userName: "Observador" }); const user = await join(server.url, { userName: "Bruno" }); - user.client.send("user_login", { userId: observer.session.id, userName: "Admin" }); + user.client.send("user_login", { userId: observer.session.username, userName: "Admin" }); const error = await user.client.take("error"); assert.equal(error.payload.code, "already_logged_in"); @@ -64,7 +74,7 @@ describe("identidade atribuída pelo servidor", () => { const seen = await observer.client.take( (m) => m.type === "chat_message" && m.payload.content === "depois da tentativa", ); - assert.equal(seen.payload.userId, user.session.id); + assert.equal(seen.payload.username, user.session.username); assert.equal(seen.payload.userName, "Bruno"); observer.client.close(); @@ -77,7 +87,7 @@ describe("identidade atribuída pelo servidor", () => { userName: "Intruso", resumeToken: "a".repeat(43), }); - assert.notEqual(attacker.session.id, victim.session.id); + assert.notEqual(attacker.session.username, victim.session.username); assert.equal(attacker.session.name, "Intruso"); victim.client.close(); attacker.client.close(); @@ -93,7 +103,7 @@ describe("identidade atribuída pelo servidor", () => { const seen = await observer.client.take( (m) => m.type === "chat_message" && m.payload.content === content, ); - assert.equal(seen.payload.userId, user.session.id); + assert.equal(seen.payload.username, user.session.username); assert.equal(seen.payload.userName, "Duda"); } observer.client.close(); @@ -179,3 +189,99 @@ describe("allowlist de origem", () => { client.close(); }); }); + +describe("id interno: nunca chega a quem não é administrador", () => { + const ADMIN_KEY = "chave-de-integracao-ids-0123456789"; + + test("nenhum quadro, erro ou resposta HTTP traz o id de alguém; administrador o vê por comando", async () => { + const server = await startServer({ ADMIN_KEY, METRICS_ENABLED: "true" }); + const host = await join(server.url, { userName: "Anfitriã", username: "anfitria" }); + const guest = await join(server.url, { userName: "Convidada", username: "convidada" }); + const admin = await join(server.url, { userName: "Operadora", username: "operadora" }); + + let seq = 0; + const run = async (client, text) => { + const requestId = `ids-${++seq}`; + client.send("command", { requestId, text }); + return ( + await client.take( + (m) => m.type === "command_result" && m.payload.requestId === requestId, + ) + ).payload; + }; + + // Uso normal, erros e moderação, vistos por quem não é administrador. + guest.client.send("chat_message", { content: "olá", clientMsgId: "g1" }); + guest.client.send("typing_start", {}); + guest.client.send("user_lookup", { username: "anfitria" }); + guest.client.send("dm_open", { username: "anfitria" }); + const dm = await guest.client.take("dm_opened"); + guest.client.send("chat_message", { + conversationId: dm.conversationId, + content: "privado", + }); + await host.client.take("dm_opened"); + guest.client.send("user_block", { username: "anfitria" }); + await guest.client.take("block_list"); + guest.client.send("dm_open", { userId: "qualquer", username: undefined }); + guest.client.send("chat_message", { conversationId: "r_naoexiste000000", content: "x" }); + guest.client.send("room_list", {}); + await guest.client.take("room_list"); + for (const text of [ + "/users", + "/profile", + "/profile @anfitria", + "/id", + "/rooms", + "/invite", + ]) { + await run(guest.client, text); + } + await run(host.client, "/users"); + await run(host.client, "/profile @convidada"); + await run(host.client, "/mute @convidada 1"); + await run(host.client, "/kick @convidada"); + await guest.client.take("room_left"); + + // Ids reais, do log do servidor (que fica com quem opera). + const ids = [ + ...new Set( + server + .entries() + .filter((e) => e.event === "session_started") + .map((e) => e.user), + ), + ]; + assert.equal(ids.length, 3); + for (const [who, client] of [ + ["convidada", guest.client], + ["anfitriã", host.client], + ]) { + const wire = JSON.stringify(client.inbox); + for (const id of ids) { + assert.ok(!wire.includes(id), `id completo vazou para ${who}`); + assert.ok(!wire.includes(id.slice(0, 8)), `id curto vazou para ${who}`); + } + } + + // Respostas HTTP: só números. + for (const path of ["/", "/healthz", "/readyz", "/metrics"]) { + const body = await (await fetch(`http://127.0.0.1:${server.port}${path}`)).text(); + for (const id of ids) assert.ok(!body.includes(id), `id em ${path}`); + for (const name of ["anfitria", "convidada", "Convidada"]) { + assert.ok(!body.includes(name), `nome ou @ em ${path}`); + } + } + + // Administradora: vê os ids, e só por comando. + const before = JSON.stringify(admin.client.inbox); + for (const id of ids) assert.ok(!before.includes(id), "nem a futura admin recebia ids"); + assert.equal((await run(admin.client, `/admin ${ADMIN_KEY}`)).tone, "admin"); + const users = await run(admin.client, "/users"); + assert.ok(users.lines.some((line) => / id [0-9a-f]{8}/.test(line))); + assert.match((await run(admin.client, "/id")).text, /[0-9a-f-]{36}/); + + for (const p of [host, guest, admin]) p.client.close(); + await server.stop(); + }); +}); diff --git a/backend/test/integration/stability.test.js b/backend/test/integration/stability.test.js index b00f304..5b2fe3c 100644 --- a/backend/test/integration/stability.test.js +++ b/backend/test/integration/stability.test.js @@ -122,7 +122,7 @@ describe("agrupamento da lista de pessoas", () => { (m) => m.type === "user_list" && m.payload.length === 31, 3000, ); - assert.equal(new Set(final.payload.map((p) => p.id)).size, 31); + assert.equal(new Set(final.payload.map((p) => p.username)).size, 31); const metrics = await metricsOf(server); assert.ok( metrics.counters.userListBroadcasts < 31, diff --git a/backend/test/unit/config.test.js b/backend/test/unit/config.test.js index 505dc52..74c68f1 100644 --- a/backend/test/unit/config.test.js +++ b/backend/test/unit/config.test.js @@ -1,4 +1,4 @@ -import { test } from "node:test"; +import { describe, test } from "node:test"; import assert from "node:assert/strict"; import { ConfigError, DEFAULTS, loadConfig } from "../../src/config.js"; @@ -30,6 +30,8 @@ test("sem variáveis, os padrões reproduzem o comportamento anterior", () => { maxCreatedPerIdentity: 5, emptyTtlMs: 60000, }, + // Fase 3 da evolução: conversas privadas. + dms: { maxPerIdentity: 20, maxTotal: 5000, historySize: 100 }, adminKey: null, production: false, }); @@ -44,6 +46,7 @@ test("variáveis válidas são aplicadas", () => { HISTORY_SIZE: "200", HISTORY_ON_JOIN: "20", NODE_ENV: "production", + ALLOWED_ORIGINS: "https://chat.example", }); assert.equal(config.maxConnections, 100); assert.equal(config.messageRate.capacity, 10); @@ -99,3 +102,44 @@ test("ADMIN_KEY válida é aceita e nunca aparece na mensagem de erro de outra v assert.ok(!error.message.includes("segredo-curto")); } }); + +describe("ALLOWED_ORIGINS em produção", () => { + test("ausente ou vazia impede a inicialização", () => { + for (const value of [undefined, "", " ", " , "]) { + assert.throws( + () => loadConfig({ NODE_ENV: "production", ALLOWED_ORIGINS: value }), + (error) => error instanceof ConfigError && error.variable === "ALLOWED_ORIGINS", + String(value), + ); + } + }); + + test("curinga e entradas que não são origem são recusados em qualquer ambiente", () => { + for (const NODE_ENV of ["production", "development"]) { + for (const value of [ + "*", + "https://*.example.com", + "chat.example", + "https://chat.example/caminho", + ]) { + assert.throws( + () => loadConfig({ NODE_ENV, ALLOWED_ORIGINS: value }), + (error) => error instanceof ConfigError && error.variable === "ALLOWED_ORIGINS", + `${NODE_ENV}: ${value}`, + ); + } + } + }); + + test("com a origem oficial, sobe normalmente", () => { + const config = loadConfig({ + NODE_ENV: "production", + ALLOWED_ORIGINS: "https://chat-frontend-g42t.onrender.com", + }); + assert.deepEqual(config.allowedOrigins, ["https://chat-frontend-g42t.onrender.com"]); + }); + + test("fora de produção, vazia continua permitida (desenvolvimento local)", () => { + assert.deepEqual(loadConfig({ NODE_ENV: "development" }).allowedOrigins, []); + }); +}); diff --git a/backend/test/unit/connection.test.js b/backend/test/unit/connection.test.js index c19e7b1..86d26b3 100644 --- a/backend/test/unit/connection.test.js +++ b/backend/test/unit/connection.test.js @@ -41,7 +41,7 @@ const setup = (hubOverrides = {}) => { { ok: true, already: false } ), leaveRoom: (ws, payload) => (calls.push(["leaveRoom", payload]), { ok: true }), - roomsOf: () => [], + conversationsOf: () => ({ rooms: [], dms: [] }), isLoggedIn: () => false, userIdOf: () => null, ...hubOverrides, @@ -77,7 +77,7 @@ test("encaminha cada evento ao método certo do hub", () => { test("pedidos de sala chegam ao hub; room_list responde com as salas e o requestId", () => { const summary = { conversationId: "r_abcdefghijkl", code: "abc-defg-hij" }; - const { ws, calls, tick } = setup({ roomsOf: () => [summary] }); + const { ws, calls, tick } = setup({ conversationsOf: () => ({ rooms: [summary], dms: [] }) }); ws.frame({ type: "room_create", payload: { name: "Estudos" } }); ws.frame({ type: "room_join", payload: { code: "abc-defg-hij" } }); ws.frame({ type: "room_leave", payload: { conversationId: "r_abcdefghijkl" } }); @@ -89,7 +89,7 @@ test("pedidos de sala chegam ao hub; room_list responde com as salas e o request ["leaveRoom", { conversationId: "r_abcdefghijkl" }], ]); assert.deepEqual(ws.sent, [ - { type: "room_list", payload: { rooms: [summary], requestId: "lista-1" } }, + { type: "room_list", payload: { rooms: [summary], dms: [], requestId: "lista-1" } }, ]); }); diff --git a/backend/test/unit/contract.test.js b/backend/test/unit/contract.test.js index 9b8b14b..b083a7f 100644 --- a/backend/test/unit/contract.test.js +++ b/backend/test/unit/contract.test.js @@ -40,6 +40,8 @@ test("variedades, formatos, tons e códigos de fechamento coincidem", () => { assert.equal(client.LIMITS.roomNameMaxLength, server.LIMITS.roomNameMaxLength); assert.deepEqual(client.ROLES, server.ROLES); assert.deepEqual(client.ROOM_LEFT_REASONS, server.ROOM_LEFT_REASONS); + assert.deepEqual(client.CONVERSATION_KINDS, server.CONVERSATION_KINDS); + assert.deepEqual(client.DM_CLOSED_REASONS, server.DM_CLOSED_REASONS); }); test("limites de nome, username e mensagem são os mesmos nos dois lados e no HTML", () => { diff --git a/backend/test/unit/direct.test.js b/backend/test/unit/direct.test.js new file mode 100644 index 0000000..a08950a --- /dev/null +++ b/backend/test/unit/direct.test.js @@ -0,0 +1,484 @@ +// Conversas privadas (Fase 3 da evolução), sem rede: busca por @, abrir, +// mensagens, isolamento, bloqueio, encerramento, retomada, fim da +// identidade, limites e memória. + +import { test, describe } from "node:test"; +import assert from "node:assert/strict"; +import { createCommandExecutor } from "../../src/commands/executor.js"; +import { createDefaultRegistry } from "../../src/commands/index.js"; +import { setup } from "./harness.js"; + +/** Três pessoas conectadas, com @ conhecidos. */ +const people = (options) => { + const ctx = setup(options); + const { member, login } = ctx; + const ana = member("ana"); + const bia = member("bia"); + const caio = member("caio"); + login(ana, { userName: "Ana", username: "ana" }); + login(bia, { userName: "Bia", username: "bia" }); + login(caio, { userName: "Caio", username: "caio" }); + const idOf = (m) => ctx.hub.entryOf(m).identity.id; + return { ...ctx, ana, bia, caio, idOf }; +}; + +/** Ana abre com Bia e manda a primeira mensagem. */ +const anaTalksToBia = (options) => { + const ctx = people(options); + const opened = ctx.hub.openDm(ctx.ana, { username: "bia" }); + assert.equal(opened.ok, true); + const dm = opened.conversation; + ctx.hub.post(ctx.ana, { conversationId: dm.id, content: "oi Bia" }); + return { ...ctx, dm }; +}; + +describe("busca por @", () => { + test("acha só pelo @ exato e devolve só nome, @ e id", () => { + const { hub, ana } = people(); + const found = hub.lookup(ana, { username: "@BIA" }); + assert.equal(found.ok, true); + assert.deepEqual(found.user && { name: found.user.name, username: found.user.username }, { + name: "Bia", + username: "bia", + }); + for (const query of ["bi", "b", "bia2"]) { + assert.equal(hub.lookup(ana, { username: query }).user ?? null, null, query); + } + }); + + test("@ inválido é recusado; sem sessão também", () => { + const { hub, ana, member } = people(); + for (const username of ["", "a b", 42, undefined, "x"]) { + assert.equal(hub.lookup(ana, { username }).code, "invalid_user", String(username)); + } + assert.equal(hub.lookup(member("fora"), { username: "bia" }).code, "not_logged_in"); + }); + + test("quem só está na janela de retomada não aparece", () => { + const { hub, ana, bia } = people(); + hub.disconnect(bia); + assert.equal(hub.lookup(ana, { username: "bia" }).user, null); + }); + + test("limite de buscas: varrer @ às cegas trava", () => { + const { hub, ana } = people({ + dmGuard: { lookup: { capacity: 3, refillPerSecond: 0.001 } }, + }); + for (let i = 0; i < 3; i += 1) + assert.equal(hub.lookup(ana, { username: `x${i}xx` }).ok, true); + assert.equal(hub.lookup(ana, { username: "bia" }).code, "lookup_limited"); + }); + + test("o limite volta com o tempo", () => { + const ctx = people({ dmGuard: { lookup: { capacity: 1, refillPerSecond: 1 } } }); + ctx.hub.lookup(ctx.ana, { username: "zzz" }); + assert.equal(ctx.hub.lookup(ctx.ana, { username: "bia" }).code, "lookup_limited"); + ctx.tick(1000); + assert.equal(ctx.hub.lookup(ctx.ana, { username: "bia" }).ok, true); + }); +}); + +describe("abrir e conversar", () => { + test("quem abre recebe a conversa; a outra pessoa só fica sabendo na primeira mensagem", () => { + const { hub, ana, bia, received } = people(); + const opened = hub.openDm(ana, { username: "bia" }); + assert.equal(opened.created, true); + const [mine] = received(ana, "dm_opened"); + assert.equal(mine.conversationId, opened.conversation.id); + assert.match(mine.conversationId, /^d_/); + assert.deepEqual(mine.payload.peer, { + name: "Bia", + username: "bia", + online: true, + }); + assert.equal(mine.payload.kind, "dm"); + assert.equal(received(bia, "dm_opened").length, 0, "abrir não avisa ninguém"); + + hub.post(ana, { conversationId: opened.conversation.id, content: "oi Bia" }); + const [theirs] = received(bia, "dm_opened"); + assert.equal(theirs.payload.peer.username, "ana"); + assert.equal(theirs.payload.created, true); + assert.equal(received(bia, "message_history")[0].payload[0].payload.content, "oi Bia"); + assert.equal(received(bia, "chat_message").length, 0, "a primeira chega no histórico"); + + hub.post(bia, { conversationId: opened.conversation.id, content: "oi Ana" }); + assert.equal(received(ana, "chat_message").at(-1).payload.content, "oi Ana"); + assert.equal(received(bia, "chat_message").at(-1).payload.content, "oi Ana"); + }); + + test("o id interno não abre conversa nem aparece em nenhum quadro", () => { + const { hub, ana, bia, idOf, all } = people(); + assert.equal(hub.openDm(ana, { userId: idOf(bia) }).code, "invalid_user"); + const { conversation } = hub.openDm(ana, { username: "bia" }); + hub.post(ana, { conversationId: conversation.id, content: "oi" }); + hub.post(bia, { conversationId: conversation.id, content: "oi" }); + hub.typing(bia, { conversationId: conversation.id }, true); + hub.lookup(ana, { username: "bia" }); + const wire = JSON.stringify([...all(ana), ...all(bia)]); + assert.ok(!wire.includes(idOf(ana)) && !wire.includes(idOf(bia))); + }); + + test("abrir de novo devolve a mesma conversa, dos dois lados", () => { + const { hub, ana, bia, dm } = anaTalksToBia(); + const again = hub.openDm(ana, { username: "bia" }); + const fromBia = hub.openDm(bia, { username: "ana" }); + assert.equal(again.created, false); + assert.equal(again.conversation, dm); + assert.equal(fromBia.conversation, dm); + }); + + test("consigo mesmo, ninguém, @ inválido ou desconectado: recusado", () => { + const { hub, ana, bia } = people(); + assert.equal(hub.openDm(ana, { username: "ana" }).code, "dm_self"); + assert.equal(hub.openDm(ana, { username: "ninguem" }).code, "user_unavailable"); + assert.equal(hub.openDm(ana, { username: "a b" }).code, "invalid_user"); + assert.equal(hub.openDm(ana, { username: "