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:
@@ -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");
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user