manicanldes-backend/test/forum.spec.ts

300 lines
11 KiB
TypeScript

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/);
});
});