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 @@
*/
import { db, transaction } from "../db/connection.ts";
import { APIErrorCode } from "../../shared/api.ts";
import { APIException } from "../lib/api-exception.ts";
/**
@@ -21,45 +20,112 @@ export function createAttachment(id: string, mime: string): void {
).run(id, mime, new Date().toISOString());
}
/** The kinds of resource whose saved text can link an attachment. */
export type AttachmentResourceType =
| "dump"
| "comment"
| "playlist"
| "chat"
| "user";
/**
* Returns attachment `attachmentId`'s MIME type, for
* `GET /api/attachments/:attachmentId` to serve its file with.
*
* @throws {APIException} 404 when there is no such attachment.
* Returned to `GET /api/attachments/:attachmentId` by
* {@link getAttachmentAccess}. `ownerId` is set when only that user may see
* the image, because the resource linking it is private.
*/
export function getAttachment(attachmentId: string): { mime: string } {
export interface AttachmentAccess {
mime: string;
ownerId?: string;
}
/**
* Returns attachment `attachmentId`'s type and who may see it. An attachment
* nothing links yet is public, so the editor can show it before the text is
* saved; its id is unguessable. One linked by a private dump or playlist, or
* by a comment on a private dump, is its owner's.
*
* @throws {APIException} 404 when there is no such attachment, or when the
* resource linking it has been deleted.
*/
export function getAttachmentAccess(attachmentId: string): AttachmentAccess {
const row = db.prepare(
"SELECT mime FROM attachments WHERE id = ?",
).get(attachmentId) as { mime: string } | undefined;
"SELECT mime, resource_type, resource_id FROM attachments WHERE id = ?",
).get(attachmentId) as
| { mime: string; resource_type: string | null; resource_id: string | null }
| undefined;
if (!row) throw new APIException(404, "Attachment not found");
if (!row.resource_id) return { mime: row.mime };
if (!row) {
throw new APIException(
APIErrorCode.NOT_FOUND,
404,
"Attachment not found",
);
const owner = resourceOwner(row.resource_type, row.resource_id);
if (owner === undefined) {
throw new APIException(404, "Attachment not found");
}
return owner ? { mime: row.mime, ownerId: owner } : { mime: row.mime };
}
return { mime: row.mime };
/**
* Returns the owner of a private resource, null for a public one, and
* undefined for one that no longer exists.
*/
function resourceOwner(
type: string | null,
id: string,
): string | null | undefined {
switch (type) {
case "dump": {
const dump = db.prepare(
"SELECT user_id, is_private FROM dumps WHERE id = ?",
).get(id) as { user_id: string; is_private: number } | undefined;
return dump && (dump.is_private ? dump.user_id : null);
}
case "comment": {
const comment = db.prepare(
`SELECT d.user_id, d.is_private FROM comments c
JOIN dumps d ON d.id = c.dump_id WHERE c.id = ? AND c.deleted = 0`,
).get(id) as { user_id: string; is_private: number } | undefined;
return comment && (comment.is_private ? comment.user_id : null);
}
case "playlist": {
const playlist = db.prepare(
"SELECT user_id, is_public FROM playlists WHERE id = ?",
).get(id) as { user_id: string; is_public: number } | undefined;
return playlist && (playlist.is_public ? null : playlist.user_id);
}
case "chat":
return db.prepare("SELECT 1 FROM chat_messages WHERE id = ?").get(id)
? null
: undefined;
case "user":
return db.prepare("SELECT 1 FROM users WHERE id = ?").get(id)
? null
: undefined;
default:
return undefined;
}
}
const ATTACHMENT_RE =
/\/api\/attachments\/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/g;
/**
* Binds the attachments whose URLs appear in `text` to `resourceId`, so the
* startup purge keeps them. It is called whenever a dump, comment, chat
* message, playlist or profile description is saved. An attachment already
* bound stays with its resource, so pasting another's URL claims nothing, and
* removing the link from a body never unbinds it.
* Binds the attachments whose URLs appear in `text` to the resource that saved
* it, so the startup purge keeps them as long as that resource exists, and
* they are seen by whoever may see it. It is called whenever a dump, comment,
* chat message, playlist or profile description is saved. An attachment
* already bound stays with its resource, so pasting another's URL claims
* nothing, and removing the link from a body never unbinds it.
*/
export function linkAttachments(text: string, resourceId: string): void {
export function linkAttachments(
text: string,
resourceType: AttachmentResourceType,
resourceId: string,
): void {
const ids = [...text.matchAll(ATTACHMENT_RE)].map((m) => m[1]);
if (ids.length === 0) return;
const update = db.prepare(
"UPDATE attachments SET resource_id = ? WHERE id = ? AND resource_id IS NULL",
"UPDATE attachments SET resource_type = ?, resource_id = ? WHERE id = ? AND resource_id IS NULL",
);
transaction(() => {
for (const id of ids) update.run(resourceId, id);
for (const id of ids) update.run(resourceType, resourceId, id);
});
}

View File

@@ -6,7 +6,6 @@
* @module
*/
import { APIErrorCode } from "../../shared/api.ts";
import { APIException } from "../lib/api-exception.ts";
import type {
Category,
@@ -32,35 +31,28 @@ import { VALIDATION } from "../../shared/validation.ts";
function validateSlug(slug: string): void {
if (!isValidSlugFormat(slug)) {
throw new APIException(
APIErrorCode.BAD_REQUEST,
400,
"Slug must be lowercase letters, numbers and hyphens",
);
}
if (slug.length > VALIDATION.CATEGORY_SLUG_MAX) {
throw new APIException(
APIErrorCode.BAD_REQUEST,
400,
`Slug must be at most ${VALIDATION.CATEGORY_SLUG_MAX} characters`,
);
}
if (isReservedSlug(slug)) {
throw new APIException(
APIErrorCode.BAD_REQUEST,
400,
`Slug "${slug}" is reserved`,
);
throw new APIException(400, `Slug "${slug}" is reserved`);
}
}
function requireName(name: string): string {
const trimmed = name.trim();
if (!trimmed) {
throw new APIException(APIErrorCode.BAD_REQUEST, 400, "Name is required");
throw new APIException(400, "Name is required");
}
if (trimmed.length > VALIDATION.CATEGORY_NAME_MAX) {
throw new APIException(
APIErrorCode.BAD_REQUEST,
400,
`Name must be at most ${VALIDATION.CATEGORY_NAME_MAX} characters`,
);
@@ -76,18 +68,10 @@ function requireName(name: string): string {
function uniqueConflict(err: unknown, slug: string, name: string): never {
const msg = err instanceof Error ? err.message : String(err);
if (msg.includes("categories.name")) {
throw new APIException(
APIErrorCode.VALIDATION_ERROR,
409,
`Name "${name}" is already in use`,
);
throw new APIException(409, `Name "${name}" is already in use`);
}
if (msg.includes("UNIQUE") || msg.includes("unique")) {
throw new APIException(
APIErrorCode.VALIDATION_ERROR,
409,
`Slug "${slug}" is already in use`,
);
throw new APIException(409, `Slug "${slug}" is already in use`);
}
throw err as Error;
}
@@ -100,7 +84,7 @@ function uniqueConflict(err: unknown, slug: string, name: string): never {
export function getCategoryById(id: string): Category {
const row = db.prepare(`SELECT * FROM categories WHERE id = ?;`).get(id);
if (!row || !isCategoryRow(row)) {
throw new APIException(APIErrorCode.NOT_FOUND, 404, "Category not found");
throw new APIException(404, "Category not found");
}
return categoryRowToApi(row);
}
@@ -113,7 +97,7 @@ export function getCategoryById(id: string): Category {
export function getCategoryBySlug(slug: string): Category {
const row = db.prepare(`SELECT * FROM categories WHERE slug = ?;`).get(slug);
if (!row || !isCategoryRow(row)) {
throw new APIException(APIErrorCode.NOT_FOUND, 404, "Category not found");
throw new APIException(404, "Category not found");
}
return categoryRowToApi(row);
}
@@ -231,7 +215,7 @@ export function updateCategory(
export function deleteCategory(id: string): void {
const result = db.prepare(`DELETE FROM categories WHERE id = ?;`).run(id);
if (result.changes === 0) {
throw new APIException(APIErrorCode.NOT_FOUND, 404, "Category not found");
throw new APIException(404, "Category not found");
}
}
@@ -251,11 +235,7 @@ export function assertCategoriesExist(categoryIds: string[]): void {
`SELECT COUNT(*) as count FROM categories WHERE id IN (${placeholders});`,
).get(...unique) as { count: number } | undefined;
if ((found?.count ?? 0) !== unique.length) {
throw new APIException(
APIErrorCode.BAD_REQUEST,
400,
"One or more categories do not exist",
);
throw new APIException(400, "One or more categories do not exist");
}
}
}

View File

@@ -8,7 +8,6 @@
* @module
*/
import { APIErrorCode } from "../../shared/api.ts";
import { APIException } from "../lib/api-exception.ts";
import type { ChatMessage } from "../../shared/chat.ts";
import { chatMessageRowToApi, isChatMessageRow } from "../model/chat.ts";
@@ -47,7 +46,7 @@ function fetchMessage(id: string): ChatMessage {
`SELECT ${SELECT_COLS} ${FROM_JOINS} WHERE m.id = ?;`,
).get(id);
if (!row || !isChatMessageRow(row)) {
throw new APIException(APIErrorCode.NOT_FOUND, 404, "Message not found");
throw new APIException(404, "Message not found");
}
return chatMessageRowToApi(row);
}
@@ -67,15 +66,10 @@ export function createChatMessage(
): ChatMessage {
const trimmed = body.trim();
if (!trimmed) {
throw new APIException(
APIErrorCode.VALIDATION_ERROR,
400,
"Message cannot be empty",
);
throw new APIException(400, "Message cannot be empty");
}
if (trimmed.length > VALIDATION.CHAT_MESSAGE_MAX) {
throw new APIException(
APIErrorCode.VALIDATION_ERROR,
400,
`Message exceeds ${VALIDATION.CHAT_MESSAGE_MAX} characters`,
);
@@ -93,7 +87,7 @@ export function createChatMessage(
`INSERT INTO chat_messages (id, user_id, body, created_at, reply_to_id) VALUES (?, ?, ?, ?, ?);`,
).run(id, userId, trimmed, createdAt, replyTo);
// Unclaimed attachments are deleted as orphans at startup.
linkAttachments(trimmed, id);
linkAttachments(trimmed, "chat", id);
return fetchMessage(id);
}
@@ -103,7 +97,7 @@ function getMessageOwner(id: string): string {
id,
) as { user_id: string } | undefined;
if (!row) {
throw new APIException(APIErrorCode.NOT_FOUND, 404, "Message not found");
throw new APIException(404, "Message not found");
}
return row.user_id;
}
@@ -113,7 +107,7 @@ function getMessageOwner(id: string): string {
* links to. `canModerate` lets a moderator edit anyone's message. The caller
* broadcasts the result.
*
* @throws {APIException} 404 when there is no such message, 401 when the user
* @throws {APIException} 404 when there is no such message, 403 when the user
* is neither its author nor a moderator, 400 when the body is blank or too
* long.
*/
@@ -125,30 +119,21 @@ export function updateChatMessage(
): ChatMessage {
const ownerId = getMessageOwner(id);
if (ownerId !== requestingUserId && !canModerate) {
throw new APIException(
APIErrorCode.UNAUTHORIZED,
401,
"Not authorized to edit this message",
);
throw new APIException(403, "Not authorized to edit this message");
}
const trimmed = body.trim();
if (!trimmed) {
throw new APIException(
APIErrorCode.VALIDATION_ERROR,
400,
"Message cannot be empty",
);
throw new APIException(400, "Message cannot be empty");
}
if (trimmed.length > VALIDATION.CHAT_MESSAGE_MAX) {
throw new APIException(
APIErrorCode.VALIDATION_ERROR,
400,
`Message exceeds ${VALIDATION.CHAT_MESSAGE_MAX} characters`,
);
}
db.prepare(`UPDATE chat_messages SET body = ?, updated_at = ? WHERE id = ?;`)
.run(trimmed, new Date().toISOString(), id);
linkAttachments(trimmed, id);
linkAttachments(trimmed, "chat", id);
return fetchMessage(id);
}
@@ -156,7 +141,7 @@ export function updateChatMessage(
* Deletes a message on a `chat_delete`. `canModerate` lets a moderator delete
* anyone's message. Replies to it keep their `replyToId`, without its preview.
*
* @throws {APIException} 404 when there is no such message, 401 when the user
* @throws {APIException} 404 when there is no such message, 403 when the user
* is neither its author nor a moderator.
*/
export function deleteChatMessage(
@@ -166,11 +151,7 @@ export function deleteChatMessage(
): void {
const ownerId = getMessageOwner(id);
if (ownerId !== requestingUserId && !canModerate) {
throw new APIException(
APIErrorCode.UNAUTHORIZED,
401,
"Not authorized to delete this message",
);
throw new APIException(403, "Not authorized to delete this message");
}
db.prepare(`DELETE FROM chat_messages WHERE id = ?;`).run(id);
}
@@ -195,11 +176,7 @@ export interface ChatCursor {
/** Converts query rows to messages, or throws a 500 if one doesn't parse. */
function toMessages(rows: unknown[]): ChatMessage[] {
if (!rows.every(isChatMessageRow)) {
throw new APIException(
APIErrorCode.SERVER_ERROR,
500,
"Malformed chat message data",
);
throw new APIException(500, "Malformed chat message data");
}
return rows.map(chatMessageRowToApi);
}
@@ -284,7 +261,7 @@ export function getChatReadState(userId: string): ChatReadState {
FROM users u WHERE u.id = ?;`,
).get(userId) as { read_at: string; unread: number } | undefined;
if (!row) {
throw new APIException(APIErrorCode.NOT_FOUND, 404, "User not found");
throw new APIException(404, "User not found");
}
return { readAt: row.read_at, unread: row.unread };
}
@@ -301,11 +278,7 @@ export function getChatReadState(userId: string): ChatReadState {
export function markChatRead(userId: string, at: string): ChatReadState {
const parsed = new Date(at);
if (Number.isNaN(parsed.getTime())) {
throw new APIException(
APIErrorCode.VALIDATION_ERROR,
400,
"Invalid read marker",
);
throw new APIException(400, "Invalid read marker");
}
const newest = db.prepare(
`SELECT MAX(created_at) AS newest FROM chat_messages;`,

View File

@@ -8,7 +8,6 @@
* @module
*/
import { APIErrorCode } from "../../shared/api.ts";
import { APIException } from "../lib/api-exception.ts";
import { isUserRow, type User, userRowToApi } from "../model/user.ts";
import { db } from "../db/connection.ts";
@@ -36,7 +35,7 @@ function commentVisibility(commentId: string, userId: string): boolean {
WHERE c.id = ?;`,
).get(commentId) as { is_private: number; user_id: string } | undefined;
if (!row || (row.is_private && row.user_id !== userId)) {
throw new APIException(APIErrorCode.NOT_FOUND, 404, "Comment not found");
throw new APIException(404, "Comment not found");
}
return Boolean(row.is_private);
}
@@ -72,11 +71,7 @@ export function castCommentLike(
db.exec("ROLLBACK;");
} catch { /* ignore if no active transaction */ }
if (err instanceof Error && err.message.includes("UNIQUE constraint")) {
throw new APIException(
APIErrorCode.VALIDATION_ERROR,
409,
"Already liked",
);
throw new APIException(409, "Already liked");
}
throw err;
}
@@ -110,7 +105,7 @@ export function removeCommentLike(
).run(commentId, userId);
if (result.changes === 0) {
db.exec("ROLLBACK;");
throw new APIException(APIErrorCode.NOT_FOUND, 404, "Like not found");
throw new APIException(404, "Like not found");
}
db.prepare(
`UPDATE comments SET like_count = like_count - 1 WHERE id = ?;`,
@@ -165,11 +160,7 @@ export function getCommentLikers(
).all(commentId, limit + 1, offset);
if (!rawRows.every(isUserRow)) {
throw new APIException(
APIErrorCode.SERVER_ERROR,
500,
"Malformed user data",
);
throw new APIException(500, "Malformed user data");
}
return pageOf(rawRows.map(userRowToApi), limit);

View File

@@ -6,7 +6,6 @@
* @module
*/
import { APIErrorCode } from "../../shared/api.ts";
import { APIException } from "../lib/api-exception.ts";
import type { Comment } from "../../shared/comment.ts";
import { type SQLOutputValue } from "node:sqlite";
@@ -29,14 +28,10 @@ function fetchComment(commentId: string): Comment {
`SELECT ${SELECT_COLS} FROM comments c JOIN users u ON c.user_id = u.id WHERE c.id = ?;`,
).get(commentId);
if (!row || !isCommentRow(row as Record<string, SQLOutputValue>)) {
throw new APIException(APIErrorCode.NOT_FOUND, 404, "Comment not found");
throw new APIException(404, "Comment not found");
}
if (!isCommentRow(row)) {
throw new APIException(
APIErrorCode.SERVER_ERROR,
500,
"Malformed comment data",
);
throw new APIException(500, "Malformed comment data");
}
return commentRowToApi(row);
}
@@ -52,7 +47,7 @@ export function getCommentDumpId(commentId: string): string {
commentId,
) as { dump_id: string } | undefined;
if (!row) {
throw new APIException(APIErrorCode.NOT_FOUND, 404, "Comment not found");
throw new APIException(404, "Comment not found");
}
return row.dump_id;
}
@@ -70,11 +65,7 @@ export function getComments(dumpId: string): Comment[] {
WHERE c.dump_id = ? ORDER BY c.created_at ASC;`,
).all(dumpId);
if (!rows.every(isCommentRow)) {
throw new APIException(
APIErrorCode.SERVER_ERROR,
500,
"Malformed comment data",
);
throw new APIException(500, "Malformed comment data");
}
return rows.map(commentRowToApi);
}
@@ -82,8 +73,11 @@ export function getComments(dumpId: string): Comment[] {
/**
* Posts a comment on dump `dumpId`, replying to `parentId` if given, for
* `POST /api/dumps/:dumpId/comments`. It notifies the dump's poster and the
* users it mentions, and links the comment's attachments and backlinks.
* `parentId` isn't checked to be a comment on the same dump.
* users it mentions, unless the dump is private, and links the comment's
* attachments and backlinks. The route has checked that the caller may see
* the dump.
*
* @throws {APIException} 400 when `parentId` isn't a comment on the same dump.
*/
export function createComment(
dumpId: string,
@@ -91,6 +85,13 @@ export function createComment(
body: string,
parentId?: string,
): Comment {
if (parentId !== undefined) {
const parent = db.prepare(`SELECT dump_id FROM comments WHERE id = ?;`)
.get(parentId) as { dump_id: string } | undefined;
if (parent?.dump_id !== dumpId) {
throw new APIException(400, "The comment replied to isn't on this dump");
}
}
const id = crypto.randomUUID();
const createdAt = new Date();
db.prepare(
@@ -104,24 +105,27 @@ export function createComment(
createdAt.toISOString(),
);
const comment = fetchComment(id);
const dumpRow = db.prepare(`SELECT title FROM dumps WHERE id = ?;`).get(
dumpId,
) as { title: string } | undefined;
const dumpRow = db.prepare(
`SELECT title, is_private FROM dumps WHERE id = ?;`,
).get(dumpId) as { title: string; is_private: number } | undefined;
notifyDumpOwnerNewComment(userId, id, dumpId);
notifyMentions(userId, body, "comment", id, dumpRow?.title ?? "", dumpId);
linkAttachments(body, id);
if (dumpRow && !dumpRow.is_private) {
notifyMentions(userId, body, "comment", id, dumpRow.title, dumpId);
}
linkAttachments(body, "comment", id);
relinkBacklinks("comment", id, dumpId, body);
return comment;
}
/**
* Replaces a comment's body, for `PATCH /api/comments/:commentId`.
* `canModerate` lets someone other than the author do it. It notifies the users
* it mentions for the first time and relinks the attachments and backlinks. The
* route broadcasts the comment unless `isPrivate`.
* `canModerate` lets someone other than the author do it. It notifies, in the
* author's name, the users it mentions for the first time, unless the dump is
* private, and relinks the attachments and backlinks. The route broadcasts the
* comment unless `isPrivate`.
*
* @throws {APIException} 404 when there is no such comment, 400 when it is
* deleted, 401 when the user is neither its author nor a moderator.
* deleted, 403 when the user is neither its author nor a moderator.
*/
export function updateComment(
commentId: string,
@@ -133,22 +137,14 @@ export function updateComment(
`SELECT c.dump_id, d.is_private FROM comments c JOIN dumps d ON c.dump_id = d.id WHERE c.id = ?;`,
).get(commentId) as { dump_id: string; is_private: number } | undefined;
if (!row) {
throw new APIException(APIErrorCode.NOT_FOUND, 404, "Comment not found");
throw new APIException(404, "Comment not found");
}
const existing = fetchComment(commentId);
if (existing.deleted) {
throw new APIException(
APIErrorCode.VALIDATION_ERROR,
400,
"Cannot edit a deleted comment",
);
throw new APIException(400, "Cannot edit a deleted comment");
}
if (existing.userId !== requestingUserId && !canModerate) {
throw new APIException(
APIErrorCode.UNAUTHORIZED,
401,
"Not authorized to edit this comment",
);
throw new APIException(403, "Not authorized to edit this comment");
}
const now = new Date().toISOString();
db.prepare(`UPDATE comments SET body = ?, updated_at = ? WHERE id = ?;`).run(
@@ -156,18 +152,21 @@ export function updateComment(
now,
commentId,
);
const dumpRow = db.prepare(`SELECT title FROM dumps WHERE id = ?;`).get(
row.dump_id,
) as { title: string } | undefined;
notifyMentions(
requestingUserId,
body,
"comment",
commentId,
dumpRow?.title ?? "",
row.dump_id,
);
linkAttachments(body, commentId);
if (!row.is_private) {
const dumpRow = db.prepare(`SELECT title FROM dumps WHERE id = ?;`).get(
row.dump_id,
) as { title: string } | undefined;
// A moderator's edit keeps the author's words, so the author mentions.
notifyMentions(
existing.userId,
body,
"comment",
commentId,
dumpRow?.title ?? "",
row.dump_id,
);
}
linkAttachments(body, "comment", commentId);
relinkBacklinks("comment", commentId, row.dump_id, body);
return {
comment: fetchComment(commentId),
@@ -182,7 +181,7 @@ export function updateComment(
* dropped, but the row stays so its replies keep their place. The route
* broadcasts the deletion unless `isPrivate`.
*
* @throws {APIException} 404 when there is no such comment, 401 when the user
* @throws {APIException} 404 when there is no such comment, 403 when the user
* is neither its author nor a moderator.
*/
export function deleteComment(
@@ -194,15 +193,11 @@ export function deleteComment(
`SELECT c.dump_id, d.is_private FROM comments c JOIN dumps d ON c.dump_id = d.id WHERE c.id = ?;`,
).get(commentId) as { dump_id: string; is_private: number } | undefined;
if (!row) {
throw new APIException(APIErrorCode.NOT_FOUND, 404, "Comment not found");
throw new APIException(404, "Comment not found");
}
const comment = fetchComment(commentId);
if (comment.userId !== requestingUserId && !canModerate) {
throw new APIException(
APIErrorCode.UNAUTHORIZED,
401,
"Not authorized to delete this comment",
);
throw new APIException(403, "Not authorized to delete this comment");
}
db.prepare(`UPDATE comments SET deleted = 1, body = '' WHERE id = ?;`).run(
commentId,

View File

@@ -9,7 +9,6 @@
* @module
*/
import { APIErrorCode } from "../../shared/api.ts";
import { APIException } from "../lib/api-exception.ts";
import type {
CreateUrlDumpRequest,
@@ -31,11 +30,7 @@ import {
tryFetchRichContent,
} from "./rich-content-service.ts";
import { isValidHttpUrl } from "../remote/fetch.ts";
import {
broadcastDumpDeleted,
broadcastDumpUpdated,
broadcastNewDump,
} from "./ws-service.ts";
import { broadcastDumpChange } from "./ws-service.ts";
import {
notifyMentions,
notifyUserFollowersNewDump,
@@ -72,14 +67,12 @@ function isAllowedMime(mime: string): boolean {
function assertFileDumpText(title?: string, comment?: string): void {
if (title && title.trim().length > VALIDATION.DUMP_TITLE_MAX) {
throw new APIException(
APIErrorCode.VALIDATION_ERROR,
400,
`Title must be at most ${VALIDATION.DUMP_TITLE_MAX} characters`,
);
}
if (comment && comment.length > VALIDATION.DUMP_COMMENT_MAX) {
throw new APIException(
APIErrorCode.VALIDATION_ERROR,
400,
`Comment must be at most ${VALIDATION.DUMP_COMMENT_MAX} characters`,
);
@@ -109,7 +102,7 @@ export async function createUrlDump(
userId: string,
): Promise<Dump> {
if (!isValidHttpUrl(request.url)) {
throw new APIException(APIErrorCode.BAD_REQUEST, 400, "Invalid URL");
throw new APIException(400, "Invalid URL");
}
assertCategoriesExist(request.categoryIds ?? []);
@@ -159,13 +152,14 @@ export async function createUrlDump(
isPrivate,
categoryIds,
};
if (!isPrivate) {
broadcastNewDump(dump);
notifyUserFollowersNewDump(userId, dumpId, title);
}
broadcastDumpChange(null, dump);
if (!isPrivate) notifyUserFollowersNewDump(userId, dumpId, title);
if (request.comment) {
notifyMentions(userId, request.comment, "dump", dumpId, title);
linkAttachments(request.comment, dumpId);
// A private dump's mentions are notified if it goes public.
if (!isPrivate) {
notifyMentions(userId, request.comment, "dump", dumpId, title);
}
linkAttachments(request.comment, "dump", dumpId);
}
relinkBacklinks("dump_comment", dumpId, dumpId, request.comment ?? "");
return dump;
@@ -189,18 +183,10 @@ export async function createFileDump(
): Promise<Dump> {
assertFileDumpText(title, comment);
if (!isAllowedMime(file.type)) {
throw new APIException(
APIErrorCode.BAD_REQUEST,
400,
`File type '${file.type}' is not allowed`,
);
throw new APIException(400, `File type '${file.type}' is not allowed`);
}
if (file.size > DUMP_MAX_FILE_SIZE_BYTES) {
throw new APIException(
APIErrorCode.BAD_REQUEST,
400,
"File too large (max 50 MB)",
);
throw new APIException(400, "File too large (max 50 MB)");
}
assertCategoriesExist(categoryIds);
@@ -257,13 +243,14 @@ export async function createFileDump(
isPrivate,
categoryIds: dedupedCategoryIds,
};
if (!isPrivate) {
broadcastNewDump(dump);
notifyUserFollowersNewDump(userId, dumpId, finalTitle);
}
broadcastDumpChange(null, dump);
if (!isPrivate) notifyUserFollowersNewDump(userId, dumpId, finalTitle);
if (comment) {
notifyMentions(userId, comment, "dump", dumpId, finalTitle);
linkAttachments(comment, dumpId);
// A private dump's mentions are notified if it goes public.
if (!isPrivate) {
notifyMentions(userId, comment, "dump", dumpId, finalTitle);
}
linkAttachments(comment, "dump", dumpId);
}
relinkBacklinks("dump_comment", dumpId, dumpId, comment ?? "");
return dump;
@@ -307,7 +294,7 @@ function fetchDump(idOrSlug: string): Dump {
idOrSlug,
);
if (!row || !isDumpRow(row)) {
throw new APIException(APIErrorCode.NOT_FOUND, 404, "Dump not found");
throw new APIException(404, "Dump not found");
}
return dumpRowToApi(row);
}
@@ -322,7 +309,7 @@ function fetchDump(idOrSlug: string): Dump {
export function getDump(dumpId: string, requestingUserId?: string): Dump {
const dump = fetchDump(dumpId);
if (dump.isPrivate && dump.userId !== requestingUserId) {
throw new APIException(APIErrorCode.NOT_FOUND, 404, "Dump not found");
throw new APIException(404, "Dump not found");
}
attachCategoryIds([dump]);
return dump;
@@ -391,11 +378,7 @@ export function listDumps(
).all(limit + 1, offset);
if (!rows || !rows.every(isDumpRow)) {
throw new APIException(
APIErrorCode.SERVER_ERROR,
500,
"Malformed dump data",
);
throw new APIException(500, "Malformed dump data");
}
const items = rows.map(dumpRowToApi);
@@ -500,19 +483,18 @@ export async function updateDump(
} else {
attachCategoryIds([updatedDump]);
}
if (updatedDump.isPrivate && !dump.isPrivate) broadcastDumpDeleted(dumpId);
else if (!updatedDump.isPrivate) broadcastDumpUpdated(updatedDump);
// Going public is an arrival for everyone who couldn't see it before.
if (dump.isPrivate && !updatedDump.isPrivate) broadcastNewDump(updatedDump);
broadcastDumpChange(dump, updatedDump);
if (updatedDump.comment) {
notifyMentions(
dump.userId,
updatedDump.comment,
"dump",
dumpId,
updatedDump.title,
);
linkAttachments(updatedDump.comment, dumpId);
if (!updatedDump.isPrivate) {
notifyMentions(
dump.userId,
updatedDump.comment,
"dump",
dumpId,
updatedDump.title,
);
}
linkAttachments(updatedDump.comment, "dump", dumpId);
}
relinkBacklinks("dump_comment", dumpId, dumpId, updatedDump.comment ?? "");
return updatedDump;
@@ -521,7 +503,7 @@ export async function updateDump(
const newUrl = request.url ?? dump.url!;
if (!isValidHttpUrl(newUrl)) {
throw new APIException(APIErrorCode.BAD_REQUEST, 400, "Invalid URL");
throw new APIException(400, "Invalid URL");
}
let { richContent, title } = dump;
@@ -567,7 +549,7 @@ export async function updateDump(
);
if (result.changes === 0) {
throw new APIException(APIErrorCode.NOT_FOUND, 404, "Dump not found");
throw new APIException(404, "Dump not found");
}
if (request.categoryIds !== undefined) {
@@ -578,19 +560,18 @@ export async function updateDump(
attachCategoryIds([updatedDump]);
}
if (updatedDump.isPrivate && !dump.isPrivate) broadcastDumpDeleted(dumpId);
else if (!updatedDump.isPrivate) broadcastDumpUpdated(updatedDump);
// Going public is an arrival for everyone who couldn't see it before.
if (dump.isPrivate && !updatedDump.isPrivate) broadcastNewDump(updatedDump);
broadcastDumpChange(dump, updatedDump);
if (updatedDump.comment) {
notifyMentions(
dump.userId,
updatedDump.comment,
"dump",
dumpId,
updatedDump.title,
);
linkAttachments(updatedDump.comment, dumpId);
if (!updatedDump.isPrivate) {
notifyMentions(
dump.userId,
updatedDump.comment,
"dump",
dumpId,
updatedDump.title,
);
}
linkAttachments(updatedDump.comment, "dump", dumpId);
}
relinkBacklinks("dump_comment", dumpId, dumpId, updatedDump.comment ?? "");
return updatedDump;
@@ -617,23 +598,15 @@ export async function replaceFileDump(
): Promise<Dump> {
assertFileDumpText(title, comment);
if (!isAllowedMime(file.type)) {
throw new APIException(
APIErrorCode.BAD_REQUEST,
400,
`File type '${file.type}' is not allowed`,
);
throw new APIException(400, `File type '${file.type}' is not allowed`);
}
if (file.size > DUMP_MAX_FILE_SIZE_BYTES) {
throw new APIException(
APIErrorCode.BAD_REQUEST,
400,
"File too large (max 50 MB)",
);
throw new APIException(400, "File too large (max 50 MB)");
}
const dump = fetchDump(dumpId);
if (dump.kind !== "file") {
throw new APIException(APIErrorCode.BAD_REQUEST, 400, "Not a file dump");
throw new APIException(400, "Not a file dump");
}
if (categoryIds !== undefined) assertCategoriesExist(categoryIds);
@@ -696,8 +669,10 @@ export async function replaceFileDump(
}
if (comment) {
notifyMentions(dump.userId, comment, "dump", dumpId, finalTitle);
linkAttachments(comment, dumpId);
if (!finalPrivate) {
notifyMentions(dump.userId, comment, "dump", dumpId, finalTitle);
}
linkAttachments(comment, "dump", dumpId);
}
relinkBacklinks("dump_comment", dumpId, dumpId, comment ?? "");
const updatedDump: Dump = {
@@ -711,9 +686,7 @@ export async function replaceFileDump(
isPrivate: finalPrivate,
updatedAt: now,
};
if (updatedDump.isPrivate && !dump.isPrivate) broadcastDumpDeleted(dumpId);
else if (!updatedDump.isPrivate) broadcastDumpUpdated(updatedDump);
if (dump.isPrivate && !updatedDump.isPrivate) broadcastNewDump(updatedDump);
broadcastDumpChange(dump, updatedDump);
return updatedDump;
}
@@ -736,11 +709,7 @@ export function getDumpsByUser(
`SELECT ${SELECT_COLS} FROM dumps WHERE user_id = ?${privacyFilter} ORDER BY created_at DESC LIMIT ? OFFSET ?;`,
).all(userId, limit + 1, offset);
if (!rows.every(isDumpRow)) {
throw new APIException(
APIErrorCode.SERVER_ERROR,
500,
"Malformed dump data",
);
throw new APIException(500, "Malformed dump data");
}
const items = rows.map(dumpRowToApi);
attachCategoryIds(items);
@@ -783,11 +752,7 @@ export function getVotedDumpsByUser(
}
if (!rows.every(isDumpRow)) {
throw new APIException(
APIErrorCode.SERVER_ERROR,
500,
"Malformed dump data",
);
throw new APIException(500, "Malformed dump data");
}
const items = rows.map(dumpRowToApi);
attachCategoryIds(items);
@@ -805,11 +770,7 @@ export async function refreshDumpMetadata(dumpId: string): Promise<Dump> {
const dump = fetchDump(dumpId);
if (dump.kind !== "url" || !dump.url) {
throw new APIException(
APIErrorCode.BAD_REQUEST,
400,
"Only URL dumps support metadata refresh",
);
throw new APIException(400, "Only URL dumps support metadata refresh");
}
// A failed fetch yields a stub with no title or thumbnail. Written over the
@@ -819,7 +780,6 @@ export async function refreshDumpMetadata(dumpId: string): Promise<Dump> {
});
if (!ok) {
throw new APIException(
APIErrorCode.SERVER_ERROR,
502,
"Could not reach the page to refresh its metadata",
);
@@ -833,7 +793,7 @@ export async function refreshDumpMetadata(dumpId: string): Promise<Dump> {
`UPDATE dumps SET title = ?, rich_content = ? WHERE id = ?;`,
).run(row.title, row.rich_content, row.id);
if (!updatedDump.isPrivate) broadcastDumpUpdated(updatedDump);
broadcastDumpChange(dump, updatedDump);
return updatedDump;
}
@@ -856,8 +816,7 @@ export function getDumpThumbnailInfo(
/**
* Records that a dump has a custom thumbnail of type `mime`, for
* `PUT /api/dumps/:dumpId/thumbnail`. The route writes the file after this
* call returns.
* `PUT /api/dumps/:dumpId/thumbnail`, once the route has written the file.
*
* @throws {APIException} 404 when there is no such dump.
*/
@@ -868,7 +827,7 @@ export function setDumpThumbnail(dumpId: string, mime: string): Dump {
dump.id,
);
const updatedDump: Dump = { ...dump, thumbnailMime: mime };
if (!updatedDump.isPrivate) broadcastDumpUpdated(updatedDump);
broadcastDumpChange(dump, updatedDump);
return updatedDump;
}
@@ -884,7 +843,7 @@ export async function removeDumpThumbnail(dumpId: string): Promise<Dump> {
.run(dump.id);
await Deno.remove(`${THUMBNAILS_DIR}/${dump.id}-custom`).catch(() => {});
const updatedDump: Dump = { ...dump, thumbnailMime: undefined };
if (!updatedDump.isPrivate) broadcastDumpUpdated(updatedDump);
broadcastDumpChange(dump, updatedDump);
return updatedDump;
}
@@ -900,7 +859,7 @@ export async function deleteDump(dumpId: string): Promise<void> {
const result = db.prepare(`DELETE FROM dumps WHERE id = ?;`).run(dumpId);
if (result.changes === 0) {
throw new APIException(APIErrorCode.NOT_FOUND, 404, "Dump not found");
throw new APIException(404, "Dump not found");
}
if (dump.kind === "file") {
@@ -911,5 +870,5 @@ export async function deleteDump(dumpId: string): Promise<void> {
await Deno.remove(`${THUMBNAILS_DIR}/${dump.id}-custom`).catch(() => {});
}
broadcastDumpDeleted(dumpId);
broadcastDumpChange(dump, null);
}

View File

@@ -6,7 +6,6 @@
* @module
*/
import { APIErrorCode } from "../../shared/api.ts";
import { APIException } from "../lib/api-exception.ts";
import type { Dump } from "../../shared/dump.ts";
import type { FollowStatus } from "../../shared/follow.ts";
@@ -35,11 +34,7 @@ import { attachCategoryIds } from "./category-service.ts";
*/
export function followUser(followerId: string, followedUserId: string): void {
if (followerId === followedUserId) {
throw new APIException(
APIErrorCode.BAD_REQUEST,
400,
"Cannot follow yourself",
);
throw new APIException(400, "Cannot follow yourself");
}
// The unique index answers "already following" without a race.
let isNew = true;
@@ -85,14 +80,10 @@ export function followPlaylist(followerId: string, playlistId: string): void {
).get(playlistId) as { id: string; is_public: number } | undefined;
if (!row) {
throw new APIException(APIErrorCode.NOT_FOUND, 404, "Playlist not found");
throw new APIException(404, "Playlist not found");
}
if (!row.is_public) {
throw new APIException(
APIErrorCode.UNAUTHORIZED,
403,
"Cannot follow a private playlist",
);
throw new APIException(403, "Cannot follow a private playlist");
}
let isNew = true;
@@ -142,11 +133,7 @@ export function getFollowStatus(followerId: string): FollowStatus {
).all(followerId);
if (!rawUserRows.every(isFollowRow) || !rawPlaylistRows.every(isFollowRow)) {
throw new APIException(
APIErrorCode.SERVER_ERROR,
500,
"Malformed follow data",
);
throw new APIException(500, "Malformed follow data");
}
return {
@@ -188,11 +175,7 @@ export function getFollowedUsersDumpFeed(
const userFeedRows = rawRows as Parameters<typeof isDumpRow>[0][];
if (!userFeedRows.every(isDumpRow)) {
throw new APIException(
APIErrorCode.SERVER_ERROR,
500,
"Malformed dump data",
);
throw new APIException(500, "Malformed dump data");
}
const items = userFeedRows.map(dumpRowToApi);
attachCategoryIds(items);
@@ -236,11 +219,7 @@ export function getFollowedPlaylistsDumpFeed(
).all(...catParams, followerId, limit + 1, offset);
if (!rawRows.every(isDumpRow)) {
throw new APIException(
APIErrorCode.SERVER_ERROR,
500,
"Malformed dump data",
);
throw new APIException(500, "Malformed dump data");
}
const items = rawRows.map(dumpRowToApi);
attachCategoryIds(items);
@@ -273,11 +252,7 @@ export function getFollowedPlaylistsByUser(
).all(userId, limit + 1, offset);
if (!rawRows.every(isPlaylistRow)) {
throw new APIException(
APIErrorCode.SERVER_ERROR,
500,
"Malformed playlist data",
);
throw new APIException(500, "Malformed playlist data");
}
return pageOf(rawRows.map(playlistRowToApi), limit);
}
@@ -309,11 +284,7 @@ export function getFollowedUsersByUser(
).all(userId, limit + 1, offset);
if (!rawRows.every(isUserRow)) {
throw new APIException(
APIErrorCode.SERVER_ERROR,
500,
"Malformed user data",
);
throw new APIException(500, "Malformed user data");
}
return pageOf(rawRows.map(userRowToApi), limit);

View File

@@ -7,7 +7,6 @@
*/
import { randomBytes } from "node:crypto";
import { APIErrorCode } from "../../shared/api.ts";
import { APIException } from "../lib/api-exception.ts";
import { db } from "../db/connection.ts";
import { isInviteRow } from "../model/invite.ts";
@@ -44,29 +43,17 @@ export function validateInvite(token: string): string {
).get(token);
if (!row || !isInviteRow(row)) {
throw new APIException(
APIErrorCode.NOT_FOUND,
404,
"Invalid or expired invite",
);
throw new APIException(404, "Invalid or expired invite");
}
if (row.used_at !== null) {
throw new APIException(
APIErrorCode.VALIDATION_ERROR,
409,
"Invite already used",
);
throw new APIException(409, "Invite already used");
}
const expiresAt = new Date(row.created_at).getTime() +
UNUSED_INVITES_RETENTION_DAYS * 24 * 60 * 60 * 1000;
if (Date.now() > expiresAt) {
throw new APIException(
APIErrorCode.NOT_FOUND,
404,
"Invalid or expired invite",
);
throw new APIException(404, "Invalid or expired invite");
}
return row.inviter_id;
@@ -86,11 +73,7 @@ export function claimInvite(token: string): string {
`UPDATE invites SET used_at = ? WHERE token = ? AND used_at IS NULL;`,
).run(new Date().toISOString(), token);
if (result.changes === 0) {
throw new APIException(
APIErrorCode.VALIDATION_ERROR,
409,
"Invite already used",
);
throw new APIException(409, "Invite already used");
}
return inviterId;
}

View File

@@ -14,7 +14,6 @@ import type {
NotificationType,
UserDumpPostedData,
} from "../../shared/notification.ts";
import { APIErrorCode } from "../../shared/api.ts";
import { APIException } from "../lib/api-exception.ts";
import { db, transaction } from "../db/connection.ts";
import {
@@ -88,11 +87,7 @@ export function getNotificationsForUser(
).all(userId, limit + 1, offset);
if (!rawRows.every(isNotificationRow)) {
throw new APIException(
APIErrorCode.SERVER_ERROR,
500,
"Malformed notification data",
);
throw new APIException(500, "Malformed notification data");
}
return pageOf(rawRows.map(notificationRowToApi), limit);
}

View File

@@ -7,7 +7,6 @@
* @module
*/
import { APIErrorCode } from "../../shared/api.ts";
import { APIException } from "../lib/api-exception.ts";
import { db } from "../db/connection.ts";
import { isPasswordResetTokenRow } from "../model/password-reset.ts";
@@ -88,7 +87,6 @@ export async function resetPassword(
newPassword.length > VALIDATION.PASSWORD_MAX
) {
throw new APIException(
APIErrorCode.VALIDATION_ERROR,
400,
`Password must be ${VALIDATION.PASSWORD_MIN}–${VALIDATION.PASSWORD_MAX} characters`,
);
@@ -96,11 +94,7 @@ export async function resetPassword(
const payload = await verifyPasswordResetToken(token);
if (!payload) {
throw new APIException(
APIErrorCode.VALIDATION_ERROR,
400,
"Invalid or expired reset link",
);
throw new APIException(400, "Invalid or expired reset link");
}
const row = db.prepare(
@@ -108,11 +102,7 @@ export async function resetPassword(
).get(token);
if (!row || !isPasswordResetTokenRow(row)) {
throw new APIException(
APIErrorCode.NOT_FOUND,
404,
"Reset token not found",
);
throw new APIException(404, "Reset token not found");
}
// Claim the link before the async hash: checking `used_at` first and
@@ -121,11 +111,7 @@ export async function resetPassword(
`UPDATE password_reset_tokens SET used_at = ? WHERE token = ? AND used_at IS NULL;`,
).run(new Date().toISOString(), token);
if (claimed.changes === 0) {
throw new APIException(
APIErrorCode.VALIDATION_ERROR,
409,
"Reset link has already been used",
);
throw new APIException(409, "Reset link has already been used");
}
try {

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
? {

View File

@@ -7,7 +7,6 @@
* @module
*/
import { APIErrorCode } from "../../shared/api.ts";
import { APIException } from "../lib/api-exception.ts";
import type {
Invitee,
@@ -27,7 +26,7 @@ import {
import { db } from "../db/connection.ts";
import { closeUserSockets, disconnectUser } from "./ws-service.ts";
import { hashPassword } from "../lib/jwt.ts";
import { hashPassword } from "../lib/password.ts";
import { linkAttachments } from "./attachment-service.ts";
/** Selects full `UserRow`s from `users u`, with the inviter's name joined. */
@@ -42,8 +41,8 @@ const USER_SELECT =
* `POST /api/users/register`. The caller has validated `request` and claimed
* the invite.
*
* @throws {APIException} 400 when the username is taken, 409 when the email
* is.
* @throws {APIException} 409 when the username or the email is taken, in any
* case.
*/
export async function createUser(
request: RegisterUserRequest,
@@ -53,15 +52,11 @@ export async function createUser(
const createdAt = new Date();
const existingUser = db.prepare(
"SELECT id FROM users WHERE username = ?;",
"SELECT id FROM users WHERE lower(username) = lower(?);",
).get(request.username);
if (existingUser) {
throw new APIException(
APIErrorCode.VALIDATION_ERROR,
400,
"Username already exists",
);
throw new APIException(409, "Username already exists");
}
assertEmailAvailable(request.email);
@@ -82,16 +77,9 @@ export async function createUser(
request.email,
);
} catch (err) {
// A parallel sign-up can take the name while the hash is computed; the
// UNIQUE constraint is the real guard. Emails have no such constraint.
if (err instanceof Error && err.message.includes("UNIQUE")) {
throw new APIException(
APIErrorCode.VALIDATION_ERROR,
400,
"Username already exists",
);
}
throw err;
// A parallel sign-up can take the name or the address while the hash is
// computed; the unique indexes are the real guard.
throw uniqueViolationToConflict(err);
}
return {
@@ -115,7 +103,7 @@ export function getUserById(userId: string): User {
).get(userId);
if (!userRow || !isUserRow(userRow)) {
throw new APIException(APIErrorCode.NOT_FOUND, 404, "User not found");
throw new APIException(404, "User not found");
}
return userRowToApi(userRow);
@@ -152,7 +140,7 @@ export function getUserByUsername(username: string): User {
).get(username);
if (!userRow || !isUserRow(userRow)) {
throw new APIException(APIErrorCode.NOT_FOUND, 404, "User not found");
throw new APIException(404, "User not found");
}
return userRowToApi(userRow);
@@ -168,21 +156,28 @@ function assertEmailAvailable(email: string, exceptUserId?: string): void {
`SELECT id FROM users WHERE lower(email) = lower(?) AND id != ?;`,
).get(email, exceptUserId ?? "");
if (row) {
throw new APIException(
APIErrorCode.VALIDATION_ERROR,
409,
"Email already in use",
);
throw new APIException(409, "Email already in use");
}
}
/**
* Returns the user whose email is exactly `email`, or null, for
* `requestPasswordReset`. Unlike the uniqueness check, it is case-sensitive.
* Returns `err` as a 409 when it is SQLite's unique violation on a username or
* an email, and as it is otherwise.
*/
function uniqueViolationToConflict(err: unknown): unknown {
if (!(err instanceof Error) || !err.message.includes("UNIQUE")) return err;
return err.message.includes("email")
? new APIException(409, "Email already in use")
: new APIException(409, "Username already exists");
}
/**
* Returns the user whose email is `email`, in any case, or null, for
* `requestPasswordReset`.
*/
export function getUserByEmail(email: string): User | null {
const userRow = db.prepare(
`${USER_SELECT} WHERE u.email = ?`,
`${USER_SELECT} WHERE lower(u.email) = lower(?)`,
).get(email);
if (!userRow || !isUserRow(userRow)) return null;
@@ -236,7 +231,7 @@ export function listUsers(): User[] {
).all();
if (!userRows || !userRows.every(isUserRow)) {
throw new APIException(APIErrorCode.NOT_FOUND, 404, "No user found");
throw new APIException(404, "No user found");
}
return userRows.map(userRowToApi);
@@ -275,20 +270,25 @@ export async function updateUser(
const updatedUserRow = userApiToRow(updatedUser);
const userResult = db.prepare(
`UPDATE users SET username = ?, password_hash = ?, role = ?, description = ?, email = ?, updated_at = ? WHERE id = ?`,
).run(
updatedUserRow.username,
updatedUserRow.password_hash,
updatedUserRow.role,
updatedUserRow.description,
updatedUserRow.email,
now.toISOString(),
updatedUserRow.id,
);
let userResult;
try {
userResult = db.prepare(
`UPDATE users SET username = ?, password_hash = ?, role = ?, description = ?, email = ?, updated_at = ? WHERE id = ?`,
).run(
updatedUserRow.username,
updatedUserRow.password_hash,
updatedUserRow.role,
updatedUserRow.description,
updatedUserRow.email,
now.toISOString(),
updatedUserRow.id,
);
} catch (err) {
throw uniqueViolationToConflict(err);
}
if (userResult.changes === 0) {
throw new APIException(APIErrorCode.NOT_FOUND, 404, "User not found");
throw new APIException(404, "User not found");
}
if (password) {
@@ -300,7 +300,7 @@ export async function updateUser(
}
if (updatedUser.description) {
linkAttachments(updatedUser.description, userId);
linkAttachments(updatedUser.description, "user", userId);
}
return updatedUser;
@@ -319,7 +319,7 @@ export function updateUserAvatar(userId: string, mime: string): void {
).run(mime, new Date().toISOString(), userId);
if (result.changes === 0) {
throw new APIException(APIErrorCode.NOT_FOUND, 404, "User not found");
throw new APIException(404, "User not found");
}
}
@@ -371,6 +371,6 @@ export function deleteUser(userId: string): void {
).run(userId);
if (result.changes === 0) {
throw new APIException(APIErrorCode.NOT_FOUND, 404, "User not found");
throw new APIException(404, "User not found");
}
}

View File

@@ -8,7 +8,6 @@
* @module
*/
import { APIErrorCode } from "../../shared/api.ts";
import { APIException } from "../lib/api-exception.ts";
import { isUserRow, type User, userRowToApi } from "../model/user.ts";
import { db } from "../db/connection.ts";
@@ -34,7 +33,7 @@ function visibleDump(dumpId: string, userId: string): { isPrivate: boolean } {
`SELECT is_private, user_id FROM dumps WHERE id = ?;`,
).get(dumpId) as { is_private: number; user_id: string } | undefined;
if (!row || (row.is_private && row.user_id !== userId)) {
throw new APIException(APIErrorCode.NOT_FOUND, 404, "Dump not found");
throw new APIException(404, "Dump not found");
}
return { isPrivate: Boolean(row.is_private) };
}
@@ -67,11 +66,7 @@ export function castVote(dumpId: string, userId: string): VoteResult {
db.exec("ROLLBACK;");
} catch { /* ignore if no active transaction */ }
if (err instanceof Error && err.message.includes("UNIQUE constraint")) {
throw new APIException(
APIErrorCode.VALIDATION_ERROR,
409,
"Already voted",
);
throw new APIException(409, "Already voted");
}
throw err;
}
@@ -101,7 +96,7 @@ export function removeVote(dumpId: string, userId: string): VoteResult {
).run(dumpId, userId);
if (result.changes === 0) {
db.exec("ROLLBACK;");
throw new APIException(APIErrorCode.NOT_FOUND, 404, "Vote not found");
throw new APIException(404, "Vote not found");
}
db.prepare(
`UPDATE dumps SET vote_count = vote_count - 1 WHERE id = ?;`,
@@ -155,11 +150,7 @@ export function getDumpVoters(
).all(dumpId, limit + 1, offset);
if (!rawRows.every(isUserRow)) {
throw new APIException(
APIErrorCode.SERVER_ERROR,
500,
"Malformed user data",
);
throw new APIException(500, "Malformed user data");
}
return pageOf(rawRows.map(userRowToApi), limit);

View File

@@ -169,27 +169,43 @@ export function broadcastPresence(): void {
}
/**
* Sends everyone `dump_created`. The dump service also sends it when a private
* dump goes public, since to everyone else that dump is new.
* Tells the clients that may see a dump how it changed, for the dump service
* after every write. `before` is null for a new dump, `after` for a deleted
* one. A private dump's changes reach its owner's sockets alone. When a dump
* goes private, everyone else gets `dump_deleted`; when it goes public, they get
* `dump_created`, since to them it is new.
*/
export function broadcastNewDump(dump: Dump): void {
broadcast({ type: "dump_created", dump });
}
export function broadcastDumpChange(
before: Dump | null,
after: Dump | null,
): void {
const dump = after ?? before;
if (!dump) return;
const ownerId = dump.userId;
const toOwner = (client: WsClient) => client.userId === ownerId;
const toOthers = (client: WsClient) => client.userId !== ownerId;
/**
* Sends everyone `dump_updated`, for a public dump that changed. The dump
* service calls it.
*/
export function broadcastDumpUpdated(dump: Dump): void {
broadcast({ type: "dump_updated", dump });
}
/**
* Sends everyone `dump_deleted`. The dump service also sends it when a public
* dump goes private, so that everyone else drops it.
*/
export function broadcastDumpDeleted(dumpId: string): void {
broadcast({ type: "dump_deleted", dumpId });
if (!after) {
broadcast(
{ type: "dump_deleted", dumpId: dump.id },
dump.isPrivate ? toOwner : undefined,
);
} else if (!before) {
broadcast(
{ type: "dump_created", dump: after },
after.isPrivate ? toOwner : undefined,
);
} else if (after.isPrivate) {
broadcast({ type: "dump_updated", dump: after }, toOwner);
if (!before.isPrivate) {
broadcast({ type: "dump_deleted", dumpId: after.id }, toOthers);
}
} else if (before.isPrivate) {
broadcast({ type: "dump_updated", dump: after }, toOwner);
broadcast({ type: "dump_created", dump: after }, toOthers);
} else {
broadcast({ type: "dump_updated", dump: after });
}
}
/**