feat(forum): add independently moderated threads and replies #45
|
|
@ -86,3 +86,5 @@ Explicit messaging consent and eligibility: see [Phase 4F API guide](docs/messag
|
|||
Blog drafts, publication and SEO metadata: see [Phase 4G API guide](docs/blog-publishing-api.md).
|
||||
|
||||
Live customer segments and consent-aware audience checks: see [Phase 4H API guide](docs/customer-segments-api.md).
|
||||
|
||||
Moderated community discussions: see [Phase 5A API guide](docs/forum-api.md).
|
||||
|
|
|
|||
|
|
@ -0,0 +1,32 @@
|
|||
# Moderated community discussions (Phase 5A)
|
||||
|
||||
Active accounts can submit immutable discussion threads and flat replies. Everything begins pending and stays private until an independent staff moderator approves it. Customers explicitly choose the public display alias; the application never substitutes their account name or contact details. Submission and moderation history remain append-only.
|
||||
|
||||
| Method | Route | Access |
|
||||
| ------ | ------------------------------------------------------ | --------------------------------------------------------------------------------- |
|
||||
| POST | `/api/v1/forum/threads` | Active session; create a pending thread. |
|
||||
| POST | `/api/v1/forum/threads/:id/replies` | Active session; create a pending reply under an available approved thread. |
|
||||
| GET | `/api/v1/forum/posts` | Active session; own submissions and moderation status, paginated. |
|
||||
| GET | `/api/v1/forum-moderation` | `forum.read`; scoped queue/history with optional `status` and `threadId` filters. |
|
||||
| POST | `/api/v1/forum-moderation/:id/decision` | `forum.moderate`; approve, reject, or hide with an immutable reason. |
|
||||
| GET | `/api/v1/storefront/:organizationId/forum` | Public; available approved threads. |
|
||||
| GET | `/api/v1/storefront/:organizationId/forum/:id` | Public; one available approved thread. |
|
||||
| GET | `/api/v1/storefront/:organizationId/forum/:id/replies` | Public; available approved replies under that thread. |
|
||||
|
||||
Thread input is `{ "title": "Candle care question", "displayName": "Candle fan", "body": "How do I care for my candle?", "idempotencyKey": "<uuid>" }`. Replies omit `title`; reply targets must be root threads, not other replies. Title is 3–160 single-line characters, alias 1–80, and body 10–5,000 with line breaks/tabs supported. All text is trimmed, bounded plain text; HTML and unsafe control characters are rejected. Identity, organization, timestamps, and moderation metadata are never client-editable. Frontends must render/escape content as text.
|
||||
|
||||
Each account may have at most 20 pending posts across threads/replies in its organization. Existing authentication and request rate limits also apply. Moderation releases pending capacity; approved posts do not consume that quota. Submission retries with the same account/key and normalized input return the existing post/current status without another audit event. Changed input, including a different parent thread, returns `IDEMPOTENCY_CONFLICT` (409). Exact reply retries remain readable by their author even if the parent later becomes unavailable, without creating or publishing content.
|
||||
|
||||
Own responses contain only post ID, thread ID, alias, title/body, submission date, and `moderationStatus`. Staff queue/decision responses additionally provide author ID, current account status, and moderation records/notes. `forum.read` and `forum.moderate` are separate permissions; self-moderation returns `FORUM_SELF_MODERATION` (403) even for Owners. Existing system Owners gain both permissions; custom roles remain explicit.
|
||||
|
||||
Moderation input is `{ "decision": "APPROVED", "note": "Content checked by staff", "idempotencyKey": "<uuid>" }`, with note 3–1,000 characters. Pending posts can receive one approval or rejection; only approved posts can subsequently be hidden. Rejection and hiding are terminal. Invalid transitions return `FORUM_MODERATION_STATE` (409); inactive authors cannot be approved (`FORUM_AUTHOR_INACTIVE`, 409). Approval of a reply also requires a currently available root thread. Exact latest or historical decision-key retries return the current record without repeating decisions or audits; changed commands return `IDEMPOTENCY_CONFLICT` (409).
|
||||
|
||||
Public queries require approval, no hiding event, and an active author. Replies additionally require the parent thread to meet those conditions. Hiding a root therefore removes it and every reply from public discovery without rewriting reply evidence. Public responses expose only IDs/parent IDs, chosen alias, title/body and submission date; account IDs, profile/contact information, staff notes, decision history, hashes and keys are absent. Missing, private, unavailable, reply-as-thread, and foreign-scope roots return `FORUM_NOT_FOUND` (404). All public routes use the existing shared storefront rate limit and pagination (default 25, maximum 100; offset maximum 10,000).
|
||||
|
||||
Writes recheck live account/permission inside the existing organization lock. Native guards serialize pending quotas, require scoped approved root targets, reject self-moderation, enforce decision sequence/transitions, and freeze both submissions and decisions. Audit actions are `forum.submitted`, `forum.approved`, `forum.rejected`, and `forum.hidden`. Publishing or hiding occurs through evidence append, with no mutable status flag to bypass moderation.
|
||||
|
||||
Deploy the additive enum/tables/permission migration before the application. Composite user/parent/post foreign keys enforce organization scope. Existing migrations and commerce records are untouched. Older code ignores the new tables; preserve submission, moderation, and audit history on rollback. Shared multiline validation preserves blog behavior.
|
||||
|
||||
This milestone provides moderated flat discussions, not editing/deletion, nested replies, categories, attachments, voting, reporting/appeals, moderator restoration, realtime chat, outbound notifications, or a forum frontend. Immutable posts avoid edits bypassing review; customers can submit corrected text under a fresh key. Additional community delivery work can follow actual usage and policy decisions.
|
||||
|
||||
Verification covers private pending submissions, independent moderation, public alias projection, separately moderated replies, parent hiding/inactive authors, scoped access, replay conflicts, immutable native records, pending quotas, competing decisions, strict text/shape validation, schema drift, and prior blog validation. Multi-connection native PostgreSQL CI remains subject to the existing test setup.
|
||||
|
|
@ -67,6 +67,8 @@ Wishlist, verified reviews/moderation, seasonal campaigns, discounts, cart recov
|
|||
|
||||
Moderated forums, advanced analytics, forecasts, accounting adapters, profitability and workflow automation. SaaS tenancy/billing requires a separate architecture decision before implementation; an organization table alone does not provide tenant isolation.
|
||||
|
||||
- 5A (backend implemented): immutable discussion threads and flat replies, independent append-only approval/rejection/hiding, private author history, public alias-only discovery, parent visibility gates, and pending-submission quotas. Forum UI, editing/appeals, media, realtime features and notifications remain separate milestones.
|
||||
|
||||
## Definition of done for every feature
|
||||
|
||||
Small cohesive files; no duplicated business rules; unit tests for success, failure and boundaries; HTTP/integration tests where behavior crosses boundaries; schema migration and upgrade validation when persistence changes; documented API and permission contract; passing checks; focused Conventional Commit; reviewed pull request. Do not mark an entire phase complete until its end-to-end acceptance criteria pass.
|
||||
|
|
|
|||
|
|
@ -0,0 +1,43 @@
|
|||
enum ForumDecisionKind {
|
||||
APPROVED
|
||||
REJECTED
|
||||
HIDDEN
|
||||
}
|
||||
model ForumPost {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
organizationId String @map("organization_id") @db.Uuid
|
||||
userId String @map("user_id") @db.Uuid
|
||||
threadId String? @map("thread_id") @db.Uuid
|
||||
displayName String @map("display_name") @db.VarChar(80)
|
||||
title String? @db.VarChar(160)
|
||||
body String @db.VarChar(5000)
|
||||
idempotencyKey String @map("idempotency_key") @db.Uuid
|
||||
requestHash String @map("request_hash") @db.Char(64)
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
|
||||
user User @relation(fields: [userId, organizationId], references: [id, organizationId], onDelete: Restrict)
|
||||
thread ForumPost? @relation("ForumReplies", fields: [threadId, organizationId], references: [id, organizationId], onDelete: Restrict)
|
||||
replies ForumPost[] @relation("ForumReplies")
|
||||
events ForumModeration[]
|
||||
@@unique([id, organizationId])
|
||||
@@unique([userId, organizationId, idempotencyKey])
|
||||
@@index([organizationId, threadId, createdAt, id])
|
||||
@@index([organizationId, userId, createdAt, id])
|
||||
@@map("forum_posts")
|
||||
}
|
||||
model ForumModeration {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
organizationId String @map("organization_id") @db.Uuid
|
||||
postId String @map("post_id") @db.Uuid
|
||||
actorId String @map("actor_id") @db.Uuid
|
||||
sequence Int
|
||||
kind ForumDecisionKind
|
||||
note String @db.VarChar(1000)
|
||||
idempotencyKey String @map("idempotency_key") @db.Uuid
|
||||
requestHash String @map("request_hash") @db.Char(64)
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
|
||||
post ForumPost @relation(fields: [postId, organizationId], references: [id, organizationId], onDelete: Restrict)
|
||||
actor User @relation(fields: [actorId, organizationId], references: [id, organizationId], onDelete: Restrict)
|
||||
@@unique([postId, sequence])
|
||||
@@unique([organizationId, idempotencyKey])
|
||||
@@map("forum_moderation")
|
||||
}
|
||||
|
|
@ -50,5 +50,6 @@
|
|||
"20261007120000_cart_recovery": "a415f3b458c55bf37a95f8d2f3b31dfc7ae4427f04aabc9f0910f1201caa6d31",
|
||||
"20261007130000_messaging_consent": "b4fd5b1cf6a7cd17083a4b5fbef815ec1ebc25ba7538c6de18c05e16212155dd",
|
||||
"20261007140000_blog_publishing": "92e8d98a8e89f3eda28b6cf5c3b45125a325e5d8e852f1e5a0a3cf5d7eff65a4",
|
||||
"20261007150000_customer_segments": "bcafd50bc12dc44b7ee532ba4ca23da0b12eb3f0e89ad4b168789a22e110969a"
|
||||
"20261007150000_customer_segments": "bcafd50bc12dc44b7ee532ba4ca23da0b12eb3f0e89ad4b168789a22e110969a",
|
||||
"20261007160000_moderated_forums": "3a7dce2115e06acd0f4b02d366721db5ebcf8b5f31106b5d85093c1374a2b6a5"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,85 @@
|
|||
CREATE TYPE "ForumDecisionKind" AS ENUM ('APPROVED', 'REJECTED', 'HIDDEN');
|
||||
CREATE TABLE "forum_posts" (
|
||||
"id" UUID NOT NULL, "organization_id" UUID NOT NULL, "user_id" UUID NOT NULL, "thread_id" UUID,
|
||||
"display_name" VARCHAR(80) NOT NULL, "title" VARCHAR(160), "body" VARCHAR(5000) NOT NULL,
|
||||
"idempotency_key" UUID NOT NULL, "request_hash" CHAR(64) NOT NULL,
|
||||
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT "forum_posts_pkey" PRIMARY KEY ("id"),
|
||||
CONSTRAINT "forum_posts_user_id_organization_id_fkey" FOREIGN KEY ("user_id", "organization_id") REFERENCES "users"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE,
|
||||
CONSTRAINT "forum_post_content" CHECK (char_length(btrim(display_name)) >= 1 AND char_length(btrim(body)) >= 10 AND request_hash ~ '^[a-f0-9]{64}$'),
|
||||
CONSTRAINT "forum_post_kind" CHECK ((thread_id IS NULL AND title IS NOT NULL AND char_length(btrim(title)) >= 3) OR (thread_id IS NOT NULL AND title IS NULL AND thread_id <> id))
|
||||
);
|
||||
CREATE UNIQUE INDEX "forum_posts_id_organization_id_key" ON "forum_posts"("id", "organization_id");
|
||||
CREATE UNIQUE INDEX "forum_posts_user_id_organization_id_idempotency_key_key" ON "forum_posts"("user_id", "organization_id", "idempotency_key");
|
||||
CREATE INDEX "forum_posts_organization_id_thread_id_created_at_id_idx" ON "forum_posts"("organization_id", "thread_id", "created_at", "id");
|
||||
CREATE INDEX "forum_posts_organization_id_user_id_created_at_id_idx" ON "forum_posts"("organization_id", "user_id", "created_at", "id");
|
||||
ALTER TABLE forum_posts ADD CONSTRAINT "forum_posts_thread_id_organization_id_fkey" FOREIGN KEY ("thread_id", "organization_id") REFERENCES "forum_posts"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
CREATE TABLE "forum_moderation" (
|
||||
"id" UUID NOT NULL, "organization_id" UUID NOT NULL, "post_id" UUID NOT NULL, "actor_id" UUID NOT NULL,
|
||||
"sequence" INTEGER NOT NULL, "kind" "ForumDecisionKind" NOT NULL, "note" VARCHAR(1000) NOT NULL,
|
||||
"idempotency_key" UUID NOT NULL, "request_hash" CHAR(64) NOT NULL,
|
||||
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT "forum_moderation_pkey" PRIMARY KEY ("id"),
|
||||
CONSTRAINT "forum_moderation_post_id_organization_id_fkey" FOREIGN KEY ("post_id", "organization_id") REFERENCES "forum_posts"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE,
|
||||
CONSTRAINT "forum_moderation_actor_id_organization_id_fkey" FOREIGN KEY ("actor_id", "organization_id") REFERENCES "users"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE,
|
||||
CONSTRAINT "forum_moderation_terms" CHECK (sequence BETWEEN 1 AND 2 AND char_length(btrim(note)) >= 3 AND request_hash ~ '^[a-f0-9]{64}$')
|
||||
);
|
||||
CREATE UNIQUE INDEX "forum_moderation_post_id_sequence_key" ON "forum_moderation"("post_id", "sequence");
|
||||
CREATE UNIQUE INDEX "forum_moderation_organization_id_idempotency_key_key" ON "forum_moderation"("organization_id", "idempotency_key");
|
||||
CREATE FUNCTION reject_forum_mutation() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
BEGIN RAISE EXCEPTION 'Forum submissions and moderation history are immutable'; END;
|
||||
$$;
|
||||
CREATE TRIGGER forum_posts_immutable BEFORE UPDATE OR DELETE ON forum_posts FOR EACH ROW EXECUTE FUNCTION reject_forum_mutation();
|
||||
CREATE TRIGGER forum_moderation_immutable BEFORE UPDATE OR DELETE ON forum_moderation FOR EACH ROW EXECUTE FUNCTION reject_forum_mutation();
|
||||
|
||||
CREATE FUNCTION guard_forum_submission() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
DECLARE parent forum_posts%ROWTYPE;
|
||||
BEGIN
|
||||
PERFORM id FROM organizations WHERE id = NEW.organization_id FOR UPDATE;
|
||||
IF NOT EXISTS (SELECT 1 FROM users WHERE id = NEW.user_id AND organization_id = NEW.organization_id AND status = 'ACTIVE')
|
||||
THEN RAISE EXCEPTION 'Forum submission requires an active author'; END IF;
|
||||
IF (SELECT COUNT(*) FROM forum_posts p WHERE p.user_id = NEW.user_id AND p.organization_id = NEW.organization_id
|
||||
AND NOT EXISTS (SELECT 1 FROM forum_moderation m WHERE m.post_id = p.id)) >= 20
|
||||
THEN RAISE EXCEPTION 'Forum pending submission limit reached'; END IF;
|
||||
IF NEW.thread_id IS NOT NULL THEN
|
||||
SELECT * INTO parent FROM forum_posts WHERE id = NEW.thread_id AND organization_id = NEW.organization_id FOR UPDATE;
|
||||
IF parent.id IS NULL OR parent.thread_id IS NOT NULL
|
||||
OR NOT EXISTS (SELECT 1 FROM users WHERE id = parent.user_id AND status = 'ACTIVE')
|
||||
OR NOT EXISTS (SELECT 1 FROM forum_moderation WHERE post_id = parent.id AND kind = 'APPROVED')
|
||||
OR EXISTS (SELECT 1 FROM forum_moderation WHERE post_id = parent.id AND kind = 'HIDDEN')
|
||||
THEN RAISE EXCEPTION 'Reply requires an available approved thread'; END IF;
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$;
|
||||
CREATE TRIGGER forum_posts_eligibility BEFORE INSERT ON forum_posts FOR EACH ROW EXECUTE FUNCTION guard_forum_submission();
|
||||
|
||||
CREATE FUNCTION guard_forum_moderation() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
DECLARE target forum_posts%ROWTYPE; parent forum_posts%ROWTYPE; last_kind "ForumDecisionKind";
|
||||
BEGIN
|
||||
PERFORM id FROM organizations WHERE id = NEW.organization_id FOR UPDATE;
|
||||
SELECT * INTO target FROM forum_posts WHERE id = NEW.post_id AND organization_id = NEW.organization_id FOR UPDATE;
|
||||
IF target.id IS NULL OR target.user_id = NEW.actor_id THEN RAISE EXCEPTION 'Forum post requires an independent moderator'; END IF;
|
||||
SELECT kind INTO last_kind FROM forum_moderation WHERE post_id = target.id ORDER BY sequence DESC LIMIT 1;
|
||||
IF NEW.kind = 'HIDDEN' THEN
|
||||
IF NEW.sequence <> 2 OR last_kind IS DISTINCT FROM 'APPROVED'::"ForumDecisionKind"
|
||||
THEN RAISE EXCEPTION 'Only approved posts can be hidden'; END IF;
|
||||
ELSE
|
||||
IF NEW.sequence <> 1 OR last_kind IS NOT NULL THEN RAISE EXCEPTION 'Post already decided'; END IF;
|
||||
IF NEW.kind = 'APPROVED' THEN
|
||||
IF NOT EXISTS (SELECT 1 FROM users WHERE id = target.user_id AND status = 'ACTIVE') THEN RAISE EXCEPTION 'Inactive author cannot be approved'; END IF;
|
||||
IF target.thread_id IS NOT NULL THEN
|
||||
SELECT * INTO parent FROM forum_posts WHERE id = target.thread_id FOR UPDATE;
|
||||
IF NOT EXISTS (SELECT 1 FROM users WHERE id = parent.user_id AND status = 'ACTIVE')
|
||||
OR NOT EXISTS (SELECT 1 FROM forum_moderation WHERE post_id = parent.id AND kind = 'APPROVED')
|
||||
OR EXISTS (SELECT 1 FROM forum_moderation WHERE post_id = parent.id AND kind = 'HIDDEN')
|
||||
THEN RAISE EXCEPTION 'Reply approval requires an available thread'; END IF;
|
||||
END IF;
|
||||
END IF;
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$;
|
||||
CREATE TRIGGER forum_moderation_transition BEFORE INSERT ON forum_moderation FOR EACH ROW EXECUTE FUNCTION guard_forum_moderation();
|
||||
UPDATE roles SET permissions = ARRAY(SELECT DISTINCT unnest(permissions || ARRAY['forum.read', 'forum.moderate']))
|
||||
WHERE is_system = true AND name = 'Owner';
|
||||
|
|
@ -94,6 +94,8 @@ model User {
|
|||
blogsCreated BlogArticle[] @relation("BlogCreator")
|
||||
blogsPublished BlogArticle[] @relation("BlogPublisher")
|
||||
blogsWithdrawn BlogArticle[] @relation("BlogWithdrawer")
|
||||
forumPosts ForumPost[]
|
||||
forumDecisions ForumModeration[]
|
||||
reviewPurchases ReviewPurchaseVerification[] @relation("ReviewBuyer")
|
||||
reviewVerifications ReviewPurchaseVerification[] @relation("ReviewVerifier")
|
||||
reviewRevocations ReviewPurchaseRevocation[]
|
||||
|
|
|
|||
|
|
@ -17,9 +17,11 @@ import { CampaignsModule } from './campaigns/campaigns.module';
|
|||
import { MessagingModule } from './messaging/messaging.module';
|
||||
import { BlogModule } from './blog/blog.module';
|
||||
import { SegmentsModule } from './segments/segments.module';
|
||||
import { ForumModule } from './forum/forum.module';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
ForumModule,
|
||||
SegmentsModule,
|
||||
BlogModule,
|
||||
MessagingModule,
|
||||
|
|
|
|||
|
|
@ -1,20 +1,12 @@
|
|||
import { z } from 'zod';
|
||||
import { text } from '../common/input';
|
||||
import { text, multilineText } from '../common/input';
|
||||
import { groupSchema } from '../catalog/catalog.schemas';
|
||||
import { pageSchema } from '../identity/identity.schemas';
|
||||
export const blogSlugSchema = groupSchema.shape.slug;
|
||||
const fields = {
|
||||
title: text(160),
|
||||
summary: text(500),
|
||||
body: z
|
||||
.string()
|
||||
.trim()
|
||||
.min(1)
|
||||
.max(20000)
|
||||
.regex(
|
||||
/^[^<>\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]*$/,
|
||||
'Plain text only',
|
||||
),
|
||||
body: multilineText(20000),
|
||||
};
|
||||
const version = z.number().int().min(0).max(2147483646);
|
||||
export const blogCreateSchema = z
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import { REVIEW_ERRORS } from './review-errors';
|
|||
import { CAMPAIGN_ERRORS } from './campaign-errors';
|
||||
import { MESSAGING_ERRORS } from './messaging-errors';
|
||||
import { BLOG_ERRORS } from './blog-errors';
|
||||
import { FORUM_ERRORS } from './forum-errors';
|
||||
import { CHECKOUT_ERRORS } from './checkout-errors';
|
||||
import { OPERATIONS_ERRORS } from './operations-errors';
|
||||
import { PLATFORM_ERRORS } from './platform-errors';
|
||||
|
|
@ -17,6 +18,7 @@ import { B2B_ARTWORK_ERRORS } from './b2b-artwork-errors';
|
|||
import { B2B_ORDER_ERRORS } from './b2b-order-errors';
|
||||
import { B2B_PAYMENT_ERRORS } from './b2b-payment-errors';
|
||||
export const ERRORS = {
|
||||
...FORUM_ERRORS,
|
||||
...BLOG_ERRORS,
|
||||
...MESSAGING_ERRORS,
|
||||
...CAMPAIGN_ERRORS,
|
||||
|
|
|
|||
|
|
@ -0,0 +1,27 @@
|
|||
export const FORUM_ERRORS = {
|
||||
FORUM_NOT_FOUND: [
|
||||
404,
|
||||
'Discussion not found',
|
||||
'Scoped or public forum lookup failed',
|
||||
],
|
||||
FORUM_PENDING_LIMIT: [
|
||||
409,
|
||||
'Too many pending submissions',
|
||||
'Forum pending submission quota exceeded',
|
||||
],
|
||||
FORUM_SELF_MODERATION: [
|
||||
403,
|
||||
'An independent moderator is required',
|
||||
'Self moderation rejected',
|
||||
],
|
||||
FORUM_MODERATION_STATE: [
|
||||
409,
|
||||
'Post cannot receive this decision',
|
||||
'Invalid forum moderation transition',
|
||||
],
|
||||
FORUM_AUTHOR_INACTIVE: [
|
||||
409,
|
||||
'Author is not active',
|
||||
'Inactive forum author approval rejected',
|
||||
],
|
||||
} as const;
|
||||
|
|
@ -10,3 +10,13 @@ export const ids = z
|
|||
.array(z.uuid())
|
||||
.max(20)
|
||||
.refine((values) => new Set(values).size === values.length);
|
||||
export const multilineText = (max: number, min = 1) =>
|
||||
z
|
||||
.string()
|
||||
.trim()
|
||||
.min(min)
|
||||
.max(max)
|
||||
.regex(
|
||||
/^[^<>\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]*$/,
|
||||
'Plain text only',
|
||||
);
|
||||
|
|
|
|||
|
|
@ -0,0 +1,43 @@
|
|||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Get,
|
||||
Param,
|
||||
ParseUUIDPipe,
|
||||
Post,
|
||||
Query,
|
||||
} from '@nestjs/common';
|
||||
import {
|
||||
CurrentPrincipal,
|
||||
RequirePermission,
|
||||
} from '../identity/access.decorator';
|
||||
import type { Principal } from '../identity/identity.types';
|
||||
import { SchemaPipe } from '../common/validation.pipe';
|
||||
import {
|
||||
forumDecisionSchema,
|
||||
forumQueueSchema,
|
||||
type ForumDecisionInput,
|
||||
type ForumQueue,
|
||||
} from './forum.schemas';
|
||||
import { ForumModerationStore } from './forum-moderation.store';
|
||||
@Controller('forum-moderation')
|
||||
export class ForumModerationController {
|
||||
constructor(private readonly moderation: ForumModerationStore) {}
|
||||
@Get()
|
||||
@RequirePermission('forum.read')
|
||||
list(
|
||||
@CurrentPrincipal() actor: Principal,
|
||||
@Query(new SchemaPipe(forumQueueSchema)) page: ForumQueue,
|
||||
) {
|
||||
return this.moderation.list(actor, page);
|
||||
}
|
||||
@Post(':id/decision')
|
||||
@RequirePermission('forum.moderate')
|
||||
decide(
|
||||
@CurrentPrincipal() actor: Principal,
|
||||
@Param('id', ParseUUIDPipe) id: string,
|
||||
@Body(new SchemaPipe(forumDecisionSchema)) input: ForumDecisionInput,
|
||||
) {
|
||||
return this.moderation.decide(actor, id, input);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,91 @@
|
|||
import { Injectable } from '@nestjs/common';
|
||||
import { DatabaseService } from '../database/database.service';
|
||||
import { AccessStore } from '../identity/access.store';
|
||||
import type { Principal } from '../identity/identity.types';
|
||||
import { AppError } from '../common/errors/app-error';
|
||||
import { assertReplay, commandHash } from '../common/idempotency';
|
||||
import { recordAudit } from '../identity/audit';
|
||||
import {
|
||||
forumInclude,
|
||||
requireForumPost,
|
||||
requirePublicThread,
|
||||
} from './forum-view';
|
||||
import type { ForumDecisionInput, ForumQueue } from './forum.schemas';
|
||||
@Injectable()
|
||||
export class ForumModerationStore {
|
||||
constructor(
|
||||
private readonly db: DatabaseService,
|
||||
private readonly access: AccessStore,
|
||||
) {}
|
||||
list(actor: Principal, query: ForumQueue) {
|
||||
return this.db.forumPost.findMany({
|
||||
where: {
|
||||
organizationId: actor.organizationId,
|
||||
...(query.threadId ? { threadId: query.threadId } : {}),
|
||||
...(query.status
|
||||
? {
|
||||
events:
|
||||
query.status === 'PENDING'
|
||||
? { none: {} }
|
||||
: query.status === 'APPROVED'
|
||||
? { some: { kind: 'APPROVED' }, none: { kind: 'HIDDEN' } }
|
||||
: { some: { kind: query.status } },
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
include: forumInclude,
|
||||
orderBy: [{ createdAt: 'asc' }, { id: 'asc' }],
|
||||
skip: query.offset,
|
||||
take: query.limit,
|
||||
});
|
||||
}
|
||||
decide(actor: Principal, id: string, input: ForumDecisionInput) {
|
||||
const requestHash = commandHash(id, input.decision, input.note);
|
||||
return this.access.mutate(actor, 'forum.moderate', async (tx) => {
|
||||
const post = await requireForumPost(tx, actor.organizationId, id);
|
||||
const previous = await tx.forumModeration.findUnique({
|
||||
where: {
|
||||
organizationId_idempotencyKey: {
|
||||
organizationId: actor.organizationId,
|
||||
idempotencyKey: input.idempotencyKey,
|
||||
},
|
||||
},
|
||||
});
|
||||
if (previous) {
|
||||
assertReplay(previous.requestHash, requestHash);
|
||||
return post;
|
||||
}
|
||||
if (post.userId === actor.userId)
|
||||
throw new AppError('FORUM_SELF_MODERATION');
|
||||
const last = post.events.at(-1)?.kind;
|
||||
if (input.decision === 'HIDDEN' ? last !== 'APPROVED' : !!last)
|
||||
throw new AppError('FORUM_MODERATION_STATE');
|
||||
if (input.decision === 'APPROVED') {
|
||||
if (post.user.status !== 'ACTIVE')
|
||||
throw new AppError('FORUM_AUTHOR_INACTIVE');
|
||||
if (post.threadId)
|
||||
await requirePublicThread(tx, actor.organizationId, post.threadId);
|
||||
}
|
||||
await tx.forumModeration.create({
|
||||
data: {
|
||||
organizationId: actor.organizationId,
|
||||
postId: id,
|
||||
actorId: actor.userId,
|
||||
sequence: input.decision === 'HIDDEN' ? 2 : 1,
|
||||
kind: input.decision,
|
||||
note: input.note,
|
||||
idempotencyKey: input.idempotencyKey,
|
||||
requestHash,
|
||||
},
|
||||
});
|
||||
await recordAudit(
|
||||
tx,
|
||||
actor.organizationId,
|
||||
actor.userId,
|
||||
'forum.' + input.decision.toLowerCase(),
|
||||
id,
|
||||
);
|
||||
return requireForumPost(tx, actor.organizationId, id);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,38 @@
|
|||
import { Injectable } from '@nestjs/common';
|
||||
import { DatabaseService } from '../database/database.service';
|
||||
import type { PageInput } from '../identity/identity.schemas';
|
||||
import {
|
||||
publicForumSelect,
|
||||
publicForumWhere,
|
||||
requirePublicThread,
|
||||
} from './forum-view';
|
||||
@Injectable()
|
||||
export class ForumPublicStore {
|
||||
constructor(private readonly db: DatabaseService) {}
|
||||
list(organizationId: string, page: PageInput) {
|
||||
return this.db.forumPost.findMany({
|
||||
where: { ...publicForumWhere(organizationId), threadId: null },
|
||||
select: publicForumSelect,
|
||||
orderBy: [{ createdAt: 'desc' }, { id: 'desc' }],
|
||||
skip: page.offset,
|
||||
take: page.limit,
|
||||
});
|
||||
}
|
||||
get(organizationId: string, id: string) {
|
||||
return requirePublicThread(this.db, organizationId, id);
|
||||
}
|
||||
async replies(organizationId: string, id: string, page: PageInput) {
|
||||
await requirePublicThread(this.db, organizationId, id);
|
||||
return this.db.forumPost.findMany({
|
||||
where: {
|
||||
...publicForumWhere(organizationId),
|
||||
threadId: id,
|
||||
thread: { ...publicForumWhere(organizationId), threadId: null },
|
||||
},
|
||||
select: publicForumSelect,
|
||||
orderBy: [{ createdAt: 'asc' }, { id: 'asc' }],
|
||||
skip: page.offset,
|
||||
take: page.limit,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,87 @@
|
|||
import { Injectable } from '@nestjs/common';
|
||||
import { AccessStore } from '../identity/access.store';
|
||||
import { DatabaseService } from '../database/database.service';
|
||||
import type { Principal } from '../identity/identity.types';
|
||||
import type { PageInput } from '../identity/identity.schemas';
|
||||
import { AppError } from '../common/errors/app-error';
|
||||
import { assertReplay, commandHash } from '../common/idempotency';
|
||||
import { recordAudit } from '../identity/audit';
|
||||
import { forumInclude, ownForumView, requirePublicThread } from './forum-view';
|
||||
import type { ForumReplyInput, ForumThreadInput } from './forum.schemas';
|
||||
@Injectable()
|
||||
export class ForumSubmissionStore {
|
||||
constructor(
|
||||
private readonly db: DatabaseService,
|
||||
private readonly access: AccessStore,
|
||||
) {}
|
||||
async own(actor: Principal, page: PageInput) {
|
||||
const posts = await this.db.forumPost.findMany({
|
||||
where: { organizationId: actor.organizationId, userId: actor.userId },
|
||||
include: forumInclude,
|
||||
orderBy: [{ createdAt: 'desc' }, { id: 'desc' }],
|
||||
skip: page.offset,
|
||||
take: page.limit,
|
||||
});
|
||||
return posts.map(ownForumView);
|
||||
}
|
||||
submit(
|
||||
actor: Principal,
|
||||
input: ForumReplyInput | ForumThreadInput,
|
||||
threadId: string | null = null,
|
||||
) {
|
||||
const title = 'title' in input ? input.title : null;
|
||||
const requestHash = commandHash(
|
||||
threadId ?? '',
|
||||
title ?? '',
|
||||
input.displayName,
|
||||
input.body,
|
||||
);
|
||||
return this.access.mutate(actor, null, async (tx) => {
|
||||
const scope = {
|
||||
userId: actor.userId,
|
||||
organizationId: actor.organizationId,
|
||||
};
|
||||
const previous = await tx.forumPost.findUnique({
|
||||
where: {
|
||||
userId_organizationId_idempotencyKey: {
|
||||
...scope,
|
||||
idempotencyKey: input.idempotencyKey,
|
||||
},
|
||||
},
|
||||
include: forumInclude,
|
||||
});
|
||||
if (previous) {
|
||||
assertReplay(previous.requestHash, requestHash);
|
||||
return ownForumView(previous);
|
||||
}
|
||||
if (threadId)
|
||||
await requirePublicThread(tx, actor.organizationId, threadId);
|
||||
if (
|
||||
(await tx.forumPost.count({
|
||||
where: { ...scope, events: { none: {} } },
|
||||
})) >= 20
|
||||
)
|
||||
throw new AppError('FORUM_PENDING_LIMIT');
|
||||
const post = await tx.forumPost.create({
|
||||
data: {
|
||||
...scope,
|
||||
threadId,
|
||||
title,
|
||||
displayName: input.displayName,
|
||||
body: input.body,
|
||||
idempotencyKey: input.idempotencyKey,
|
||||
requestHash,
|
||||
},
|
||||
include: forumInclude,
|
||||
});
|
||||
await recordAudit(
|
||||
tx,
|
||||
actor.organizationId,
|
||||
actor.userId,
|
||||
'forum.submitted',
|
||||
post.id,
|
||||
);
|
||||
return ownForumView(post);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,60 @@
|
|||
import type { Prisma } from '../generated/prisma/client';
|
||||
import type { DatabaseService } from '../database/database.service';
|
||||
import { AppError } from '../common/errors/app-error';
|
||||
export const forumInclude = {
|
||||
events: { orderBy: { sequence: 'asc' as const } },
|
||||
user: { select: { status: true } },
|
||||
};
|
||||
export type ForumRecord = Prisma.ForumPostGetPayload<{
|
||||
include: typeof forumInclude;
|
||||
}>;
|
||||
export function ownForumView(post: ForumRecord) {
|
||||
return {
|
||||
id: post.id,
|
||||
threadId: post.threadId,
|
||||
displayName: post.displayName,
|
||||
title: post.title,
|
||||
body: post.body,
|
||||
createdAt: post.createdAt,
|
||||
moderationStatus: post.events.at(-1)?.kind ?? 'PENDING',
|
||||
};
|
||||
}
|
||||
export const publicForumSelect = {
|
||||
id: true,
|
||||
threadId: true,
|
||||
displayName: true,
|
||||
title: true,
|
||||
body: true,
|
||||
createdAt: true,
|
||||
};
|
||||
export const publicForumWhere = (
|
||||
organizationId: string,
|
||||
): Prisma.ForumPostWhereInput => ({
|
||||
organizationId,
|
||||
user: { status: 'ACTIVE' },
|
||||
events: { some: { kind: 'APPROVED' }, none: { kind: 'HIDDEN' } },
|
||||
});
|
||||
export async function requireForumPost(
|
||||
db: DatabaseService | Prisma.TransactionClient,
|
||||
organizationId: string,
|
||||
id: string,
|
||||
) {
|
||||
const post = await db.forumPost.findFirst({
|
||||
where: { id, organizationId },
|
||||
include: forumInclude,
|
||||
});
|
||||
if (!post) throw new AppError('FORUM_NOT_FOUND');
|
||||
return post;
|
||||
}
|
||||
export async function requirePublicThread(
|
||||
db: DatabaseService | Prisma.TransactionClient,
|
||||
organizationId: string,
|
||||
id: string,
|
||||
) {
|
||||
const post = await db.forumPost.findFirst({
|
||||
where: { ...publicForumWhere(organizationId), id, threadId: null },
|
||||
select: publicForumSelect,
|
||||
});
|
||||
if (!post) throw new AppError('FORUM_NOT_FOUND');
|
||||
return post;
|
||||
}
|
||||
|
|
@ -0,0 +1,46 @@
|
|||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Get,
|
||||
Param,
|
||||
ParseUUIDPipe,
|
||||
Post,
|
||||
Query,
|
||||
} from '@nestjs/common';
|
||||
import { CurrentPrincipal } from '../identity/access.decorator';
|
||||
import type { Principal } from '../identity/identity.types';
|
||||
import { pageSchema, type PageInput } from '../identity/identity.schemas';
|
||||
import { SchemaPipe } from '../common/validation.pipe';
|
||||
import {
|
||||
forumThreadSchema,
|
||||
forumReplySchema,
|
||||
type ForumThreadInput,
|
||||
type ForumReplyInput,
|
||||
} from './forum.schemas';
|
||||
import { ForumSubmissionStore } from './forum-submission.store';
|
||||
@Controller('forum')
|
||||
export class ForumController {
|
||||
constructor(private readonly posts: ForumSubmissionStore) {}
|
||||
@Get('posts')
|
||||
own(
|
||||
@CurrentPrincipal() actor: Principal,
|
||||
@Query(new SchemaPipe(pageSchema)) page: PageInput,
|
||||
) {
|
||||
return this.posts.own(actor, page);
|
||||
}
|
||||
@Post('threads')
|
||||
submit(
|
||||
@CurrentPrincipal() actor: Principal,
|
||||
@Body(new SchemaPipe(forumThreadSchema)) input: ForumThreadInput,
|
||||
) {
|
||||
return this.posts.submit(actor, input);
|
||||
}
|
||||
@Post('threads/:id/replies')
|
||||
reply(
|
||||
@CurrentPrincipal() actor: Principal,
|
||||
@Param('id', ParseUUIDPipe) id: string,
|
||||
@Body(new SchemaPipe(forumReplySchema)) input: ForumReplyInput,
|
||||
) {
|
||||
return this.posts.submit(actor, input, id);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
import { Module } from '@nestjs/common';
|
||||
import { DatabaseModule } from '../database/database.module';
|
||||
import { IdentityModule } from '../identity/identity.module';
|
||||
import { StorefrontGuard } from '../catalog/storefront.guard';
|
||||
import { ForumController } from './forum.controller';
|
||||
import { ForumModerationController } from './forum-moderation.controller';
|
||||
import { PublicForumController } from './public-forum.controller';
|
||||
import { ForumSubmissionStore } from './forum-submission.store';
|
||||
import { ForumModerationStore } from './forum-moderation.store';
|
||||
import { ForumPublicStore } from './forum-public.store';
|
||||
@Module({
|
||||
imports: [DatabaseModule, IdentityModule],
|
||||
controllers: [
|
||||
ForumController,
|
||||
ForumModerationController,
|
||||
PublicForumController,
|
||||
],
|
||||
providers: [
|
||||
ForumSubmissionStore,
|
||||
ForumModerationStore,
|
||||
ForumPublicStore,
|
||||
StorefrontGuard,
|
||||
],
|
||||
})
|
||||
export class ForumModule {}
|
||||
|
|
@ -0,0 +1,29 @@
|
|||
import { z } from 'zod';
|
||||
import { text, multilineText } from '../common/input';
|
||||
import { pageSchema } from '../identity/identity.schemas';
|
||||
const fields = {
|
||||
displayName: text(80),
|
||||
body: multilineText(5000, 10),
|
||||
idempotencyKey: z.uuid(),
|
||||
};
|
||||
export const forumReplySchema = z.object(fields).strict();
|
||||
export const forumThreadSchema = forumReplySchema
|
||||
.extend({ title: text(160, 3) })
|
||||
.strict();
|
||||
export const forumDecisionSchema = z
|
||||
.object({
|
||||
decision: z.enum(['APPROVED', 'REJECTED', 'HIDDEN']),
|
||||
note: text(1000, 3),
|
||||
idempotencyKey: z.uuid(),
|
||||
})
|
||||
.strict();
|
||||
export const forumQueueSchema = pageSchema
|
||||
.extend({
|
||||
status: z.enum(['PENDING', 'APPROVED', 'REJECTED', 'HIDDEN']).optional(),
|
||||
threadId: z.uuid().optional(),
|
||||
})
|
||||
.strict();
|
||||
export type ForumReplyInput = z.infer<typeof forumReplySchema>;
|
||||
export type ForumThreadInput = z.infer<typeof forumThreadSchema>;
|
||||
export type ForumDecisionInput = z.infer<typeof forumDecisionSchema>;
|
||||
export type ForumQueue = z.infer<typeof forumQueueSchema>;
|
||||
|
|
@ -0,0 +1,41 @@
|
|||
import {
|
||||
Controller,
|
||||
Get,
|
||||
Param,
|
||||
ParseUUIDPipe,
|
||||
Query,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { Public } from '../identity/access.decorator';
|
||||
import { StorefrontGuard } from '../catalog/storefront.guard';
|
||||
import { pageSchema, type PageInput } from '../identity/identity.schemas';
|
||||
import { SchemaPipe } from '../common/validation.pipe';
|
||||
import { ForumPublicStore } from './forum-public.store';
|
||||
@Public()
|
||||
@UseGuards(StorefrontGuard)
|
||||
@Controller('storefront/:organizationId/forum')
|
||||
export class PublicForumController {
|
||||
constructor(private readonly posts: ForumPublicStore) {}
|
||||
@Get()
|
||||
list(
|
||||
@Param('organizationId', ParseUUIDPipe) org: string,
|
||||
@Query(new SchemaPipe(pageSchema)) page: PageInput,
|
||||
) {
|
||||
return this.posts.list(org, page);
|
||||
}
|
||||
@Get(':id')
|
||||
get(
|
||||
@Param('organizationId', ParseUUIDPipe) org: string,
|
||||
@Param('id', ParseUUIDPipe) id: string,
|
||||
) {
|
||||
return this.posts.get(org, id);
|
||||
}
|
||||
@Get(':id/replies')
|
||||
replies(
|
||||
@Param('organizationId', ParseUUIDPipe) org: string,
|
||||
@Param('id', ParseUUIDPipe) id: string,
|
||||
@Query(new SchemaPipe(pageSchema)) page: PageInput,
|
||||
) {
|
||||
return this.posts.replies(org, id, page);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,4 +1,6 @@
|
|||
export const PERMISSIONS = [
|
||||
'forum.read',
|
||||
'forum.moderate',
|
||||
'segments.read',
|
||||
'blog.read',
|
||||
'blog.manage',
|
||||
|
|
|
|||
|
|
@ -0,0 +1,44 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import {
|
||||
forumThreadSchema,
|
||||
forumReplySchema,
|
||||
forumDecisionSchema,
|
||||
} from '../src/forum/forum.schemas';
|
||||
|
||||
it('validates bounded plain-text submissions, aliases, decisions and root/reply shapes', () => {
|
||||
const input = {
|
||||
displayName: 'Reader',
|
||||
title: 'Candle question',
|
||||
body: 'A multiline question.\nAnother line.',
|
||||
idempotencyKey: randomUUID(),
|
||||
};
|
||||
expect(forumThreadSchema.safeParse(input).success).toBe(true);
|
||||
expect(forumReplySchema.safeParse(input).success).toBe(false);
|
||||
const { title: _title, ...reply } = input;
|
||||
expect(forumReplySchema.safeParse(reply).success).toBe(true);
|
||||
for (const fields of [
|
||||
{ body: '<b>Question</b>' },
|
||||
{ body: '\u0000' },
|
||||
{ body: 'short' },
|
||||
{ body: 'x'.repeat(5001) },
|
||||
{ displayName: '' },
|
||||
{ userId: randomUUID() },
|
||||
])
|
||||
expect(forumThreadSchema.safeParse({ ...input, ...fields }).success).toBe(
|
||||
false,
|
||||
);
|
||||
expect(
|
||||
forumDecisionSchema.safeParse({
|
||||
decision: 'APPROVED',
|
||||
note: 'Checked content',
|
||||
idempotencyKey: randomUUID(),
|
||||
}).success,
|
||||
).toBe(true);
|
||||
expect(
|
||||
forumDecisionSchema.safeParse({
|
||||
decision: 'PUBLISHED',
|
||||
note: 'Checked content',
|
||||
idempotencyKey: randomUUID(),
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
|
|
@ -0,0 +1,299 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import { identityApp, type IdentityApp } from './helpers/identity-app';
|
||||
import { secondActor } from './helpers/commerce';
|
||||
|
||||
describe('independently moderated community discussions', () => {
|
||||
let ctx: IdentityApp;
|
||||
beforeAll(async () => {
|
||||
ctx = await identityApp();
|
||||
});
|
||||
afterAll(async () => {
|
||||
await ctx.close();
|
||||
});
|
||||
beforeEach(async () => {
|
||||
await ctx.clearLimits();
|
||||
});
|
||||
const threadInput = () => ({
|
||||
title: 'Candle care question',
|
||||
displayName: 'Candle fan',
|
||||
body: 'How do I care for my candle?\nI am new to candles.',
|
||||
idempotencyKey: randomUUID(),
|
||||
});
|
||||
const submit = (token: string, input = threadInput()) =>
|
||||
ctx
|
||||
.api()
|
||||
.post('/api/v1/forum/threads')
|
||||
.auth(token, { type: 'bearer' })
|
||||
.send(input);
|
||||
const decision = (
|
||||
id: string,
|
||||
kind = 'APPROVED',
|
||||
token = ctx.token,
|
||||
key = randomUUID(),
|
||||
) =>
|
||||
ctx
|
||||
.api()
|
||||
.post('/api/v1/forum-moderation/' + id + '/decision')
|
||||
.auth(token, { type: 'bearer' })
|
||||
.send({
|
||||
decision: kind,
|
||||
note: 'Content checked by staff',
|
||||
idempotencyKey: key,
|
||||
});
|
||||
const publicUrl = () =>
|
||||
'/api/v1/storefront/' + ctx.owner.organizationId + '/forum';
|
||||
it('keeps submissions private until approval and publishes only aliases/content', async () => {
|
||||
const actor = await secondActor(ctx);
|
||||
const input = threadInput();
|
||||
const pending = await submit(actor.token, input).expect(201);
|
||||
expect(pending.body.moderationStatus).toBe('PENDING');
|
||||
await ctx
|
||||
.api()
|
||||
.get(publicUrl() + '/' + pending.body.id)
|
||||
.expect(404);
|
||||
const own = await ctx
|
||||
.api()
|
||||
.get('/api/v1/forum/posts')
|
||||
.auth(actor.token, { type: 'bearer' })
|
||||
.expect(200);
|
||||
expect(own.body).toHaveLength(1);
|
||||
await decision(pending.body.id).expect(201);
|
||||
const published = await ctx
|
||||
.api()
|
||||
.get(publicUrl() + '/' + pending.body.id)
|
||||
.expect(200);
|
||||
expect(published.body).toMatchObject({
|
||||
id: pending.body.id,
|
||||
displayName: input.displayName,
|
||||
title: input.title,
|
||||
body: input.body,
|
||||
});
|
||||
expect(JSON.stringify(published.body)).not.toMatch(
|
||||
/userId|organizationId|actorId|note|requestHash|idempotencyKey|email|password/,
|
||||
);
|
||||
const feed = await ctx
|
||||
.api()
|
||||
.get(publicUrl())
|
||||
.query({ limit: 1 })
|
||||
.expect(200);
|
||||
expect(feed.body.some((p: any) => p.id === pending.body.id)).toBe(true);
|
||||
const another = await secondActor(ctx);
|
||||
expect(
|
||||
(
|
||||
await ctx
|
||||
.api()
|
||||
.get('/api/v1/forum/posts')
|
||||
.auth(another.token, { type: 'bearer' })
|
||||
.expect(200)
|
||||
).body,
|
||||
).toEqual([]);
|
||||
});
|
||||
it('moderates replies separately and hiding a parent suppresses its approved replies', async () => {
|
||||
const author = await secondActor(ctx);
|
||||
const contributor = await secondActor(ctx);
|
||||
const thread = await submit(author.token).expect(201);
|
||||
const replyInput = {
|
||||
displayName: 'Helpful reader',
|
||||
body: 'Trim the wick before lighting again.',
|
||||
idempotencyKey: randomUUID(),
|
||||
};
|
||||
const reply = (body = replyInput) =>
|
||||
ctx
|
||||
.api()
|
||||
.post('/api/v1/forum/threads/' + thread.body.id + '/replies')
|
||||
.auth(contributor.token, { type: 'bearer' })
|
||||
.send(body);
|
||||
await reply().expect(404);
|
||||
await decision(thread.body.id).expect(201);
|
||||
const pending = await reply().expect(201);
|
||||
const repliesUrl = publicUrl() + '/' + thread.body.id + '/replies';
|
||||
expect((await ctx.api().get(repliesUrl).expect(200)).body).toEqual([]);
|
||||
await decision(pending.body.id).expect(201);
|
||||
expect((await ctx.api().get(repliesUrl).expect(200)).body[0]).toMatchObject(
|
||||
{
|
||||
id: pending.body.id,
|
||||
threadId: thread.body.id,
|
||||
displayName: replyInput.displayName,
|
||||
},
|
||||
);
|
||||
await decision(thread.body.id, 'HIDDEN').expect(201);
|
||||
await ctx.api().get(repliesUrl).expect(404);
|
||||
await ctx
|
||||
.api()
|
||||
.get(publicUrl() + '/' + thread.body.id)
|
||||
.expect(404);
|
||||
const replay = await reply().expect(201);
|
||||
expect(replay.body.id).toBe(pending.body.id);
|
||||
await reply({ ...replyInput, idempotencyKey: randomUUID() }).expect(404);
|
||||
await ctx
|
||||
.api()
|
||||
.post('/api/v1/forum/threads/' + pending.body.id + '/replies')
|
||||
.auth(author.token, { type: 'bearer' })
|
||||
.send({ ...replyInput, idempotencyKey: randomUUID() })
|
||||
.expect(404);
|
||||
});
|
||||
it('enforces independent decisions, replay conflicts and terminal rejection/hiding', async () => {
|
||||
const moderator = await secondActor(ctx, true, [
|
||||
'forum.read',
|
||||
'forum.moderate',
|
||||
]);
|
||||
const input = threadInput();
|
||||
const thread = await submit(moderator.token, input).expect(201);
|
||||
await decision(thread.body.id, 'APPROVED', moderator.token).expect(403);
|
||||
await expect(
|
||||
ctx.executeSql(
|
||||
`INSERT INTO forum_moderation (id, organization_id, post_id, actor_id, sequence, kind, note, idempotency_key, request_hash) VALUES ('${randomUUID()}', '${moderator.organizationId}', '${thread.body.id}', '${moderator.userId}', 1, 'APPROVED', 'Direct self decision', '${randomUUID()}', '${'a'.repeat(64)}')`,
|
||||
),
|
||||
).rejects.toThrow(/independent moderator/);
|
||||
expect((await submit(moderator.token, input).expect(201)).body.id).toBe(
|
||||
thread.body.id,
|
||||
);
|
||||
expect(
|
||||
(
|
||||
await submit(moderator.token, {
|
||||
...input,
|
||||
body: 'Different content entirely.',
|
||||
}).expect(409)
|
||||
).body.code,
|
||||
).toBe('IDEMPOTENCY_CONFLICT');
|
||||
const key = randomUUID();
|
||||
await decision(thread.body.id, 'REJECTED', ctx.token, key).expect(201);
|
||||
await decision(thread.body.id, 'REJECTED', ctx.token, key).expect(201);
|
||||
await decision(thread.body.id, 'APPROVED', ctx.token, key).expect(409);
|
||||
await decision(thread.body.id).expect(409);
|
||||
await decision(thread.body.id, 'HIDDEN').expect(409);
|
||||
expect(
|
||||
await ctx.db.auditEvent.count({
|
||||
where: { targetId: thread.body.id, action: 'forum.rejected' },
|
||||
}),
|
||||
).toBe(1);
|
||||
const queue = await ctx
|
||||
.api()
|
||||
.get('/api/v1/forum-moderation')
|
||||
.auth(moderator.token, { type: 'bearer' })
|
||||
.query({ status: 'REJECTED' })
|
||||
.expect(200);
|
||||
expect(queue.body.some((p: any) => p.id === thread.body.id)).toBe(true);
|
||||
await expect(
|
||||
ctx.executeSql(
|
||||
`UPDATE forum_posts SET body = 'Changed' WHERE id = '${thread.body.id}'`,
|
||||
),
|
||||
).rejects.toThrow(/immutable/);
|
||||
await expect(
|
||||
ctx.executeSql(
|
||||
`DELETE FROM forum_moderation WHERE post_id = '${thread.body.id}'`,
|
||||
),
|
||||
).rejects.toThrow(/immutable/);
|
||||
});
|
||||
it('enforces organization scope, active authors and strict plain-text input', async () => {
|
||||
const actor = await secondActor(ctx);
|
||||
const thread = await submit(actor.token).expect(201);
|
||||
const foreign = await secondActor(ctx, false, [
|
||||
'forum.read',
|
||||
'forum.moderate',
|
||||
]);
|
||||
await decision(thread.body.id, 'APPROVED', foreign.token).expect(404);
|
||||
expect(
|
||||
(
|
||||
await ctx
|
||||
.api()
|
||||
.get('/api/v1/forum-moderation')
|
||||
.auth(foreign.token, { type: 'bearer' })
|
||||
.expect(200)
|
||||
).body,
|
||||
).toEqual([]);
|
||||
await ctx
|
||||
.api()
|
||||
.get('/api/v1/forum-moderation')
|
||||
.auth(actor.token, { type: 'bearer' })
|
||||
.expect(403);
|
||||
await submit(actor.token, {
|
||||
...threadInput(),
|
||||
body: '<script>bad()</script>',
|
||||
}).expect(400);
|
||||
await submit(actor.token, {
|
||||
...threadInput(),
|
||||
body: 'x'.repeat(5001),
|
||||
}).expect(400);
|
||||
await ctx
|
||||
.api()
|
||||
.post('/api/v1/forum/threads')
|
||||
.auth(actor.token, { type: 'bearer' })
|
||||
.send({ ...threadInput(), userId: ctx.owner.userId })
|
||||
.expect(400);
|
||||
await ctx
|
||||
.api()
|
||||
.post('/api/v1/forum/threads')
|
||||
.send(threadInput())
|
||||
.expect(401);
|
||||
await decision(thread.body.id).expect(201);
|
||||
await ctx.db.user.update({
|
||||
where: { id: actor.userId },
|
||||
data: { status: 'SUSPENDED' },
|
||||
});
|
||||
await ctx
|
||||
.api()
|
||||
.get(publicUrl() + '/' + thread.body.id)
|
||||
.expect(404);
|
||||
await submit(actor.token).expect(401);
|
||||
await ctx.api().get(publicUrl()).query({ limit: 101 }).expect(400);
|
||||
});
|
||||
it('caps pending submissions and serializes competing moderation decisions', async () => {
|
||||
const actor = await secondActor(ctx);
|
||||
for (let i = 0; i < 20; i++) await submit(actor.token).expect(201);
|
||||
expect((await submit(actor.token).expect(409)).body.code).toBe(
|
||||
'FORUM_PENDING_LIMIT',
|
||||
);
|
||||
await expect(
|
||||
ctx.executeSql(
|
||||
`INSERT INTO forum_posts (id, organization_id, user_id, display_name, title, body, idempotency_key, request_hash) VALUES ('${randomUUID()}', '${actor.organizationId}', '${actor.userId}', 'Reader', 'Another question', 'Another pending candle question.', '${randomUUID()}', '${'a'.repeat(64)}')`,
|
||||
),
|
||||
).rejects.toThrow(/pending submission limit/);
|
||||
const own = await ctx
|
||||
.api()
|
||||
.get('/api/v1/forum/posts')
|
||||
.auth(actor.token, { type: 'bearer' })
|
||||
.expect(200);
|
||||
const results = await Promise.all([
|
||||
decision(own.body[0].id),
|
||||
decision(own.body[0].id, 'REJECTED'),
|
||||
]);
|
||||
expect(results.map((r) => r.status).sort()).toEqual([201, 409]);
|
||||
await submit(actor.token).expect(201);
|
||||
});
|
||||
it('rejects inactive-author approval and replies cannot be approved after parent hiding', async () => {
|
||||
const author = await secondActor(ctx);
|
||||
const thread = await submit(author.token).expect(201);
|
||||
await ctx.db.user.update({
|
||||
where: { id: author.userId },
|
||||
data: { status: 'SUSPENDED' },
|
||||
});
|
||||
expect((await decision(thread.body.id).expect(409)).body.code).toBe(
|
||||
'FORUM_AUTHOR_INACTIVE',
|
||||
);
|
||||
await ctx.db.user.update({
|
||||
where: { id: author.userId },
|
||||
data: { status: 'ACTIVE' },
|
||||
});
|
||||
await decision(thread.body.id).expect(201);
|
||||
const contributor = await secondActor(ctx);
|
||||
const reply = await ctx
|
||||
.api()
|
||||
.post('/api/v1/forum/threads/' + thread.body.id + '/replies')
|
||||
.auth(contributor.token, { type: 'bearer' })
|
||||
.send({
|
||||
displayName: 'Reader',
|
||||
body: 'This is a pending reply.',
|
||||
idempotencyKey: randomUUID(),
|
||||
})
|
||||
.expect(201);
|
||||
await decision(thread.body.id, 'HIDDEN').expect(201);
|
||||
await decision(reply.body.id).expect(404);
|
||||
await decision(reply.body.id, 'REJECTED').expect(201);
|
||||
await expect(
|
||||
ctx.executeSql(
|
||||
`INSERT INTO forum_posts (id, organization_id, user_id, thread_id, display_name, body, idempotency_key, request_hash) VALUES ('${randomUUID()}', '${contributor.organizationId}', '${contributor.userId}', '${thread.body.id}', 'Reader', 'Another reply under a hidden thread.', '${randomUUID()}', '${'a'.repeat(64)}')`,
|
||||
),
|
||||
).rejects.toThrow(/available approved thread/);
|
||||
});
|
||||
});
|
||||
Loading…
Reference in New Issue