Files
gerbeur/api/routes/ws.ts
khannurien 14e3ab125b v3: fix the privacy and security findings of the comment pass — private dumps' broadcasts, mentions and attachments reached people who can't see them, and a few smaller holes. A dump's every write now goes through ws-service's broadcastDumpChange(before, after), which decides the audience: a private dump's creation, edits and deletion reach its owner's sockets alone (its deletion id went to everyone before), going private is dump_deleted for everyone else and dump_updated for the owner (whose other tabs dropped it), going public dump_created for everyone else. Mentions in a private dump, a comment on one, or a private playlist's description notify no one until it goes public (mentions are deduplicated per context, so going public notifies them once), and a moderator's edit of a comment, chat message or playlist mentions in the author's name. A link preview of a private playlist is refused, as one of a private dump already was: the preview is stored in the linking dump, which others may see. Attachments record the type of the resource that links them (migration 0018 backfills it); one linked by a private dump or playlist, or a comment on a private dump, is served only with its owner's media token, which Markdown now adds to attachment URLs, and one whose resource is gone answers 404 and is purged at startup. The Bandcamp provider claimed bandcamp.com.evil.example (the pattern wasn't anchored) and now reuses bandcamp-tralbum's anchored one; the YouTube provider took any site's ?list= for a YouTube playlist and missed m., music., youtube-nocookie and /live/ links, and now shares canonical-url's rules. Sign-in does the same scrypt work for an unknown username as for a wrong password, so timing no longer tells which exist. Usernames and emails are unique regardless of case (migration 0017, which refuses to run over existing clashes and names them): "Bob" and "bob" could both sign up and a mention picked one, emails had no constraint, and a reset request in another case silently sent nothing. The Open Graph tags escape the site name and build their URLs on PUBLIC_URL and FRONTEND_URL instead of the request's origin, which a proxy may rewrite.
Error statuses follow one rule: APIException takes a status and derives the code from it (BAD_REQUEST 400, UNAUTHORIZED 401, FORBIDDEN 403, NOT_FOUND 404, CONFLICT 409, RATE_LIMITED 429, SERVER_ERROR 500, BAD_GATEWAY 502), so a code can't contradict its status. That fixed real bugs: a wrong current password on change-password answered 401, on which authFetch signs the user out; editing or deleting someone else's comment or chat message answered 401 rather than 403; one invalid dump edit answered 422. A taken username is 409, like a taken email.

Along the way: the database is created from schema.sql by connection.ts when the file doesn't exist, so every task works on a fresh checkout (dev and serve never ran db/init.ts, which is gone); the startup purge compared ISO dates with SQLite's datetime() as text and kept anything from the current UTC day, and now compares ISO cutoffs; the seeded admin's hash comes from lib/password.ts (split out of jwt.ts, which needs the JWT secret) rather than a copy of its format; avatar, thumbnail and playlist-cover uploads go through replaceUploadedFile, which writes beside the old file and renames over it before the record announces it (a failed avatar write lost the old avatar; a thumbnail was announced before it existed); upload.ts derives its size message from MAX_IMAGE_SIZE_BYTES and stops re-exporting the upload folders; ALLOWED_IMAGE_MIMES, which duplicated detectImageMime, is gone; the SPA fallback no longer calls next() after answering; a reply must answer a comment on the same dump (a foreign or unknown parent was a 500 or a cross-dump thread). 211 backend and 628 frontend tests pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 15:19:07 +00:00

513 lines
14 KiB
TypeScript

/**
* Opens the WebSocket that `WSProvider` keeps for each tab, and handles what
* the client sends over it. Voting, comment likes and every chat write go
* through here, not through HTTP. The messages are typed in `shared/ws.ts`,
* and `services/ws-service.ts` sends the broadcasts.
*
* - `GET /ws?token=`, public. A valid session `token` signs the socket in, and
* an invalid one leaves it anonymous. Answers 403 to an origin not in
* {@link ALLOWED_ORIGINS}, and 426 to a request that isn't an upgrade.
*
* @module
*/
import { Router } from "@oak/oak";
import { ALLOWED_ORIGINS } from "../config.ts";
import { authenticate } from "../lib/auth.ts";
import {
broadcastChatMessage,
broadcastChatMessageDeleted,
broadcastChatMessageUpdated,
broadcastCommentLikeUpdate,
broadcastPresence,
broadcastTyping,
broadcastVoteUpdate,
getOnlineUsers,
handleClientPong,
isUserChatOpen,
type RateLimit,
register,
sendToUser,
setClientTyping,
takeToken,
unregister,
type WsClient,
} from "../services/ws-service.ts";
import {
createChatMessage,
deleteChatMessage,
getChatReadState,
markChatRead,
updateChatMessage,
} from "../services/chat-service.ts";
import {
getUnreadCount,
notifyMentions,
} from "../services/notification-service.ts";
import { hasPermission } from "../../shared/permissions.ts";
import {
castVote,
getUserVotes,
removeVote,
} from "../services/vote-service.ts";
import {
castCommentLike,
getUserCommentLikes,
removeCommentLike,
} from "../services/comment-like-service.ts";
import { getUserById } from "../services/user-service.ts";
import { APIException } from "../lib/api-exception.ts";
import type {
ClientToServerMessage,
ServerToClientMessage,
} from "../../shared/ws.ts";
import type { User } from "../model/user.ts";
/**
* Mounted by `api/main.ts` behind the error, Open Graph and CORS middleware.
* An `APIException` thrown by a handler becomes the JSON error response there.
*/
const router: Router = new Router();
/**
* Checks whether a socket may be opened from `origin`. Browsers don't apply
* CORS to WebSockets, so this is what stops another site from opening one with
* its visitors' tokens.
*/
function isAllowedOrigin(origin: string): boolean {
return ALLOWED_ORIGINS.includes(origin);
}
router.get("/ws", async (ctx) => {
const origin = ctx.request.headers.get("origin") ?? "";
if (!isAllowedOrigin(origin)) {
ctx.response.status = 403;
return;
}
if (!ctx.isUpgradable) {
ctx.response.status = 426;
return;
}
// A revoked token (deleted user, changed password) opens an anonymous
// socket. The client signs out on its next API call, which gets a 401.
const token = ctx.request.url.searchParams.get("token");
const authPayload = token ? await authenticate(token) : null;
let user: User | undefined;
try {
user = authPayload ? getUserById(authPayload.userId) : undefined;
} catch {
user = undefined;
}
const socket = ctx.upgrade();
const client: WsClient = {
socket,
userId: user?.id,
username: user?.username,
role: user?.role,
avatarMime: user?.avatarMime,
};
// addEventListener, since `onopen =` proved unreliable under Deno.serve.
socket.addEventListener("open", () => {
register(client);
// The new socket is registered, so it gets this presence_update too,
// before its welcome.
broadcastPresence();
try {
const myVotes = user ? getUserVotes(user.id) : [];
const myCommentLikes = user ? getUserCommentLikes(user.id) : [];
const unreadNotificationCount = user ? getUnreadCount(user.id) : 0;
const chatRead = user ? getChatReadState(user.id) : undefined;
socket.send(JSON.stringify({
type: "welcome",
users: getOnlineUsers(),
myVotes,
myCommentLikes,
unreadNotificationCount,
chatReadAt: chatRead?.readAt,
unreadChatCount: chatRead?.unread ?? 0,
}));
} catch (err) {
console.error("[ws] welcome send failed:", err);
}
});
socket.addEventListener("message", (event) => {
// An exception escaping a WebSocket listener is uncaught in Deno and ends
// the process, so nothing a client sends may throw out of here.
try {
handleMessage(client, event.data);
} catch (err) {
console.error("[ws] message handler failed:", err);
}
});
socket.addEventListener("close", () => {
unregister(client);
broadcastPresence();
// The sweep only sees registered clients, so it would never clear this one.
if (client.typingAt) broadcastTyping();
});
});
/**
* Parses one message from a client and dispatches it by `type`. A message that
* isn't JSON, or whose `type` is unknown, is ignored. Its fields are still
* untrusted, so each handler checks their types.
*/
function handleMessage(client: WsClient, data: unknown): void {
if (typeof data !== "string") return;
let parsed: unknown;
try {
parsed = JSON.parse(data);
} catch {
return;
}
if (
typeof parsed !== "object" || parsed === null ||
typeof (parsed as { type?: unknown }).type !== "string"
) return;
const msg = parsed as ClientToServerMessage;
const { socket } = client;
switch (msg.type) {
case "ping":
send(socket, { type: "pong" });
break;
case "pong":
handleClientPong(client);
break;
case "vote_cast":
handleVote(client, msg.dumpId, "cast");
break;
case "vote_remove":
handleVote(client, msg.dumpId, "remove");
break;
case "comment_like_cast":
handleCommentLike(client, msg.commentId, "cast");
break;
case "comment_like_remove":
handleCommentLike(client, msg.commentId, "remove");
break;
case "chat_send":
handleChatSend(client, msg.body, msg.replyToId, msg.nonce);
break;
case "chat_typing":
// Typing is cosmetic: past the limit it's dropped, with no error.
if (
client.userId &&
takeToken(`typing:${client.userId}`, TYPING_LIMIT)
) {
setClientTyping(client, msg.typing === true);
}
break;
case "chat_focus":
client.chatOpen = msg.open === true;
break;
case "chat_edit":
handleChatEdit(client, msg.id, msg.body);
break;
case "chat_delete":
handleChatDelete(client, msg.id);
break;
case "chat_read":
handleChatRead(client, msg.at);
break;
}
}
/** Sends `data` unless the socket is closing, where `send` would throw. */
function send(socket: WebSocket, data: ServerToClientMessage): void {
if (socket.readyState === WebSocket.OPEN) socket.send(JSON.stringify(data));
}
/**
* Handles `vote_cast` and `vote_remove`. It acks the voter with `vote_ack` and
* broadcasts `votes_update`. A failure goes back as an `error` naming the dump
* and the action, so the client can undo its optimistic vote at once.
*/
function handleVote(
client: WsClient,
dumpId: unknown,
action: "cast" | "remove",
): void {
const { socket } = client;
if (!client.userId) {
send(socket, { type: "error", message: "Authentication required" });
return;
}
if (typeof dumpId !== "string") return;
try {
const { voteCount, isPrivate } = action === "cast"
? castVote(dumpId, client.userId)
: removeVote(dumpId, client.userId);
send(socket, {
type: "vote_ack",
dumpId,
action,
voteCount,
});
// Only a private dump's owner can see it, and so vote on it.
broadcastVoteUpdate(
dumpId,
voteCount,
client.userId,
action,
isPrivate ? client.userId : undefined,
);
} catch (err) {
const message = err instanceof APIException ? err.message : "Vote failed";
send(socket, { type: "error", message, dumpId, action });
}
}
/**
* Handles `comment_like_cast` and `comment_like_remove`, as
* {@link handleVote} does votes.
*/
function handleCommentLike(
client: WsClient,
commentId: unknown,
action: "cast" | "remove",
): void {
const { socket } = client;
if (!client.userId) {
send(socket, { type: "error", message: "Authentication required" });
return;
}
if (typeof commentId !== "string") return;
try {
const { likeCount, isPrivate } = action === "cast"
? castCommentLike(commentId, client.userId)
: removeCommentLike(commentId, client.userId);
send(socket, {
type: "comment_like_ack",
commentId,
action,
likeCount,
});
broadcastCommentLikeUpdate(
commentId,
likeCount,
client.userId,
action,
isPrivate ? client.userId : undefined,
);
} catch (err) {
const message = err instanceof APIException ? err.message : "Like failed";
send(socket, { type: "error", message, commentId, action });
}
}
/**
* Limits each user's chat writes, sends, edits and deletes together, to a burst
* of 8, then one every 1.5 s. The buckets are per user, so more tabs don't buy
* more.
*/
const CHAT_WRITE_LIMIT: RateLimit = { capacity: 8, refill: 1 / 1.5 };
const TYPING_LIMIT: RateLimit = { capacity: 10, refill: 1 };
/**
* Limits each user's `chat_read`. One over the limit is dropped, and the next
* one catches up, since a marker only moves forward.
*/
const CHAT_READ_LIMIT: RateLimit = { capacity: 10, refill: 1 };
/**
* Sends a chat-scoped `error`. With the `nonce` of a `chat_send`, the chatbox
* marks that pending message failed. Without one, it shows `message` as a
* notice.
*/
function sendChatError(
client: WsClient,
message: string,
nonce?: string,
): void {
send(client.socket, { type: "error", scope: "chat", message, nonce });
}
/**
* Returns the id of the user behind a chat write, or undefined after sending
* the error when they are signed out or over {@link CHAT_WRITE_LIMIT}.
*/
function chatWriter(client: WsClient, nonce?: string): string | undefined {
if (!client.userId) {
sendChatError(client, "Authentication required", nonce);
return undefined;
}
if (!takeToken(`chat:${client.userId}`, CHAT_WRITE_LIMIT)) {
sendChatError(
client,
"You're sending messages too fast — wait a moment",
nonce,
);
return undefined;
}
return client.userId;
}
/**
* Returns `value` when it is a string of at most `maxLength`, else undefined.
*/
function optionalString(value: unknown, maxLength: number): string | undefined {
return typeof value === "string" && value.length <= maxLength
? value
: undefined;
}
/**
* Handles `chat_send`. It stores the message, broadcasts it, and notifies the
* @mentioned users who aren't reading the chat.
*/
function handleChatSend(
client: WsClient,
body: unknown,
replyToId: unknown,
rawNonce: unknown,
): void {
const nonce = optionalString(rawNonce, 64);
const userId = chatWriter(client, nonce);
if (!userId) return;
if (typeof body !== "string") {
sendChatError(client, "Message cannot be empty", nonce);
return;
}
try {
const message = createChatMessage(
userId,
body,
optionalString(replyToId, 64),
);
// Before the broadcast, so the typing indicator doesn't linger beside the
// message.
setClientTyping(client, false);
broadcastChatMessage(message, nonce);
notifyMentions(
userId,
message.body,
"chat",
message.id,
"",
undefined,
isUserChatOpen,
);
} catch (err) {
sendChatError(
client,
err instanceof APIException ? err.message : "Failed to send message",
nonce,
);
}
}
/**
* Checks whether the client's user may edit and delete others' chat messages.
* The role is read from the database, not from the socket's connect, so that a
* demoted moderator loses the right at once.
*/
function canModerateChat(client: WsClient): boolean {
if (!client.userId) return false;
try {
client.role = getUserById(client.userId).role;
} catch {
client.role = undefined;
}
return !!client.role && hasPermission(client.role, "chat:moderate");
}
/**
* Handles `chat_edit`. It stores the new body, broadcasts it, and notifies, in
* the author's name, the users the edit newly mentions.
*/
function handleChatEdit(client: WsClient, id: unknown, body: unknown): void {
const userId = chatWriter(client);
if (!userId) return;
if (typeof id !== "string" || typeof body !== "string") {
sendChatError(client, "Invalid message");
return;
}
try {
const message = updateChatMessage(
id,
body,
userId,
canModerateChat(client),
);
broadcastChatMessageUpdated(message);
// Mentions already notified for this message are deduplicated, so only
// the new ones notify. A moderator's edit keeps the author's words, so the
// author mentions.
notifyMentions(
message.userId,
message.body,
"chat",
message.id,
"",
undefined,
isUserChatOpen,
);
} catch (err) {
sendChatError(
client,
err instanceof APIException ? err.message : "Failed to edit message",
);
}
}
/** Handles `chat_delete`. It deletes the message and broadcasts its id. */
function handleChatDelete(client: WsClient, id: unknown): void {
const userId = chatWriter(client);
if (!userId) return;
if (typeof id !== "string") {
sendChatError(client, "Invalid message");
return;
}
try {
deleteChatMessage(id, userId, canModerateChat(client));
broadcastChatMessageDeleted(id);
} catch (err) {
sendChatError(
client,
err instanceof APIException ? err.message : "Failed to delete message",
);
}
}
/**
* Handles `chat_read`. It moves the user's read marker and sends
* `chat_read_update` to all their sockets, so every tab and device updates its
* badge together.
*/
function handleChatRead(client: WsClient, at: unknown): void {
if (!client.userId || typeof at !== "string") return;
if (!takeToken(`read:${client.userId}`, CHAT_READ_LIMIT)) return;
try {
const state = markChatRead(client.userId, at);
sendToUser(client.userId, {
type: "chat_read_update",
readAt: state.readAt,
unread: state.unread,
});
} catch {
// A malformed marker changes nothing, and the client doesn't wait for an
// answer.
}
}
export default router;