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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
150 changes: 98 additions & 52 deletions README.md

Large diffs are not rendered by default.

18 changes: 9 additions & 9 deletions backend/src/commands/handlers/admin.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 <nome ou id> [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(
Expand All @@ -125,11 +125,11 @@ export const adminCommands = [
permission: PERMISSIONS.MODERATOR,
requiresRoom: true,
description: "Libera alguém silenciado nesta sala.",
syntax: "/unmute <nome ou id>",
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()) {
Expand All @@ -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 <nome ou id>",
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;
Expand Down
9 changes: 6 additions & 3 deletions backend/src/commands/handlers/basic.js
Original file line number Diff line number Diff line change
@@ -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 = [
Expand Down Expand Up @@ -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,
Expand All @@ -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`,
Expand Down
18 changes: 10 additions & 8 deletions backend/src/commands/handlers/profile.js
Original file line number Diff line number Diff line change
@@ -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[]} */
Expand All @@ -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 <novo nome>",
examples: ["/nick João Silva"],
params: [{ name: "novo nome", type: "text" }],
Expand Down Expand Up @@ -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ê".
Expand All @@ -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
Expand All @@ -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",
Expand Down
7 changes: 4 additions & 3 deletions backend/src/commands/handlers/shared.js
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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,
Expand Down
47 changes: 44 additions & 3 deletions backend/src/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 === "";
Expand Down Expand Up @@ -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 &&
Expand All @@ -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
Expand All @@ -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
*/
Expand All @@ -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,
Expand Down Expand Up @@ -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,
};
};
43 changes: 43 additions & 0 deletions backend/src/errors.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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.",
},
});

/**
Expand Down
7 changes: 6 additions & 1 deletion backend/src/metrics.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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 } = {}) {
Expand Down
Loading
Loading