Files
gerbeur/api/routes/playlists.ts
khannurien 364c498a24
All checks were successful
Build and Publish Docker Image / build-and-push (push) Successful in 51s
v3: dependencies upgraded and deno audit clean, every API response typed end to end, no explicit any left — and the site search stops handing out password hashes — deno audit reported 19 advisories (11 high); none remain. nodemailer 9 → 10.0.10 closes four of them (a quadratic address parser, two recipient-domain allow-list bypasses, resolveContent ignoring disableFileAccess/disableUrlAccess); 10's one break is Node ≥ 20, and 10.0.11 is a day too young for the minimum release age. react-router 8.0.1 → 8.4.0 closes the RSC-mode CSRF bypass. Refreshing the lockfile clears the transitive ones that came in through Vite, ESLint and Lingui: postcss, nanoid, picomatch, browserslist, brace-expansion and baseline-browser-mapping. Everything else moves to its latest too — Lingui 6.8 (its SWC plugin 6.7), React 19.3, Vite 8.3.1, react-hook-form 7.89, marked, jose, ESLint 10.11, typescript-eslint 8.70, the @types — and frimousse 0.3 → 0.4, whose declarations only add (custom emoji data resolvers, a cache). TypeScript stays on 6.0: typescript-eslint supports < 6.1, so 7.0 would stop the lint. allowScripts names @swc/core 1.16.2 and drops esbuild, which Vite 8 no longer installs.
Search: GET /api/search sent each matching user's full row — password hash and email included — to anyone, signed in or not, because searchUsersGlobal returned User[] and the route passed it through. It returns profiles only now, stripped where the rows are read, and the search test fails on the old code. Types alone wouldn't have caught it (a User is structurally a PublicUser), so the strip is explicit and tested.

Typed routes. Every JSON response is declared as APIResponse<T>, the way the typed routes already did, with the missing shapes named in api/model/interfaces.ts: PublicUser (no hash, no email) and SelfUser (your own profile, with email) plus toPublicUser/toSelfUser in place of ten hand-written destructurings, AuthTokens, AuthResponse, MediaTokenResponse, InviteResponse, AttachmentResponse, SearchResults, LinkPreview, UserSuggestion and Invitee. Request bodies are `unknown` and narrowed by the existing guards, or by a new fieldOf(obj, key) where a route reads one field — no more reading off Oak's `any` or casting to Record<string, unknown>. The password-reset routes answer `{ success: true, data: null }` rather than a bare `{ success: true }`, so every success fits the envelope; the frontend only reads `success`.

Socket protocol: routes/ws.ts had its own send() taking Record<string, unknown>, so nothing checked what it sent. It takes ServerToClientMessage now, which turned up two mismatches: `pong` was missing from the union although the server answers every client ping with one, and vote_ack carried a `success: true` no type declares and no client reads. The union has PongMessage and vote_ack lost the field.

No explicit any. The YouTube playlist parse reads ytInitialData as `unknown` through a small at(node, …path) that checks each step, instead of `type Json = any`. The backend test helpers type the response body as the server's envelope: request<T>() and get/post/put/patch/del<T>() name what `data` holds, res.data throws with the server's message when the call didn't succeed and res.error when it didn't fail, and each test says which API type it expects, so a test reading a field the route doesn't send no longer compiles. Assertions that a field is absent are `assertFalse("passwordHash" in …)` rather than reading a field the type says isn't there. The socket tests' messages are ServerToClientMessage, with next()/all() keyed by type so each returns that message's shape.

No double casts in src/ either. window.YT and onYouTubeIframeAPIReady are declared on Window; the test's fake player is a class forwarding to the spies the tests inspect. WSContext, FollowContext and PlayerContext export their defaults (defaultWSValue, defaultFollowValue, defaultPlayerValue), which the tests import instead of reading React's private _currentValue. handleMentionKeyDown takes a MentionKey — the key fields it reads — so the test builds a plain object; useUserDumpFeed declares sentinelRef as the callback ref it is. In src/test/setup.ts the IntersectionObserver fake implements IntersectionObserver, and report(isIntersecting, top?) builds complete entries in place of partial ones cast in five files; the Animation fake implements Animation; the canvas getContext stub goes in through defineProperty. The XHR fake's last request is optional behind a getter that fails if none was made, the keyframes are checked with matchers, and the roleless legacy session is built by leaving the role out. One test changes meaning slightly: "leaving the view…" relied on entries with no position at all, and now leaves and re-enters at the same height, which is what it describes. The one cast left is in api/test/ws.test.ts: deno.json's "dom" lib hides Deno's WebSocket overload that takes handshake headers, and dropping that lib would break the editor's view of src/; it's commented and names the real signature.

Also: the notifications test answered a Response-typed promise with a plain object, which failed `tsc -b`; it uses the fetch stub's deferred() now. ESLint didn't read the `deno-lint-ignore no-explicit-any` comments, so `eslint .` failed on three files; those anys are gone. `deno fmt` over api/ and src/ (not the compiled src/locales/*.js); the reflow left all 332 message ids intact, and the .po files only have their source line references updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-27 16:05:29 +00:00

214 lines
6.2 KiB
TypeScript

import { Router } from "@oak/oak";
import { parseOptionalAuth } from "../lib/auth.ts";
import {
APIErrorCode,
APIException,
type APIResponse,
isCreatePlaylistRequest,
isReorderPlaylistRequest,
isUpdatePlaylistRequest,
type Playlist,
type PlaylistMembership,
type PlaylistWithDumps,
} from "../model/interfaces.ts";
import { authMiddleware, type AuthState } from "../middleware/auth.ts";
import { can } from "../lib/permissions.ts";
import {
addDumpToPlaylist,
createPlaylist,
deletePlaylist,
getEditablePlaylist,
getPlaylist,
getPlaylistImageInfo,
getPlaylistMembershipsForDump,
removeDumpFromPlaylist,
reorderPlaylist,
setPlaylistImage,
updatePlaylist,
} from "../services/playlist-service.ts";
import {
PLAYLIST_IMAGES_DIR,
serveUploadedFile,
validateImageUpload,
} from "../lib/upload.ts";
const router = new Router<AuthState>({ prefix: "/api/playlists" });
// GET /api/playlists/by-dump/:dumpId/memberships — must be before /:playlistId
router.get("/by-dump/:dumpId/memberships", authMiddleware, (ctx) => {
const { dumpId } = ctx.params;
const userId = ctx.state.user.userId;
const responseBody: APIResponse<PlaylistMembership[]> = {
success: true,
data: getPlaylistMembershipsForDump(dumpId, userId),
};
ctx.response.body = responseBody;
});
// POST /api/playlists — create
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",
);
}
const responseBody: APIResponse<Playlist> = {
success: true,
data: createPlaylist(body, ctx.state.user.userId),
};
ctx.response.status = 201;
ctx.response.body = responseBody;
});
// GET /api/playlists/:playlistId — optional auth
router.get("/:playlistId", async (ctx) => {
const requestingUserId = await parseOptionalAuth(ctx);
const responseBody: APIResponse<PlaylistWithDumps> = {
success: true,
data: getPlaylist(ctx.params.playlistId, requestingUserId),
};
ctx.response.body = responseBody;
});
// PUT /api/playlists/:playlistId — update metadata
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",
);
}
const playlist = updatePlaylist(
ctx.params.playlistId,
body,
ctx.state.user.userId,
can(ctx.state.user, "playlist:moderate"),
);
const responseBody: APIResponse<Playlist> = { success: true, data: playlist };
ctx.response.body = responseBody;
});
// DELETE /api/playlists/:playlistId
router.delete("/:playlistId", authMiddleware, (ctx) => {
deletePlaylist(
ctx.params.playlistId,
ctx.state.user.userId,
can(ctx.state.user, "playlist:moderate"),
);
ctx.response.status = 204;
});
// POST /api/playlists/:playlistId/dumps/:dumpId — add dump
router.post("/:playlistId/dumps/:dumpId", authMiddleware, (ctx) => {
addDumpToPlaylist(
ctx.params.playlistId,
ctx.params.dumpId,
ctx.state.user.userId,
can(ctx.state.user, "playlist:moderate"),
);
ctx.response.status = 204;
});
// DELETE /api/playlists/:playlistId/dumps/:dumpId — remove dump
router.delete("/:playlistId/dumps/:dumpId", authMiddleware, (ctx) => {
removeDumpFromPlaylist(
ctx.params.playlistId,
ctx.params.dumpId,
ctx.state.user.userId,
can(ctx.state.user, "playlist:moderate"),
);
ctx.response.status = 204;
});
// POST /api/playlists/:playlistId/image — upload playlist image
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",
);
}
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");
}
const data = new Uint8Array(await file.arrayBuffer());
const mime = validateImageUpload(data);
// The file goes in before the row changes. Setting image_mime and bumping
// updated_at announces the cover (the `?v=` on its URL, the socket event),
// so the bytes must already be there: an earlier fetch would cache the old
// cover under the new URL, and a failed write would leave a cover that 404s.
// Written beside and renamed over, so the old cover is never half-replaced.
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;
}
const playlist = setPlaylistImage(
id,
mime,
ctx.state.user.userId,
can(ctx.state.user, "playlist:moderate"),
);
const responseBody: APIResponse<Playlist> = { success: true, data: playlist };
ctx.response.body = responseBody;
});
// GET /api/playlists/:playlistId/image — serve playlist image
router.get("/:playlistId/image", async (ctx) => {
const info = getPlaylistImageInfo(ctx.params.playlistId);
if (!info) {
ctx.response.status = 404;
return;
}
await serveUploadedFile(
ctx,
`${PLAYLIST_IMAGES_DIR}/${info.id}`,
info.imageMime,
);
});
// PUT /api/playlists/:playlistId/order — reorder
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",
);
}
reorderPlaylist(
ctx.params.playlistId,
body.dumpIds,
ctx.state.user.userId,
can(ctx.state.user, "playlist:moderate"),
);
const responseBody: APIResponse<null> = { success: true, data: null };
ctx.response.body = responseBody;
});
export default router;