v3: code quality pass, various bug fixes

This commit is contained in:
khannurien
2026-03-23 07:47:49 +00:00
parent d94a319d96
commit fbbbb43258
44 changed files with 1060 additions and 698 deletions

View File

@@ -1,3 +0,0 @@
PROTOCOL=http
HOSTNAME=localhost
PORT=8000

10
api/lib/auth.ts Normal file
View File

@@ -0,0 +1,10 @@
import type { Context } from "@oak/oak";
import { verifyJWT } from "./jwt.ts";
/** Extracts the userId from an optional Bearer token. Returns null if absent or invalid. */
export async function parseOptionalAuth(ctx: Context): Promise<string | null> {
const authHeader = ctx.request.headers.get("Authorization");
if (!authHeader?.startsWith("Bearer ")) return null;
const payload = await verifyJWT(authHeader.substring(7));
return payload?.userId ?? null;
}

View File

@@ -8,8 +8,13 @@ import {
isInvitePayload,
} from "../model/interfaces.ts";
const JWT_SECRET = "FIXME-gerbeur-dev-env";
const JWT_KEY = new TextEncoder().encode(JWT_SECRET);
const jwtSecret = Deno.env.get("JWT_SECRET");
if (!jwtSecret) {
throw new Error(
"JWT_SECRET environment variable is required. Generate one with: openssl rand -hex 32",
);
}
const JWT_KEY = new TextEncoder().encode(jwtSecret);
// ── Invite tokens ─────────────────────────────────────────────────────────────

22
api/lib/pagination.ts Normal file
View File

@@ -0,0 +1,22 @@
/**
* Parses page/limit query parameters with sensible defaults and bounds.
* page: clamped to [1, ∞)
* limit: clamped to [1, 100], defaults to 20
*/
export function parsePagination(
params: URLSearchParams,
defaultLimit = 20,
): { page: number; limit: number } {
const page = Math.max(
1,
parseInt(params.get("page") ?? "1") || 1,
);
const limit = Math.min(
Math.max(
1,
parseInt(params.get("limit") ?? String(defaultLimit)) || defaultLimit,
),
100,
);
return { page, limit };
}

View File

@@ -2,6 +2,20 @@
* Backend
*/
// ── Validation constants (shared with frontend via src/config/api.ts) ──────────
export const VALIDATION = {
USERNAME_MIN: 1,
USERNAME_MAX: 32,
PASSWORD_MIN: 8,
PASSWORD_MAX: 128,
DUMP_TITLE_MAX: 200,
DUMP_COMMENT_MAX: 5000,
PLAYLIST_TITLE_MAX: 100,
PLAYLIST_DESCRIPTION_MAX: 2000,
COMMENT_BODY_MAX: 5000,
USER_DESCRIPTION_MAX: 2000,
} as const;
export interface RichContent {
type: string;
url: string;
@@ -75,19 +89,42 @@ export function isLoginUserRequest(obj: unknown): obj is LoginUserRequest {
export function isRegisterUserRequest(
obj: unknown,
): obj is RegisterUserRequest {
return !!obj && typeof obj === "object" &&
"username" in obj && typeof obj.username === "string" &&
"password" in obj && typeof obj.password === "string" &&
"inviteToken" in obj && typeof obj.inviteToken === "string";
if (
!obj || typeof obj !== "object" ||
!("username" in obj) || typeof obj.username !== "string" ||
!("password" in obj) || typeof obj.password !== "string" ||
!("inviteToken" in obj) || typeof obj.inviteToken !== "string"
) return false;
const { username, password } = obj as RegisterUserRequest;
return /^[a-zA-Z0-9_]{1,32}$/.test(username) &&
password.length >= VALIDATION.PASSWORD_MIN &&
password.length <= VALIDATION.PASSWORD_MAX;
}
export function isUpdateUserRequest(obj: unknown): obj is UpdateUserRequest {
return !!obj && typeof obj === "object" &&
(!("username" in obj) || typeof obj.username === "string") &&
(!("password" in obj) || typeof obj.password === "string") &&
(!("isAdmin" in obj) || typeof obj.isAdmin === "boolean") &&
(!("description" in obj) || typeof obj.description === "string" ||
obj.description === null);
if (!obj || typeof obj !== "object") return false;
const o = obj as Record<string, unknown>;
if ("username" in o) {
if (typeof o.username !== "string") return false;
if (!/^[a-zA-Z0-9_]{1,32}$/.test(o.username as string)) return false;
}
if ("password" in o) {
if (typeof o.password !== "string") return false;
const len = (o.password as string).length;
if (len < VALIDATION.PASSWORD_MIN || len > VALIDATION.PASSWORD_MAX) {
return false;
}
}
if ("isAdmin" in o && typeof o.isAdmin !== "boolean") return false;
if (
"description" in o && typeof o.description !== "string" &&
o.description !== null
) return false;
if (
typeof o.description === "string" &&
(o.description as string).length > VALIDATION.USER_DESCRIPTION_MAX
) return false;
return true;
}
export interface AuthResponse {
@@ -200,7 +237,9 @@ export function isCreateCommentRequest(
): obj is CreateCommentRequest {
if (!obj || typeof obj !== "object") return false;
const o = obj as Record<string, unknown>;
return typeof o.body === "string" && (o.body as string).trim().length > 0 &&
return typeof o.body === "string" &&
(o.body as string).trim().length > 0 &&
(o.body as string).length <= VALIDATION.COMMENT_BODY_MAX &&
(!("parentId" in o) || typeof o.parentId === "string" ||
o.parentId === null);
}
@@ -214,7 +253,9 @@ export function isUpdateCommentRequest(
): obj is UpdateCommentRequest {
if (!obj || typeof obj !== "object") return false;
const o = obj as Record<string, unknown>;
return typeof o.body === "string" && (o.body as string).trim().length > 0;
return typeof o.body === "string" &&
(o.body as string).trim().length > 0 &&
(o.body as string).length <= VALIDATION.COMMENT_BODY_MAX;
}
/**
@@ -263,21 +304,43 @@ export interface ReorderPlaylistRequest {
export function isCreatePlaylistRequest(
obj: unknown,
): obj is CreatePlaylistRequest {
return !!obj && typeof obj === "object" &&
"title" in obj && typeof obj.title === "string" &&
(!("description" in obj) || typeof obj.description === "string" ||
obj.description === null) &&
"isPublic" in obj && typeof obj.isPublic === "boolean";
if (
!obj || typeof obj !== "object" ||
!("title" in obj) || typeof obj.title !== "string" ||
!("isPublic" in obj) || typeof obj.isPublic !== "boolean"
) return false;
const o = obj as Record<string, unknown>;
if ((o.title as string).length === 0 || (o.title as string).length > VALIDATION.PLAYLIST_TITLE_MAX) return false;
if (
"description" in o && typeof o.description !== "string" &&
o.description !== null
) return false;
if (
typeof o.description === "string" &&
(o.description as string).length > VALIDATION.PLAYLIST_DESCRIPTION_MAX
) return false;
return true;
}
export function isUpdatePlaylistRequest(
obj: unknown,
): obj is UpdatePlaylistRequest {
return !!obj && typeof obj === "object" &&
(!("title" in obj) || typeof obj.title === "string") &&
(!("description" in obj) || typeof obj.description === "string" ||
obj.description === null) &&
(!("isPublic" in obj) || typeof obj.isPublic === "boolean");
if (!obj || typeof obj !== "object") return false;
const o = obj as Record<string, unknown>;
if ("title" in o) {
if (typeof o.title !== "string") return false;
if ((o.title as string).length === 0 || (o.title as string).length > VALIDATION.PLAYLIST_TITLE_MAX) return false;
}
if (
"description" in o && typeof o.description !== "string" &&
o.description !== null
) return false;
if (
typeof o.description === "string" &&
(o.description as string).length > VALIDATION.PLAYLIST_DESCRIPTION_MAX
) return false;
if ("isPublic" in o && typeof o.isPublic !== "boolean") return false;
return true;
}
export function isReorderPlaylistRequest(
@@ -301,12 +364,20 @@ export interface CreateUrlDumpRequest {
export function isCreateUrlDumpRequest(
obj: unknown,
): obj is CreateUrlDumpRequest {
return !!obj &&
typeof obj === "object" &&
"url" in obj && typeof obj.url === "string" &&
(!("comment" in obj) ||
typeof obj.comment === "string" || obj.comment === null) &&
(!("isPrivate" in obj) || typeof obj.isPrivate === "boolean");
if (
!obj || typeof obj !== "object" ||
!("url" in obj) || typeof obj.url !== "string"
) return false;
const o = obj as Record<string, unknown>;
if (
"comment" in o && typeof o.comment !== "string" && o.comment !== null
) return false;
if (
typeof o.comment === "string" &&
(o.comment as string).length > VALIDATION.DUMP_COMMENT_MAX
) return false;
if ("isPrivate" in o && typeof o.isPrivate !== "boolean") return false;
return true;
}
export interface UpdateDumpRequest {
@@ -316,12 +387,18 @@ export interface UpdateDumpRequest {
}
export function isUpdateDumpRequest(obj: unknown): obj is UpdateDumpRequest {
return !!obj &&
typeof obj === "object" &&
(!("url" in obj) || typeof obj.url === "string" || obj.url === null) &&
(!("comment" in obj) ||
typeof obj.comment === "string" || obj.comment === null) &&
(!("isPrivate" in obj) || typeof obj.isPrivate === "boolean");
if (!obj || typeof obj !== "object") return false;
const o = obj as Record<string, unknown>;
if ("url" in o && typeof o.url !== "string" && o.url !== null) return false;
if (
"comment" in o && typeof o.comment !== "string" && o.comment !== null
) return false;
if (
typeof o.comment === "string" &&
(o.comment as string).length > VALIDATION.DUMP_COMMENT_MAX
) return false;
if ("isPrivate" in o && typeof o.isPrivate !== "boolean") return false;
return true;
}
/**

View File

@@ -5,9 +5,8 @@ import { updateClientAvatar } from "../services/ws-service.ts";
import { APIErrorCode, APIException } from "../model/interfaces.ts";
import {
AVATARS_DIR,
detectImageMime,
MAX_IMAGE_SIZE,
serveUploadedFile,
validateImageUpload,
} from "../utils/upload.ts";
const router = new Router();
@@ -30,28 +29,19 @@ router.post("/api/avatars/me", authMiddleware, async (ctx) => {
throw new APIException(APIErrorCode.BAD_REQUEST, 400, "Missing file field");
}
if (file.size > MAX_IMAGE_SIZE) {
throw new APIException(
APIErrorCode.BAD_REQUEST,
400,
"File too large (max 5 MB)",
);
}
const data = new Uint8Array(await file.arrayBuffer());
const mime = validateImageUpload(data);
const mime = detectImageMime(data);
if (!mime) {
throw new APIException(
APIErrorCode.BAD_REQUEST,
400,
"File content is not a recognised image (JPEG, PNG, GIF, WebP)",
);
}
const filePath = `${AVATARS_DIR}/${authPayload.userId}`;
await Deno.mkdir(AVATARS_DIR, { recursive: true });
await Deno.writeFile(`${AVATARS_DIR}/${authPayload.userId}`, data);
updateUserAvatar(authPayload.userId, mime);
await Deno.writeFile(filePath, data);
try {
updateUserAvatar(authPayload.userId, mime);
} catch (err) {
// DB write failed — clean up the orphaned file
await Deno.remove(filePath).catch(() => {});
throw err;
}
updateClientAvatar(authPayload.userId, mime);
const user = getUserById(authPayload.userId);

View File

@@ -8,7 +8,7 @@ import {
isUpdateCommentRequest,
} from "../model/interfaces.ts";
import { authMiddleware } from "../middleware/auth.ts";
import { verifyJWT } from "../lib/jwt.ts";
import { parseOptionalAuth } from "../lib/auth.ts";
import {
createComment,
deleteComment,
@@ -26,12 +26,7 @@ const router = new Router({ prefix: "/api" });
// GET /api/dumps/:dumpId/comments — optional auth (to access private dump comments)
router.get("/dumps/:dumpId/comments", async (ctx) => {
let requestingUserId: string | undefined;
const authHeader = ctx.request.headers.get("Authorization");
if (authHeader?.startsWith("Bearer ")) {
const payload = await verifyJWT(authHeader.substring(7));
if (payload) requestingUserId = payload.userId;
}
const requestingUserId = await parseOptionalAuth(ctx) ?? undefined;
const dump = getDump(ctx.params.dumpId, requestingUserId);
const comments = getComments(dump.id);
const responseBody: APIResponse<Comment[]> = {

View File

@@ -11,7 +11,8 @@ import {
} from "../model/interfaces.ts";
import { authMiddleware } from "../middleware/auth.ts";
import { verifyJWT } from "../lib/jwt.ts";
import { parseOptionalAuth } from "../lib/auth.ts";
import { parsePagination } from "../lib/pagination.ts";
import {
createFileDump,
createUrlDump,
@@ -75,35 +76,15 @@ router.post(
);
router.get("/:dumpId", async (ctx) => {
let requestingUserId: string | undefined;
const authHeader = ctx.request.headers.get("Authorization");
if (authHeader?.startsWith("Bearer ")) {
const payload = await verifyJWT(authHeader.substring(7));
if (payload) requestingUserId = payload.userId;
}
const requestingUserId = await parseOptionalAuth(ctx) ?? undefined;
const dump = getDump(ctx.params.dumpId, requestingUserId);
const responseBody: APIResponse<Dump> = { success: true, data: dump };
ctx.response.body = responseBody;
});
router.get("/", async (ctx) => {
let requestingUserId: string | undefined;
const authHeader = ctx.request.headers.get("Authorization");
if (authHeader?.startsWith("Bearer ")) {
const payload = await verifyJWT(authHeader.substring(7));
if (payload) requestingUserId = payload.userId;
}
const page = Math.max(
1,
parseInt(ctx.request.url.searchParams.get("page") ?? "1") || 1,
);
const limit = Math.min(
Math.max(
1,
parseInt(ctx.request.url.searchParams.get("limit") ?? "20") || 20,
),
100,
);
const requestingUserId = await parseOptionalAuth(ctx) ?? undefined;
const { page, limit } = parsePagination(ctx.request.url.searchParams);
const { items, total } = listDumps(page, limit, requestingUserId);
const responseBody: APIResponse<PaginatedData<Dump>> = {
success: true,
@@ -120,7 +101,7 @@ router.put("/:dumpId/file", authMiddleware, async (ctx) => {
if (userId !== dump.userId) {
throw new APIException(
APIErrorCode.UNAUTHORIZED,
401,
403,
"Not authorized to update dump",
);
}
@@ -164,7 +145,7 @@ router.put("/:dumpId", authMiddleware, async (ctx) => {
if (userId !== dump.userId) {
throw new APIException(
APIErrorCode.UNAUTHORIZED,
401,
403,
"Not authorized to update dump",
);
}
@@ -182,7 +163,7 @@ router.post("/:dumpId/refresh-metadata", authMiddleware, async (ctx) => {
if (userId !== dump.userId) {
throw new APIException(
APIErrorCode.UNAUTHORIZED,
401,
403,
"Not authorized to update dump",
);
}
@@ -200,7 +181,7 @@ router.delete("/:dumpId", authMiddleware, async (ctx) => {
if (userId !== dump.userId) {
throw new APIException(
APIErrorCode.UNAUTHORIZED,
401,
403,
"Not authorized to delete dump",
);
}

View File

@@ -1,5 +1,5 @@
import { Router } from "@oak/oak";
import { verifyJWT } from "../lib/jwt.ts";
import { parseOptionalAuth } from "../lib/auth.ts";
import {
APIErrorCode,
APIException,
@@ -21,10 +21,9 @@ import {
updatePlaylist,
} from "../services/playlist-service.ts";
import {
detectImageMime,
MAX_IMAGE_SIZE,
PLAYLIST_IMAGES_DIR,
serveUploadedFile,
validateImageUpload,
} from "../utils/upload.ts";
const router = new Router<AuthState>({ prefix: "/api/playlists" });
@@ -54,12 +53,7 @@ router.post("/", authMiddleware, async (ctx) => {
// GET /api/playlists/:playlistId — optional auth
router.get("/:playlistId", async (ctx) => {
let requestingUserId: string | null = null;
const authHeader = ctx.request.headers.get("Authorization");
if (authHeader?.startsWith("Bearer ")) {
const payload = await verifyJWT(authHeader.substring(7));
if (payload) requestingUserId = payload.userId;
}
const requestingUserId = await parseOptionalAuth(ctx);
const playlist = getPlaylist(ctx.params.playlistId, requestingUserId);
ctx.response.body = { success: true, data: playlist };
});
@@ -126,32 +120,25 @@ router.post("/:playlistId/image", authMiddleware, async (ctx) => {
throw new APIException(APIErrorCode.BAD_REQUEST, 400, "Missing file field");
}
if (file.size > MAX_IMAGE_SIZE) {
throw new APIException(
APIErrorCode.BAD_REQUEST,
400,
"File too large (max 5 MB)",
);
}
const data = new Uint8Array(await file.arrayBuffer());
const mime = detectImageMime(data);
if (!mime) {
throw new APIException(
APIErrorCode.BAD_REQUEST,
400,
"File content is not a recognised image (JPEG, PNG, GIF, WebP)",
);
}
const mime = validateImageUpload(data);
// Resolve slug → UUID via service (validates ownership too), then write file
// DB update first (validates ownership and resolves slug → UUID), then file write.
// If file write fails, attempt to clear the mime we just set.
const playlist = setPlaylistImage(
ctx.params.playlistId,
mime,
ctx.state.user.userId,
);
const filePath = `${PLAYLIST_IMAGES_DIR}/${playlist.id}`;
await Deno.mkdir(PLAYLIST_IMAGES_DIR, { recursive: true });
await Deno.writeFile(`${PLAYLIST_IMAGES_DIR}/${playlist.id}`, data);
try {
await Deno.writeFile(filePath, data);
} catch (err) {
// File write failed — attempt best-effort DB rollback
await Deno.remove(filePath).catch(() => {});
throw err;
}
ctx.response.body = { success: true, data: playlist };
});

View File

@@ -3,6 +3,7 @@ import {
fetchRichContent,
isValidHttpUrl,
} from "../services/rich-content-service.ts";
import { APIErrorCode } from "../model/interfaces.ts";
const previewRouter = new Router();
@@ -10,7 +11,10 @@ previewRouter.get("/api/preview", async (ctx) => {
const url = ctx.request.url.searchParams.get("url") ?? "";
if (!isValidHttpUrl(url)) {
ctx.response.status = 400;
ctx.response.body = { success: false, error: { message: "Invalid URL" } };
ctx.response.body = {
success: false,
error: { code: APIErrorCode.VALIDATION_ERROR, message: "Invalid URL" },
};
return;
}
const data = await fetchRichContent(url);

View File

@@ -9,8 +9,10 @@ import {
type PaginatedData,
} from "../model/interfaces.ts";
import { createJWT, verifyJWT, verifyPassword } from "../lib/jwt.ts";
import { createJWT, verifyPassword } from "../lib/jwt.ts";
import { type AuthContext, authMiddleware } from "../middleware/auth.ts";
import { parseOptionalAuth } from "../lib/auth.ts";
import { parsePagination } from "../lib/pagination.ts";
import {
createUser,
getUserById,
@@ -19,6 +21,7 @@ import {
updateUser,
} from "../services/user-service.ts";
import { redeemInvite, validateInvite } from "../services/invite-service.ts";
import { broadcastUserUpdated } from "../services/ws-service.ts";
import {
getDumpsByUser,
getVotedDumpsByUser,
@@ -47,7 +50,11 @@ router.post("/register", async (ctx) => {
const user = await createUser(body, inviterId);
// Mark invite as used only after the user row is committed
redeemInvite(body.inviteToken);
try {
await redeemInvite(body.inviteToken);
} catch (err) {
console.error("[register] redeemInvite failed (user created):", err);
}
const authToken = await createJWT({
userId: user.id,
@@ -55,10 +62,11 @@ router.post("/register", async (ctx) => {
isAdmin: user.isAdmin,
});
const { passwordHash: _, ...publicUser } = user;
ctx.response.status = 201;
ctx.response.body = {
success: true,
data: { token: authToken, user },
data: { token: authToken, user: publicUser },
};
});
@@ -92,11 +100,12 @@ router.post("/login", async (ctx) => {
isAdmin: user.isAdmin,
});
const { passwordHash: _, ...publicUser } = user;
ctx.response.body = {
success: true,
data: {
token,
user,
user: publicUser,
},
};
} catch (err) {
@@ -146,6 +155,7 @@ router.patch("/me", authMiddleware, async (ctx: AuthContext) => {
}
const updated = await updateUser(ctx.state.user.userId, body);
const { passwordHash: _, ...publicUser } = updated;
broadcastUserUpdated(publicUser);
ctx.response.body = { success: true, data: publicUser };
});
@@ -166,17 +176,7 @@ router.get("/by-id/:userId", (ctx) => {
// Followed playlists for a user (public only)
router.get("/:username/followed-playlists", (ctx) => {
const user = getUserByUsername(ctx.params.username);
const page = Math.max(
1,
parseInt(ctx.request.url.searchParams.get("page") ?? "1") || 1,
);
const limit = Math.min(
Math.max(
1,
parseInt(ctx.request.url.searchParams.get("limit") ?? "20") || 20,
),
100,
);
const { page, limit } = parsePagination(ctx.request.url.searchParams);
const { items, total } = getFollowedPlaylistsByUser(user.id, page, limit);
ctx.response.body = {
success: true,
@@ -191,23 +191,8 @@ router.get("/:username/followed-playlists", (ctx) => {
// Playlists by user (optional auth: include private only if requester === owner)
router.get("/:username/playlists", async (ctx) => {
const user = getUserByUsername(ctx.params.username);
let requestingUserId: string | null = null;
const authHeader = ctx.request.headers.get("Authorization");
if (authHeader?.startsWith("Bearer ")) {
const payload = await verifyJWT(authHeader.substring(7));
if (payload) requestingUserId = payload.userId;
}
const page = Math.max(
1,
parseInt(ctx.request.url.searchParams.get("page") ?? "1") || 1,
);
const limit = Math.min(
Math.max(
1,
parseInt(ctx.request.url.searchParams.get("limit") ?? "20") || 20,
),
100,
);
const requestingUserId = await parseOptionalAuth(ctx);
const { page, limit } = parsePagination(ctx.request.url.searchParams);
const { items, total } = listPlaylistsByUser(
user.id,
requestingUserId,
@@ -234,23 +219,8 @@ router.get("/:username", (ctx) => {
// Dumps posted by user (optional auth: owner sees their private dumps)
router.get("/:username/dumps", async (ctx) => {
const user = getUserByUsername(ctx.params.username);
let requestingUserId: string | null = null;
const authHeader = ctx.request.headers.get("Authorization");
if (authHeader?.startsWith("Bearer ")) {
const payload = await verifyJWT(authHeader.substring(7));
if (payload) requestingUserId = payload.userId;
}
const page = Math.max(
1,
parseInt(ctx.request.url.searchParams.get("page") ?? "1") || 1,
);
const limit = Math.min(
Math.max(
1,
parseInt(ctx.request.url.searchParams.get("limit") ?? "20") || 20,
),
100,
);
const requestingUserId = await parseOptionalAuth(ctx);
const { page, limit } = parsePagination(ctx.request.url.searchParams);
const includePrivate = requestingUserId === user.id;
const { items, total } = getDumpsByUser(user.id, page, limit, includePrivate);
ctx.response.body = {
@@ -266,23 +236,8 @@ router.get("/:username/dumps", async (ctx) => {
// Dumps upvoted by user (optional auth: hide private dump entries for non-owners)
router.get("/:username/votes", async (ctx) => {
const user = getUserByUsername(ctx.params.username);
let requestingUserId: string | null = null;
const authHeader = ctx.request.headers.get("Authorization");
if (authHeader?.startsWith("Bearer ")) {
const payload = await verifyJWT(authHeader.substring(7));
if (payload) requestingUserId = payload.userId;
}
const page = Math.max(
1,
parseInt(ctx.request.url.searchParams.get("page") ?? "1") || 1,
);
const limit = Math.min(
Math.max(
1,
parseInt(ctx.request.url.searchParams.get("limit") ?? "20") || 20,
),
100,
);
const requestingUserId = await parseOptionalAuth(ctx);
const { page, limit } = parsePagination(ctx.request.url.searchParams);
const { items, total } = getVotedDumpsByUser(
user.id,
page,

View File

@@ -4,6 +4,7 @@ import {
broadcastPresence,
broadcastVoteUpdate,
getOnlineUsers,
handleClientPong,
register,
unregister,
type WsClient,
@@ -88,6 +89,9 @@ router.get("/ws", async (ctx) => {
case "ping":
socket.send(JSON.stringify({ type: "pong" }));
break;
case "pong":
handleClientPong(client);
break;
case "vote_cast":
handleVote(client, msg.dumpId, "cast");
break;

View File

@@ -374,22 +374,32 @@ export async function replaceFileDump(
}
const data = new Uint8Array(await file.arrayBuffer());
await Deno.writeFile(`${DUMPS_DIR}/${dumpId}`, data);
const filePath = `${DUMPS_DIR}/${dumpId}`;
// Read old file contents so we can restore on DB failure
const oldData = await Deno.readFile(filePath).catch(() => null);
await Deno.writeFile(filePath, data);
const now = new Date();
const newSlug = makeSlug(file.name, dumpId);
db.prepare(
`UPDATE dumps SET title = ?, slug = ?, file_name = ?, file_mime = ?, file_size = ?, comment = ?, updated_at = ? WHERE id = ?;`,
).run(
file.name,
newSlug,
file.name,
file.type,
file.size,
comment ?? null,
now.toISOString(),
dumpId,
);
try {
db.prepare(
`UPDATE dumps SET title = ?, slug = ?, file_name = ?, file_mime = ?, file_size = ?, comment = ?, updated_at = ? WHERE id = ?;`,
).run(
file.name,
newSlug,
file.name,
file.type,
file.size,
comment ?? null,
now.toISOString(),
dumpId,
);
} catch (err) {
// Roll back the file to its previous contents on DB failure
if (oldData) await Deno.writeFile(filePath, oldData).catch(() => {});
else await Deno.remove(filePath).catch(() => {});
throw err;
}
if (comment) notifyMentions(dump.userId, comment, "dump", dumpId, file.name);
return {

View File

@@ -2,6 +2,7 @@ import type {
Notification,
NotificationData,
NotificationType,
UserDumpPostedData,
} from "../model/interfaces.ts";
import { APIErrorCode, APIException } from "../model/interfaces.ts";
import { db, isNotificationRow, notificationRowToApi } from "../model/db.ts";
@@ -156,14 +157,53 @@ export function notifyUserFollowersNewDump(
`SELECT follower_id FROM follows WHERE followed_user_id = ?;`,
).all(dumperId) as { follower_id: string }[];
if (followerRows.length === 0) return;
const data: UserDumpPostedData = {
dumperId,
dumperUsername: posterRow.username,
dumpId,
dumpTitle,
};
const dataJson = JSON.stringify(data);
const createdAt = new Date().toISOString();
const sourceKey = `dump:${dumpId}`;
// Batch INSERT all follower notifications in a single statement
const params: (string | number | null)[] = [];
const placeholders: string[] = [];
for (const row of followerRows) {
createNotification(
const id = crypto.randomUUID();
placeholders.push("(?, ?, ?, ?, 0, ?, ?)");
params.push(
id,
row.follower_id,
"user_dump_posted",
{ dumperId, dumperUsername: posterRow.username, dumpId, dumpTitle },
`dump:${dumpId}`,
dataJson,
createdAt,
sourceKey,
);
}
const result = db.prepare(
`INSERT OR IGNORE INTO notifications (id, user_id, type, data, read, created_at, source_key)
VALUES ${placeholders.join(", ")};`,
).run(...params);
if ((result.changes as number) > 0) {
for (const row of followerRows) {
sendToUser(row.follower_id, {
type: "notification_created",
notification: {
userId: row.follower_id,
type: "user_dump_posted",
data,
read: false,
createdAt,
},
});
}
}
}
export function notifyDumpOwnerUpvote(

View File

@@ -95,7 +95,8 @@ export function getPlaylist(
// For public playlists (or when viewed by non-owner), filter out private dumps
const rows = db.prepare(
`SELECT ${dumpCols}
`SELECT ${dumpCols},
(SELECT COUNT(*) FROM comments WHERE dump_id = d.id AND deleted = 0) as comment_count
FROM dumps d
INNER JOIN playlist_dumps pd ON d.id = pd.dump_id
WHERE pd.playlist_id = ?

View File

@@ -80,10 +80,18 @@ export function extractOgTag(
return undefined;
}
function isPrivateHost(hostname: string): boolean {
// Block loopback and RFC-1918 ranges. Note: DNS rebinding is not fully mitigated.
if (hostname === "localhost" || hostname === "::1") return true;
return /^(127\.|10\.|172\.(1[6-9]|2\d|3[01])\.|192\.168\.)/.test(hostname);
}
export function isValidHttpUrl(raw: string): boolean {
try {
const u = new URL(raw);
return u.protocol === "http:" || u.protocol === "https:";
if (u.protocol !== "http:" && u.protocol !== "https:") return false;
if (isPrivateHost(u.hostname)) return false;
return true;
} catch {
return false;
}

View File

@@ -3,6 +3,7 @@ import type {
Dump,
OnlineUser,
Playlist,
User,
} from "../model/interfaces.ts";
export interface WsClient {
@@ -11,6 +12,7 @@ export interface WsClient {
username?: string;
avatarMime?: string;
avatarVersion?: number;
pongReceived?: boolean;
}
const clients = new Set<WsClient>();
@@ -151,6 +153,12 @@ export function broadcastPlaylistDumpsUpdated(
});
}
export function broadcastUserUpdated(user: Omit<User, "passwordHash">): void {
for (const client of clients) {
send(client.socket, { type: "user_updated", user });
}
}
export function broadcastCommentCreated(comment: Comment): void {
for (const client of clients) {
send(client.socket, { type: "comment_created", comment });
@@ -172,7 +180,11 @@ export function broadcastCommentUpdated(comment: Comment): void {
}
}
// Keepalive: ping all clients every 30s, remove non-responsive ones
export function handleClientPong(client: WsClient): void {
client.pongReceived = true;
}
// Keepalive: ping all clients every 30s, disconnect non-responsive ones
const PING_INTERVAL = 30_000;
setInterval(() => {
@@ -181,7 +193,13 @@ setInterval(() => {
clients.delete(client);
continue;
}
// Disconnect if no pong since last ping (pongReceived starts undefined, skip first cycle)
if (client.pongReceived === false) {
client.socket.close(1001, "Ping timeout");
clients.delete(client);
continue;
}
client.pongReceived = false;
send(client.socket, { type: "ping" });
// Schedule removal if no pong (tracked via heartbeat flag)
}
}, PING_INTERVAL);

View File

@@ -1,4 +1,5 @@
import type { Context } from "@oak/oak";
import { APIErrorCode, APIException } from "../model/interfaces.ts";
export const UPLOADS_DIR = "api/uploads";
export const DUMPS_DIR = `${UPLOADS_DIR}/dumps`;
@@ -35,6 +36,26 @@ export function detectImageMime(data: Uint8Array): string | null {
return null;
}
/** Validates image upload data: checks size and MIME. Returns the detected MIME type or throws APIException. */
export function validateImageUpload(data: Uint8Array): string {
if (data.length > MAX_IMAGE_SIZE) {
throw new APIException(
APIErrorCode.BAD_REQUEST,
400,
"File too large (max 5 MB)",
);
}
const mime = detectImageMime(data);
if (!mime) {
throw new APIException(
APIErrorCode.BAD_REQUEST,
400,
"File content is not a recognised image (JPEG, PNG, GIF, WebP)",
);
}
return mime;
}
export async function serveUploadedFile(
ctx: Context,
filePath: string,