fix(news): enforce shared comment publication and moderation rules

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

File diff suppressed because it is too large. Load diff
+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");
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,87 @@
import "server-only";
import { and, eq, or, sql } from "drizzle-orm";
import { db, WebsiteArticleComments, WebsiteArticles } from "@/lib/db";
import { rateLimit } from "@/lib/rate-limit";
import { isAllowed } from "@/lib/services/moderation";
export type ArticleCommentTarget = { id: string } | { slug: string };
export type ArticleCommentResult =
| { ok: true; slug: string }
| {
ok: false;
reason:
| "empty"
| "too_long"
| "invalid"
| "moderated"
| "ratelimit"
| "not_found";
retryAfter?: number;
};
/** Authenticated callers share the same quota and uncached publication check. */
export async function submitArticleComment({
userId,
target,
comment: rawComment,
}: {
userId: number;
target: ArticleCommentTarget;
comment: unknown;
}): Promise<ArticleCommentResult> {
if (!Number.isSafeInteger(userId) || userId <= 0)
return { ok: false, reason: "invalid" };
// Preserve the site's five-attempt burst; API and form consume one bucket.
const limit = await rateLimit(`comment:${userId}`, 5, 30_000);
if (!limit.ok)
return { ok: false, reason: "ratelimit", retryAfter: limit.retryAfter };
const comment =
typeof rawComment === "string" ? rawComment.normalize("NFC").trim() : "";
if (!comment) return { ok: false, reason: "empty" };
if (comment.length > 255) return { ok: false, reason: "too_long" };
let articleId = 0n;
if ("id" in target) {
if (!/^\d{1,20}$/.test(target.id)) return { ok: false, reason: "invalid" };
articleId = BigInt(target.id);
if (articleId <= 0n || articleId > 18446744073709551615n)
return { ok: false, reason: "invalid" };
} else if (!target.slug || target.slug.length > 255) {
return { ok: false, reason: "invalid" };
}
if (!(await isAllowed(comment)).ok) return { ok: false, reason: "moderated" };
// Moderate before locking: the optional remote check can take several seconds.
// A locking read sees current publication state and serializes withdrawal/deletion
// with this insert, rather than trusting a prior page or cached article lookup.
return db.transaction(async (tx): Promise<ArticleCommentResult> => {
const [article] = await tx
.select({ id: WebsiteArticles.id, slug: WebsiteArticles.slug })
.from(WebsiteArticles)
.where(
and(
"slug" in target
? eq(WebsiteArticles.slug, target.slug)
: eq(WebsiteArticles.id, articleId),
eq(WebsiteArticles.status, "published"),
or(
sql`${WebsiteArticles.publishAt} IS NULL`,
sql`${WebsiteArticles.publishAt} <= NOW()`,
),
),
)
.limit(1)
.for("update");
if (!article) return { ok: false, reason: "not_found" };
const now = new Date();
await tx.insert(WebsiteArticleComments).values({
articleId: article.id,
userId,
comment,
createdAt: now,
updatedAt: now,
});
return { ok: true, slug: article.slug };
});
}