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>
98 lines
3.0 KiB
TypeScript
98 lines
3.0 KiB
TypeScript
/**
|
|
* Stores and serves the images pasted or dropped into the text editor, which
|
|
* puts each one in the body as a link to its `GET` URL.
|
|
*
|
|
* - `POST /api/attachments` — signed in. Stores an image (multipart `file`, at
|
|
* most 5 MB) and answers its id.
|
|
* - `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
|
|
*/
|
|
|
|
import { Router } from "@oak/oak";
|
|
import { authMiddleware } from "../middleware/auth.ts";
|
|
import {
|
|
createAttachment,
|
|
getAttachmentAccess,
|
|
} from "../services/attachment-service.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 { 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.
|
|
* An `APIException` thrown by a handler becomes the JSON error response there.
|
|
*/
|
|
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(400, "Expected multipart/form-data");
|
|
}
|
|
|
|
const body = await ctx.request.body.formData();
|
|
const file = body.get("file");
|
|
|
|
if (!(file instanceof File)) {
|
|
throw new APIException(400, "Missing file");
|
|
}
|
|
|
|
const data = new Uint8Array(await file.arrayBuffer());
|
|
const mime = validateImageUpload(data);
|
|
|
|
const attachmentId = crypto.randomUUID();
|
|
await Deno.mkdir(ATTACHMENTS_DIR, { recursive: true });
|
|
await Deno.writeFile(`${ATTACHMENTS_DIR}/${attachmentId}`, data);
|
|
try {
|
|
createAttachment(attachmentId, mime);
|
|
} catch (err) {
|
|
await Deno.remove(`${ATTACHMENTS_DIR}/${attachmentId}`).catch(() => {});
|
|
throw err;
|
|
}
|
|
|
|
const responseBody: APIResponse<AttachmentResponse> = {
|
|
success: true,
|
|
data: { id: attachmentId },
|
|
};
|
|
ctx.response.status = 201;
|
|
ctx.response.body = responseBody;
|
|
});
|
|
|
|
router.get("/api/attachments/:attachmentId", async (ctx) => {
|
|
const { attachmentId } = ctx.params;
|
|
|
|
let access;
|
|
try {
|
|
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}`,
|
|
access.mime,
|
|
3600,
|
|
!!access.ownerId,
|
|
);
|
|
});
|
|
|
|
export default router;
|