v3: code quality pass, various bug fixes
This commit is contained in:
@@ -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);
|
||||
|
||||
@@ -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[]> = {
|
||||
|
||||
@@ -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",
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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 };
|
||||
});
|
||||
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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;
|
||||
|
||||
Reference in New Issue
Block a user