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

+39 -75
View File
@@ -1,15 +1,11 @@
"use server";
import { eq } from "drizzle-orm";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { auth } from "@/lib/auth";
import { db, WebsiteArticleComments, WebsiteArticles } from "@/lib/db";
import { clientIp, rateLimit } from "@/lib/rate-limit";
import { isAllowed } from "@/lib/services/moderation";
// website_article_comments.comment is VARCHAR(255); keep the write within bounds.
const COMMENT_MAX = 255;
import { sessionUserId } from "@/lib/auth/session-user";
import { logger } from "@/lib/logger";
import { submitArticleComment } from "@/lib/services/article-comment-submission";
type CommentOutcome =
| "posted"
@@ -31,86 +27,54 @@ function isNextRedirect(e: unknown): boolean {
!!e &&
typeof e === "object" &&
"digest" in e &&
typeof (e as { digest?: unknown }).digest === "string" &&
(e as { digest: string }).digest.startsWith("NEXT_REDIRECT")
typeof e.digest === "string" &&
e.digest.startsWith("NEXT_REDIRECT")
);
}
/**
* Post a comment on a news article as the SIGNED-IN user. The author id is read
* from the session (re-fetched via auth()), never from the submitted FormData,
* so a crafted form cannot post as another account. The articleId comes from the
* form and is validated as a BigInt (website_articles.id is UNSIGNED BIGINT).
*
* Errors redirect back with a machine-readable ?error= code; success redirects
* with ?comment=posted.
*/
/** The signed-in session determines ownership; form-supplied author IDs are ignored. */
export async function postComment(formData: FormData): Promise<void> {
const slugHint = String(formData.get("slug") ?? "")
let slug = String(formData.get("slug") ?? "")
.normalize("NFC")
.trim();
let outcome: CommentOutcome = "error";
let slug = slugHint;
try {
const session = await auth();
if (!session?.user?.id) {
redirect("/login");
}
const userId = Number(session.user.id);
if (!Number.isFinite(userId) || userId <= 0) {
redirect("/login");
}
await clientIp();
if (!(await rateLimit(`comment:${userId}`, 5, 30_000)).ok) {
outcome = "ratelimit";
} else {
const comment = String(formData.get("comment") ?? "")
.normalize("NFC")
.trim()
.slice(0, COMMENT_MAX);
if (!comment) {
outcome = "empty";
} else if (!(await isAllowed(comment)).ok) {
outcome = "moderated";
} else {
const articleIdRaw = String(formData.get("articleId") ?? "")
const userId = sessionUserId(session?.user?.id);
if (!userId) redirect("/login");
const result = await submitArticleComment({
userId,
target: {
id: String(formData.get("articleId") ?? "")
.normalize("NFC")
.trim();
if (!/^\d+$/.test(articleIdRaw)) {
outcome = "invalid";
} else {
const articleId = BigInt(articleIdRaw);
const [article] = await db
.select({ slug: WebsiteArticles.slug })
.from(WebsiteArticles)
.where(eq(WebsiteArticles.id, articleId))
.limit(1);
if (!article) {
outcome = "not_found";
} else {
slug = article.slug;
const now = new Date();
await db.insert(WebsiteArticleComments).values({
articleId,
userId,
comment,
createdAt: now,
updatedAt: now,
});
outcome = "posted";
}
}
}
.trim(),
},
comment: formData.get("comment"),
});
if (result.ok) {
slug = result.slug;
outcome = "posted";
} else {
outcome = result.reason === "too_long" ? "invalid" : result.reason;
}
} catch (e) {
if (isNextRedirect(e)) throw e;
outcome = "error";
} catch (error) {
if (isNextRedirect(error)) throw error;
// Driver errors can include SQL and comment text: retain only safe context.
logger.error("Article comment submission failed", {
module: "article-comments",
channel: "site",
});
}
if (slug) revalidatePath(`/news/${slug}`);
if (outcome === "posted") {
try {
revalidatePath(`/news/${slug}`);
} catch {
logger.error("Article comment refresh failed", {
module: "article-comments",
channel: "site",
});
}
}
commentRedirect(slug, outcome);
}
+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");
}
}
@@ -0,0 +1,257 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const state = vi.hoisted(() => ({
userId: 100,
sessionId: "100" as string | null,
article: {
id: "12",
slug: "public-news",
status: "published",
publishAt: null as Date | null,
},
words: [] as string[],
queries: [] as string[],
writes: [] as unknown[][],
transactions: 0,
lockedWrites: [] as boolean[],
inTransaction: false,
failRead: false,
failWrite: false,
withdrawDuringModeration: false,
log: vi.fn(),
revalidate: vi.fn(),
}));
vi.mock("@/lib/db", async () => {
const schema = await import("@/db/schema");
const { drizzle } = await import("drizzle-orm/mysql-proxy");
const db = drizzle(async (query, parameters) => {
state.queries.push(query);
if (query.includes(" from `website_wordfilter`")) {
if (state.withdrawDuringModeration) state.article.status = "draft";
return { rows: state.words.map((word) => [word]) };
}
if (
query.startsWith("select ") &&
query.includes(" from `website_articles`")
) {
if (state.failRead) throw new Error("private SQL and comment payload");
if (
query.includes("`status` = ?") &&
state.article.status !== "published"
)
return { rows: [] };
if (
query.includes("<= NOW()") &&
state.article.publishAt &&
state.article.publishAt > new Date()
)
return { rows: [] };
if (
String(parameters[0]) !== state.article.id &&
parameters[0] !== state.article.slug
)
return { rows: [] };
const columns = query
.slice(7, query.indexOf(" from "))
.split(", ")
.map((column) => column.replaceAll("`", ""));
return {
rows: [columns.map((column) => state.article[column as "id" | "slug"])],
};
}
if (query.startsWith("insert into `website_article_comments`")) {
if (state.failWrite) throw new Error("private SQL and comment payload");
state.writes.push(parameters);
state.lockedWrites.push(
state.inTransaction &&
state.queries.some((sql) => sql.endsWith("for update")),
);
return { rows: [{ insertId: 1, affectedRows: 1 }] };
}
return { rows: [] };
});
Object.defineProperty(db, "transaction", {
value: async (callback: (tx: typeof db) => Promise<unknown>) => {
state.transactions += 1;
state.inTransaction = true;
try {
return await callback(db);
} finally {
state.inTransaction = false;
}
},
});
return { ...schema, db };
});
vi.mock("@/lib/auth", () => ({
auth: async () => ({ user: { id: state.sessionId } }),
}));
vi.mock("@/lib/api-auth", () => ({
bearerUserId: async () => state.userId || null,
}));
vi.mock("@/env", () => ({ env: {} }));
vi.mock("@/lib/redis", () => ({ redis: null }));
vi.mock("@/lib/logger", () => ({ logger: { error: state.log } }));
vi.mock("next/cache", () => ({ revalidatePath: state.revalidate }));
vi.mock("next/navigation", () => ({
redirect: (url: string) => {
throw Object.assign(new Error(url), {
digest: `NEXT_REDIRECT;replace;${url};307;`,
});
},
}));
import { postComment } from "@/actions/article-comments";
import { POST } from "@/app/api/articles/[slug]/comment/route";
import { reloadWordFilter } from "@/lib/services/moderation";
function api(comment: unknown = "Hello", slug = "public-news") {
return POST(
new Request("https://hotel.test/api/articles/public-news/comment", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ comment, userId: 999 }),
}),
{ params: Promise.resolve({ slug }) },
);
}
async function site(comment = "Hello", articleId = "12") {
const form = new FormData();
form.set("comment", comment);
form.set("articleId", articleId);
form.set("slug", "public-news");
form.set("userId", "999");
try {
await postComment(form);
} catch (error) {
if (error instanceof Error && "digest" in error) return error.message;
throw error;
}
throw new Error("Expected action redirect");
}
beforeEach(() => {
state.userId += 1;
state.sessionId = String(state.userId);
state.article = {
id: "12",
slug: "public-news",
status: "published",
publishAt: null,
};
state.words = [];
state.queries = [];
state.writes = [];
state.lockedWrites = [];
state.transactions = 0;
state.inTransaction = false;
state.failRead = false;
state.failWrite = false;
state.withdrawDuringModeration = false;
state.log.mockReset();
state.revalidate.mockReset();
reloadWordFilter();
});
describe("article comment entrypoints share publication and abuse policy", () => {
it.each(["draft", "scheduled"])(
"blocks %s articles through both channels",
async (status) => {
state.article.status = status;
expect(await site()).toBe("/news/public-news?error=not_found");
expect((await api()).status).toBe(404);
expect(state.writes).toHaveLength(0);
},
);
it("blocks published articles whose scheduled date is still in the future", async () => {
state.article.publishAt = new Date(Date.now() + 60_000);
expect(await site()).toBe("/news/public-news?error=not_found");
expect((await api()).status).toBe(404);
expect(state.writes).toHaveLength(0);
});
it("keeps due articles writable and locks eligibility until each insert", async () => {
state.article.publishAt = new Date(Date.now() - 60_000);
expect(await site()).toBe("/news/public-news?comment=posted");
const response = await api();
expect(response.status).toBe(200);
expect(await response.json()).toEqual({ ok: true });
expect(state.transactions).toBe(2);
expect(state.lockedWrites).toEqual([true, true]);
expect(state.writes).toHaveLength(2);
for (const parameters of state.writes) {
expect(parameters).toContain(state.userId);
expect(parameters).not.toContain(999);
}
});
it("applies the real configured word filter to both channels", async () => {
state.words = ["forbidden"];
expect(await site("FORBIDDEN content")).toBe(
"/news/public-news?error=moderated",
);
expect((await api("FORBIDDEN content")).status).toBe(422);
expect(state.writes).toHaveLength(0);
});
it("rechecks publication after moderation completes", async () => {
state.withdrawDuringModeration = true;
expect((await api()).status).toBe(404);
expect(state.writes).toHaveLength(0);
});
it.each(["site", "api"])(
"shares five attempts across channels starting with %s",
async (first) => {
for (let i = 0; i < 5; i++) {
if (first === "site") expect(await site()).toContain("comment=posted");
else expect((await api()).status).toBe(200);
}
if (first === "site") expect((await api()).status).toBe(429);
else expect(await site()).toBe("/news/public-news?error=ratelimit");
expect(state.writes).toHaveLength(5);
},
);
it("normalizes the same text before moderation and persistence", async () => {
await site(" cafe\u0301 ");
await api(" cafe\u0301 ");
expect(state.writes).toHaveLength(2);
for (const parameters of state.writes) expect(parameters).toContain("café");
});
it.each(["failRead", "failWrite"] as const)(
"returns safe recoverable errors for %s",
async (failure) => {
state[failure] = true;
expect(await site()).toBe("/news/public-news?error=error");
const response = await api();
expect(response.status).toBe(503);
expect(await response.json()).toEqual({
error: "Could not post comment",
});
expect(state.log).toHaveBeenCalledTimes(2);
expect(JSON.stringify(state.log.mock.calls)).not.toContain("private SQL");
expect(state.writes).toHaveLength(0);
},
);
it("rejects missing articles without inserting", async () => {
expect(await site("Hello", "42")).toContain("error=not_found");
expect((await api("Hello", "missing")).status).toBe(404);
expect(state.writes).toHaveLength(0);
});
it("keeps sessions mandatory for forms and bearer authentication for API", async () => {
state.userId = 0;
state.sessionId = null;
expect(await site()).toBe("/login");
expect((await api()).status).toBe(401);
expect(state.writes).toHaveLength(0);
});
it("rejects oversized input before insertion without silently truncating", async () => {
expect(await site("a".repeat(256))).toContain("error=invalid");
expect((await api("a".repeat(256))).status).toBe(422);
expect(state.writes).toHaveLength(0);
});
it("does not turn a committed comment into a retry when revalidation fails", async () => {
state.revalidate.mockImplementation(() => {
throw new Error("cache unavailable");
});
expect(await site()).toContain("comment=posted");
expect(state.writes).toHaveLength(1);
});
});
@@ -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 };
});
}