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:
@@ -4,7 +4,9 @@
|
||||
*
|
||||
* - `POST /api/attachments` — signed in. Stores an image (multipart `file`, at
|
||||
* most 5 MB) and answers its id.
|
||||
* - `GET /api/attachments/:attachmentId` — public. Serves the image.
|
||||
* - `GET /api/attachments/:attachmentId?token=` — public, but an image in a
|
||||
* private dump or playlist, or in a comment on a private dump, needs its
|
||||
* owner's media `token`. Serves the image.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
@@ -13,16 +15,14 @@ import { Router } from "@oak/oak";
|
||||
import { authMiddleware } from "../middleware/auth.ts";
|
||||
import {
|
||||
createAttachment,
|
||||
getAttachment,
|
||||
getAttachmentAccess,
|
||||
} from "../services/attachment-service.ts";
|
||||
import { APIErrorCode, type APIResponse } from "../../shared/api.ts";
|
||||
import { authenticateMedia } from "../lib/auth.ts";
|
||||
import { type APIResponse } from "../../shared/api.ts";
|
||||
import { APIException } from "../lib/api-exception.ts";
|
||||
import type { AttachmentResponse } from "../../shared/dump.ts";
|
||||
import {
|
||||
ATTACHMENTS_DIR,
|
||||
serveUploadedFile,
|
||||
validateImageUpload,
|
||||
} from "../lib/upload.ts";
|
||||
import { serveUploadedFile, validateImageUpload } from "../lib/upload.ts";
|
||||
import { ATTACHMENTS_DIR } from "../config.ts";
|
||||
|
||||
/**
|
||||
* Mounted by `api/main.ts` behind the error, Open Graph and CORS middleware.
|
||||
@@ -33,18 +33,14 @@ const router: Router = new Router();
|
||||
router.post("/api/attachments", authMiddleware, async (ctx) => {
|
||||
const contentType = ctx.request.headers.get("content-type") ?? "";
|
||||
if (!contentType.includes("multipart/form-data")) {
|
||||
throw new APIException(
|
||||
APIErrorCode.BAD_REQUEST,
|
||||
400,
|
||||
"Expected multipart/form-data",
|
||||
);
|
||||
throw new APIException(400, "Expected multipart/form-data");
|
||||
}
|
||||
|
||||
const body = await ctx.request.body.formData();
|
||||
const file = body.get("file");
|
||||
|
||||
if (!(file instanceof File)) {
|
||||
throw new APIException(APIErrorCode.BAD_REQUEST, 400, "Missing file");
|
||||
throw new APIException(400, "Missing file");
|
||||
}
|
||||
|
||||
const data = new Uint8Array(await file.arrayBuffer());
|
||||
@@ -71,18 +67,30 @@ router.post("/api/attachments", authMiddleware, async (ctx) => {
|
||||
router.get("/api/attachments/:attachmentId", async (ctx) => {
|
||||
const { attachmentId } = ctx.params;
|
||||
|
||||
let attachment;
|
||||
let access;
|
||||
try {
|
||||
attachment = getAttachment(attachmentId);
|
||||
access = getAttachmentAccess(attachmentId);
|
||||
} catch {
|
||||
ctx.response.status = 404;
|
||||
return;
|
||||
}
|
||||
if (access.ownerId) {
|
||||
// An <img> can't send an Authorization header, so the viewer's media
|
||||
// token comes in the query string.
|
||||
const token = ctx.request.url.searchParams.get("token");
|
||||
const viewerId = token ? await authenticateMedia(token) : null;
|
||||
if (viewerId !== access.ownerId) {
|
||||
ctx.response.status = 404;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
await serveUploadedFile(
|
||||
ctx,
|
||||
`${ATTACHMENTS_DIR}/${attachmentId}`,
|
||||
attachment.mime,
|
||||
access.mime,
|
||||
3600,
|
||||
!!access.ownerId,
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -19,15 +19,16 @@ import {
|
||||
broadcastUserUpdated,
|
||||
updateClientAvatar,
|
||||
} from "../services/ws-service.ts";
|
||||
import { APIErrorCode, type APIResponse } from "../../shared/api.ts";
|
||||
import { type APIResponse } from "../../shared/api.ts";
|
||||
import { APIException } from "../lib/api-exception.ts";
|
||||
import type { SelfUser } from "../../shared/user.ts";
|
||||
import { toPublicUser, toSelfUser } from "../model/user.ts";
|
||||
import {
|
||||
AVATARS_DIR,
|
||||
replaceUploadedFile,
|
||||
serveUploadedFile,
|
||||
validateImageUpload,
|
||||
} from "../lib/upload.ts";
|
||||
import { AVATARS_DIR } from "../config.ts";
|
||||
|
||||
/**
|
||||
* Mounted by `api/main.ts` behind the error, Open Graph and CORS middleware.
|
||||
@@ -39,33 +40,23 @@ router.post("/api/avatars/me", authMiddleware, async (ctx) => {
|
||||
const authPayload = ctx.state.user;
|
||||
const contentType = ctx.request.headers.get("content-type") ?? "";
|
||||
if (!contentType.includes("multipart/form-data")) {
|
||||
throw new APIException(
|
||||
APIErrorCode.BAD_REQUEST,
|
||||
400,
|
||||
"Expected multipart/form-data",
|
||||
);
|
||||
throw new APIException(400, "Expected multipart/form-data");
|
||||
}
|
||||
|
||||
const body = await ctx.request.body.formData();
|
||||
const file = body.get("file");
|
||||
|
||||
if (!(file instanceof File)) {
|
||||
throw new APIException(APIErrorCode.BAD_REQUEST, 400, "Missing file field");
|
||||
throw new APIException(400, "Missing file field");
|
||||
}
|
||||
|
||||
const data = new Uint8Array(await file.arrayBuffer());
|
||||
const mime = validateImageUpload(data);
|
||||
|
||||
const filePath = `${AVATARS_DIR}/${authPayload.userId}`;
|
||||
await Deno.mkdir(AVATARS_DIR, { recursive: true });
|
||||
await Deno.writeFile(filePath, data);
|
||||
try {
|
||||
updateUserAvatar(authPayload.userId, mime);
|
||||
} catch (err) {
|
||||
// The row doesn't describe the new file, so don't keep it.
|
||||
await Deno.remove(filePath).catch(() => {});
|
||||
throw err;
|
||||
}
|
||||
// Written before the record announces it, or clients would fetch it too
|
||||
// early.
|
||||
await replaceUploadedFile(`${AVATARS_DIR}/${authPayload.userId}`, data);
|
||||
updateUserAvatar(authPayload.userId, mime);
|
||||
updateClientAvatar(authPayload.userId, mime);
|
||||
|
||||
const user = getUserById(authPayload.userId);
|
||||
|
||||
@@ -16,11 +16,7 @@
|
||||
|
||||
import { Router } from "@oak/oak";
|
||||
|
||||
import {
|
||||
APIErrorCode,
|
||||
type APIResponse,
|
||||
type PaginatedData,
|
||||
} from "../../shared/api.ts";
|
||||
import { type APIResponse, type PaginatedData } from "../../shared/api.ts";
|
||||
import { APIException } from "../lib/api-exception.ts";
|
||||
import type { Category } from "../../shared/category.ts";
|
||||
import type { Dump } from "../../shared/dump.ts";
|
||||
@@ -87,11 +83,7 @@ router.post(
|
||||
async (ctx) => {
|
||||
const body: unknown = await ctx.request.body.json();
|
||||
if (!isCreateCategoryRequest(body)) {
|
||||
throw new APIException(
|
||||
APIErrorCode.VALIDATION_ERROR,
|
||||
400,
|
||||
"Invalid category data",
|
||||
);
|
||||
throw new APIException(400, "Invalid category data");
|
||||
}
|
||||
const category = createCategory(body);
|
||||
const responseBody: APIResponse<Category> = {
|
||||
@@ -110,11 +102,7 @@ router.put(
|
||||
async (ctx) => {
|
||||
const body: unknown = await ctx.request.body.json();
|
||||
if (!isUpdateCategoryRequest(body)) {
|
||||
throw new APIException(
|
||||
APIErrorCode.VALIDATION_ERROR,
|
||||
400,
|
||||
"Invalid category data",
|
||||
);
|
||||
throw new APIException(400, "Invalid category data");
|
||||
}
|
||||
const category = updateCategory(ctx.params.id, body);
|
||||
const responseBody: APIResponse<Category> = {
|
||||
|
||||
@@ -18,11 +18,7 @@
|
||||
*/
|
||||
|
||||
import { Router } from "@oak/oak";
|
||||
import {
|
||||
APIErrorCode,
|
||||
type APIResponse,
|
||||
type PaginatedData,
|
||||
} from "../../shared/api.ts";
|
||||
import { type APIResponse, type PaginatedData } from "../../shared/api.ts";
|
||||
import { APIException } from "../lib/api-exception.ts";
|
||||
import type { Comment } from "../../shared/comment.ts";
|
||||
import {
|
||||
@@ -72,11 +68,7 @@ router.post("/dumps/:dumpId/comments", authMiddleware, async (ctx) => {
|
||||
const dump = getDump(ctx.params.dumpId, userId);
|
||||
const body: unknown = await ctx.request.body.json();
|
||||
if (!isCreateCommentRequest(body)) {
|
||||
throw new APIException(
|
||||
APIErrorCode.VALIDATION_ERROR,
|
||||
400,
|
||||
"Invalid comment data",
|
||||
);
|
||||
throw new APIException(400, "Invalid comment data");
|
||||
}
|
||||
const comment = createComment(
|
||||
dump.id,
|
||||
@@ -95,11 +87,7 @@ router.patch("/comments/:commentId", authMiddleware, async (ctx) => {
|
||||
const canModerate = can(ctx.state.user, "comment:moderate");
|
||||
const body: unknown = await ctx.request.body.json();
|
||||
if (!isUpdateCommentRequest(body)) {
|
||||
throw new APIException(
|
||||
APIErrorCode.VALIDATION_ERROR,
|
||||
400,
|
||||
"Invalid comment data",
|
||||
);
|
||||
throw new APIException(400, "Invalid comment data");
|
||||
}
|
||||
const { comment, isPrivate } = updateComment(
|
||||
ctx.params.commentId,
|
||||
|
||||
@@ -37,11 +37,7 @@
|
||||
|
||||
import { Router } from "@oak/oak";
|
||||
|
||||
import {
|
||||
APIErrorCode,
|
||||
type APIResponse,
|
||||
type PaginatedData,
|
||||
} from "../../shared/api.ts";
|
||||
import { type APIResponse, type PaginatedData } from "../../shared/api.ts";
|
||||
import { APIException } from "../lib/api-exception.ts";
|
||||
import type { Dump, DumpUrlMatch } from "../../shared/dump.ts";
|
||||
import {
|
||||
@@ -56,7 +52,7 @@ import { authMiddleware } from "../middleware/auth.ts";
|
||||
import { can } from "../lib/permissions.ts";
|
||||
import { parseOptionalAuth } from "../lib/auth.ts";
|
||||
import { parsePagination } from "../lib/pagination.ts";
|
||||
import { validateImageUpload } from "../lib/upload.ts";
|
||||
import { replaceUploadedFile, validateImageUpload } from "../lib/upload.ts";
|
||||
import { THUMBNAILS_DIR } from "../config.ts";
|
||||
import {
|
||||
createFileDump,
|
||||
@@ -117,11 +113,7 @@ router.post(
|
||||
const isPrivate = formData.get("isPrivate") === "true";
|
||||
|
||||
if (!(file instanceof File)) {
|
||||
throw new APIException(
|
||||
APIErrorCode.VALIDATION_ERROR,
|
||||
400,
|
||||
"A file is required",
|
||||
);
|
||||
throw new APIException(400, "A file is required");
|
||||
}
|
||||
|
||||
dump = await createFileDump(
|
||||
@@ -136,11 +128,7 @@ router.post(
|
||||
const body: unknown = await ctx.request.body.json();
|
||||
|
||||
if (!isCreateUrlDumpRequest(body)) {
|
||||
throw new APIException(
|
||||
APIErrorCode.VALIDATION_ERROR,
|
||||
400,
|
||||
"Invalid dump data",
|
||||
);
|
||||
throw new APIException(400, "Invalid dump data");
|
||||
}
|
||||
|
||||
dump = await createUrlDump(body, userId);
|
||||
@@ -221,11 +209,7 @@ router.put("/:dumpId/file", authMiddleware, async (ctx) => {
|
||||
|
||||
const dump = getDump(dumpId, userId);
|
||||
if (userId !== dump.userId && !can(ctx.state.user, "dump:moderate")) {
|
||||
throw new APIException(
|
||||
APIErrorCode.UNAUTHORIZED,
|
||||
403,
|
||||
"Not authorized to update dump",
|
||||
);
|
||||
throw new APIException(403, "Not authorized to update dump");
|
||||
}
|
||||
|
||||
const formData = await ctx.request.body.formData();
|
||||
@@ -234,11 +218,7 @@ router.put("/:dumpId/file", authMiddleware, async (ctx) => {
|
||||
const title = formData.get("title");
|
||||
|
||||
if (!(file instanceof File)) {
|
||||
throw new APIException(
|
||||
APIErrorCode.VALIDATION_ERROR,
|
||||
400,
|
||||
"A file is required",
|
||||
);
|
||||
throw new APIException(400, "A file is required");
|
||||
}
|
||||
|
||||
const updatedDump = await replaceFileDump(
|
||||
@@ -263,21 +243,13 @@ router.put("/:dumpId", authMiddleware, async (ctx) => {
|
||||
const body: unknown = await ctx.request.body.json();
|
||||
|
||||
if (!isUpdateDumpRequest(body)) {
|
||||
throw new APIException(
|
||||
APIErrorCode.VALIDATION_ERROR,
|
||||
422,
|
||||
"Erroneous user input",
|
||||
);
|
||||
throw new APIException(400, "Erroneous user input");
|
||||
}
|
||||
|
||||
const dump = getDump(dumpId, userId);
|
||||
|
||||
if (userId !== dump.userId && !can(ctx.state.user, "dump:moderate")) {
|
||||
throw new APIException(
|
||||
APIErrorCode.UNAUTHORIZED,
|
||||
403,
|
||||
"Not authorized to update dump",
|
||||
);
|
||||
throw new APIException(403, "Not authorized to update dump");
|
||||
}
|
||||
|
||||
const updatedDump = await updateDump(dump.id, body);
|
||||
@@ -291,38 +263,23 @@ router.put("/:dumpId/thumbnail", authMiddleware, async (ctx) => {
|
||||
|
||||
const dump = getDump(dumpId, userId);
|
||||
if (userId !== dump.userId && !can(ctx.state.user, "dump:moderate")) {
|
||||
throw new APIException(
|
||||
APIErrorCode.UNAUTHORIZED,
|
||||
403,
|
||||
"Not authorized to update dump",
|
||||
);
|
||||
throw new APIException(403, "Not authorized to update dump");
|
||||
}
|
||||
|
||||
const formData = await ctx.request.body.formData();
|
||||
const file = formData.get("file");
|
||||
|
||||
if (!(file instanceof File)) {
|
||||
throw new APIException(
|
||||
APIErrorCode.VALIDATION_ERROR,
|
||||
400,
|
||||
"Missing file field",
|
||||
);
|
||||
throw new APIException(400, "Missing file field");
|
||||
}
|
||||
|
||||
const data = new Uint8Array(await file.arrayBuffer());
|
||||
const mime = validateImageUpload(data);
|
||||
|
||||
// The record is written first. If the file write then fails, the thumbnail
|
||||
// route finds no custom file and falls back to the generated thumbnail.
|
||||
// Written before setDumpThumbnail announces it, or clients would fetch it
|
||||
// too early.
|
||||
await replaceUploadedFile(`${THUMBNAILS_DIR}/${dump.id}-custom`, data);
|
||||
const updatedDump = setDumpThumbnail(dump.id, mime);
|
||||
const filePath = `${THUMBNAILS_DIR}/${dump.id}-custom`;
|
||||
await Deno.mkdir(THUMBNAILS_DIR, { recursive: true });
|
||||
try {
|
||||
await Deno.writeFile(filePath, data);
|
||||
} catch (err) {
|
||||
await Deno.remove(filePath).catch(() => {});
|
||||
throw err;
|
||||
}
|
||||
|
||||
const responseBody: APIResponse<Dump> = { success: true, data: updatedDump };
|
||||
ctx.response.body = responseBody;
|
||||
@@ -334,11 +291,7 @@ router.delete("/:dumpId/thumbnail", authMiddleware, async (ctx) => {
|
||||
|
||||
const dump = getDump(dumpId, userId);
|
||||
if (userId !== dump.userId && !can(ctx.state.user, "dump:moderate")) {
|
||||
throw new APIException(
|
||||
APIErrorCode.UNAUTHORIZED,
|
||||
403,
|
||||
"Not authorized to update dump",
|
||||
);
|
||||
throw new APIException(403, "Not authorized to update dump");
|
||||
}
|
||||
|
||||
const updatedDump = await removeDumpThumbnail(dump.id);
|
||||
@@ -352,11 +305,7 @@ router.post("/:dumpId/refresh-metadata", authMiddleware, async (ctx) => {
|
||||
const dump = getDump(dumpId, userId);
|
||||
|
||||
if (userId !== dump.userId && !can(ctx.state.user, "dump:moderate")) {
|
||||
throw new APIException(
|
||||
APIErrorCode.UNAUTHORIZED,
|
||||
403,
|
||||
"Not authorized to update dump",
|
||||
);
|
||||
throw new APIException(403, "Not authorized to update dump");
|
||||
}
|
||||
|
||||
const updatedDump = await refreshDumpMetadata(dump.id);
|
||||
@@ -370,11 +319,7 @@ router.delete("/:dumpId", authMiddleware, async (ctx) => {
|
||||
const dump = getDump(dumpId, userId);
|
||||
|
||||
if (userId !== dump.userId && !can(ctx.state.user, "dump:moderate")) {
|
||||
throw new APIException(
|
||||
APIErrorCode.UNAUTHORIZED,
|
||||
403,
|
||||
"Not authorized to delete dump",
|
||||
);
|
||||
throw new APIException(403, "Not authorized to delete dump");
|
||||
}
|
||||
|
||||
await deleteDump(dump.id);
|
||||
|
||||
@@ -10,9 +10,8 @@
|
||||
*/
|
||||
|
||||
import { Router } from "@oak/oak";
|
||||
import { APIErrorCode } from "../../shared/api.ts";
|
||||
import { APIException } from "../lib/api-exception.ts";
|
||||
import { DUMPS_DIR } from "../lib/upload.ts";
|
||||
import { DUMPS_DIR } from "../config.ts";
|
||||
import { authenticateMedia } from "../lib/auth.ts";
|
||||
import { serveFile } from "../lib/serve-file.ts";
|
||||
import { dumpFileVersion, getDump } from "../services/dump-service.ts";
|
||||
@@ -60,7 +59,7 @@ router.get("/:dumpId", async (ctx) => {
|
||||
|
||||
// The id names a file on disk: nothing but an id's characters gets through.
|
||||
if (!/^[0-9a-f-]{36}$/.test(dumpId)) {
|
||||
throw new APIException(APIErrorCode.BAD_REQUEST, 400, "Invalid dump ID");
|
||||
throw new APIException(400, "Invalid dump ID");
|
||||
}
|
||||
|
||||
// Media elements can't send an Authorization header, so the viewer's media
|
||||
@@ -70,11 +69,7 @@ router.get("/:dumpId", async (ctx) => {
|
||||
const dump = getDump(dumpId, viewerId ?? undefined);
|
||||
|
||||
if (dump.kind !== "file" || !dump.fileMime || !dump.fileName) {
|
||||
throw new APIException(
|
||||
APIErrorCode.NOT_FOUND,
|
||||
404,
|
||||
"No file for this dump",
|
||||
);
|
||||
throw new APIException(404, "No file for this dump");
|
||||
}
|
||||
|
||||
const path = `${DUMPS_DIR}/${dumpId}`;
|
||||
@@ -111,7 +106,7 @@ router.get("/:dumpId", async (ctx) => {
|
||||
ranges: true,
|
||||
});
|
||||
if (!served) {
|
||||
throw new APIException(APIErrorCode.NOT_FOUND, 404, "File not found");
|
||||
throw new APIException(404, "File not found");
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
*/
|
||||
|
||||
import { Router } from "@oak/oak";
|
||||
import { APIErrorCode, type APIResponse } from "../../shared/api.ts";
|
||||
import { type APIResponse } from "../../shared/api.ts";
|
||||
import { APIException } from "../lib/api-exception.ts";
|
||||
import type { InviteResponse } from "../../shared/user.ts";
|
||||
import { type AuthContext, authMiddleware } from "../middleware/auth.ts";
|
||||
@@ -24,7 +24,7 @@ const router: Router = new Router({ prefix: "/api/invites" });
|
||||
|
||||
router.post("/", authMiddleware, (ctx: AuthContext) => {
|
||||
if (!ctx.state.user) {
|
||||
throw new APIException(APIErrorCode.UNAUTHORIZED, 401, "Not authenticated");
|
||||
throw new APIException(401, "Not authenticated");
|
||||
}
|
||||
const responseBody: APIResponse<InviteResponse> = {
|
||||
success: true,
|
||||
@@ -41,11 +41,7 @@ router.get("/:token", (ctx) => {
|
||||
const responseBody: APIResponse<null> = { success: true, data: null };
|
||||
ctx.response.body = responseBody;
|
||||
} catch {
|
||||
throw new APIException(
|
||||
APIErrorCode.NOT_FOUND,
|
||||
404,
|
||||
"Invalid or expired invite",
|
||||
);
|
||||
throw new APIException(404, "Invalid or expired invite");
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -13,11 +13,7 @@
|
||||
*/
|
||||
|
||||
import { Router } from "@oak/oak";
|
||||
import {
|
||||
APIErrorCode,
|
||||
type APIResponse,
|
||||
type PaginatedData,
|
||||
} from "../../shared/api.ts";
|
||||
import { type APIResponse, type PaginatedData } from "../../shared/api.ts";
|
||||
import { APIException } from "../lib/api-exception.ts";
|
||||
import type { Notification } from "../../shared/notification.ts";
|
||||
import { parsePagination } from "../lib/pagination.ts";
|
||||
@@ -36,7 +32,7 @@ const router: Router = new Router({ prefix: "/api/notifications" });
|
||||
|
||||
router.get("/", authMiddleware, (ctx: AuthContext) => {
|
||||
if (!ctx.state.user) {
|
||||
throw new APIException(APIErrorCode.UNAUTHORIZED, 401, "Not authenticated");
|
||||
throw new APIException(401, "Not authenticated");
|
||||
}
|
||||
const { page, limit } = parsePagination(ctx.request.url.searchParams);
|
||||
const { items, hasMore } = getNotificationsForUser(
|
||||
@@ -53,7 +49,7 @@ router.get("/", authMiddleware, (ctx: AuthContext) => {
|
||||
|
||||
router.post("/read-all", authMiddleware, (ctx: AuthContext) => {
|
||||
if (!ctx.state.user) {
|
||||
throw new APIException(APIErrorCode.UNAUTHORIZED, 401, "Not authenticated");
|
||||
throw new APIException(401, "Not authenticated");
|
||||
}
|
||||
markAllRead(ctx.state.user.userId);
|
||||
ctx.response.status = 204;
|
||||
@@ -62,7 +58,7 @@ router.post("/read-all", authMiddleware, (ctx: AuthContext) => {
|
||||
router.patch("/:id/read", authMiddleware, (ctx) => {
|
||||
const user = ctx.state.user;
|
||||
if (!user) {
|
||||
throw new APIException(APIErrorCode.UNAUTHORIZED, 401, "Not authenticated");
|
||||
throw new APIException(401, "Not authenticated");
|
||||
}
|
||||
markOneRead(ctx.params.id, user.userId);
|
||||
ctx.response.status = 204;
|
||||
|
||||
@@ -29,7 +29,7 @@
|
||||
|
||||
import { Router } from "@oak/oak";
|
||||
import { authenticateMedia, parseOptionalAuth } from "../lib/auth.ts";
|
||||
import { APIErrorCode, type APIResponse } from "../../shared/api.ts";
|
||||
import { type APIResponse } from "../../shared/api.ts";
|
||||
import { APIException } from "../lib/api-exception.ts";
|
||||
import {
|
||||
isCreatePlaylistRequest,
|
||||
@@ -57,10 +57,11 @@ import {
|
||||
updatePlaylist,
|
||||
} from "../services/playlist-service.ts";
|
||||
import {
|
||||
PLAYLIST_IMAGES_DIR,
|
||||
replaceUploadedFile,
|
||||
serveUploadedFile,
|
||||
validateImageUpload,
|
||||
} from "../lib/upload.ts";
|
||||
import { PLAYLIST_IMAGES_DIR } from "../config.ts";
|
||||
|
||||
/**
|
||||
* Mounted by `api/main.ts` behind the error, Open Graph and CORS middleware.
|
||||
@@ -84,11 +85,7 @@ router.get("/by-dump/:dumpId/memberships", authMiddleware, (ctx) => {
|
||||
router.post("/", authMiddleware, async (ctx) => {
|
||||
const body: unknown = await ctx.request.body.json();
|
||||
if (!isCreatePlaylistRequest(body)) {
|
||||
throw new APIException(
|
||||
APIErrorCode.VALIDATION_ERROR,
|
||||
400,
|
||||
"Invalid request",
|
||||
);
|
||||
throw new APIException(400, "Invalid request");
|
||||
}
|
||||
const responseBody: APIResponse<Playlist> = {
|
||||
success: true,
|
||||
@@ -110,11 +107,7 @@ router.get("/:playlistId", async (ctx) => {
|
||||
router.put("/:playlistId", authMiddleware, async (ctx) => {
|
||||
const body: unknown = await ctx.request.body.json();
|
||||
if (!isUpdatePlaylistRequest(body)) {
|
||||
throw new APIException(
|
||||
APIErrorCode.VALIDATION_ERROR,
|
||||
400,
|
||||
"Invalid request",
|
||||
);
|
||||
throw new APIException(400, "Invalid request");
|
||||
}
|
||||
const playlist = updatePlaylist(
|
||||
ctx.params.playlistId,
|
||||
@@ -158,42 +151,27 @@ router.delete("/:playlistId/dumps/:dumpId", authMiddleware, (ctx) => {
|
||||
router.post("/:playlistId/image", authMiddleware, async (ctx) => {
|
||||
const contentType = ctx.request.headers.get("content-type") ?? "";
|
||||
if (!contentType.includes("multipart/form-data")) {
|
||||
throw new APIException(
|
||||
APIErrorCode.BAD_REQUEST,
|
||||
400,
|
||||
"Expected multipart/form-data",
|
||||
);
|
||||
throw new APIException(400, "Expected multipart/form-data");
|
||||
}
|
||||
|
||||
const body = await ctx.request.body.formData();
|
||||
const file = body.get("file");
|
||||
|
||||
if (!(file instanceof File)) {
|
||||
throw new APIException(APIErrorCode.BAD_REQUEST, 400, "Missing file field");
|
||||
throw new APIException(400, "Missing file field");
|
||||
}
|
||||
|
||||
const data = new Uint8Array(await file.arrayBuffer());
|
||||
const mime = validateImageUpload(data);
|
||||
|
||||
// The file is written before setPlaylistImage announces it, or clients would
|
||||
// fetch the new `?v=` URL too early and cache the old cover under it. It is
|
||||
// written beside the old one and renamed over it, so a failed write leaves
|
||||
// the old cover whole.
|
||||
// Written before setPlaylistImage announces it, or clients would fetch the
|
||||
// new `?v=` URL too early and cache the old cover under it.
|
||||
const { id } = getEditablePlaylist(
|
||||
ctx.params.playlistId,
|
||||
ctx.state.user.userId,
|
||||
can(ctx.state.user, "playlist:moderate"),
|
||||
);
|
||||
const filePath = `${PLAYLIST_IMAGES_DIR}/${id}`;
|
||||
const tmpPath = `${filePath}.${crypto.randomUUID()}.tmp`;
|
||||
await Deno.mkdir(PLAYLIST_IMAGES_DIR, { recursive: true });
|
||||
try {
|
||||
await Deno.writeFile(tmpPath, data);
|
||||
await Deno.rename(tmpPath, filePath);
|
||||
} catch (err) {
|
||||
await Deno.remove(tmpPath).catch(() => {});
|
||||
throw err;
|
||||
}
|
||||
await replaceUploadedFile(`${PLAYLIST_IMAGES_DIR}/${id}`, data);
|
||||
const playlist = setPlaylistImage(
|
||||
id,
|
||||
mime,
|
||||
@@ -228,11 +206,7 @@ router.get("/:playlistId/image", async (ctx) => {
|
||||
router.put("/:playlistId/order", authMiddleware, async (ctx) => {
|
||||
const body: unknown = await ctx.request.body.json();
|
||||
if (!isReorderPlaylistRequest(body)) {
|
||||
throw new APIException(
|
||||
APIErrorCode.VALIDATION_ERROR,
|
||||
400,
|
||||
"Invalid request",
|
||||
);
|
||||
throw new APIException(400, "Invalid request");
|
||||
}
|
||||
reorderPlaylist(
|
||||
ctx.params.playlistId,
|
||||
|
||||
@@ -34,7 +34,7 @@ previewRouter.get("/api/preview", authMiddleware, async (ctx) => {
|
||||
if (!isValidHttpUrl(url)) {
|
||||
const responseBody: APIFailure = {
|
||||
success: false,
|
||||
error: { code: APIErrorCode.VALIDATION_ERROR, message: "Invalid URL" },
|
||||
error: { code: APIErrorCode.BAD_REQUEST, message: "Invalid URL" },
|
||||
};
|
||||
ctx.response.status = 400;
|
||||
ctx.response.body = responseBody;
|
||||
|
||||
@@ -13,7 +13,6 @@
|
||||
*/
|
||||
|
||||
import { Router } from "@oak/oak";
|
||||
import { APIErrorCode } from "../../shared/api.ts";
|
||||
import { APIException } from "../lib/api-exception.ts";
|
||||
import {
|
||||
dumpFileVersion,
|
||||
@@ -175,7 +174,7 @@ router.get("/:dumpId", async (ctx) => {
|
||||
|
||||
// The id names files on disk: nothing but an id's characters gets through.
|
||||
if (!/^[0-9a-f-]{36}$/.test(dumpId)) {
|
||||
throw new APIException(APIErrorCode.BAD_REQUEST, 400, "Invalid dump ID");
|
||||
throw new APIException(400, "Invalid dump ID");
|
||||
}
|
||||
|
||||
// Media elements can't send an Authorization header, so the viewer's media
|
||||
@@ -217,11 +216,7 @@ router.get("/:dumpId", async (ctx) => {
|
||||
if (
|
||||
!await ensureGenerated(thumbPath, () => videoStill(srcPath, thumbPath))
|
||||
) {
|
||||
throw new APIException(
|
||||
APIErrorCode.NOT_FOUND,
|
||||
404,
|
||||
"Could not generate thumbnail",
|
||||
);
|
||||
throw new APIException(404, "Could not generate thumbnail");
|
||||
}
|
||||
if (
|
||||
await serveFile(ctx, thumbPath, {
|
||||
@@ -255,11 +250,7 @@ router.get("/:dumpId", async (ctx) => {
|
||||
) return;
|
||||
}
|
||||
|
||||
throw new APIException(
|
||||
APIErrorCode.NOT_FOUND,
|
||||
404,
|
||||
"No thumbnail for this dump",
|
||||
);
|
||||
throw new APIException(404, "No thumbnail for this dump");
|
||||
});
|
||||
|
||||
export default router;
|
||||
|
||||
@@ -43,11 +43,7 @@
|
||||
|
||||
import { Router } from "@oak/oak";
|
||||
|
||||
import {
|
||||
APIErrorCode,
|
||||
type APIResponse,
|
||||
type PaginatedData,
|
||||
} from "../../shared/api.ts";
|
||||
import { type APIResponse, type PaginatedData } from "../../shared/api.ts";
|
||||
import { APIException } from "../lib/api-exception.ts";
|
||||
import {
|
||||
type AuthResponse,
|
||||
@@ -70,7 +66,8 @@ import {
|
||||
import type { Playlist } from "../../shared/playlist.ts";
|
||||
import { toPublicUser, toSelfUser, type User } from "../model/user.ts";
|
||||
|
||||
import { createJWT, createMediaToken, verifyPassword } from "../lib/jwt.ts";
|
||||
import { createJWT, createMediaToken } from "../lib/jwt.ts";
|
||||
import { hashPassword, verifyPassword } from "../lib/password.ts";
|
||||
import { type RateLimit, takeToken } from "../lib/rate-limit.ts";
|
||||
import {
|
||||
type AuthContext,
|
||||
@@ -107,6 +104,9 @@ import {
|
||||
getFollowedUsersByUser,
|
||||
} from "../services/follow-service.ts";
|
||||
|
||||
// Hashed once, at startup, for the sign-ins of usernames that don't exist.
|
||||
const UNKNOWN_USER_HASH: Promise<string> = hashPassword(crypto.randomUUID());
|
||||
|
||||
/**
|
||||
* Mounted by `api/main.ts` behind the error, Open Graph and CORS middleware.
|
||||
* An `APIException` thrown by a handler becomes the JSON error response there.
|
||||
@@ -136,7 +136,6 @@ router.post("/register", async (ctx) => {
|
||||
|
||||
if (!isRegisterUserRequest(body)) {
|
||||
throw new APIException(
|
||||
APIErrorCode.VALIDATION_ERROR,
|
||||
400,
|
||||
validateRegisterUserRequest(body) ?? "Invalid request",
|
||||
);
|
||||
@@ -180,18 +179,13 @@ router.post("/login", async (ctx) => {
|
||||
const body: unknown = await ctx.request.body.json();
|
||||
|
||||
if (!isLoginUserRequest(body)) {
|
||||
throw new APIException(
|
||||
APIErrorCode.VALIDATION_ERROR,
|
||||
400,
|
||||
"Invalid request",
|
||||
);
|
||||
throw new APIException(400, "Invalid request");
|
||||
}
|
||||
|
||||
// Per account, so guessing one user's password is slow however many
|
||||
// connections it comes from.
|
||||
if (!takeToken(`login:${body.username.toLowerCase()}`, LOGIN_LIMIT)) {
|
||||
throw new APIException(
|
||||
APIErrorCode.VALIDATION_ERROR,
|
||||
429,
|
||||
"Too many login attempts — try again in a minute",
|
||||
);
|
||||
@@ -201,21 +195,16 @@ router.post("/login", async (ctx) => {
|
||||
try {
|
||||
user = getUserByUsername(body.username);
|
||||
} catch {
|
||||
// Same answer as a wrong password: don't confirm which usernames exist.
|
||||
throw new APIException(
|
||||
APIErrorCode.VALIDATION_ERROR,
|
||||
401,
|
||||
"Invalid username or password",
|
||||
);
|
||||
user = undefined;
|
||||
}
|
||||
|
||||
const valid = await verifyPassword(body.password, user.passwordHash);
|
||||
if (!valid) {
|
||||
throw new APIException(
|
||||
APIErrorCode.VALIDATION_ERROR,
|
||||
401,
|
||||
"Invalid username or password",
|
||||
);
|
||||
// An unknown username gets the same answer as a wrong password, after the
|
||||
// same work, so neither the message nor the timing tells which exist.
|
||||
const valid = await verifyPassword(
|
||||
body.password,
|
||||
user?.passwordHash ?? await UNKNOWN_USER_HASH,
|
||||
);
|
||||
if (!user || !valid) {
|
||||
throw new APIException(401, "Invalid username or password");
|
||||
}
|
||||
|
||||
const responseBody: APIResponse<AuthResponse> = {
|
||||
@@ -228,11 +217,7 @@ router.post("/login", async (ctx) => {
|
||||
router.get("/me", authMiddleware, (ctx: AuthContext) => {
|
||||
try {
|
||||
if (!ctx.state.user) {
|
||||
throw new APIException(
|
||||
APIErrorCode.UNAUTHORIZED,
|
||||
401,
|
||||
"Not authenticated",
|
||||
);
|
||||
throw new APIException(401, "Not authenticated");
|
||||
}
|
||||
|
||||
const responseBody: APIResponse<SelfUser> = {
|
||||
@@ -243,11 +228,7 @@ router.get("/me", authMiddleware, (ctx: AuthContext) => {
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
|
||||
throw new APIException(
|
||||
APIErrorCode.SERVER_ERROR,
|
||||
500,
|
||||
"Failed to fetch user profile",
|
||||
);
|
||||
throw new APIException(500, "Failed to fetch user profile");
|
||||
}
|
||||
});
|
||||
|
||||
@@ -279,11 +260,7 @@ router.post("/reset-password", async (ctx) => {
|
||||
const token = fieldOf(body, "token");
|
||||
const newPassword = fieldOf(body, "newPassword");
|
||||
if (typeof token !== "string" || typeof newPassword !== "string") {
|
||||
throw new APIException(
|
||||
APIErrorCode.VALIDATION_ERROR,
|
||||
400,
|
||||
"Invalid request",
|
||||
);
|
||||
throw new APIException(400, "Invalid request");
|
||||
}
|
||||
await resetPassword(token, newPassword);
|
||||
const responseBody: APIResponse<null> = { success: true, data: null };
|
||||
@@ -296,11 +273,7 @@ router.post("/me/change-password", authMiddleware, async (ctx: AuthContext) => {
|
||||
const newPassword = fieldOf(body, "newPassword");
|
||||
|
||||
if (typeof currentPassword !== "string" || typeof newPassword !== "string") {
|
||||
throw new APIException(
|
||||
APIErrorCode.VALIDATION_ERROR,
|
||||
400,
|
||||
"Invalid request",
|
||||
);
|
||||
throw new APIException(400, "Invalid request");
|
||||
}
|
||||
|
||||
if (
|
||||
@@ -308,7 +281,6 @@ router.post("/me/change-password", authMiddleware, async (ctx: AuthContext) => {
|
||||
newPassword.length > VALIDATION.PASSWORD_MAX
|
||||
) {
|
||||
throw new APIException(
|
||||
APIErrorCode.VALIDATION_ERROR,
|
||||
400,
|
||||
`Password must be ${VALIDATION.PASSWORD_MIN}–${VALIDATION.PASSWORD_MAX} characters`,
|
||||
);
|
||||
@@ -317,11 +289,7 @@ router.post("/me/change-password", authMiddleware, async (ctx: AuthContext) => {
|
||||
const user = getUserById(ctx.state.user.userId);
|
||||
const valid = await verifyPassword(currentPassword, user.passwordHash);
|
||||
if (!valid) {
|
||||
throw new APIException(
|
||||
APIErrorCode.VALIDATION_ERROR,
|
||||
401,
|
||||
"Current password is incorrect",
|
||||
);
|
||||
throw new APIException(403, "Current password is incorrect");
|
||||
}
|
||||
|
||||
// Changing the password revokes every token issued before it, this
|
||||
@@ -339,11 +307,7 @@ router.post("/me/change-password", authMiddleware, async (ctx: AuthContext) => {
|
||||
router.patch("/me", authMiddleware, async (ctx: AuthContext) => {
|
||||
const body: unknown = await ctx.request.body.json();
|
||||
if (!isUpdateUserRequest(body)) {
|
||||
throw new APIException(
|
||||
APIErrorCode.VALIDATION_ERROR,
|
||||
400,
|
||||
"Invalid request",
|
||||
);
|
||||
throw new APIException(400, "Invalid request");
|
||||
}
|
||||
// Only the profile fields: a stolen token alone must not change the role,
|
||||
// the password (which needs the current one) or the username (which is
|
||||
@@ -369,19 +333,11 @@ router.patch(
|
||||
const body: unknown = await ctx.request.body.json();
|
||||
const role = fieldOf(body, "role");
|
||||
if (!isRole(role)) {
|
||||
throw new APIException(
|
||||
APIErrorCode.VALIDATION_ERROR,
|
||||
400,
|
||||
"Invalid role",
|
||||
);
|
||||
throw new APIException(400, "Invalid role");
|
||||
}
|
||||
// So that an admin can't demote themselves by mistake and leave no admin.
|
||||
if (ctx.params.userId === ctx.state.user.userId) {
|
||||
throw new APIException(
|
||||
APIErrorCode.VALIDATION_ERROR,
|
||||
400,
|
||||
"Cannot change your own role",
|
||||
);
|
||||
throw new APIException(400, "Cannot change your own role");
|
||||
}
|
||||
const updated = await updateUser(ctx.params.userId, { role });
|
||||
const publicUser = toPublicUser(updated);
|
||||
|
||||
@@ -429,8 +429,8 @@ function canModerateChat(client: WsClient): boolean {
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles `chat_edit`. It stores the new body, broadcasts it, and notifies the
|
||||
* users the edit newly @mentions.
|
||||
* Handles `chat_edit`. It stores the new body, broadcasts it, and notifies, in
|
||||
* the author's name, the users the edit newly mentions.
|
||||
*/
|
||||
function handleChatEdit(client: WsClient, id: unknown, body: unknown): void {
|
||||
const userId = chatWriter(client);
|
||||
@@ -449,10 +449,10 @@ function handleChatEdit(client: WsClient, id: unknown, body: unknown): void {
|
||||
);
|
||||
broadcastChatMessageUpdated(message);
|
||||
// Mentions already notified for this message are deduplicated, so only
|
||||
// the new ones notify. After a moderator's edit, they come from the
|
||||
// moderator.
|
||||
// the new ones notify. A moderator's edit keeps the author's words, so the
|
||||
// author mentions.
|
||||
notifyMentions(
|
||||
userId,
|
||||
message.userId,
|
||||
message.body,
|
||||
"chat",
|
||||
message.id,
|
||||
|
||||
Reference in New Issue
Block a user