update
CI / Lint, types, build, tests (push) Canceled after 0s
CI / Docker images build (push) Canceled after 0s

This commit is contained in:
olehhapuk
2026-12-03 10:53:09 +02:00
parent f8de87955b
commit 98b2e0ce4b
182 changed files with 24134 additions and 288 deletions
+644
View File
@@ -0,0 +1,644 @@
import {
REALM_MAX_ROLES,
REALM_PERMISSIONS,
type Conversation,
type InvitePreview,
type Message,
type MessagePage,
type Realm,
type RealmInvite,
type RealmMember,
type RealmRole,
type RealmListItem,
} from '@repo/contracts';
import {
createTestApp,
listen,
TestAccounts,
TestSockets,
type ClientSocket,
type TestApp,
type TestUser,
} from './helpers';
describe('Realms (e2e)', () => {
let app: TestApp;
let accounts: TestAccounts;
let sockets: TestSockets;
// Olga owns the realm. Mia becomes a moderator, Nat stays an ordinary
// member, Pat is made an admin and Quin never joins.
let olga: TestUser;
let mia: TestUser;
let nat: TestUser;
let pat: TestUser;
let quin: TestUser;
let realm: Realm;
let general: string;
let invite: RealmInvite;
let moderator: RealmRole;
let admin: RealmRole;
const everyoneRole = (of: Realm) => {
const role = of.roles.find((candidate) => candidate.isDefault);
if (!role) throw new Error('The realm has no default role.');
return role;
};
async function realmFor(account: TestUser): Promise<Realm> {
return (await account.agent.get(`/realms/${realm.id}`).expect(200)).body;
}
async function realmsOf(account: TestUser): Promise<RealmListItem[]> {
return (await account.agent.get('/realms').expect(200)).body;
}
async function membersSeenBy(account: TestUser): Promise<RealmMember[]> {
return (await account.agent.get(`/realms/${realm.id}/members`).expect(200))
.body;
}
async function newInvite(
account: TestUser,
body: object = {},
): Promise<RealmInvite> {
return (
await account.agent
.post(`/realms/${realm.id}/invites`)
.send(body)
.expect(201)
).body;
}
const post = (account: TestUser, content: string) =>
account.agent.post(`/conversations/${general}/messages`).send({ content });
/** Resolves when the socket is told this part of the realm changed. */
function realmChange(socket: ClientSocket, what: 'details' | 'members') {
return new Promise<void>((resolve, reject) => {
const timer = setTimeout(
() => reject(new Error(`No "${what}" change within 2s`)),
2000,
);
const listener = (realmId: string, changed: string) => {
if (realmId !== realm.id || changed !== what) return;
clearTimeout(timer);
socket.off('realm:changed', listener);
resolve();
};
socket.on('realm:changed', listener);
});
}
/** Resolves with the next message and what came with it. */
function nextMessage(socket: ClientSocket) {
return new Promise<[Message, { realmId: string | null }]>(
(resolve, reject) => {
const timer = setTimeout(
() => reject(new Error('No message within 2s')),
2000,
);
socket.once('message:created', (message, context) => {
clearTimeout(timer);
resolve([message, context]);
});
},
);
}
beforeAll(async () => {
app = await createTestApp();
sockets = new TestSockets(await listen(app));
accounts = new TestAccounts(app, '@realms-e2e.test');
await accounts.cleanup();
[olga, mia, nat, pat, quin] = await Promise.all(
['Olga', 'Mia', 'Nat', 'Pat', 'Quin'].map((name) =>
accounts.signUp(name),
),
);
});
afterAll(async () => {
sockets.closeAll();
await accounts.cleanup();
await app.close();
});
it('creates a realm with a first cauldron and an "Everyone" role', async () => {
await olga.agent.post('/realms').send({ name: ' ' }).expect(400);
await olga.agent
.post('/realms')
.send({ name: 'x'.repeat(51) })
.expect(400);
const response = await olga.agent
.post('/realms')
.send({ name: ' Moonlit Coven ' })
.expect(201);
realm = response.body;
general = realm.cauldrons[0].id;
expect(realm).toMatchObject({
name: 'Moonlit Coven',
ownerId: olga.id,
memberCount: 1,
permissions: [...REALM_PERMISSIONS],
});
expect(realm.cauldrons.map((cauldron) => cauldron.name)).toEqual([
'general',
]);
expect(realm.roles).toEqual([
expect.objectContaining({
name: 'Everyone',
isDefault: true,
permissions: ['createInvites', 'sendMessages'],
}),
]);
expect(await realmsOf(olga)).toEqual([
{
id: realm.id,
name: 'Moonlit Coven',
ownerId: olga.id,
hasUnread: false,
},
]);
});
it('hides a realm from people who are not in it', async () => {
const path = `/realms/${realm.id}`;
expect(await realmsOf(quin)).toEqual([]);
await quin.agent.get(path).expect(404);
await quin.agent.get(`${path}/members`).expect(404);
await quin.agent.get(`${path}/invites`).expect(404);
await quin.agent.patch(path).send({ name: 'Mine now' }).expect(404);
await quin.agent.post(`${path}/cauldrons`).send({ name: 'x' }).expect(404);
await quin.agent.post(`${path}/invites`).send({}).expect(404);
await quin.agent.delete(path).expect(404);
await quin.agent.get(`/conversations/${general}/messages`).expect(404);
await post(quin, 'let me in').expect(404);
await olga.agent.get('/realms/not-a-uuid').expect(400);
});
it('makes invite links that show where they lead', async () => {
invite = await newInvite(olga);
expect(invite).toMatchObject({
realmId: realm.id,
createdBy: { id: olga.id },
maxUses: null,
uses: 0,
});
// A week, unless asked otherwise.
const lifetimeMs = Date.parse(invite.expiresAt ?? '') - Date.now();
expect(lifetimeMs).toBeGreaterThan(6.9 * 24 * 60 * 60 * 1000);
expect(lifetimeMs).toBeLessThan(7.1 * 24 * 60 * 60 * 1000);
const preview: InvitePreview = (
await mia.agent.get(`/invites/${invite.code}`).expect(200)
).body;
expect(preview).toEqual({
code: invite.code,
realm: { id: realm.id, name: 'Moonlit Coven', memberCount: 1 },
isMember: false,
isBanned: false,
});
await mia.agent.get('/invites/AAAAAAAAAAAA').expect(404);
await mia.agent.post('/invites/AAAAAAAAAAAA/accept').expect(404);
await mia.agent.get('/invites/nope').expect(400);
await olga.agent
.post(`/realms/${realm.id}/invites`)
.send({ expiresInDays: 2 })
.expect(400);
});
it('lets someone with a link join, once, and tells the realm', async () => {
const olgaSocket = await sockets.connectAs(olga);
// Open before joining: it has to start hearing the realm on its own.
const miaSocket = await sockets.connectAs(mia);
const forOlga = realmChange(olgaSocket, 'members');
const forMia = realmChange(miaSocket, 'details');
const joined = await mia.agent
.post(`/invites/${invite.code}/accept`)
.expect(200);
expect(joined.body).toMatchObject({
id: realm.id,
memberCount: 2,
permissions: ['createInvites', 'sendMessages'],
});
await Promise.all([forOlga, forMia]);
// Using the link again changes nothing and isn't counted.
await mia.agent.post(`/invites/${invite.code}/accept`).expect(200);
const members = await membersSeenBy(mia);
expect(members.map((member) => member.user.id)).toEqual([olga.id, mia.id]);
expect(members[1]).toMatchObject({ roleIds: [] });
const [listed]: RealmInvite[] = (
await olga.agent.get(`/realms/${realm.id}/invites`).expect(200)
).body;
expect(listed).toMatchObject({ code: invite.code, uses: 1 });
expect(
(await mia.agent.get(`/invites/${invite.code}`).expect(200)).body,
).toMatchObject({ isMember: true });
// The socket that was open all along now gets the realm's messages.
const heard = nextMessage(miaSocket);
const sent = await post(olga, 'welcome, Mia').expect(201);
expect(await heard).toEqual([sent.body, { realmId: realm.id }]);
});
it('stops a link working once it is used up or revoked', async () => {
const single = await newInvite(olga, { maxUses: 1, expiresInDays: null });
expect(single).toMatchObject({ maxUses: 1, expiresAt: null });
await nat.agent.post(`/invites/${single.code}/accept`).expect(200);
await pat.agent.get(`/invites/${single.code}`).expect(404);
await pat.agent.post(`/invites/${single.code}/accept`).expect(404);
// Whoever is in the realm already is still shown it.
await nat.agent.get(`/invites/${single.code}`).expect(200);
const revoked = await newInvite(olga);
await olga.agent
.delete(`/realms/${realm.id}/invites/${revoked.code}`)
.expect(204);
await pat.agent.post(`/invites/${revoked.code}/accept`).expect(404);
expect(await realmsOf(pat)).toEqual([]);
await pat.agent.post(`/invites/${invite.code}/accept`).expect(200);
expect((await realmFor(olga)).memberCount).toBe(4);
});
it("shows members their own invites, and the realm's managers all of them", async () => {
const path = `/realms/${realm.id}/invites`;
const natsInvite = await newInvite(nat);
const seenByNat: RealmInvite[] = (await nat.agent.get(path).expect(200))
.body;
expect(seenByNat.map((item) => item.code)).toEqual([natsInvite.code]);
const seenByOlga: RealmInvite[] = (await olga.agent.get(path).expect(200))
.body;
// Newest first; the used-up and revoked ones are gone.
expect(seenByOlga.map((item) => item.code)).toEqual([
natsInvite.code,
invite.code,
]);
await nat.agent.delete(`${path}/${invite.code}`).expect(403);
await nat.agent.delete(`${path}/${natsInvite.code}`).expect(204);
await nat.agent.delete(`${path}/${natsInvite.code}`).expect(404);
});
it("carries a cauldron's messages to everyone in the realm", async () => {
const olgaSocket = await sockets.connectAs(olga);
// Connected after joining: the realm comes with the connection.
const natSocket = await sockets.connectAs(nat);
const forOlga = nextMessage(olgaSocket);
const forNat = nextMessage(natSocket);
const sent = await post(mia, 'double, double').expect(201);
expect(sent.body).toMatchObject({
conversationId: general,
author: { id: mia.id, name: 'Mia' },
});
expect(await forOlga).toEqual([sent.body, { realmId: realm.id }]);
expect(await forNat).toEqual([sent.body, { realmId: realm.id }]);
const history: MessagePage = (
await pat.agent.get(`/conversations/${general}/messages`).expect(200)
).body;
expect(history.items.map((item) => item.content)).toEqual([
'double, double',
'welcome, Mia',
]);
});
it('keeps cauldrons out of the list of chats', async () => {
const chats: Conversation[] = (
await mia.agent.get('/conversations').expect(200)
).body;
expect(chats).toEqual([]);
await mia.agent.get(`/conversations/${general}`).expect(404);
await mia.agent
.patch(`/conversations/${general}`)
.send({ name: 'Ours' })
.expect(404);
await mia.agent
.delete(`/conversations/${general}/members/${mia.id}`)
.expect(404);
});
it('lets only those who manage cauldrons add, rename and delete them', async () => {
const path = `/realms/${realm.id}/cauldrons`;
await nat.agent.post(path).send({ name: 'potions' }).expect(403);
await olga.agent.post(path).send({ name: '' }).expect(400);
const olgaSocket = await sockets.connectAs(olga);
const natSocket = await sockets.connectAs(nat);
const forNat = realmChange(natSocket, 'details');
const created = await olga.agent
.post(path)
.send({ name: ' potions ' })
.expect(201);
expect(created.body).toMatchObject({ name: 'potions' });
await forNat;
expect(
(await realmFor(nat)).cauldrons.map((cauldron) => cauldron.name),
).toEqual(['general', 'potions']);
await nat.agent
.patch(`${path}/${created.body.id}`)
.send({ name: 'mine' })
.expect(403);
const renamed = await olga.agent
.patch(`${path}/${created.body.id}`)
.send({ name: 'brews' })
.expect(200);
expect(renamed.body).toEqual({ id: created.body.id, name: 'brews' });
// A new cauldron is as open as the first one.
const heard = nextMessage(olgaSocket);
await nat.agent
.post(`/conversations/${created.body.id}/messages`)
.send({ content: 'eye of newt' })
.expect(201);
expect((await heard)[0]).toMatchObject({ content: 'eye of newt' });
await nat.agent.delete(`${path}/${created.body.id}`).expect(403);
await olga.agent.delete(`${path}/${created.body.id}`).expect(204);
await olga.agent.delete(`${path}/${created.body.id}`).expect(404);
await nat.agent
.get(`/conversations/${created.body.id}/messages`)
.expect(404);
// Another realm's owner can't reach into this one by id.
const other = await quin.agent
.post('/realms')
.send({ name: 'Elsewhere' })
.expect(201);
await quin.agent
.patch(`/realms/${other.body.id}/cauldrons/${general}`)
.send({ name: 'taken' })
.expect(404);
await quin.agent
.delete(`/realms/${other.body.id}/cauldrons/${general}`)
.expect(404);
await quin.agent.delete(`/realms/${other.body.id}`).expect(204);
});
it('gives members the permissions of the roles they hold', async () => {
const roles = `/realms/${realm.id}/roles`;
await nat.agent
.post(roles)
.send({ name: 'Boss', permissions: ['manageRealm'] })
.expect(403);
await olga.agent
.post(roles)
.send({ name: 'Boss', permissions: ['rule'] })
.expect(400);
moderator = (
await olga.agent
.post(roles)
.send({
name: 'Moderator',
permissions: ['manageRoles', 'kickMembers'],
})
.expect(201)
).body;
admin = (
await olga.agent
.post(roles)
.send({
name: 'Admin',
permissions: ['manageRealm', 'manageCauldrons', 'kickMembers'],
})
.expect(201)
).body;
expect(moderator).toMatchObject({ name: 'Moderator', isDefault: false });
const miaSocket = await sockets.connectAs(mia);
const natSocket = await sockets.connectAs(nat);
const forMia = realmChange(miaSocket, 'details');
const forNat = realmChange(natSocket, 'members');
const updated = await olga.agent
.put(`/realms/${realm.id}/members/${mia.id}/roles`)
.send({ roleIds: [moderator.id] })
.expect(200);
expect(updated.body).toMatchObject({
user: { id: mia.id },
roleIds: [moderator.id],
});
await Promise.all([forMia, forNat]);
await olga.agent
.put(`/realms/${realm.id}/members/${pat.id}/roles`)
.send({ roleIds: [admin.id] })
.expect(200);
expect((await realmFor(mia)).permissions).toEqual([
'manageRoles',
'kickMembers',
'createInvites',
'sendMessages',
]);
expect((await realmFor(nat)).permissions).toEqual([
'createInvites',
'sendMessages',
]);
expect((await realmFor(nat)).roles.map((role) => role.name)).toEqual([
'Everyone',
'Moderator',
'Admin',
]);
// What a role allows shows at once: Pat may now rename the realm.
await pat.agent
.patch(`/realms/${realm.id}`)
.send({ name: 'Moonlit Coven' })
.expect(200);
await mia.agent
.patch(`/realms/${realm.id}`)
.send({ name: 'Mia’s' })
.expect(403);
});
it("doesn't let anyone hand out more than they can do themselves", async () => {
const roles = `/realms/${realm.id}/roles`;
const rolesOf = (member: TestUser) =>
`/realms/${realm.id}/members/${member.id}/roles`;
// Mia manages roles, but can't manage the realm or its cauldrons.
await mia.agent
.post(roles)
.send({ name: 'Usurper', permissions: ['manageRealm'] })
.expect(403);
await mia.agent
.patch(`${roles}/${moderator.id}`)
.send({ permissions: ['manageRoles', 'kickMembers', 'manageRealm'] })
.expect(403);
await mia.agent
.patch(`${roles}/${admin.id}`)
.send({ name: 'Nobody' })
.expect(403);
await mia.agent.delete(`${roles}/${admin.id}`).expect(403);
await mia.agent
.put(rolesOf(mia))
.send({ roleIds: [moderator.id, admin.id] })
.expect(403);
// Taking a bigger role away is refused as well.
await mia.agent.put(rolesOf(pat)).send({ roleIds: [] }).expect(403);
await mia.agent
.put(rolesOf(olga))
.send({ roleIds: [moderator.id] })
.expect(403);
await nat.agent
.put(rolesOf(nat))
.send({ roleIds: [moderator.id] })
.expect(403);
// Within her own reach she can make, give and delete roles.
const helper: RealmRole = (
await mia.agent
.post(roles)
.send({ name: 'Helper', permissions: ['kickMembers'] })
.expect(201)
).body;
await mia.agent
.put(rolesOf(nat))
.send({ roleIds: [helper.id] })
.expect(200);
expect((await realmFor(nat)).permissions).toContain('kickMembers');
// Leaving Pat's bigger role where it is, is no change to it.
await mia.agent
.put(rolesOf(pat))
.send({ roleIds: [admin.id, helper.id] })
.expect(200);
await mia.agent.delete(`${roles}/${helper.id}`).expect(204);
expect((await realmFor(nat)).permissions).not.toContain('kickMembers');
const patNow = (await membersSeenBy(olga)).find(
(member) => member.user.id === pat.id,
);
expect(patNow?.roleIds).toEqual([admin.id]);
await mia.agent
.put(rolesOf(nat))
.send({ roleIds: [helper.id] })
.expect(400);
await mia.agent
.put(rolesOf(nat))
.send({ roleIds: [everyoneRole(realm).id] })
.expect(400);
await mia.agent
.put(rolesOf(quin))
.send({ roleIds: [moderator.id] })
.expect(404);
});
it('keeps the "Everyone" role, while letting what it allows change', async () => {
const everyone = `/realms/${realm.id}/roles/${everyoneRole(realm).id}`;
await olga.agent.delete(everyone).expect(400);
await olga.agent.patch(everyone).send({ name: 'Peasants' }).expect(400);
await olga.agent
.patch(everyone)
.send({ permissions: ['createInvites'] })
.expect(200);
await post(nat, 'can anyone hear me?').expect(403);
// Reading stays open, and the owner can always post.
await nat.agent.get(`/conversations/${general}/messages`).expect(200);
await post(olga, 'quiet, please').expect(201);
await olga.agent
.patch(everyone)
.send({ permissions: ['createInvites', 'sendMessages'] })
.expect(200);
await post(nat, 'thank you').expect(201);
});
it('lets moderators remove members, but nobody above them', async () => {
const membersPath = `/realms/${realm.id}/members`;
await nat.agent.delete(`${membersPath}/${mia.id}`).expect(403);
await mia.agent.delete(`${membersPath}/${olga.id}`).expect(403);
// Pat can do things Mia can't.
await mia.agent.delete(`${membersPath}/${pat.id}`).expect(403);
await mia.agent.delete(`${membersPath}/${quin.id}`).expect(404);
const natSocket = await sockets.connectAs(nat);
const olgaSocket = await sockets.connectAs(olga);
const forNat = realmChange(natSocket, 'details');
const forOlga = realmChange(olgaSocket, 'members');
await mia.agent.delete(`${membersPath}/${nat.id}`).expect(204);
await Promise.all([forNat, forOlga]);
expect(await realmsOf(nat)).toEqual([]);
await nat.agent.get(`/realms/${realm.id}`).expect(404);
await nat.agent.get(`/conversations/${general}/messages`).expect(404);
await post(nat, 'still here?').expect(404);
let natHeard = false;
natSocket.on('message:created', () => {
natHeard = true;
});
const heard = nextMessage(olgaSocket);
await post(mia, 'members only').expect(201);
await heard;
expect(natHeard).toBe(false);
// Messages of someone who was removed stay, with their name.
const history: MessagePage = (
await olga.agent.get(`/conversations/${general}/messages`).expect(200)
).body;
expect(history.items).toContainEqual(
expect.objectContaining({
content: 'thank you',
author: expect.objectContaining({ id: nat.id, name: 'Nat' }),
}),
);
});
it('lets members leave, but not the owner', async () => {
const membersPath = `/realms/${realm.id}/members`;
await olga.agent.delete(`${membersPath}/${olga.id}`).expect(400);
await mia.agent.delete(`${membersPath}/${mia.id}`).expect(204);
expect(await realmsOf(mia)).toEqual([]);
const members = await membersSeenBy(olga);
expect(members.map((member) => member.user.id)).toEqual([olga.id, pat.id]);
// Coming back with a link starts from nothing: the old roles are gone.
await mia.agent.post(`/invites/${invite.code}/accept`).expect(200);
expect((await realmFor(mia)).permissions).toEqual([
'createInvites',
'sendMessages',
]);
});
it(`holds a realm to ${REALM_MAX_ROLES} roles`, async () => {
const roles = `/realms/${realm.id}/roles`;
const existing = (await realmFor(olga)).roles.length;
for (let index = existing; index < REALM_MAX_ROLES; index += 1) {
await olga.agent
.post(roles)
.send({ name: `Role ${index}`, permissions: [] })
.expect(201);
}
await olga.agent
.post(roles)
.send({ name: 'One too many', permissions: [] })
.expect(409);
expect((await realmFor(olga)).roles).toHaveLength(REALM_MAX_ROLES);
});
it('lets only the owner delete the realm, with everything in it', async () => {
// Pat manages the realm, which still isn't owning it.
await pat.agent.delete(`/realms/${realm.id}`).expect(403);
const patSocket = await sockets.connectAs(pat);
const forPat = realmChange(patSocket, 'details');
await olga.agent.delete(`/realms/${realm.id}`).expect(204);
await forPat;
for (const account of [olga, mia, pat]) {
expect(await realmsOf(account)).toEqual([]);
await account.agent.get(`/realms/${realm.id}`).expect(404);
await account.agent.get(`/conversations/${general}/messages`).expect(404);
}
await quin.agent.get(`/invites/${invite.code}`).expect(404);
await quin.agent.post(`/invites/${invite.code}/accept`).expect(404);
});
});