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>
This commit is contained in:
khannurien
2026-09-29 15:19:07 +00:00
parent 0d4e344d77
commit 14e3ab125b
69 changed files with 1011 additions and 1069 deletions

View File

@@ -7,7 +7,6 @@
* @module
*/
import { APIErrorCode } from "../../shared/api.ts";
import { APIException } from "../lib/api-exception.ts";
import type {
CreatePlaylistRequest,
@@ -63,15 +62,15 @@ export function getPlaylistById(idOrSlug: string): Playlist {
? db.prepare(`SELECT ${PLAYLIST_SELECT} WHERE p.id = ?;`).get(idOrSlug)
: db.prepare(`SELECT ${PLAYLIST_SELECT} WHERE p.slug = ?;`).get(idOrSlug);
if (!row || !isPlaylistRow(row)) {
throw new APIException(APIErrorCode.NOT_FOUND, 404, "Playlist not found");
throw new APIException(404, "Playlist not found");
}
return playlistRowToApi(row);
}
/**
* Creates a playlist owned by `userId`, for `POST /api/playlists`. It notifies
* the users its description mentions, links the attachments it embeds, and
* broadcasts `playlist_created`.
* Creates a playlist owned by `userId`, for `POST /api/playlists`. If it is
* public, it notifies the users its description mentions. It links the
* attachments the description embeds and broadcasts `playlist_created`.
*/
export function createPlaylist(
req: CreatePlaylistRequest,
@@ -102,8 +101,11 @@ export function createPlaylist(
createdAt,
};
if (req.description) {
notifyMentions(userId, req.description, "playlist", id, req.title);
linkAttachments(req.description, id);
// A private playlist's mentions are notified if it goes public.
if (req.isPublic) {
notifyMentions(userId, req.description, "playlist", id, req.title);
}
linkAttachments(req.description, "playlist", id);
}
broadcastPlaylistCreated(playlist);
return playlist;
@@ -124,7 +126,7 @@ export function getPlaylist(
const playlist = getPlaylistById(playlistId);
if (!playlist.isPublic && requestingUserId !== playlist.userId) {
throw new APIException(APIErrorCode.NOT_FOUND, 404, "Playlist not found");
throw new APIException(404, "Playlist not found");
}
const rows = db.prepare(
@@ -195,8 +197,9 @@ export function listPlaylistsByUser(
/**
* Applies `req` to a playlist for `PUT /api/playlists/:playlistId`, and returns
* it as it now is. The slug follows the title. `canModerate` lets someone
* other than the owner edit it. It notifies the users the description
* mentions, links its attachments and broadcasts `playlist_updated`.
* other than the owner edit it. If the playlist is public, it notifies, in the
* owner's name, the users the description mentions. It links the description's
* attachments and broadcasts `playlist_updated`.
*
* @throws {APIException} 404 when there is no such playlist, 403 when the user
* is neither its owner nor a moderator.
@@ -210,7 +213,7 @@ export function updatePlaylist(
const playlist = getPlaylistById(playlistId);
if (playlist.userId !== requestingUserId && !canModerate) {
throw new APIException(APIErrorCode.UNAUTHORIZED, 403, "Forbidden");
throw new APIException(403, "Forbidden");
}
const newTitle = req.title ?? playlist.title;
@@ -243,14 +246,16 @@ export function updatePlaylist(
updatedAt: now,
};
if (newDescription) {
notifyMentions(
requestingUserId,
newDescription,
"playlist",
playlist.id,
newTitle,
);
linkAttachments(newDescription, playlist.id);
if (newIsPublic) {
notifyMentions(
playlist.userId,
newDescription,
"playlist",
playlist.id,
newTitle,
);
}
linkAttachments(newDescription, "playlist", playlist.id);
}
broadcastPlaylistUpdated(updated, playlist.isPublic);
return updated;
@@ -271,7 +276,7 @@ export function deletePlaylist(
const playlist = getPlaylistById(playlistId);
if (playlist.userId !== requestingUserId && !canModerate) {
throw new APIException(APIErrorCode.UNAUTHORIZED, 403, "Forbidden");
throw new APIException(403, "Forbidden");
}
db.prepare(`DELETE FROM playlists WHERE id = ?;`).run(playlist.id);
@@ -293,7 +298,7 @@ export function getEditablePlaylist(
): Playlist {
const playlist = getPlaylistById(playlistId);
if (playlist.userId !== requestingUserId && !canModerate) {
throw new APIException(APIErrorCode.UNAUTHORIZED, 403, "Forbidden");
throw new APIException(403, "Forbidden");
}
return playlist;
}
@@ -347,7 +352,7 @@ export function addDumpToPlaylist(
const playlist = getPlaylistById(playlistId);
if (playlist.userId !== requestingUserId && !canModerate) {
throw new APIException(APIErrorCode.UNAUTHORIZED, 403, "Forbidden");
throw new APIException(403, "Forbidden");
}
// Else someone else's private dump would land in the playlist, and its title
@@ -358,7 +363,7 @@ export function addDumpToPlaylist(
| { title: string; is_private: number; user_id: string }
| undefined;
if (!dump || (dump.is_private && dump.user_id !== requestingUserId)) {
throw new APIException(APIErrorCode.NOT_FOUND, 404, "Dump not found");
throw new APIException(404, "Dump not found");
}
const minRow = db.prepare(
@@ -376,11 +381,7 @@ export function addDumpToPlaylist(
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
if (msg.includes("UNIQUE") || msg.includes("unique")) {
throw new APIException(
APIErrorCode.VALIDATION_ERROR,
409,
"Dump already in playlist",
);
throw new APIException(409, "Dump already in playlist");
}
throw err;
}
@@ -415,7 +416,7 @@ export function removeDumpFromPlaylist(
const playlist = getPlaylistById(playlistId);
if (playlist.userId !== requestingUserId && !canModerate) {
throw new APIException(APIErrorCode.UNAUTHORIZED, 403, "Forbidden");
throw new APIException(403, "Forbidden");
}
db.prepare(
@@ -443,7 +444,7 @@ export function reorderPlaylist(
const playlist = getPlaylistById(playlistId);
if (playlist.userId !== requestingUserId && !canModerate) {
throw new APIException(APIErrorCode.UNAUTHORIZED, 403, "Forbidden");
throw new APIException(403, "Forbidden");
}
// The requester can only name the dumps GET showed them. A hidden one
@@ -461,7 +462,6 @@ export function reorderPlaylist(
!visibleIds.every((id) => newSet.has(id))
) {
throw new APIException(
APIErrorCode.BAD_REQUEST,
400,
"dumpIds must match current playlist members exactly",
);
@@ -504,11 +504,7 @@ export function getPlaylistMembershipsForDump(
return rows.map((row) => {
if (!isPlaylistRow(row)) {
throw new APIException(
APIErrorCode.SERVER_ERROR,
500,
"Malformed playlist data",
);
throw new APIException(500, "Malformed playlist data");
}
return {
playlist: playlistRowToApi(row),
@@ -551,7 +547,7 @@ export function getPlaylistImageInfo(
): { id: string; imageMime: string; isPublic: boolean } | undefined {
const playlist = getPlaylistById(idOrSlug);
if (!playlist.isPublic && requestingUserId !== playlist.userId) {
throw new APIException(APIErrorCode.NOT_FOUND, 404, "Playlist not found");
throw new APIException(404, "Playlist not found");
}
return playlist.imageMime
? {