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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ VITE_SOCKET_URL=ws://localhost:8080
# ─── Backend ────────────────────────────────────────────────────────────
# Origens autorizadas a abrir conexão, separadas por vírgula, no formato
# esquema://host[:porta], sem caminho (ex.: https://meuchat.com,http://localhost:5173).
# Com a lista definida, conexões sem cabeçalho Origin também são recusadas.
# Comparação exata, sem curinga. Em produção: ver docs/DEPLOY_RENDER.md.
# Vazia: qualquer origem é aceita, e o servidor registra um aviso ao subir.
# CONFIGURE EM PRODUÇÃO. Uma entrada inválida impede o servidor de subir.
ALLOWED_ORIGINS=
Expand Down
10 changes: 6 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ Cada item corresponde a código neste repositório.

| Funcionalidade | Onde |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------- |
| Entrada com um nome (até 30 caracteres), sem senha | `frontend/src/ui/entry.js` |
| Entrada com nome completo (até 60 caracteres) e nome de usuário único na sala (`@username`), sem conta nem senha; botão Sair libera a identidade na hora | `frontend/src/ui/entry.js` |
| Mensagens em tempo real para todos os conectados (até 1000 caracteres) | `backend/src/server.js`, `frontend/src/state/events.js` |
| Últimas 50 mensagens enviadas a quem entra | `backend/src/server.js` |
| Interface em painéis: barra lateral (sala, atalhos, conexão, você), conversa com mensagens agrupadas e painel de pessoas; gavetas em tablet e celular | `frontend/index.html`, `frontend/src/ui/layout.js` |
Expand Down Expand Up @@ -355,9 +355,10 @@ O backend não tem etapa de build: roda direto com Node.

## Deploy

O repositório **não contém configuração de deploy** (Dockerfile, Procfile ou
arquivo de plataforma). O projeto é composto de duas partes publicadas
separadamente:
A hospedagem é no **Render**, descrita em [`render.yaml`](./render.yaml) (Blueprint
com os dois serviços, health check e cabeçalhos de segurança do site estático).
Como aplicar, variáveis e verificação: [`docs/DEPLOY_RENDER.md`](./docs/DEPLOY_RENDER.md).
O projeto é composto de duas partes publicadas separadamente:

**Frontend (estático)** — duas formas, ambas verificadas no
[`docs/refactor-report.md`](./docs/refactor-report.md) §10:
Expand Down Expand Up @@ -449,6 +450,7 @@ prevista no roadmap (F5-06).
| [`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 |
Expand Down
6 changes: 3 additions & 3 deletions backend/src/commands/handlers/admin.js
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ export const adminCommands = [
permission: PERMISSIONS.ADMIN,
description: "Impede alguém de enviar mensagens, por um tempo (minutos) ou até /unmute.",
syntax: "/mute <nome ou id> [minutos]",
examples: ["/mute Ana", "/mute Ana 10", '/mute "João Silva" 5'],
examples: ["/mute @ana 10", "/mute Ana", '/mute "João Silva" 5'],
params: [
{ name: "nome ou id", type: "word" },
{ name: "minutos", type: "int", optional: true, min: 1, max: 1440 },
Expand All @@ -121,7 +121,7 @@ export const adminCommands = [
permission: PERMISSIONS.ADMIN,
description: "Libera alguém silenciado.",
syntax: "/unmute <nome ou id>",
examples: ["/unmute Ana"],
examples: ["/unmute @ana", "/unmute Ana"],
params: [{ name: "nome ou id", type: "word" }],
run: (ctx) => {
const found = findModerationTarget(ctx, ctx.args["nome ou id"]);
Expand All @@ -141,7 +141,7 @@ export const adminCommands = [
permission: PERMISSIONS.ADMIN,
description: "Remove alguém da sala agora. A pessoa pode voltar, mas como identidade nova.",
syntax: "/kick <nome ou id>",
examples: ["/kick Ana", '/kick "João Silva"'],
examples: ["/kick @ana", "/kick Ana", '/kick "João Silva"'],
params: [{ name: "nome ou id", type: "word" }],
run: (ctx) => {
const found = findModerationTarget(ctx, ctx.args["nome ou id"]);
Expand Down
4 changes: 2 additions & 2 deletions backend/src/commands/handlers/basic.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ export const basicCommands = [
name: "users",
aliases: ["online", "who"],
category: "basic",
description: "Lista quem está na sala agora, com o id curto de cada pessoa.",
description: "Lista quem está na sala agora, com o @username e o id curto de cada pessoa.",
syntax: "/users",
examples: ["/users"],
run: (ctx) => {
Expand All @@ -58,7 +58,7 @@ export const basicCommands = [
identity.away !== null ? `ausente: ${identity.away}` : null,
isMuted(identity, time) ? "silenciado" : null,
].filter(Boolean);
return `${identity.name} · ${identity.id.slice(0, 8)}${tags.length ? ` · ${tags.join(" · ")}` : ""}`;
return `${identity.name} (@${identity.username}) · ${identity.id.slice(0, 8)}${tags.length ? ` · ${tags.join(" · ")}` : ""}`;
});
return ctx.reply.result(
people.length === 1 ? "1 pessoa na sala" : `${people.length} pessoas na sala`,
Expand Down
3 changes: 2 additions & 1 deletion backend/src/commands/handlers/profile.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ export const profileCommands = [
category: "profile",
description: "Mostra o perfil público de alguém (ou o seu).",
syntax: "/profile [nome ou id]",
examples: ["/profile", "/profile Ana"],
examples: ["/profile", "/profile @ana", "/profile Ana"],
params: [{ name: "nome ou id", type: "text", optional: true }],
run: (ctx) => {
let identity = ctx.identity;
Expand All @@ -53,6 +53,7 @@ export const profileCommands = [
return ctx.reply.result(identity.name, {
title: "Perfil",
lines: [
`Username: @${identity.username}`,
`Id: ${identity.id}`,
`Papel: ${identity.role === "admin" ? "administrador" : "participante"}`,
`Status: ${identity.away !== null ? `ausente (${identity.away})` : "presente"}${isMuted(identity, time) ? " · silenciado" : ""}`,
Expand Down
4 changes: 2 additions & 2 deletions backend/src/commands/handlers/shared.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export const publishFor = (ctx, message) => {
};

/**
* Encontra exatamente uma pessoa na sala por nome ou id (prefixo 6+).
* Encontra exatamente uma pessoa na sala por @username, nome ou id (prefixo 6+).
* @param {any} ctx
* @param {string} query
* @returns {{ok: true, target: {member: unknown, identity: any}} | {ok: false, response: any}}
Expand All @@ -52,7 +52,7 @@ export const findTarget = (ctx, query) => {
ok: false,
response: ctx.reply.error(
ctx.errors.AMBIGUOUS_TARGET,
`Há ${found.length} pessoas chamadas "${query}". Use o id mostrado em /users.`,
`Há ${found.length} pessoas chamadas "${query}". Use o @username mostrado em /users.`,
),
};
}
Expand Down
13 changes: 12 additions & 1 deletion backend/src/errors.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ export const ERROR_CODES = Object.freeze({
INVALID_MESSAGE: "invalid_message",
UNKNOWN_TYPE: "unknown_type",
INVALID_NAME: "invalid_name",
INVALID_USERNAME: "invalid_username",
USERNAME_TAKEN: "username_taken",
EMPTY_MESSAGE: "empty_message",
ALREADY_LOGGED_IN: "already_logged_in",
NOT_LOGGED_IN: "not_logged_in",
Expand All @@ -44,7 +46,16 @@ const CATALOG = Object.freeze({
[ERROR_CODES.UNKNOWN_TYPE]: { category: PROTOCOL, message: "Tipo de mensagem desconhecido." },
[ERROR_CODES.INVALID_NAME]: {
category: VALIDATION,
message: "Nome inválido. Use de 1 a 30 caracteres.",
message: "Nome inválido. Use de 1 a 60 caracteres.",
},
[ERROR_CODES.INVALID_USERNAME]: {
category: VALIDATION,
message:
"Username inválido ou reservado. Use de 3 a 20 caracteres: letras minúsculas sem acento, números, ponto ou _.",
},
[ERROR_CODES.USERNAME_TAKEN]: {
category: VALIDATION,
message: "Este username já está em uso na sala. Escolha outro.",
},
[ERROR_CODES.EMPTY_MESSAGE]: { category: VALIDATION, message: "Mensagem vazia." },
[ERROR_CODES.ALREADY_LOGGED_IN]: {
Expand Down
1 change: 1 addition & 0 deletions backend/src/metrics.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ export const createMetrics = ({ now = () => Date.now(), startedAt = Date.now() }
connectionsRejected: {},
heartbeatTimeouts: 0,
loginTimeouts: 0,
logouts: 0,
slowConsumerDisconnects: 0,
framesReceived: {},
invalidFrames: {},
Expand Down
20 changes: 16 additions & 4 deletions backend/src/protocol.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,11 @@ import { describeError, ERROR_CODES } from "./errors.js";

/** Limites do contrato, aplicados pelo servidor e espelhados no cliente. */
export const LIMITS = Object.freeze({
nameMaxLength: 30,
/** Nome completo de exibição. */
nameMaxLength: 60,
/** Username (`@nome`): único entre as identidades vivas da sala. */
usernameMinLength: 3,
usernameMaxLength: 20,
messageMaxLength: 1000,
resumeTokenMaxLength: 100,
/** Texto bruto de um comando (`/nome argumentos`). */
Expand All @@ -33,6 +37,8 @@ export const CLIENT_EVENTS = Object.freeze({
TYPING_START: "typing_start",
TYPING_STOP: "typing_stop",
COMMAND: "command",
/** Sair da sala: libera a identidade temporária e o username na hora. */
LOGOUT: "user_logout",
});

/** Eventos que o servidor envia. */
Expand Down Expand Up @@ -91,6 +97,8 @@ export const TONES = Object.freeze({
export const CLOSE_CODES = Object.freeze({
LOGIN_TIMEOUT: 4001,
REMOVED: 4003,
/** A própria pessoa saiu (`user_logout`); o cliente não reconecta. */
LOGGED_OUT: 4004,
});

const SIGNAL_EVENTS = new Set([CLIENT_EVENTS.TYPING_START, CLIENT_EVENTS.TYPING_STOP]);
Expand Down Expand Up @@ -144,7 +152,7 @@ export const errorCodeForEnvelope = (reason) =>
*/
export const serverMessage = Object.freeze({
/**
* @param {{id: string, name: string, role?: string}} user
* @param {{id: string, name: string, username?: string, role?: string}} user
* @param {string} resumeToken
* @param {number} [historyVersion] muda quando a sala é limpa (`/clearall`)
*/
Expand All @@ -153,6 +161,7 @@ export const serverMessage = Object.freeze({
payload: {
id: user.id,
name: user.name,
username: user.username ?? "",
resumeToken,
role: user.role ?? ROLES.MEMBER,
historyVersion,
Expand All @@ -166,7 +175,8 @@ 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}, content: string, timestamp: string,
* id: string, user: {id: string, name: string, username?: string},
* content: string, timestamp: string,
* kind?: string, format?: string | null, clientMsgId?: string | null,
* }} message
*/
Expand All @@ -184,6 +194,7 @@ export const serverMessage = Object.freeze({
payload: {
userId: user.id,
userName: user.name,
...(user.username ? { username: user.username } : {}),
content,
timestamp,
...(kind !== MESSAGE_KINDS.TEXT ? { kind } : {}),
Expand Down Expand Up @@ -211,13 +222,14 @@ export const serverMessage = Object.freeze({
/**
* `status` já existia ("online"); agora também "away". `role` e
* `statusText` são aditivos.
* @param {{id: string, name: string, role?: string, away?: string | null}[]} users
* @param {{id: string, 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,
role: user.role ?? ROLES.MEMBER,
...(user.away ? { statusText: user.away } : {}),
Expand Down
55 changes: 49 additions & 6 deletions backend/src/room/room.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import {
readContent,
readName,
readResumeToken,
readUsername,
} from "../validation.js";
import { isMuted } from "./policy.js";

Expand Down Expand Up @@ -240,15 +241,34 @@ export const createRoom = ({

const requested = readName(payload.userName);
if (!requested.ok) return requested;
const requestedUsername = readUsername(payload.username);
if (!requestedUsername.ok) return requestedUsername;

let identity = identities.claim(readResumeToken(payload.resumeToken));
// Entrada nova (sem token válido): nome e username obrigatórios,
// e o username não pode estar com outra identidade viva.
const token = readResumeToken(payload.resumeToken);
const fresh = () => {
if (!requested.name) return { ok: false, code: ERROR_CODES.INVALID_NAME };
if (!requestedUsername.username) {
return { ok: false, code: ERROR_CODES.INVALID_USERNAME };
}
if (identities.isUsernameTaken(requestedUsername.username)) {
return { ok: false, code: ERROR_CODES.USERNAME_TAKEN };
}
return null;
};

let identity = identities.claim(token);
const resumed = identity !== null;
let replaced = null;
let returningInGrace = false;

if (identity === null) {
if (!requested.name) return { ok: false, code: ERROR_CODES.INVALID_NAME };
identity = identities.create(requested.name);
// Retomada com o mesmo id: o username é o guardado; o do
// payload só vale para uma identidade nova.
const refused = fresh();
if (refused) return refused;
identity = identities.create(requested.name, requestedUsername.username);
} else if (identity.holder !== null && identity.holder !== member) {
// A conexão antiga ainda consta (queda não detectada): a pessoa
// é a mesma, então ela sai em silêncio e a nova assume.
Expand Down Expand Up @@ -279,6 +299,22 @@ export const createRoom = ({

leave,

/**
* A própria pessoa sai (`user_logout`): sai na hora, sem janela de
* retomada, e a identidade é encerrada — token inválido e username
* livre. Voltar é sempre como identidade nova. Quem chama fecha a
* conexão.
* @param {unknown} member
* @returns {boolean} se a conexão estava na sala
*/
logout(member) {
const entry = members.get(member);
if (!entry) return false;
leave(member, { reason: "logout" });
identities.revoke(entry.identity);
return true;
},

/**
* Mensagem digitada. O autor é a identidade da conexão; `kind` e
* `format` do payload são ignorados (só comandos os produzem).
Expand Down Expand Up @@ -450,8 +486,9 @@ export const createRoom = ({
[...members.entries()].map(([member, entry]) => ({ member, identity: entry.identity })),

/**
* Localiza pessoas na sala por id (ou prefixo de id com 6+
* caracteres) ou por nome (sem diferenciar maiúsculas).
* Localiza pessoas 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 com o mesmo nome).
* @param {string} query
*/
findMembers(query) {
Expand All @@ -461,11 +498,17 @@ export const createRoom = ({
member,
identity: entry.identity,
}));
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))
: [];
if (byId.length > 0) return byId;
return all.filter(({ identity }) => identity.name.toLowerCase() === wanted);
const byName = all.filter(({ identity }) => identity.name.toLowerCase() === wanted);
if (byName.length > 0) return byName;
// Sem @ e sem nome igual: o texto ainda pode ser um username.
return all.filter(({ identity }) => identity.username === wanted);
},

get memberCount() {
Expand Down
Loading
Loading