fix(news): enforce shared comment publication and moderation rules
CI / check (push) Failing after 1m46s
CI / deploy (push) Skipped
CI / publish-container (push) Skipped

This commit is contained in:
Simo committed 2026-09-13 20:14:32 +02:00
1 parent 8aefb415b6
commit fe34d4ac93
7 files changed
+554 -126

No files matched your search

+40 -48
View File
@@ -1,60 +1,52 @@
// Public REST API — post a comment on an article as the Bearer-authed user.
//
// POST /api/articles/:slug/comment — looks up the website_article by slug for
// its id, then inserts a website_article_comments row owned by the user behind
// the Authorization: Bearer token. Comment is required, non-empty, max 255
// chars (matches the VARCHAR(255) column). Fails soft — never returns a 500 for
// DB issues, just a generic error envelope.
import { eq } from "drizzle-orm";
import { apiError, apiJson } from "@/lib/api";
// Public REST API: comments belong to the authenticated Bearer token's user.
import { apiError, apiJson, apiUnavailable } from "@/lib/api";
import { bearerUserId } from "@/lib/api-auth";
import { db, WebsiteArticleComments, WebsiteArticles } from "@/lib/db";
import { rateLimit } from "@/lib/rate-limit";
import { logger } from "@/lib/logger";
import { submitArticleComment } from "@/lib/services/article-comment-submission";
export async function POST(
req: Request,
{ params }: { params: Promise<{ slug: string }> },
) {
const uid = await bearerUserId(req, ["articles:write"]);
if (!uid) return apiError("Unauthorized", 401);
if (!(await rateLimit(`article-comment:${uid}`, 10, 60_000)).ok) {
return apiError("Too many comments. Please wait a minute.", 429);
}
const { slug } = await params;
const body = (await req.json().catch(() => ({}))) as { comment?: unknown };
const comment = typeof body.comment === "string" ? body.comment.trim() : "";
if (!comment) {
return apiError("Comment is required", 422);
}
if (comment.length > 255) {
return apiError("Comment may not be longer than 255 characters", 422);
}
try {
const [article] = await db
.select({ id: WebsiteArticles.id })
.from(WebsiteArticles)
.where(eq(WebsiteArticles.slug, slug))
.limit(1);
if (!article) {
return apiError("Article not found", 404);
}
const now = new Date();
await db.insert(WebsiteArticleComments).values({
articleId: article.id,
const uid = await bearerUserId(req, ["articles:write"]);
if (!uid) return apiError("Unauthorized", 401);
const { slug } = await params;
const body: unknown = await req.json().catch(() => null);
const result = await submitArticleComment({
userId: uid,
comment,
createdAt: now,
updatedAt: now,
target: { slug },
comment:
body && typeof body === "object" && "comment" in body
? body.comment
: undefined,
});
return apiJson({ ok: true });
if (result.ok) return apiJson({ ok: true });
switch (result.reason) {
case "ratelimit": {
const response = apiError(
"Too many comments. Please wait a minute.",
429,
);
response.headers.set("Retry-After", String(result.retryAfter ?? 30));
return response;
}
case "empty":
return apiError("Comment is required", 422);
case "too_long":
return apiError("Comment may not be longer than 255 characters", 422);
case "moderated":
return apiError("Comment was blocked by moderation", 422);
case "invalid":
case "not_found":
return apiError("Article not found", 404);
}
} catch {
return apiError("Could not post comment", 400);
// Driver errors may contain SQL and user content; log a safe diagnostic.
logger.error("Article comment submission failed", {
module: "article-comments",
channel: "api",
});
return apiUnavailable("Could not post comment");
}
}