Files
electro4ort/apps/api/test/moderation.e2e-spec.ts
T
olehhapuk 98b2e0ce4b
CI / Lint, types, build, tests (push) Canceled after 0s
CI / Docker images build (push) Canceled after 0s
update
2026-12-03 10:53:09 +02:00

397 lines
13 KiB
TypeScript

import { randomUUID } from 'node:crypto';
import type {
Conversation,
FriendsOverview,
InvitePreview,
Message,
MessagePage,
Realm,
RealmBan,
RealmInvite,
RealmMember,
RealmRole,
} from '@repo/contracts';
import {
befriend,
createTestApp,
listen,
nextEvent,
TestAccounts,
TestSockets,
uploadFile,
type ClientSocket,
type TestApp,
type TestUser,
} from './helpers';
describe('Moderation (e2e)', () => {
let app: TestApp;
let accounts: TestAccounts;
let sockets: TestSockets;
// Rosa owns the group and the realm. Sam and Tess are her friends and in
// both; Uma is a stranger to everyone until she joins the realm.
let rosa: TestUser;
let sam: TestUser;
let tess: TestUser;
let uma: TestUser;
let rosaSocket: ClientSocket;
let samSocket: ClientSocket;
async function post(
account: TestUser,
conversationId: string,
body: { content?: string; attachmentIds?: string[] },
): Promise<Message> {
return (
await account.agent
.post(`/conversations/${conversationId}/messages`)
.send(body)
.expect(201)
).body;
}
const remove = (account: TestUser, message: Message) =>
account.agent.delete(
`/conversations/${message.conversationId}/messages/${message.id}`,
);
async function historyOf(
account: TestUser,
conversationId: string,
): Promise<string[]> {
const page: MessagePage = (
await account.agent
.get(`/conversations/${conversationId}/messages`)
.expect(200)
).body;
return page.items.map((item) => item.id);
}
async function friendsOf(account: TestUser): Promise<FriendsOverview> {
return (await account.agent.get('/friends').expect(200)).body;
}
beforeAll(async () => {
app = await createTestApp();
sockets = new TestSockets(await listen(app));
accounts = new TestAccounts(app, '@moderation-e2e.test');
await accounts.cleanup();
[rosa, sam, tess, uma] = await Promise.all(
['Rosa', 'Sam', 'Tess', 'Uma'].map((name) => accounts.signUp(name)),
);
await befriend(rosa, sam);
await befriend(rosa, tess);
await befriend(sam, tess);
[rosaSocket, samSocket] = await Promise.all([
sockets.connectAs(rosa),
sockets.connectAs(sam),
]);
});
afterAll(async () => {
sockets.closeAll();
await accounts.cleanup();
await app.close();
});
describe('deleting messages', () => {
let direct: Conversation;
let group: Conversation;
beforeAll(async () => {
direct = (
await rosa.agent
.post('/conversations/direct')
.send({ userId: sam.id })
.expect(200)
).body;
group = (
await rosa.agent
.post('/conversations/group')
.send({ memberIds: [sam.id, tess.id] })
.expect(201)
).body;
});
it('lets the author delete their message, and tells everyone there', async () => {
const message = await post(rosa, direct.id, { content: 'oops' });
const forSam = nextEvent(samSocket, 'message:deleted');
const forRosa = nextEvent(rosaSocket, 'message:deleted');
await remove(rosa, message).expect(204);
const deletion = {
conversationId: direct.id,
messageId: message.id,
realmId: null,
};
expect(await forSam).toEqual(deletion);
expect(await forRosa).toEqual(deletion);
expect(await historyOf(sam, direct.id)).not.toContain(message.id);
// Gone is gone.
await remove(rosa, message).expect(404);
});
it("refuses someone else's message in a direct chat", async () => {
const message = await post(rosa, direct.id, { content: 'mine' });
await remove(sam, message).expect(403);
// Someone who can't read the chat isn't told the message exists.
await remove(tess, message).expect(404);
await rosa.agent
.delete(`/conversations/${direct.id}/messages/${randomUUID()}`)
.expect(404);
expect(await historyOf(sam, direct.id)).toContain(message.id);
});
it('takes the unread count and the files along', async () => {
const unreadOf = async () =>
(
(await sam.agent.get(`/conversations/${direct.id}`).expect(200))
.body as Conversation
).unreadCount;
const before = await unreadOf();
const fileId = await uploadFile(
app,
rosa,
{ filename: 'notes.txt', contentType: 'text/plain' },
Buffer.from('for your eyes only'),
);
const message = await post(rosa, direct.id, { attachmentIds: [fileId] });
expect(await unreadOf()).toBe(before + 1);
await sam.agent.get(`/attachments/${fileId}`).expect(302);
await remove(rosa, message).expect(204);
expect(await unreadOf()).toBe(before);
await sam.agent.get(`/attachments/${fileId}`).expect(404);
});
it("lets a group's owner delete anyone's message there", async () => {
const fromSam = await post(sam, group.id, { content: 'spam' });
const fromRosa = await post(rosa, group.id, { content: 'rules' });
await remove(tess, fromSam).expect(403);
await remove(sam, fromRosa).expect(403);
await remove(rosa, fromSam).expect(204);
expect(await historyOf(tess, group.id)).toEqual([fromRosa.id]);
});
});
describe('in a realm', () => {
let realm: Realm;
let cauldronId: string;
let invite: RealmInvite;
let keeper: RealmRole;
const membersOf = async (account: TestUser) =>
(
(await account.agent.get(`/realms/${realm.id}/members`).expect(200))
.body as RealmMember[]
).map((member) => member.user.id);
const join = (account: TestUser) =>
account.agent.post(`/invites/${invite.code}/accept`);
const ban = (by: TestUser, target: TestUser, body: object = {}) =>
by.agent.put(`/realms/${realm.id}/bans/${target.id}`).send(body);
beforeAll(async () => {
realm = (
await rosa.agent.post('/realms').send({ name: 'Order' }).expect(201)
).body;
cauldronId = realm.cauldrons[0].id;
invite = (
await rosa.agent
.post(`/realms/${realm.id}/invites`)
.send({ expiresInDays: null })
.expect(201)
).body;
for (const account of [sam, tess, uma]) await join(account).expect(200);
// Sam becomes a keeper: may delete messages and ban, nothing more.
keeper = (
await rosa.agent
.post(`/realms/${realm.id}/roles`)
.send({
name: 'Keeper',
permissions: ['manageMessages', 'banMembers'],
})
.expect(201)
).body;
await rosa.agent
.put(`/realms/${realm.id}/members/${sam.id}/roles`)
.send({ roleIds: [keeper.id] })
.expect(200);
});
it('lets members with "manageMessages" delete what others posted', async () => {
const fromUma = await post(uma, cauldronId, { content: 'rude' });
const fromSam = await post(sam, cauldronId, { content: 'calm down' });
// Tess has no such permission; Uma may only delete her own.
await remove(tess, fromUma).expect(403);
await remove(uma, fromSam).expect(403);
const forRosa = nextEvent(rosaSocket, 'message:deleted');
await remove(sam, fromUma).expect(204);
expect(await forRosa).toEqual({
conversationId: cauldronId,
messageId: fromUma.id,
realmId: realm.id,
});
await remove(sam, fromSam).expect(204);
expect(await historyOf(tess, cauldronId)).toEqual([]);
});
it('takes "banMembers" to ban, and to see or lift bans', async () => {
await ban(tess, uma).expect(403);
await tess.agent.get(`/realms/${realm.id}/bans`).expect(403);
await tess.agent.delete(`/realms/${realm.id}/bans/${uma.id}`).expect(403);
// Someone outside the realm isn't told it exists.
const outsider = await accounts.signUp('Vic');
await ban(outsider, uma).expect(404);
});
it('never bans the owner, oneself, or someone who can do more', async () => {
await ban(sam, rosa).expect(403);
await ban(sam, sam).expect(400);
// Tess is given more than Sam has.
const elder: RealmRole = (
await rosa.agent
.post(`/realms/${realm.id}/roles`)
.send({ name: 'Elder', permissions: ['manageRealm'] })
.expect(201)
).body;
await rosa.agent
.put(`/realms/${realm.id}/members/${tess.id}/roles`)
.send({ roleIds: [elder.id] })
.expect(200);
await ban(sam, tess).expect(403);
expect(await membersOf(rosa)).toContain(tess.id);
await ban(sam, uma, { reason: 'x'.repeat(201) }).expect(400);
});
it('puts a banned member out and keeps them out', async () => {
const umaSocket = await sockets.connectAs(uma);
const forUma = nextEvent(umaSocket, 'realm:changed');
await ban(sam, uma, { reason: ' Kept being rude ' }).expect(204);
// They are told the realm changed, which takes it off their list.
expect(await forUma).toBe(realm.id);
expect(await membersOf(rosa)).not.toContain(uma.id);
await uma.agent.get(`/realms/${realm.id}`).expect(404);
await uma.agent.get(`/conversations/${cauldronId}/messages`).expect(404);
const preview: InvitePreview = (
await uma.agent.get(`/invites/${invite.code}`).expect(200)
).body;
expect(preview).toMatchObject({ isMember: false, isBanned: true });
await join(uma).expect(403);
expect(await membersOf(rosa)).not.toContain(uma.id);
// Someone no longer in the realm can't be banned again.
await ban(sam, uma).expect(404);
});
it('lists bans with who made them and why', async () => {
const bans: RealmBan[] = (
await rosa.agent.get(`/realms/${realm.id}/bans`).expect(200)
).body;
expect(bans).toEqual([
{
user: {
id: uma.id,
name: 'Uma',
username: uma.username,
image: null,
},
bannedBy: expect.objectContaining({ id: sam.id }),
reason: 'Kept being rude',
createdAt: expect.any(String),
},
]);
});
it('lets them back in once the ban is lifted', async () => {
await sam.agent.delete(`/realms/${realm.id}/bans/${uma.id}`).expect(204);
await sam.agent.delete(`/realms/${realm.id}/bans/${uma.id}`).expect(404);
expect(
(await rosa.agent.get(`/realms/${realm.id}/bans`).expect(200)).body,
).toEqual([]);
// Lifting a ban doesn't bring them back by itself.
expect(await membersOf(rosa)).not.toContain(uma.id);
await join(uma).expect(200);
expect(await membersOf(rosa)).toContain(uma.id);
});
});
describe('blocking', () => {
let direct: Conversation;
const block = (account: TestUser, userId: string) =>
account.agent.put(`/friends/blocks/${userId}`);
const unblock = (account: TestUser, userId: string) =>
account.agent.delete(`/friends/blocks/${userId}`);
const ask = (account: TestUser, target: TestUser) =>
account.agent
.post('/friends/requests')
.send({ username: target.username });
const ids = (people: { id: string }[]) => people.map((person) => person.id);
beforeAll(async () => {
direct = (
await tess.agent
.post('/conversations/direct')
.send({ userId: sam.id })
.expect(200)
).body;
});
it('refuses to block oneself or nobody', async () => {
await block(tess, tess.id).expect(400);
await block(tess, 'no-such-user').expect(404);
await unblock(tess, sam.id).expect(404);
});
it('ends the friendship, and both are told their lists changed', async () => {
const forSam = nextEvent(samSocket, 'friends:changed');
await block(tess, sam.id).expect(204);
await forSam;
// Doing it again changes nothing.
await block(tess, sam.id).expect(204);
const mine = await friendsOf(tess);
expect(ids(mine.friends)).not.toContain(sam.id);
expect(ids(mine.blocked)).toEqual([sam.id]);
const theirs = await friendsOf(sam);
expect(ids(theirs.friends)).not.toContain(tess.id);
// The blocked person isn't shown who blocked them.
expect(theirs.blocked).toEqual([]);
});
it('keeps the two from becoming friends again or messaging', async () => {
await ask(sam, tess).expect(403);
await ask(tess, sam).expect(409);
await sam.agent
.post(`/conversations/${direct.id}/messages`)
.send({ content: 'hello?' })
.expect(403);
await sam.agent.post(`/conversations/${direct.id}/call`).expect(403);
expect((await friendsOf(tess)).incoming).toEqual([]);
});
it('drops a request that was waiting', async () => {
const wes = await accounts.signUp('Wes');
await ask(wes, tess).expect(201);
expect((await friendsOf(tess)).incoming).toHaveLength(1);
await block(tess, wes.id).expect(204);
expect((await friendsOf(tess)).incoming).toEqual([]);
expect((await friendsOf(wes)).outgoing).toEqual([]);
});
it('lets them ask again once unblocked', async () => {
await unblock(tess, sam.id).expect(204);
expect(
(await friendsOf(tess)).blocked.map((user) => user.id),
).not.toContain(sam.id);
// Unblocking doesn't restore the friendship.
expect(ids((await friendsOf(tess)).friends)).not.toContain(sam.id);
await ask(sam, tess).expect(201);
});
});
});