v3: fix the backend's correctness findings — each by a rule shared across the code rather than one more special case. Link previews: readTextCapped decoded every page as UTF-8, so a Latin-1 page came out garbled unless it went through the curl fallback, which re-encoded it on its own; pages are now decoded in the charset their Content-Type or <meta> declares, and the curl fallback hands the bytes over as they are. The image proxy served and cached for a day an error answer that claimed an image type, and read a body without Content-Length whole before checking its size; it now refuses an error status and reads through the same capped reader. The icons task's Twemoji fetch gives up after 15 s instead of holding the start up, and extractLinkHref, which only its tests used, is gone. Backlinks matched a linked URL against the raw url column, so https://x.com/ missed a dump posted as https://x.com; they now compare canonical URLs, as reposts do. The four LIKE searches put the query in raw, so % and _ were wildcards and the mention search for "a_b" found "axb"; lib/like.ts escapes them. Every list query now treats a malformed row the same way, a 500 through model/rows.ts's parseRows, where ten of them silently dropped it; the playlist dumps query uses the model's column list rather than a hand-written copy, and the aliased list is derived from the plain one. The vote and like services commit through transaction() instead of their own BEGIN and ROLLBACK, which would have rolled back a caller's transaction.
Validation: the dump validators refuse the nulls their shared types don't allow (a null title or note on creation, a null URL on edit); a playlist title of spaces is refused and titles are stored trimmed; usernames and emails are checked by the same USERNAME_RE and EMAIL_RE in shared/validation.ts on sign-up, on PATCH /api/users/me (which checked other limits) and in the sign-up form. Mentions are read by shared/mention.ts's mentionedUsernames, which skips code and URLs as Markdown shows them: https://mastodon.social/@bob or a `@bob` in code notified bob; the editor's suggestions derive their trigger from the same pattern instead of a copy. Following an unknown user is a 404 rather than a foreign-key 500, and following a private playlist a 404 rather than a 403 that confirmed it exists. `ws` and `emojibase` are reserved category slugs, since the server answers them before the app. GET /api/users/me no longer turns every error into a 500. Dead code goes: adminOnlyMiddleware, verifyEmailTransport, listUsers, deleteUser with disconnectUser and the force_logout message only it sent, PATCH /api/notifications/:id/read (with markOneRead), isSlugAvailable, the unreachable 500 in fetchComment, and the `if (!ctx.state.user)` checks behind authMiddleware. 214 backend and 627 frontend tests pass. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -14,6 +14,8 @@ import {
|
||||
isDumpRow,
|
||||
} from "../model/dump.ts";
|
||||
import { UUID_RE } from "../lib/slugify.ts";
|
||||
import { canonicalizeUrl } from "../lib/canonical-url.ts";
|
||||
import { parseRows } from "../model/rows.ts";
|
||||
|
||||
/**
|
||||
* Matches an http(s) URL in Markdown. It stops at the delimiters of
|
||||
@@ -28,15 +30,6 @@ const URL_RE = /https?:\/\/[^\s)\]<>"']+/g;
|
||||
*/
|
||||
const DUMP_PATH_RE = /^\/dumps\/([^/?#]+)/;
|
||||
|
||||
/** Returns `url` as the URL parser normalizes it, or null when it isn't one. */
|
||||
function canonicalize(url: string): string | null {
|
||||
try {
|
||||
return new URL(url).toString();
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Returns the id of the dump with id or slug `idOrSlug`, or null. */
|
||||
function resolveDumpPathId(idOrSlug: string): string | null {
|
||||
const row = UUID_RE.test(idOrSlug)
|
||||
@@ -48,8 +41,8 @@ function resolveDumpPathId(idOrSlug: string): string | null {
|
||||
/**
|
||||
* Replaces the backlinks from one text, a dump's note (`dump_comment`) or one
|
||||
* of its comments (`comment`), with the links its current `text` holds. A link
|
||||
* counts when it is a dump's page on this site or the exact URL a dump was
|
||||
* posted with. The dump and comment services call it on every save, and with
|
||||
* counts when it is a dump's page on this site, or when it is the URL a dump
|
||||
* was posted with, compared by `canonicalizeUrl` as reposts are. The dump and comment services call it on every save, and with
|
||||
* an empty `text` when a comment is deleted.
|
||||
*/
|
||||
export function relinkBacklinks(
|
||||
@@ -62,11 +55,9 @@ export function relinkBacklinks(
|
||||
const externalUrls = new Set<string>();
|
||||
|
||||
for (const match of text.matchAll(URL_RE)) {
|
||||
const canonical = canonicalize(match[0]);
|
||||
if (!canonical) continue;
|
||||
let parsed: URL;
|
||||
try {
|
||||
parsed = new URL(canonical);
|
||||
parsed = new URL(match[0]);
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
@@ -75,14 +66,15 @@ export function relinkBacklinks(
|
||||
const resolved = resolveDumpPathId(decodeURIComponent(pathMatch[1]));
|
||||
if (resolved) targetIds.add(resolved);
|
||||
} else {
|
||||
externalUrls.add(canonical);
|
||||
const canonical = canonicalizeUrl(match[0]);
|
||||
if (canonical) externalUrls.add(canonical);
|
||||
}
|
||||
}
|
||||
|
||||
if (externalUrls.size > 0) {
|
||||
const placeholders = [...externalUrls].map(() => "?").join(", ");
|
||||
const rows = db.prepare(
|
||||
`SELECT id FROM dumps WHERE url IN (${placeholders});`,
|
||||
`SELECT id FROM dumps WHERE url_canonical IN (${placeholders});`,
|
||||
).all(...externalUrls) as { id: string }[];
|
||||
for (const row of rows) targetIds.add(row.id);
|
||||
}
|
||||
@@ -122,5 +114,5 @@ export function getRelatedDumps(
|
||||
ORDER BY created_at DESC LIMIT 20;`,
|
||||
).all(dumpId, dumpId, requestingUserId ?? "");
|
||||
|
||||
return rows.filter(isDumpRow).map(dumpRowToApi);
|
||||
return parseRows(rows, isDumpRow, dumpRowToApi);
|
||||
}
|
||||
|
||||
@@ -23,6 +23,7 @@ import {
|
||||
import { type Page, pageOf } from "../lib/pagination.ts";
|
||||
import { isReservedSlug, isValidSlugFormat } from "../lib/reserved-slugs.ts";
|
||||
import { VALIDATION } from "../../shared/validation.ts";
|
||||
import { parseRows } from "../model/rows.ts";
|
||||
|
||||
/**
|
||||
* Throws a 400 unless `slug` is well-formed, short enough and not reserved,
|
||||
@@ -120,7 +121,7 @@ export function listCategories(): Category[] {
|
||||
const rows = db.prepare(
|
||||
`SELECT * FROM categories ORDER BY position ASC, slug ASC;`,
|
||||
).all();
|
||||
return rows.filter(isCategoryRow).map(categoryRowToApi);
|
||||
return parseRows(rows, isCategoryRow, categoryRowToApi);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -317,7 +318,7 @@ export function listDumpsByCategory(
|
||||
ORDER BY d.created_at DESC LIMIT ? OFFSET ?;`,
|
||||
).all(category.id, ...privacyParams, limit + 1, offset);
|
||||
|
||||
const items = rows.filter(isDumpRow).map(dumpRowToApi);
|
||||
const items = parseRows(rows, isDumpRow, dumpRowToApi);
|
||||
attachCategoryIds(items);
|
||||
return pageOf(items, limit);
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
|
||||
import { APIException } from "../lib/api-exception.ts";
|
||||
import { isUserRow, type User, userRowToApi } from "../model/user.ts";
|
||||
import { db } from "../db/connection.ts";
|
||||
import { db, transaction } from "../db/connection.ts";
|
||||
import { type Page, pageOf } from "../lib/pagination.ts";
|
||||
import { notifyCommentOwnerLike } from "./notification-service.ts";
|
||||
|
||||
@@ -54,22 +54,19 @@ export function castCommentLike(
|
||||
const isPrivate = commentVisibility(commentId, userId);
|
||||
let likeCount: number;
|
||||
try {
|
||||
db.exec("BEGIN;");
|
||||
db.prepare(
|
||||
`INSERT INTO comment_likes (comment_id, user_id, created_at) VALUES (?, ?, ?);`,
|
||||
).run(commentId, userId, new Date().toISOString());
|
||||
db.prepare(
|
||||
`UPDATE comments SET like_count = like_count + 1 WHERE id = ?;`,
|
||||
).run(commentId);
|
||||
const row = db.prepare(
|
||||
`SELECT like_count FROM comments WHERE id = ?;`,
|
||||
).get(commentId) as { like_count: number } | undefined;
|
||||
db.exec("COMMIT;");
|
||||
likeCount = row?.like_count ?? 0;
|
||||
likeCount = transaction(() => {
|
||||
db.prepare(
|
||||
`INSERT INTO comment_likes (comment_id, user_id, created_at) VALUES (?, ?, ?);`,
|
||||
).run(commentId, userId, new Date().toISOString());
|
||||
db.prepare(
|
||||
`UPDATE comments SET like_count = like_count + 1 WHERE id = ?;`,
|
||||
).run(commentId);
|
||||
const row = db.prepare(
|
||||
`SELECT like_count FROM comments WHERE id = ?;`,
|
||||
).get(commentId) as { like_count: number };
|
||||
return row.like_count;
|
||||
});
|
||||
} catch (err) {
|
||||
try {
|
||||
db.exec("ROLLBACK;");
|
||||
} catch { /* ignore if no active transaction */ }
|
||||
if (err instanceof Error && err.message.includes("UNIQUE constraint")) {
|
||||
throw new APIException(409, "Already liked");
|
||||
}
|
||||
@@ -98,13 +95,11 @@ export function removeCommentLike(
|
||||
WHERE c.id = ?;`,
|
||||
).get(commentId) as { is_private: number } | undefined;
|
||||
const isPrivate = Boolean(dumpRow?.is_private);
|
||||
try {
|
||||
db.exec("BEGIN;");
|
||||
return transaction(() => {
|
||||
const result = db.prepare(
|
||||
`DELETE FROM comment_likes WHERE comment_id = ? AND user_id = ?;`,
|
||||
).run(commentId, userId);
|
||||
if (result.changes === 0) {
|
||||
db.exec("ROLLBACK;");
|
||||
throw new APIException(404, "Like not found");
|
||||
}
|
||||
db.prepare(
|
||||
@@ -112,14 +107,9 @@ export function removeCommentLike(
|
||||
).run(commentId);
|
||||
const row = db.prepare(
|
||||
`SELECT like_count FROM comments WHERE id = ?;`,
|
||||
).get(commentId) as { like_count: number } | undefined;
|
||||
db.exec("COMMIT;");
|
||||
return { likeCount: row?.like_count ?? 0, isPrivate };
|
||||
} catch (err) {
|
||||
if (err instanceof APIException) throw err;
|
||||
db.exec("ROLLBACK;");
|
||||
throw err;
|
||||
}
|
||||
).get(commentId) as { like_count: number };
|
||||
return { likeCount: row.like_count, isPrivate };
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -8,7 +8,6 @@
|
||||
|
||||
import { APIException } from "../lib/api-exception.ts";
|
||||
import type { Comment } from "../../shared/comment.ts";
|
||||
import { type SQLOutputValue } from "node:sqlite";
|
||||
import { commentRowToApi, isCommentRow } from "../model/comment.ts";
|
||||
import { db } from "../db/connection.ts";
|
||||
import {
|
||||
@@ -27,9 +26,7 @@ function fetchComment(commentId: string): Comment {
|
||||
const row = db.prepare(
|
||||
`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(404, "Comment not found");
|
||||
}
|
||||
if (!row) throw new APIException(404, "Comment not found");
|
||||
if (!isCommentRow(row)) {
|
||||
throw new APIException(500, "Malformed comment data");
|
||||
}
|
||||
|
||||
@@ -54,6 +54,8 @@ import {
|
||||
attachCategoryIds,
|
||||
setDumpCategories,
|
||||
} from "./category-service.ts";
|
||||
import { LIKE, likePattern } from "../lib/like.ts";
|
||||
import { parseRows } from "../model/rows.ts";
|
||||
|
||||
function isAllowedMime(mime: string): boolean {
|
||||
return DUMP_ALLOWED_MIME_PREFIXES.some((p) => mime.startsWith(p)) ||
|
||||
@@ -327,11 +329,11 @@ export function searchDumps(
|
||||
requestingUserId?: string,
|
||||
): { items: Dump[]; total: number } {
|
||||
if (!query.trim()) return { items: [], total: 0 };
|
||||
const pattern = `%${query}%`;
|
||||
const pattern = likePattern(query);
|
||||
const offset = (page - 1) * limit;
|
||||
|
||||
const searchClause =
|
||||
`(title LIKE ? OR comment LIKE ? OR json_extract(rich_content,'$.title') LIKE ? OR json_extract(rich_content,'$.description') LIKE ?)`;
|
||||
`(title ${LIKE} OR comment ${LIKE} OR json_extract(rich_content,'$.title') ${LIKE} OR json_extract(rich_content,'$.description') ${LIKE})`;
|
||||
const searchParams = [pattern, pattern, pattern, pattern] as const;
|
||||
|
||||
if (requestingUserId) {
|
||||
@@ -341,7 +343,7 @@ export function searchDumps(
|
||||
const totalRow = db.prepare(
|
||||
`SELECT COUNT(*) as count FROM dumps WHERE (is_private = 0 OR user_id = ?) AND ${searchClause};`,
|
||||
).get(requestingUserId, ...searchParams) as { count: number } | undefined;
|
||||
const items = rows.filter(isDumpRow).map(dumpRowToApi);
|
||||
const items = parseRows(rows, isDumpRow, dumpRowToApi);
|
||||
attachCategoryIds(items);
|
||||
return { items, total: totalRow?.count ?? 0 };
|
||||
} else {
|
||||
@@ -351,7 +353,7 @@ export function searchDumps(
|
||||
const totalRow = db.prepare(
|
||||
`SELECT COUNT(*) as count FROM dumps WHERE is_private = 0 AND ${searchClause};`,
|
||||
).get(...searchParams) as { count: number } | undefined;
|
||||
const items = rows.filter(isDumpRow).map(dumpRowToApi);
|
||||
const items = parseRows(rows, isDumpRow, dumpRowToApi);
|
||||
attachCategoryIds(items);
|
||||
return { items, total: totalRow?.count ?? 0 };
|
||||
}
|
||||
|
||||
@@ -78,18 +78,6 @@ function getTransporter(): Transporter {
|
||||
return transporter;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks the connection to the SMTP server, or resolves false when email is
|
||||
* disabled. Nothing calls it yet.
|
||||
*
|
||||
* @throws {Error} When the server can't be reached or refuses the login.
|
||||
*/
|
||||
export async function verifyEmailTransport(): Promise<boolean> {
|
||||
if (!isEmailEnabled()) return false;
|
||||
await getTransporter().verify();
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends `message` and resolves once the SMTP server has accepted it. The
|
||||
* transport is created on the first send.
|
||||
|
||||
@@ -30,12 +30,16 @@ import { attachCategoryIds } from "./category-service.ts";
|
||||
* Makes `followerId` follow `followedUserId`, and notifies the followed user.
|
||||
* Following again changes nothing.
|
||||
*
|
||||
* @throws {APIException} 400 when a user tries to follow themselves.
|
||||
* @throws {APIException} 400 when a user tries to follow themselves, 404 when
|
||||
* there is no such user.
|
||||
*/
|
||||
export function followUser(followerId: string, followedUserId: string): void {
|
||||
if (followerId === followedUserId) {
|
||||
throw new APIException(400, "Cannot follow yourself");
|
||||
}
|
||||
if (!db.prepare(`SELECT 1 FROM users WHERE id = ?;`).get(followedUserId)) {
|
||||
throw new APIException(404, "User not found");
|
||||
}
|
||||
// The unique index answers "already following" without a race.
|
||||
let isNew = true;
|
||||
try {
|
||||
@@ -71,7 +75,7 @@ export function unfollowUser(followerId: string, followedUserId: string): void {
|
||||
* Following again changes nothing. A follow outlives the playlist going
|
||||
* private, but the feeds and lists skip it while it is.
|
||||
*
|
||||
* @throws {APIException} 404 when there is no such playlist, 403 when it is
|
||||
* @throws {APIException} 404 when there is no such playlist, or when it is
|
||||
* private.
|
||||
*/
|
||||
export function followPlaylist(followerId: string, playlistId: string): void {
|
||||
@@ -82,8 +86,9 @@ export function followPlaylist(followerId: string, playlistId: string): void {
|
||||
if (!row) {
|
||||
throw new APIException(404, "Playlist not found");
|
||||
}
|
||||
// Private is answered as missing, so as not to confirm that it exists.
|
||||
if (!row.is_public) {
|
||||
throw new APIException(403, "Cannot follow a private playlist");
|
||||
throw new APIException(404, "Playlist not found");
|
||||
}
|
||||
|
||||
let isNew = true;
|
||||
|
||||
@@ -22,7 +22,7 @@ import {
|
||||
} from "../model/notification.ts";
|
||||
import { type Page, pageOf } from "../lib/pagination.ts";
|
||||
import { sendToUser } from "./ws-service.ts";
|
||||
import { MENTION_RE } from "../../shared/mention.ts";
|
||||
import { mentionedUsernames } from "../../shared/mention.ts";
|
||||
|
||||
/**
|
||||
* Stores a notification for `userId` and pushes it live. With a `sourceKey`,
|
||||
@@ -113,16 +113,6 @@ export function markAllRead(userId: string): void {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Marks one of `userId`'s notifications read. An id that isn't theirs changes
|
||||
* nothing, and says nothing.
|
||||
*/
|
||||
export function markOneRead(notificationId: string, userId: string): void {
|
||||
db.prepare(
|
||||
`UPDATE notifications SET read = 1 WHERE id = ? AND user_id = ?;`,
|
||||
).run(notificationId, userId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Notifies `followedUserId` that `followerId` follows them, once however often
|
||||
* they unfollow and follow again. `followUser` calls it.
|
||||
@@ -301,11 +291,7 @@ export function notifyMentions(
|
||||
).get(mentionerUserId) as { username: string } | undefined;
|
||||
if (!mentionerRow) return;
|
||||
|
||||
const usernames = [
|
||||
...new Set(
|
||||
[...body.matchAll(MENTION_RE)].map((m) => m[1].toLowerCase()),
|
||||
),
|
||||
];
|
||||
const usernames = mentionedUsernames(body);
|
||||
|
||||
for (const username of usernames) {
|
||||
const mentionedRow = db.prepare(
|
||||
|
||||
@@ -18,7 +18,7 @@ import type {
|
||||
import type { Dump } from "../../shared/dump.ts";
|
||||
import { db, transaction } from "../db/connection.ts";
|
||||
import {
|
||||
DUMP_COLUMNS_ALIASED,
|
||||
DUMP_SELECT_COLUMNS_ALIASED,
|
||||
dumpRowToApi,
|
||||
isDumpRow,
|
||||
} from "../model/dump.ts";
|
||||
@@ -40,6 +40,8 @@ import {
|
||||
isMemberVisibleTo,
|
||||
type PlaylistMember,
|
||||
} from "../lib/playlist-members.ts";
|
||||
import { LIKE, likePattern } from "../lib/like.ts";
|
||||
import { parseRows } from "../model/rows.ts";
|
||||
|
||||
/**
|
||||
* The select list and `FROM` clause of a playlist query, adding the owner's
|
||||
@@ -78,14 +80,15 @@ export function createPlaylist(
|
||||
): Playlist {
|
||||
const id = crypto.randomUUID();
|
||||
const createdAt = new Date();
|
||||
const slug = makeSlug(req.title, id);
|
||||
const title = req.title.trim();
|
||||
const slug = makeSlug(title, id);
|
||||
db.prepare(
|
||||
`INSERT INTO playlists (id, user_id, title, slug, description, is_public, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?);`,
|
||||
).run(
|
||||
id,
|
||||
userId,
|
||||
req.title,
|
||||
title,
|
||||
slug,
|
||||
req.description ?? null,
|
||||
req.isPublic ? 1 : 0,
|
||||
@@ -94,7 +97,7 @@ export function createPlaylist(
|
||||
const playlist: Playlist = {
|
||||
id,
|
||||
userId,
|
||||
title: req.title,
|
||||
title,
|
||||
slug,
|
||||
description: req.description,
|
||||
isPublic: req.isPublic,
|
||||
@@ -103,7 +106,7 @@ export function createPlaylist(
|
||||
if (req.description) {
|
||||
// A private playlist's mentions are notified if it goes public.
|
||||
if (req.isPublic) {
|
||||
notifyMentions(userId, req.description, "playlist", id, req.title);
|
||||
notifyMentions(userId, req.description, "playlist", id, title);
|
||||
}
|
||||
linkAttachments(req.description, "playlist", id);
|
||||
}
|
||||
@@ -130,8 +133,7 @@ export function getPlaylist(
|
||||
}
|
||||
|
||||
const rows = db.prepare(
|
||||
`SELECT ${DUMP_COLUMNS_ALIASED},
|
||||
(SELECT COUNT(*) FROM comments WHERE dump_id = d.id AND deleted = 0) as comment_count
|
||||
`SELECT ${DUMP_SELECT_COLUMNS_ALIASED}
|
||||
FROM dumps d
|
||||
INNER JOIN playlist_dumps pd ON d.id = pd.dump_id
|
||||
WHERE pd.playlist_id = ?
|
||||
@@ -139,7 +141,7 @@ export function getPlaylist(
|
||||
ORDER BY pd.position ASC;`,
|
||||
).all(playlist.id, requestingUserId ?? "");
|
||||
|
||||
const dumps: Dump[] = rows.filter(isDumpRow).map(dumpRowToApi);
|
||||
const dumps: Dump[] = parseRows(rows, isDumpRow, dumpRowToApi);
|
||||
const visibleDumps = dumps.filter((d) =>
|
||||
isMemberVisibleTo(d, playlist, requestingUserId)
|
||||
);
|
||||
@@ -158,8 +160,8 @@ export function searchPlaylists(
|
||||
requestingUserId?: string,
|
||||
): Playlist[] {
|
||||
if (!query.trim()) return [];
|
||||
const pattern = `%${query}%`;
|
||||
const searchClause = `(p.title LIKE ? OR p.description LIKE ?)`;
|
||||
const pattern = likePattern(query);
|
||||
const searchClause = `(p.title ${LIKE} OR p.description ${LIKE})`;
|
||||
|
||||
const rows = requestingUserId
|
||||
? db.prepare(
|
||||
@@ -169,7 +171,7 @@ export function searchPlaylists(
|
||||
`SELECT ${PLAYLIST_SELECT} WHERE p.is_public = 1 AND ${searchClause} ORDER BY p.created_at DESC LIMIT ?;`,
|
||||
).all(pattern, pattern, limit);
|
||||
|
||||
return rows.filter(isPlaylistRow).map(playlistRowToApi);
|
||||
return parseRows(rows, isPlaylistRow, playlistRowToApi);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -191,7 +193,7 @@ export function listPlaylistsByUser(
|
||||
: `SELECT ${PLAYLIST_SELECT} WHERE p.user_id = ? AND p.is_public = 1 ORDER BY p.created_at DESC LIMIT ? OFFSET ?;`;
|
||||
|
||||
const rows = db.prepare(sql).all(userId, limit + 1, offset);
|
||||
return pageOf(rows.filter(isPlaylistRow).map(playlistRowToApi), limit);
|
||||
return pageOf(parseRows(rows, isPlaylistRow, playlistRowToApi), limit);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -213,10 +215,10 @@ export function updatePlaylist(
|
||||
const playlist = getPlaylistById(playlistId);
|
||||
|
||||
if (playlist.userId !== requestingUserId && !canModerate) {
|
||||
throw new APIException(403, "Forbidden");
|
||||
throw new APIException(403, "Only its owner or a moderator may do that");
|
||||
}
|
||||
|
||||
const newTitle = req.title ?? playlist.title;
|
||||
const newTitle = req.title?.trim() ?? playlist.title;
|
||||
const newDescription = "description" in req
|
||||
? (req.description ?? null)
|
||||
: (playlist.description ?? null);
|
||||
@@ -276,7 +278,7 @@ export function deletePlaylist(
|
||||
const playlist = getPlaylistById(playlistId);
|
||||
|
||||
if (playlist.userId !== requestingUserId && !canModerate) {
|
||||
throw new APIException(403, "Forbidden");
|
||||
throw new APIException(403, "Only its owner or a moderator may do that");
|
||||
}
|
||||
|
||||
db.prepare(`DELETE FROM playlists WHERE id = ?;`).run(playlist.id);
|
||||
@@ -298,7 +300,7 @@ export function getEditablePlaylist(
|
||||
): Playlist {
|
||||
const playlist = getPlaylistById(playlistId);
|
||||
if (playlist.userId !== requestingUserId && !canModerate) {
|
||||
throw new APIException(403, "Forbidden");
|
||||
throw new APIException(403, "Only its owner or a moderator may do that");
|
||||
}
|
||||
return playlist;
|
||||
}
|
||||
@@ -352,7 +354,7 @@ export function addDumpToPlaylist(
|
||||
const playlist = getPlaylistById(playlistId);
|
||||
|
||||
if (playlist.userId !== requestingUserId && !canModerate) {
|
||||
throw new APIException(403, "Forbidden");
|
||||
throw new APIException(403, "Only its owner or a moderator may do that");
|
||||
}
|
||||
|
||||
// Else someone else's private dump would land in the playlist, and its title
|
||||
@@ -416,7 +418,7 @@ export function removeDumpFromPlaylist(
|
||||
const playlist = getPlaylistById(playlistId);
|
||||
|
||||
if (playlist.userId !== requestingUserId && !canModerate) {
|
||||
throw new APIException(403, "Forbidden");
|
||||
throw new APIException(403, "Only its owner or a moderator may do that");
|
||||
}
|
||||
|
||||
db.prepare(
|
||||
@@ -444,7 +446,7 @@ export function reorderPlaylist(
|
||||
const playlist = getPlaylistById(playlistId);
|
||||
|
||||
if (playlist.userId !== requestingUserId && !canModerate) {
|
||||
throw new APIException(403, "Forbidden");
|
||||
throw new APIException(403, "Only its owner or a moderator may do that");
|
||||
}
|
||||
|
||||
// The requester can only name the dumps GET showed them. A hidden one
|
||||
@@ -530,7 +532,7 @@ export function getPlaylistsForDump(
|
||||
ORDER BY p.created_at DESC LIMIT 20;`,
|
||||
).all(dumpId, requestingUserId ?? "");
|
||||
|
||||
return rows.filter(isPlaylistRow).map(playlistRowToApi);
|
||||
return parseRows(rows, isPlaylistRow, playlistRowToApi);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -24,10 +24,12 @@ import {
|
||||
userRowToApi,
|
||||
} from "../model/user.ts";
|
||||
import { db } from "../db/connection.ts";
|
||||
import { closeUserSockets, disconnectUser } from "./ws-service.ts";
|
||||
import { closeUserSockets } from "./ws-service.ts";
|
||||
|
||||
import { hashPassword } from "../lib/password.ts";
|
||||
import { linkAttachments } from "./attachment-service.ts";
|
||||
import { LIKE, likePattern } from "../lib/like.ts";
|
||||
import { parseRows } from "../model/rows.ts";
|
||||
|
||||
/** Selects full `UserRow`s from `users u`, with the inviter's name joined. */
|
||||
const USER_SELECT =
|
||||
@@ -194,8 +196,8 @@ export function searchUsers(
|
||||
): UserSuggestion[] {
|
||||
if (!query) return [];
|
||||
const rows = db.prepare(
|
||||
`SELECT id, username, avatar_mime FROM users WHERE username LIKE ? ORDER BY username LIMIT ?;`,
|
||||
).all(`${query}%`, limit) as {
|
||||
`SELECT id, username, avatar_mime FROM users WHERE username ${LIKE} ORDER BY username LIMIT ?;`,
|
||||
).all(likePattern(query, "prefix"), limit) as {
|
||||
id: string;
|
||||
username: string;
|
||||
avatar_mime: string | null;
|
||||
@@ -213,28 +215,11 @@ export function searchUsers(
|
||||
*/
|
||||
export function searchUsersGlobal(query: string, limit: number): PublicUser[] {
|
||||
if (!query.trim()) return [];
|
||||
const pattern = `%${query}%`;
|
||||
const pattern = likePattern(query);
|
||||
const rows = db.prepare(
|
||||
`${USER_SELECT} WHERE (u.username LIKE ? OR u.description LIKE ?) ORDER BY u.username LIMIT ?;`,
|
||||
`${USER_SELECT} WHERE (u.username ${LIKE} OR u.description ${LIKE}) ORDER BY u.username LIMIT ?;`,
|
||||
).all(pattern, pattern, limit);
|
||||
return rows.filter(isUserRow).map(userRowToApi).map(toPublicUser);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns every user. Nothing calls it.
|
||||
*
|
||||
* @throws {APIException} 404 when a row doesn't parse as a user.
|
||||
*/
|
||||
export function listUsers(): User[] {
|
||||
const userRows = db.prepare(
|
||||
`${USER_SELECT}`,
|
||||
).all();
|
||||
|
||||
if (!userRows || !userRows.every(isUserRow)) {
|
||||
throw new APIException(404, "No user found");
|
||||
}
|
||||
|
||||
return userRows.map(userRowToApi);
|
||||
return parseRows(rows, isUserRow, userRowToApi).map(toPublicUser);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -357,20 +342,3 @@ export function getInviteTree(userId: string): Invitee[] {
|
||||
createdAt: new Date(r.created_at),
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes user `userId` and disconnects their sockets. Nothing calls it.
|
||||
*
|
||||
* @throws {APIException} 404 when there is no such user.
|
||||
*/
|
||||
export function deleteUser(userId: string): void {
|
||||
disconnectUser(userId);
|
||||
|
||||
const result = db.prepare(
|
||||
`DELETE FROM users WHERE id = ?;`,
|
||||
).run(userId);
|
||||
|
||||
if (result.changes === 0) {
|
||||
throw new APIException(404, "User not found");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
|
||||
import { APIException } from "../lib/api-exception.ts";
|
||||
import { isUserRow, type User, userRowToApi } from "../model/user.ts";
|
||||
import { db } from "../db/connection.ts";
|
||||
import { db, transaction } from "../db/connection.ts";
|
||||
import { type Page, pageOf } from "../lib/pagination.ts";
|
||||
import { notifyDumpOwnerUpvote } from "./notification-service.ts";
|
||||
|
||||
@@ -49,22 +49,19 @@ export function castVote(dumpId: string, userId: string): VoteResult {
|
||||
const { isPrivate } = visibleDump(dumpId, userId);
|
||||
let voteCount: number;
|
||||
try {
|
||||
db.exec("BEGIN;");
|
||||
db.prepare(
|
||||
`INSERT INTO votes (dump_id, user_id, created_at) VALUES (?, ?, ?);`,
|
||||
).run(dumpId, userId, new Date().toISOString());
|
||||
db.prepare(
|
||||
`UPDATE dumps SET vote_count = vote_count + 1 WHERE id = ?;`,
|
||||
).run(dumpId);
|
||||
const row = db.prepare(
|
||||
`SELECT vote_count FROM dumps WHERE id = ?;`,
|
||||
).get(dumpId) as { vote_count: number } | undefined;
|
||||
db.exec("COMMIT;");
|
||||
voteCount = row?.vote_count ?? 0;
|
||||
voteCount = transaction(() => {
|
||||
db.prepare(
|
||||
`INSERT INTO votes (dump_id, user_id, created_at) VALUES (?, ?, ?);`,
|
||||
).run(dumpId, userId, new Date().toISOString());
|
||||
db.prepare(
|
||||
`UPDATE dumps SET vote_count = vote_count + 1 WHERE id = ?;`,
|
||||
).run(dumpId);
|
||||
const row = db.prepare(
|
||||
`SELECT vote_count FROM dumps WHERE id = ?;`,
|
||||
).get(dumpId) as { vote_count: number };
|
||||
return row.vote_count;
|
||||
});
|
||||
} catch (err) {
|
||||
try {
|
||||
db.exec("ROLLBACK;");
|
||||
} catch { /* ignore if no active transaction */ }
|
||||
if (err instanceof Error && err.message.includes("UNIQUE constraint")) {
|
||||
throw new APIException(409, "Already voted");
|
||||
}
|
||||
@@ -89,28 +86,21 @@ export function removeVote(dumpId: string, userId: string): VoteResult {
|
||||
dumpId,
|
||||
) as { is_private: number } | undefined;
|
||||
const isPrivate = Boolean(row?.is_private);
|
||||
try {
|
||||
db.exec("BEGIN;");
|
||||
return transaction(() => {
|
||||
const result = db.prepare(
|
||||
`DELETE FROM votes WHERE dump_id = ? AND user_id = ?;`,
|
||||
).run(dumpId, userId);
|
||||
if (result.changes === 0) {
|
||||
db.exec("ROLLBACK;");
|
||||
throw new APIException(404, "Vote not found");
|
||||
}
|
||||
db.prepare(
|
||||
`UPDATE dumps SET vote_count = vote_count - 1 WHERE id = ?;`,
|
||||
).run(dumpId);
|
||||
const count = db.prepare(
|
||||
const row = db.prepare(
|
||||
`SELECT vote_count FROM dumps WHERE id = ?;`,
|
||||
).get(dumpId) as { vote_count: number } | undefined;
|
||||
db.exec("COMMIT;");
|
||||
return { voteCount: count?.vote_count ?? 0, isPrivate };
|
||||
} catch (err) {
|
||||
if (err instanceof APIException) throw err;
|
||||
db.exec("ROLLBACK;");
|
||||
throw err;
|
||||
}
|
||||
).get(dumpId) as { vote_count: number };
|
||||
return { voteCount: row.vote_count, isPrivate };
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -135,19 +135,6 @@ export function sendToUser(userId: string, data: ServerToClientMessage): void {
|
||||
broadcast(data, (client) => client.userId === userId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends `force_logout` to every socket of `userId`, then closes them. The user
|
||||
* service calls it before deleting the account, so every tab signs out.
|
||||
*/
|
||||
export function disconnectUser(userId: string): void {
|
||||
for (const client of clients) {
|
||||
if (client.userId === userId) {
|
||||
send(client.socket, { type: "force_logout" });
|
||||
client.socket.close(1000, "Account deleted");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes every socket of `userId` without signing anyone out. The user service
|
||||
* calls it on a password change. Each tab reconnects with the token it holds:
|
||||
|
||||
Reference in New Issue
Block a user