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
+15 -2
View File
@@ -23,8 +23,21 @@ describe('AppController (e2e)', () => {
.expect('Hello World!');
});
it('/me (GET) requires a session', () => {
return request(app.getHttpServer()).get('/me').expect(401);
it('/health (GET)', () => {
return request(app.getHttpServer())
.get('/health')
.expect(200)
.expect({ status: 'ok' });
});
it('/ready (GET) reports the database and Redis', async () => {
const response = await request(app.getHttpServer())
.get('/ready')
.expect(200);
expect(response.body.info).toMatchObject({
database: { status: 'up' },
redis: { status: 'up' },
});
});
afterEach(async () => {
+456
View File
@@ -0,0 +1,456 @@
import { createHash, randomUUID } from 'node:crypto';
import { ConfigService } from '@nestjs/config';
import type {
Call,
CallAccess,
CallsOverview,
Conversation,
Realm,
} from '@repo/contracts';
import { AccessToken, TokenVerifier } from 'livekit-server-sdk';
import request from 'supertest';
import { CallRooms } from '../src/calls/call-rooms';
import { CallsStore } from '../src/calls/calls.store';
import type { Env } from '../src/config/env';
import {
befriend,
createTestApp,
listen,
nextEvent,
TestAccounts,
TestSockets,
type ClientSocket,
type TestApp,
type TestUser,
} from './helpers';
/**
* Stands in for the media server: who is in which room is whatever the
* test says, the way browsers joining and leaving would change it.
*/
class FakeCallRooms implements Pick<
CallRooms,
'list' | 'participants' | 'remove' | 'close'
> {
private readonly rooms = new Map<string, string[]>();
join(room: string, identity: string) {
this.rooms.set(room, [...(this.rooms.get(room) ?? []), identity]);
}
leave(room: string, identity: string) {
const left = (this.rooms.get(room) ?? []).filter((id) => id !== identity);
if (left.length > 0) this.rooms.set(room, left);
else this.rooms.delete(room);
}
list() {
return Promise.resolve([...this.rooms.keys()]);
}
participants(room: string) {
return Promise.resolve(this.rooms.get(room) ?? []);
}
remove(room: string, identity: string) {
this.leave(room, identity);
return Promise.resolve();
}
close(room: string) {
this.rooms.delete(room);
return Promise.resolve();
}
}
/** How a report is signed, when not the way the media server would. */
interface Signing {
secret?: string;
/** Sign this instead of the body that is sent. */
body?: string;
/** The answer to expect; 200 unless said. */
status?: number;
}
describe('Calls (e2e)', () => {
let app: TestApp;
let accounts: TestAccounts;
let sockets: TestSockets;
const rooms = new FakeCallRooms();
let apiKey: string;
let apiSecret: string;
// Alice is friends with Bob and Carol, who are friends too. Dave is
// nobody's friend but joins Alice's realm.
let alice: TestUser;
let bob: TestUser;
let carol: TestUser;
let dave: TestUser;
let aliceSocket: ClientSocket;
let bobSocket: ClientSocket;
let carolSocket: ClientSocket;
let daveSocket: ClientSocket;
/** Alice and Bob. */
let direct: Conversation;
/** Alice (owner), Bob and Carol. */
let group: Conversation;
/** Alice's, with Dave in it. */
let realm: Realm;
let cauldronId: string;
async function callsOf(account: TestUser): Promise<Call[]> {
const overview: CallsOverview = (
await account.agent.get('/calls').expect(200)
).body;
expect(overview.enabled).toBe(true);
return overview.calls;
}
const idsIn = (call: Call | undefined) =>
call?.participants.map((participant) => participant.id);
/**
* Sends what the media server would, signed the way it signs, and checks
* how the API answers.
*/
async function report(
event: string,
room: string,
{ status = 200, ...sign }: Signing = {},
) {
const body = JSON.stringify({
event,
room: { name: room },
id: randomUUID(),
});
const token = new AccessToken(apiKey, sign.secret ?? apiSecret);
token.sha256 = createHash('sha256')
.update(sign.body ?? body)
.digest('base64');
return request(app.getHttpServer())
.post('/livekit/webhook')
.set('Content-Type', 'application/webhook+json')
.set('Authorization', await token.toJwt())
.send(body)
.expect(status);
}
/** Someone's browser connects to a call, and the media server says so. */
async function joins(account: TestUser, conversationId: string) {
rooms.join(conversationId, account.id);
await report('participant_joined', conversationId);
}
async function leaves(account: TestUser, conversationId: string) {
rooms.leave(conversationId, account.id);
await report('participant_left', conversationId);
}
beforeAll(async () => {
app = await createTestApp((builder) =>
builder.overrideProvider(CallRooms).useValue(rooms),
);
const config = app.get<ConfigService<Env, true>>(ConfigService);
apiKey = config.getOrThrow('LIVEKIT_API_KEY', { infer: true });
apiSecret = config.getOrThrow('LIVEKIT_API_SECRET', { infer: true });
sockets = new TestSockets(await listen(app));
accounts = new TestAccounts(app, '@calls-e2e.test');
await accounts.cleanup();
[alice, bob, carol, dave] = await Promise.all(
['Alice', 'Bob', 'Carol', 'Dave'].map((name) => accounts.signUp(name)),
);
await befriend(alice, bob);
await befriend(alice, carol);
await befriend(bob, carol);
direct = (
await alice.agent
.post('/conversations/direct')
.send({ userId: bob.id })
.expect(200)
).body;
group = (
await alice.agent
.post('/conversations/group')
.send({ memberIds: [bob.id, carol.id] })
.expect(201)
).body;
realm = (await alice.agent.post('/realms').send({ name: 'Calls' })).body;
cauldronId = realm.cauldrons[0].id;
const invite = (
await alice.agent.post(`/realms/${realm.id}/invites`).send({}).expect(201)
).body;
await dave.agent.post(`/invites/${invite.code}/accept`).expect(200);
[aliceSocket, bobSocket, carolSocket, daveSocket] = await Promise.all(
[alice, bob, carol, dave].map((account) => sockets.connectAs(account)),
);
});
afterAll(async () => {
sockets.closeAll();
// Whatever a failed test left behind; the store is shared with the
// API in development.
const store = app.get(CallsStore);
await Promise.all(
[direct.id, group.id, cauldronId].map((id) => store.delete(id)),
);
await accounts.cleanup();
await app.close();
});
describe('joining', () => {
it('hands out a token for this user and this call alone', async () => {
const access: CallAccess = (
await alice.agent.post(`/conversations/${direct.id}/call`).expect(200)
).body;
expect(access.url).toBe('ws://livekit.invalid');
const claims = await new TokenVerifier(apiKey, apiSecret).verify(
access.token,
);
expect(claims.sub).toBe(alice.id);
expect(claims.name).toBe('Alice');
expect(claims.video).toMatchObject({
room: direct.id,
roomJoin: true,
canPublish: true,
canSubscribe: true,
});
expect(claims.video?.roomAdmin).toBeUndefined();
// Good for minutes, not hours.
const lifetime = (claims.exp ?? 0) - Date.now() / 1000;
expect(lifetime).toBeGreaterThan(60);
expect(lifetime).toBeLessThanOrEqual(5 * 60);
});
it('lets in the members of a group and of a realm', async () => {
await carol.agent.post(`/conversations/${group.id}/call`).expect(200);
await dave.agent.post(`/conversations/${cauldronId}/call`).expect(200);
});
it("answers 404 for a place the user can't read", async () => {
await carol.agent.post(`/conversations/${direct.id}/call`).expect(404);
await dave.agent.post(`/conversations/${group.id}/call`).expect(404);
await bob.agent.post(`/conversations/${cauldronId}/call`).expect(404);
await alice.agent.post(`/conversations/${randomUUID()}/call`).expect(404);
await alice.agent.post('/conversations/nope/call').expect(400);
});
it('asks for a session', async () => {
await request(app.getHttpServer())
.post(`/conversations/${direct.id}/call`)
.expect(401);
await request(app.getHttpServer()).get('/calls').expect(401);
});
it('takes the permission to post, in a realm', async () => {
const everyone = realm.roles.find((role) => role.isDefault);
const role = `/realms/${realm.id}/roles/${everyone?.id}`;
await alice.agent
.patch(role)
.send({ permissions: ['createInvites'] })
.expect(200);
await dave.agent.post(`/conversations/${cauldronId}/call`).expect(403);
// The owner may do everything.
await alice.agent.post(`/conversations/${cauldronId}/call`).expect(200);
await alice.agent
.patch(role)
.send({ permissions: ['createInvites', 'sendMessages'] })
.expect(200);
await dave.agent.post(`/conversations/${cauldronId}/call`).expect(200);
});
});
describe('reports from the media server', () => {
it('refuses what the media server did not sign', async () => {
const unsigned = () =>
request(app.getHttpServer())
.post('/livekit/webhook')
.set('Content-Type', 'application/webhook+json');
const body = JSON.stringify({
event: 'participant_joined',
room: { name: direct.id },
});
rooms.join(direct.id, alice.id);
await unsigned().send(body).expect(401);
await unsigned().set('Authorization', 'nonsense').send(body).expect(401);
await report('participant_joined', direct.id, {
secret: 'someone-elses-secret-0123456789-0123456789',
status: 401,
});
// Signed, but for a different body.
await report('participant_joined', direct.id, {
body: '{}',
status: 401,
});
expect(await callsOf(alice)).toEqual([]);
rooms.leave(direct.id, alice.id);
});
it('takes no notice of rooms that are not calls of this app', async () => {
rooms.join('some-other-room', 'someone');
await report('participant_joined', 'some-other-room');
rooms.leave('some-other-room', 'someone');
// A well-formed id of nothing: nobody to tell, so the room is closed.
const nothing = randomUUID();
rooms.join(nothing, alice.id);
await report('participant_joined', nothing);
expect(await rooms.participants(nothing)).toEqual([]);
expect(await callsOf(alice)).toEqual([]);
});
});
describe('a call in a direct chat', () => {
let startedAt: string;
it('starts when the first person joins, and both are told', async () => {
const forAlice = nextEvent(aliceSocket, 'call:changed');
const forBob = nextEvent(bobSocket, 'call:changed');
await joins(alice, direct.id);
const call = await forBob;
expect(call).toEqual({
conversationId: direct.id,
realmId: null,
participants: [
{
id: alice.id,
name: 'Alice',
username: alice.username,
image: null,
},
],
startedAt: expect.any(String),
});
expect(await forAlice).toEqual(call);
startedAt = call.startedAt;
expect(await callsOf(alice)).toEqual([call]);
expect(await callsOf(bob)).toEqual([call]);
// Nobody else hears of it.
expect(await callsOf(carol)).toEqual([]);
});
it('lists people in the order they joined', async () => {
const forAlice = nextEvent(aliceSocket, 'call:changed');
await joins(bob, direct.id);
const call = await forAlice;
expect(idsIn(call)).toEqual([alice.id, bob.id]);
expect(call.startedAt).toBe(startedAt);
});
it('says nothing when a report changes nothing', async () => {
let events = 0;
const count = () => (events += 1);
aliceSocket.on('call:changed', count);
await report('participant_joined', direct.id);
await report('track_published', direct.id);
// An event that was sent would have arrived before this answer.
await callsOf(alice);
aliceSocket.off('call:changed', count);
expect(events).toBe(0);
});
it('is over when the last person leaves', async () => {
const afterAlice = nextEvent(bobSocket, 'call:changed');
await leaves(alice, direct.id);
expect(idsIn(await afterAlice)).toEqual([bob.id]);
const afterBob = nextEvent(aliceSocket, 'call:changed');
await leaves(bob, direct.id);
expect(await afterBob).toEqual({
conversationId: direct.id,
realmId: null,
participants: [],
startedAt,
});
expect(await callsOf(alice)).toEqual([]);
});
});
describe('a call in a group', () => {
it('reaches every member', async () => {
const forCarol = nextEvent(carolSocket, 'call:changed');
await joins(alice, group.id);
await joins(bob, group.id);
expect((await forCarol).conversationId).toBe(group.id);
expect(idsIn((await callsOf(carol)).at(0))).toEqual([alice.id, bob.id]);
expect(await callsOf(dave)).toEqual([]);
});
it('drops someone who is removed from the group', async () => {
const forAlice = nextEvent(aliceSocket, 'call:changed');
await alice.agent
.delete(`/conversations/${group.id}/members/${bob.id}`)
.expect(204);
expect(await rooms.participants(group.id)).toEqual([alice.id]);
expect(idsIn(await forAlice)).toEqual([alice.id]);
// And they can't get back in.
await bob.agent.post(`/conversations/${group.id}/call`).expect(404);
expect(await callsOf(bob)).toEqual([]);
await leaves(alice, group.id);
});
});
describe('a call in a cauldron', () => {
it("reaches the realm's members", async () => {
const forDave = nextEvent(daveSocket, 'call:changed');
await joins(alice, cauldronId);
await joins(dave, cauldronId);
expect(await forDave).toMatchObject({
conversationId: cauldronId,
realmId: realm.id,
});
expect(idsIn((await callsOf(dave)).at(0))).toEqual([alice.id, dave.id]);
expect(await callsOf(bob)).toEqual([]);
});
it('drops someone who leaves the realm', async () => {
const forAlice = nextEvent(aliceSocket, 'call:changed');
await dave.agent
.delete(`/realms/${realm.id}/members/${dave.id}`)
.expect(204);
expect(await rooms.participants(cauldronId)).toEqual([alice.id]);
expect(idsIn(await forAlice)).toEqual([alice.id]);
expect(await callsOf(dave)).toEqual([]);
});
it('ends with the cauldron', async () => {
const second: { id: string } = (
await alice.agent
.post(`/realms/${realm.id}/cauldrons`)
.send({ name: 'second' })
.expect(201)
).body;
await joins(alice, second.id);
expect((await callsOf(alice)).map((call) => call.conversationId)).toEqual(
expect.arrayContaining([cauldronId, second.id]),
);
await alice.agent
.delete(`/realms/${realm.id}/cauldrons/${second.id}`)
.expect(204);
expect(await rooms.participants(second.id)).toEqual([]);
expect(await app.get(CallsStore).get(second.id)).toBeUndefined();
});
it('ends with the realm', async () => {
await alice.agent.delete(`/realms/${realm.id}`).expect(204);
expect(await rooms.participants(cauldronId)).toEqual([]);
expect(await app.get(CallsStore).get(cauldronId)).toBeUndefined();
expect(await callsOf(alice)).toEqual([]);
});
});
describe('a friendship that ends', () => {
it('ends the call between the two', async () => {
await joins(alice, direct.id);
await joins(bob, direct.id);
const forBob = nextEvent(bobSocket, 'call:changed');
await alice.agent.delete(`/friends/${bob.id}`).expect(204);
expect(await rooms.participants(direct.id)).toEqual([]);
expect(idsIn(await forBob)).toEqual([]);
expect(await callsOf(alice)).toEqual([]);
// The chat is still theirs to read, but not to call in.
await alice.agent.post(`/conversations/${direct.id}/call`).expect(403);
});
});
});
+326
View File
@@ -0,0 +1,326 @@
import type {
Conversation,
FriendsOverview,
Message,
MessagePage,
} from '@repo/contracts';
import request from 'supertest';
import {
befriend,
connected,
createTestApp,
listen,
nextEvent,
TestAccounts,
TestSockets,
type TestApp,
type TestUser,
} from './helpers';
describe('Friends, conversations and realtime (e2e)', () => {
let app: TestApp;
let accounts: TestAccounts;
let sockets: TestSockets;
let alice: TestUser;
let bob: TestUser;
let carol: TestUser;
async function overviewOf(account: TestUser): Promise<FriendsOverview> {
const response = await account.agent.get('/friends').expect(200);
return response.body;
}
beforeAll(async () => {
app = await createTestApp();
sockets = new TestSockets(await listen(app));
accounts = new TestAccounts(app, '@chat-e2e.test');
await accounts.cleanup();
alice = await accounts.signUp('Alice');
bob = await accounts.signUp('Bob');
carol = await accounts.signUp('Carol');
});
afterAll(async () => {
sockets.closeAll();
await accounts.cleanup();
await app.close();
});
describe('friends', () => {
it('requires a session', () => {
return request(app.getHttpServer()).get('/friends').expect(401);
});
it('answers 404 for an unknown username and 400 for your own', async () => {
await alice.agent
.post('/friends/requests')
.send({ username: 'nobody_by_this_name' })
.expect(404);
await alice.agent
.post('/friends/requests')
.send({ username: alice.username })
.expect(400);
});
it('sends a request that shows up on both sides', async () => {
const response = await alice.agent
.post('/friends/requests')
.send({ username: bob.username })
.expect(201);
expect(response.body).toMatchObject({
status: 'pending',
user: { id: bob.id, username: bob.username, name: 'Bob' },
});
const aliceSide = await overviewOf(alice);
expect(aliceSide.outgoing.map((pending) => pending.user.id)).toEqual([
bob.id,
]);
expect(aliceSide.incoming).toEqual([]);
const bobSide = await overviewOf(bob);
expect(bobSide.incoming.map((pending) => pending.user.id)).toEqual([
alice.id,
]);
expect(bobSide.friends).toEqual([]);
});
it('answers 409 when the request was already sent', () => {
return alice.agent
.post('/friends/requests')
.send({ username: bob.username })
.expect(409);
});
it("doesn't let the sender or a third person accept it", async () => {
await alice.agent.post(`/friends/requests/${bob.id}/accept`).expect(404);
await carol.agent
.post(`/friends/requests/${alice.id}/accept`)
.expect(404);
});
it('makes the two friends once it is accepted', async () => {
await bob.agent.post(`/friends/requests/${alice.id}/accept`).expect(204);
const aliceSide = await overviewOf(alice);
expect(aliceSide.friends.map((friend) => friend.id)).toEqual([bob.id]);
expect(aliceSide.outgoing).toEqual([]);
const bobSide = await overviewOf(bob);
expect(bobSide.friends.map((friend) => friend.id)).toEqual([alice.id]);
expect(bobSide.incoming).toEqual([]);
await alice.agent
.post('/friends/requests')
.send({ username: bob.username })
.expect(409);
});
it('accepts straight away when both ask each other', async () => {
await carol.agent
.post('/friends/requests')
.send({ username: alice.username })
.expect(201);
const response = await alice.agent
.post('/friends/requests')
.send({ username: carol.username })
.expect(201);
expect(response.body.status).toBe('accepted');
expect((await overviewOf(carol)).friends.map((f) => f.id)).toEqual([
alice.id,
]);
});
it('removes a friend for both', async () => {
await alice.agent.delete(`/friends/${carol.id}`).expect(204);
expect((await overviewOf(carol)).friends).toEqual([]);
expect((await overviewOf(alice)).friends.map((f) => f.id)).toEqual([
bob.id,
]);
await alice.agent.delete(`/friends/${carol.id}`).expect(404);
});
});
describe('direct conversations', () => {
let conversation: Conversation;
it("doesn't open a chat with someone who isn't a friend", async () => {
await carol.agent
.post('/conversations/direct')
.send({ userId: alice.id })
.expect(403);
await alice.agent
.post('/conversations/direct')
.send({ userId: alice.id })
.expect(400);
});
it('opens one chat per pair of friends', async () => {
const first = await alice.agent
.post('/conversations/direct')
.send({ userId: bob.id })
.expect(200);
conversation = first.body;
expect(conversation.type).toBe('direct');
expect(conversation.lastMessage).toBeNull();
expect(conversation.members.map((member) => member.id).sort()).toEqual(
[alice.id, bob.id].sort(),
);
const again = await bob.agent
.post('/conversations/direct')
.send({ userId: alice.id })
.expect(200);
expect(again.body.id).toBe(conversation.id);
});
it('posts messages and pages through them, newest first', async () => {
const sent: Message[] = [];
for (const content of ['one', ' two ', 'three']) {
const author = sent.length === 1 ? bob : alice;
const response = await author.agent
.post(`/conversations/${conversation.id}/messages`)
.send({ content })
.expect(201);
sent.push(response.body);
}
expect(sent[1]).toMatchObject({
content: 'two',
author: { id: bob.id, name: 'Bob' },
});
const newest = await bob.agent
.get(`/conversations/${conversation.id}/messages?limit=2`)
.expect(200);
const firstPage: MessagePage = newest.body;
expect(firstPage.items.map((message) => message.content)).toEqual([
'three',
'two',
]);
expect(firstPage.nextCursor).toBe(sent[1].id);
const older = await bob.agent
.get(
`/conversations/${conversation.id}/messages?limit=2&before=${firstPage.nextCursor}`,
)
.expect(200);
expect(older.body).toEqual({ items: [sent[0]], nextCursor: null });
});
it('lists the conversation with its latest message', async () => {
const response = await bob.agent.get('/conversations').expect(200);
expect(response.body).toHaveLength(1);
expect(response.body[0]).toMatchObject({
id: conversation.id,
lastMessage: { content: 'three', author: { id: alice.id } },
});
});
it('rejects an empty or oversized message', async () => {
const path = `/conversations/${conversation.id}/messages`;
await alice.agent.post(path).send({ content: ' ' }).expect(400);
await alice.agent
.post(path)
.send({ content: 'x'.repeat(4001) })
.expect(400);
await alice.agent.get(`${path}?limit=0`).expect(400);
await alice.agent.get(`${path}?before=not-an-id`).expect(400);
});
it('hides the conversation from people who are not in it', async () => {
await carol.agent.get(`/conversations/${conversation.id}`).expect(404);
await carol.agent
.get(`/conversations/${conversation.id}/messages`)
.expect(404);
await carol.agent
.post(`/conversations/${conversation.id}/messages`)
.send({ content: 'let me in' })
.expect(404);
expect(
(await carol.agent.get('/conversations').expect(200)).body,
).toEqual([]);
});
describe('realtime', () => {
it('refuses a socket without a session', async () => {
await expect(connected(sockets.connect())).rejects.toThrow(
'Unauthorized',
);
});
it('refuses a socket opened from another site', async () => {
const socket = sockets.connect(bob.cookie, {
origin: 'https://evil.example',
});
await expect(connected(socket)).rejects.toThrow('Unauthorized');
});
it('pushes a new message to both members, and only to them', async () => {
const aliceSocket = sockets.connect(alice.cookie);
const bobSocket = sockets.connect(bob.cookie);
const carolSocket = sockets.connect(carol.cookie);
await Promise.all([aliceSocket, bobSocket, carolSocket].map(connected));
let carolGotIt = false;
carolSocket.on('message:created', () => {
carolGotIt = true;
});
const forAlice = nextEvent(aliceSocket, 'message:created');
const forBob = nextEvent(bobSocket, 'message:created');
const response = await alice.agent
.post(`/conversations/${conversation.id}/messages`)
.send({ content: 'live!' })
.expect(201);
expect(await forBob).toEqual(response.body);
expect(await forAlice).toEqual(response.body);
expect(carolGotIt).toBe(false);
});
it('tells both people when a friend request arrives', async () => {
const bobSocket = sockets.connect(bob.cookie);
const carolSocket = sockets.connect(carol.cookie);
await Promise.all([bobSocket, carolSocket].map(connected));
const forBob = nextEvent(bobSocket, 'friends:changed');
const forCarol = nextEvent(carolSocket, 'friends:changed');
await carol.agent
.post('/friends/requests')
.send({ username: bob.username })
.expect(201);
await Promise.all([forBob, forCarol]);
});
it('closes the socket when its session signs out', async () => {
const dave = await accounts.signUp('Dave');
const socket = sockets.connect(dave.cookie);
await connected(socket);
const disconnected = new Promise<string>((resolve) => {
socket.once('disconnect', resolve);
});
await accounts.signOut(dave).expect(200);
expect(await disconnected).toBe('io server disconnect');
});
});
it('keeps the history but stops new messages after unfriending', async () => {
await bob.agent.delete(`/friends/${alice.id}`).expect(204);
await alice.agent
.post(`/conversations/${conversation.id}/messages`)
.send({ content: 'still there?' })
.expect(403);
const history = await alice.agent
.get(`/conversations/${conversation.id}/messages`)
.expect(200);
expect(history.body.items).toHaveLength(4);
// Befriending again brings the same conversation back to life.
await befriend(alice, bob);
await alice.agent
.post(`/conversations/${conversation.id}/messages`)
.send({ content: 'back' })
.expect(201);
});
});
});
+305
View File
@@ -0,0 +1,305 @@
import {
GROUP_MAX_MEMBERS,
type Conversation,
type MessagePage,
} from '@repo/contracts';
import {
befriend,
createTestApp,
listen,
nextEvent,
TestAccounts,
TestSockets,
type TestApp,
type TestUser,
} from './helpers';
describe('Group chats (e2e)', () => {
let app: TestApp;
let accounts: TestAccounts;
let sockets: TestSockets;
// Alice is friends with Bob and Carol; Bob is also friends with Dave.
// Erin is nobody's friend.
let alice: TestUser;
let bob: TestUser;
let carol: TestUser;
let dave: TestUser;
let erin: TestUser;
let group: Conversation;
const idsOf = (conversation: Conversation) =>
conversation.members.map((member) => member.id).sort();
async function listOf(account: TestUser): Promise<Conversation[]> {
return (await account.agent.get('/conversations').expect(200)).body;
}
beforeAll(async () => {
app = await createTestApp();
sockets = new TestSockets(await listen(app));
accounts = new TestAccounts(app, '@groups-e2e.test');
await accounts.cleanup();
[alice, bob, carol, dave, erin] = await Promise.all(
['Alice', 'Bob', 'Carol', 'Dave', 'Erin'].map((name) =>
accounts.signUp(name),
),
);
await befriend(alice, bob);
await befriend(alice, carol);
await befriend(bob, dave);
});
afterAll(async () => {
sockets.closeAll();
await accounts.cleanup();
await app.close();
});
it('only starts a group with at least two friends', async () => {
const create = (memberIds: string[]) =>
alice.agent.post('/conversations/group').send({ memberIds });
await create([bob.id]).expect(400);
await create([bob.id, bob.id]).expect(400);
await create([bob.id, alice.id]).expect(400);
await create([bob.id, erin.id]).expect(403);
await create([bob.id, 'no-such-user']).expect(403);
expect(await listOf(alice)).toEqual([]);
});
it('creates a group owned by its creator and tells everyone in it', async () => {
const bobSocket = await sockets.connectAs(bob);
const carolSocket = await sockets.connectAs(carol);
const forBob = nextEvent(bobSocket, 'conversations:changed');
const forCarol = nextEvent(carolSocket, 'conversations:changed');
const response = await alice.agent
.post('/conversations/group')
.send({ name: ' Coven ', memberIds: [bob.id, carol.id] })
.expect(201);
group = response.body;
expect(group).toMatchObject({
type: 'group',
name: 'Coven',
ownerId: alice.id,
lastMessage: null,
});
expect(idsOf(group)).toEqual([alice.id, bob.id, carol.id].sort());
expect(group.members[0].id).toBe(alice.id);
await Promise.all([forBob, forCarol]);
for (const member of [alice, bob, carol]) {
expect((await listOf(member)).map((item) => item.id)).toEqual([group.id]);
}
});
it('lets members who are not friends with each other talk', async () => {
const aliceSocket = await sockets.connectAs(alice);
const bobSocket = await sockets.connectAs(bob);
const forAlice = nextEvent(aliceSocket, 'message:created');
const forBob = nextEvent(bobSocket, 'message:created');
// Carol and Bob never befriended each other.
const response = await carol.agent
.post(`/conversations/${group.id}/messages`)
.send({ content: 'hello, coven' })
.expect(201);
expect(response.body.author).toMatchObject({ id: carol.id, name: 'Carol' });
expect(await forAlice).toEqual(response.body);
expect(await forBob).toEqual(response.body);
});
it('lets any member rename it, and clear the name', async () => {
const aliceSocket = await sockets.connectAs(alice);
const forAlice = nextEvent(aliceSocket, 'conversations:changed');
const renamed = await bob.agent
.patch(`/conversations/${group.id}`)
.send({ name: 'Night shift' })
.expect(200);
expect(renamed.body.name).toBe('Night shift');
await forAlice;
const cleared = await carol.agent
.patch(`/conversations/${group.id}`)
.send({ name: ' ' })
.expect(200);
expect(cleared.body.name).toBeNull();
await bob.agent
.patch(`/conversations/${group.id}`)
.send({ name: 'x'.repeat(101) })
.expect(400);
});
it('hides the group from people who are not in it', async () => {
await dave.agent.get(`/conversations/${group.id}`).expect(404);
await dave.agent
.patch(`/conversations/${group.id}`)
.send({ name: 'Mine now' })
.expect(404);
await dave.agent
.post(`/conversations/${group.id}/members`)
.send({ userIds: [erin.id] })
.expect(404);
await dave.agent
.delete(`/conversations/${group.id}/members/${bob.id}`)
.expect(404);
});
it('lets a member add their own friends, who then see the history', async () => {
const path = `/conversations/${group.id}/members`;
// Dave is Bob's friend, not Alice's.
await alice.agent
.post(path)
.send({ userIds: [dave.id] })
.expect(403);
await alice.agent.post(path).send({ userIds: [] }).expect(400);
const daveSocket = await sockets.connectAs(dave);
const forDave = nextEvent(daveSocket, 'conversations:changed');
const added = await bob.agent
.post(path)
.send({ userIds: [dave.id] })
.expect(200);
expect(idsOf(added.body)).toEqual(
[alice.id, bob.id, carol.id, dave.id].sort(),
);
// The owner comes first; whoever joins later goes last.
expect(added.body.members[0].id).toBe(alice.id);
expect(added.body.members.at(-1).id).toBe(dave.id);
await forDave;
const history = await dave.agent
.get(`/conversations/${group.id}/messages`)
.expect(200);
expect(
(history.body as MessagePage).items.map((item) => item.content),
).toEqual(['hello, coven']);
// Adding someone who is already in changes nothing.
const again = await bob.agent
.post(path)
.send({ userIds: [dave.id] })
.expect(200);
expect(again.body.members).toHaveLength(4);
});
it('lets only the owner remove someone', async () => {
const path = `/conversations/${group.id}/members`;
await bob.agent.delete(`${path}/${carol.id}`).expect(403);
await alice.agent.delete(`${path}/${erin.id}`).expect(404);
const carolSocket = await sockets.connectAs(carol);
const forCarol = nextEvent(carolSocket, 'conversations:changed');
await alice.agent.delete(`${path}/${carol.id}`).expect(204);
await forCarol;
expect(await listOf(carol)).toEqual([]);
await carol.agent.get(`/conversations/${group.id}/messages`).expect(404);
await carol.agent
.post(`/conversations/${group.id}/messages`)
.send({ content: 'still here?' })
.expect(404);
});
it("keeps a removed member's messages, with their name", async () => {
const history = await bob.agent
.get(`/conversations/${group.id}/messages`)
.expect(200);
expect((history.body as MessagePage).items[0]).toMatchObject({
content: 'hello, coven',
author: { id: carol.id, name: 'Carol' },
});
});
it('stops messages reaching someone who was removed', async () => {
const carolSocket = await sockets.connectAs(carol);
const daveSocket = await sockets.connectAs(dave);
let carolGotIt = false;
carolSocket.on('message:created', () => {
carolGotIt = true;
});
const forDave = nextEvent(daveSocket, 'message:created');
await bob.agent
.post(`/conversations/${group.id}/messages`)
.send({ content: 'members only' })
.expect(201);
await forDave;
expect(carolGotIt).toBe(false);
});
it('passes ownership on when the owner leaves', async () => {
await alice.agent
.delete(`/conversations/${group.id}/members/${alice.id}`)
.expect(204);
expect(await listOf(alice)).toEqual([]);
// Bob has been in it longer than Dave.
const [remaining] = await listOf(bob);
expect(remaining.ownerId).toBe(bob.id);
expect(idsOf(remaining)).toEqual([bob.id, dave.id].sort());
// And the new owner has the owner's powers.
await bob.agent
.delete(`/conversations/${group.id}/members/${dave.id}`)
.expect(204);
});
it('deletes the group when the last person leaves', async () => {
await bob.agent
.delete(`/conversations/${group.id}/members/${bob.id}`)
.expect(204);
for (const account of [alice, bob, carol, dave]) {
expect(await listOf(account)).toEqual([]);
await account.agent.get(`/conversations/${group.id}`).expect(404);
}
});
it('keeps group actions away from direct conversations', async () => {
const direct = await alice.agent
.post('/conversations/direct')
.send({ userId: bob.id })
.expect(200);
const path = `/conversations/${direct.body.id}`;
expect(direct.body).toMatchObject({ name: null, ownerId: null });
await alice.agent.patch(path).send({ name: 'Us' }).expect(400);
await alice.agent
.post(`${path}/members`)
.send({ userIds: [carol.id] })
.expect(400);
await alice.agent.delete(`${path}/members/${alice.id}`).expect(400);
});
it(`holds a group to ${GROUP_MAX_MEMBERS} people`, async () => {
const friends = await Promise.all(
Array.from({ length: GROUP_MAX_MEMBERS }, (_, index) =>
accounts.signUp(`Friend${index}`),
),
);
for (const friend of friends) await befriend(alice, friend);
const [extra, ...others] = friends;
await alice.agent
.post('/conversations/group')
.send({ memberIds: friends.map((friend) => friend.id) })
.expect(400);
const full = await alice.agent
.post('/conversations/group')
.send({ memberIds: others.map((friend) => friend.id) })
.expect(201);
expect(full.body.members).toHaveLength(GROUP_MAX_MEMBERS);
await alice.agent
.post(`/conversations/${full.body.id}/members`)
.send({ userIds: [extra.id] })
.expect(409);
const [unchanged] = (await listOf(alice)).filter(
(item) => item.id === full.body.id,
);
expect(unchanged.members).toHaveLength(GROUP_MAX_MEMBERS);
});
});
+272
View File
@@ -0,0 +1,272 @@
import { randomUUID } from 'node:crypto';
import { INestApplication } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { getDrizzleToken } from '@nestjs/drizzle';
import { Test, type TestingModuleBuilder } from '@nestjs/testing';
import type {
AttachmentUpload,
ClientToServerEvents,
CreateAttachment,
ServerToClientEvents,
} from '@repo/contracts';
import { and, eq, inArray, isNull, like, notExists } from 'drizzle-orm';
import { io, type Socket } from 'socket.io-client';
import request from 'supertest';
import type { App } from 'supertest/types';
import { AppModule } from '../src/app.module';
import type { Env } from '../src/config/env';
import type { Database } from '../src/db/database';
import { setUpHttp } from '../src/setup';
import {
attachment,
conversation,
conversationMember,
user,
} from '../src/db/schema';
export type TestApp = INestApplication<App>;
export type Agent = ReturnType<typeof request.agent>;
export interface TestUser {
id: string;
name: string;
username: string;
/** Sends requests as this user. */
agent: Agent;
/** The session cookie, for clients that aren't supertest (sockets). */
cookie: string;
}
/**
* The whole app, as main.ts starts it. `adjust` can swap providers for
* stand-ins before it is put together.
*/
export async function createTestApp(
adjust: (builder: TestingModuleBuilder) => TestingModuleBuilder = (builder) =>
builder,
): Promise<TestApp> {
const moduleFixture = await adjust(
Test.createTestingModule({ imports: [AppModule] }),
).compile();
// Same option as main.ts: Better Auth reads the raw body itself.
const app = moduleFixture.createNestApplication<TestApp>({
bodyParser: false,
});
setUpHttp(app);
await app.init();
return app;
}
/**
* Creates accounts in the local database for one spec file. Each file passes
* its own email domain, and `cleanup()` deletes every account under it (and,
* through cascades, everything those accounts own), then the conversations
* that are left with no members.
*/
export class TestAccounts {
// Spec files run side by side and may start in the same millisecond, so
// the time alone wouldn't keep their usernames apart.
private readonly run =
Date.now().toString(36) + randomUUID().replaceAll('-', '').slice(0, 4);
private readonly password = randomUUID();
private readonly origin: string;
constructor(
private readonly app: TestApp,
private readonly emailDomain: string,
) {
[this.origin] = app
.get<ConfigService<Env, true>>(ConfigService)
.getOrThrow('TRUSTED_ORIGINS', { infer: true });
}
emailOf(name: string) {
return `${name.toLowerCase()}-${this.run}${this.emailDomain}`;
}
/** A username that is unique to this run, e.g. "alice_m1x2y3". */
usernameOf(name: string) {
return `${name.toLowerCase()}_${this.run}`;
}
/** The raw sign-up request, for asserting on refusals. */
requestSignUp(agent: Agent, name: string, username?: string) {
return agent
.post('/api/auth/sign-up/email')
.set('Origin', this.origin)
.send({
name,
email: this.emailOf(name),
password: this.password,
username,
});
}
async signUp(name: string): Promise<TestUser> {
const agent = request.agent(this.app.getHttpServer());
const username = this.usernameOf(name);
const response = await this.requestSignUp(agent, name, username).expect(
200,
);
const setCookie = response.get('Set-Cookie') ?? [];
return {
id: response.body.user.id,
name,
username,
agent,
cookie: setCookie.map((cookie) => cookie.split(';')[0]).join('; '),
};
}
signOut(account: TestUser) {
return account.agent
.post('/api/auth/sign-out')
.set('Origin', this.origin)
.send({});
}
async cleanup() {
const db = this.app.get<Database>(getDrizzleToken());
const accounts = db
.select({ id: user.id })
.from(user)
.where(like(user.email, `%${this.emailDomain}`));
// Attachments outlive their uploader (for a day, until the cleanup), so
// these go first, while they can still be told apart.
await db.delete(attachment).where(inArray(attachment.uploaderId, accounts));
await db.delete(user).where(like(user.email, `%${this.emailDomain}`));
// Deleting a user removes their memberships and messages, not the
// conversation row itself. Cauldrons never have members and go with
// their realm, so they are left alone (another spec may be using them).
await db
.delete(conversation)
.where(
and(
isNull(conversation.realmId),
notExists(
db
.select()
.from(conversationMember)
.where(eq(conversationMember.conversationId, conversation.id)),
),
),
);
}
}
/** Makes two accounts friends: one asks, the other accepts. */
export async function befriend(asker: TestUser, answerer: TestUser) {
await asker.agent
.post('/friends/requests')
.send({ username: answerer.username })
.expect(201);
await answerer.agent.post(`/friends/requests/${asker.id}/accept`).expect(204);
}
/** Asks for an upload the way the web app does, without sending the file. */
export async function requestUpload(
account: TestUser,
file: CreateAttachment,
): Promise<AttachmentUpload> {
return (await account.agent.post('/attachments').send(file).expect(201)).body;
}
/**
* Sends bytes to a signed upload address. No session goes along: the
* signature in the address is what lets the request in.
*/
export function putFile(
app: TestApp,
{ upload }: AttachmentUpload,
bytes: Buffer,
) {
const { pathname, search } = new URL(upload.url);
return (
request(app.getHttpServer())
.put(pathname + search)
.set(upload.headers)
// As they are: left alone, the client would rewrite the bytes of a file
// whose type is JSON.
.serialize(() => bytes as unknown as string)
.send(bytes)
);
}
/** Uploads a file in full; answers with the id to list in a message. */
export async function uploadFile(
app: TestApp,
account: TestUser,
file: Omit<CreateAttachment, 'size'>,
bytes: Buffer,
): Promise<string> {
const upload = await requestUpload(account, { ...file, size: bytes.length });
await putFile(app, upload, bytes).expect(200);
return upload.attachment.id;
}
export type ClientSocket = Socket<ServerToClientEvents, ClientToServerEvents>;
/** Starts the app on a free port and returns its address, for sockets. */
export async function listen(app: TestApp): Promise<string> {
await app.listen(0);
return (await app.getUrl()).replace('[::1]', '127.0.0.1');
}
/** Opens sockets to a listening test app and closes them all at the end. */
export class TestSockets {
private readonly sockets: ClientSocket[] = [];
constructor(private readonly url: string) {}
/** Opens a socket the way a browser would, with the session cookie. */
connect(cookie?: string, headers: Record<string, string> = {}): ClientSocket {
const socket: ClientSocket = io(this.url, {
transports: ['websocket'],
forceNew: true,
reconnection: false,
extraHeaders: { ...(cookie ? { cookie } : {}), ...headers },
});
this.sockets.push(socket);
return socket;
}
/** A socket for this account, once the API has let it in. */
async connectAs(account: TestUser): Promise<ClientSocket> {
const socket = this.connect(account.cookie);
await connected(socket);
return socket;
}
closeAll() {
for (const socket of this.sockets) socket.disconnect();
}
}
/** Resolves when the API accepts the socket; rejects when it refuses. */
export function connected(socket: ClientSocket) {
return new Promise<void>((resolve, reject) => {
socket.once('connect', resolve);
socket.once('connect_error', reject);
});
}
/** Resolves with the next event's first argument (undefined if none). */
export function nextEvent<Event extends keyof ServerToClientEvents>(
socket: ClientSocket,
event: Event,
) {
return new Promise<Parameters<ServerToClientEvents[Event]>[0]>(
(resolve, reject) => {
const timer = setTimeout(
() => reject(new Error(`No "${event}" event within 2s`)),
2000,
);
// The cast: TypeScript can't relate the listener of a generic event
// name to that event's own signature.
socket.once(event, ((payload?: unknown) => {
clearTimeout(timer);
resolve(payload as Parameters<ServerToClientEvents[Event]>[0]);
}) as never);
},
);
}
+571
View File
@@ -0,0 +1,571 @@
import {
ATTACHMENT_MAX_SIZE,
MESSAGE_MAX_REACTIONS,
type Conversation,
type ConversationRead,
type Message,
type MessagePage,
type Realm,
type RealmInvite,
type RealmListItem,
} from '@repo/contracts';
import request from 'supertest';
import {
befriend,
createTestApp,
listen,
nextEvent,
putFile,
requestUpload,
TestAccounts,
TestSockets,
uploadFile,
type ClientSocket,
type TestApp,
type TestUser,
} from './helpers';
const PNG = { filename: 'cat.png', contentType: 'image/png' };
const NOTES = { filename: 'notes.txt', contentType: 'text/plain' };
describe('Attachments, reactions and unread counts (e2e)', () => {
let app: TestApp;
let accounts: TestAccounts;
let sockets: TestSockets;
// Ada and Ben are friends with a direct chat; Cy is a friend of neither.
// Ada owns a realm that Ben joins part-way through.
let ada: TestUser;
let ben: TestUser;
let cy: TestUser;
let adaSocket: ClientSocket;
let benSocket: ClientSocket;
let chat: string;
async function send(
account: TestUser,
conversationId: string,
body: { content?: string; attachmentIds?: string[] },
): Promise<Message> {
return (
await account.agent
.post(`/conversations/${conversationId}/messages`)
.send(body)
.expect(201)
).body;
}
async function historyFor(
account: TestUser,
conversationId: string,
): Promise<Message[]> {
const page: MessagePage = (
await account.agent
.get(`/conversations/${conversationId}/messages`)
.expect(200)
).body;
return page.items;
}
async function chatFor(account: TestUser): Promise<Conversation> {
return (await account.agent.get(`/conversations/${chat}`).expect(200)).body;
}
const reactionPath = (
conversationId: string,
messageId: string,
emoji: string,
) =>
`/conversations/${conversationId}/messages/${messageId}/reactions/${encodeURIComponent(emoji)}`;
/** Follows the redirect of GET /attachments/:id and fetches the file. */
async function download(account: TestUser, attachmentId: string) {
const redirect = await account.agent
.get(`/attachments/${attachmentId}`)
.expect(302);
const { pathname, search } = new URL(redirect.get('Location') ?? '');
return request(app.getHttpServer())
.get(pathname + search)
.buffer(true)
.parse((res, done) => {
const chunks: Buffer[] = [];
res.on('data', (chunk: Buffer) => chunks.push(chunk));
res.on('end', () => done(null, Buffer.concat(chunks)));
})
.expect(200);
}
beforeAll(async () => {
app = await createTestApp();
sockets = new TestSockets(await listen(app));
accounts = new TestAccounts(app, '@messages-e2e.test');
await accounts.cleanup();
ada = await accounts.signUp('Ada');
ben = await accounts.signUp('Ben');
cy = await accounts.signUp('Cy');
await befriend(ada, ben);
const opened = await ada.agent
.post('/conversations/direct')
.send({ userId: ben.id })
.expect(200);
chat = opened.body.id;
adaSocket = await sockets.connectAs(ada);
benSocket = await sockets.connectAs(ben);
});
afterAll(async () => {
sockets.closeAll();
await accounts.cleanup();
await app.close();
});
describe('attachments', () => {
const picture = Buffer.from('not really a picture, but bytes all the same');
let pictureId: string;
it('requires a session to ask for an upload', () => {
return request(app.getHttpServer())
.post('/attachments')
.send({ ...PNG, size: 10 })
.expect(401);
});
it('refuses empty and oversized files and odd types', async () => {
await ada.agent
.post('/attachments')
.send({ ...PNG, size: 0 })
.expect(400);
await ada.agent
.post('/attachments')
.send({ ...PNG, size: ATTACHMENT_MAX_SIZE + 1 })
.expect(400);
await ada.agent
.post('/attachments')
.send({ filename: 'x', contentType: 'nonsense', size: 10 })
.expect(400);
});
it('only accepts the bytes it was told to expect', async () => {
const upload = await requestUpload(ada, {
...PNG,
size: picture.length,
width: 640,
height: 480,
});
expect(upload.attachment).toEqual({
id: upload.attachment.id,
filename: 'cat.png',
contentType: 'image/png',
size: picture.length,
width: 640,
height: 480,
});
expect(upload.upload.method).toBe('PUT');
// Too short, and the wrong type: neither is stored.
const short = await putFile(app, upload, picture.subarray(0, 5));
expect(short.status).toBeGreaterThanOrEqual(400);
const mistyped = await putFile(app, upload, picture).set(
'Content-Type',
'text/html',
);
expect(mistyped.status).toBeGreaterThanOrEqual(400);
// A message can't carry a file that hasn't arrived.
await ada.agent
.post(`/conversations/${chat}/messages`)
.send({ attachmentIds: [upload.attachment.id] })
.expect(400);
await putFile(app, upload, picture).expect(200);
pictureId = upload.attachment.id;
});
it('refuses a tampered upload address', async () => {
const upload = await requestUpload(ada, { ...NOTES, size: 4 });
const { pathname, search } = new URL(upload.upload.url);
await request(app.getHttpServer())
.put(pathname + search.slice(0, -4) + 'AAAA')
.set(upload.upload.headers)
.send(Buffer.from('boo!'))
.expect(403);
await ada.agent
.delete(`/attachments/${upload.attachment.id}`)
.expect(204);
});
it('lets the uploader see a file before it is sent, and no one else', async () => {
expect((await download(ada, pictureId)).body).toEqual(picture);
await ben.agent.get(`/attachments/${pictureId}`).expect(404);
});
it("won't put someone else's upload on a message", async () => {
await ben.agent
.post(`/conversations/${chat}/messages`)
.send({ content: 'mine now', attachmentIds: [pictureId] })
.expect(400);
});
it('posts a message with nothing but a file, and tells both people', async () => {
const forBen = nextEvent(benSocket, 'message:created');
const message = await send(ada, chat, { attachmentIds: [pictureId] });
expect(message.content).toBe('');
expect(message.attachments).toEqual([
{
id: pictureId,
filename: 'cat.png',
contentType: 'image/png',
size: picture.length,
width: 640,
height: 480,
},
]);
expect((await forBen).attachments).toEqual(message.attachments);
expect((await historyFor(ben, chat)).at(0)?.attachments).toEqual(
message.attachments,
);
const last = (await chatFor(ben)).lastMessage;
expect(last?.attachments.map((file) => file.id)).toEqual([pictureId]);
});
it('serves the file to people in the chat, pictures inline', async () => {
const response = await download(ben, pictureId);
expect(response.body).toEqual(picture);
expect(response.get('Content-Type')).toBe('image/png');
expect(response.get('Content-Disposition')).toMatch(/^inline/);
});
it('hides it from everyone else', async () => {
await cy.agent.get(`/attachments/${pictureId}`).expect(404);
await request(app.getHttpServer())
.get(`/attachments/${pictureId}`)
.expect(401);
});
it("won't send the same file twice or take back one that was sent", async () => {
await ada.agent
.post(`/conversations/${chat}/messages`)
.send({ content: 'again', attachmentIds: [pictureId] })
.expect(400);
await ada.agent.delete(`/attachments/${pictureId}`).expect(404);
await download(ben, pictureId);
});
it('keeps several files in the order they were uploaded, as downloads', async () => {
const first = await uploadFile(app, ada, NOTES, Buffer.from('one'));
const second = await uploadFile(
app,
ada,
{ filename: 'page.html', contentType: 'text/html' },
Buffer.from('<script>alert(1)</script>'),
);
const message = await send(ada, chat, {
content: 'two files',
attachmentIds: [second, first],
});
expect(message.attachments.map((file) => file.id)).toEqual([
first,
second,
]);
// No sizes are kept for what isn't shown as a picture.
expect(message.attachments[0]).toMatchObject({
width: null,
height: null,
});
const page = await download(ben, second);
expect(page.get('Content-Disposition')).toMatch(
/^attachment; filename="page\.html"/,
);
expect(page.get('X-Content-Type-Options')).toBe('nosniff');
});
it('takes back an upload that was never sent', async () => {
const id = await uploadFile(app, ada, NOTES, Buffer.from('draft'));
await ben.agent.delete(`/attachments/${id}`).expect(404);
await ada.agent.delete(`/attachments/${id}`).expect(204);
await ada.agent.get(`/attachments/${id}`).expect(404);
await ada.agent
.post(`/conversations/${chat}/messages`)
.send({ attachmentIds: [id] })
.expect(400);
});
it('stores a JSON file as it is, without reading it as a request', async () => {
const bytes = Buffer.from('{"not": "a request body"}');
const id = await uploadFile(
app,
ada,
{ filename: 'data.json', contentType: 'application/json' },
bytes,
);
expect((await download(ada, id)).body).toEqual(bytes);
await ada.agent.delete(`/attachments/${id}`).expect(204);
});
});
describe('reactions', () => {
let message: Message;
beforeAll(async () => {
message = await send(ada, chat, { content: 'React to this' });
});
it('adds a reaction once and tells both people', async () => {
const forAda = nextEvent(adaSocket, 'reaction:changed');
const forBen = nextEvent(benSocket, 'reaction:changed');
await ben.agent.put(reactionPath(chat, message.id, '👍')).expect(204);
const change = {
conversationId: chat,
messageId: message.id,
emoji: '👍',
count: 1,
userId: ben.id,
added: true,
};
expect(await forAda).toEqual(change);
expect(await forBen).toEqual(change);
// Again changes nothing.
await ben.agent.put(reactionPath(chat, message.id, '👍')).expect(204);
expect((await historyFor(ben, chat)).at(0)?.reactions).toEqual([
{ emoji: '👍', count: 1, mine: true },
]);
expect((await historyFor(ada, chat)).at(0)?.reactions).toEqual([
{ emoji: '👍', count: 1, mine: false },
]);
});
it('counts people per emoji, in the order the emoji were first used', async () => {
await ada.agent.put(reactionPath(chat, message.id, '👨‍👩‍👧')).expect(204);
await ada.agent.put(reactionPath(chat, message.id, '👍')).expect(204);
expect((await historyFor(ada, chat)).at(0)?.reactions).toEqual([
{ emoji: '👍', count: 2, mine: true },
{ emoji: '👨‍👩‍👧', count: 1, mine: true },
]);
});
it('takes a reaction back and tells both people', async () => {
const forAda = nextEvent(adaSocket, 'reaction:changed');
await ben.agent.delete(reactionPath(chat, message.id, '👍')).expect(204);
expect(await forAda).toMatchObject({
emoji: '👍',
count: 1,
userId: ben.id,
added: false,
});
// Taking back what isn't there is fine.
await ben.agent.delete(reactionPath(chat, message.id, '👍')).expect(204);
await ada.agent.delete(reactionPath(chat, message.id, '👨‍👩‍👧')).expect(204);
expect((await historyFor(ben, chat)).at(0)?.reactions).toEqual([
{ emoji: '👍', count: 1, mine: false },
]);
});
it('only takes single emoji', async () => {
await ben.agent.put(reactionPath(chat, message.id, 'lol')).expect(400);
await ben.agent.put(reactionPath(chat, message.id, '👍👍')).expect(400);
});
it('answers 404 to outsiders and for a message from elsewhere', async () => {
await cy.agent.put(reactionPath(chat, message.id, '👍')).expect(404);
const realm: Realm = (
await ada.agent.post('/realms').send({ name: 'Elsewhere' }).expect(201)
).body;
await ada.agent
.put(reactionPath(realm.cauldrons[0].id, message.id, '👍'))
.expect(404);
await ada.agent.delete(`/realms/${realm.id}`).expect(204);
});
it(`stops at ${MESSAGE_MAX_REACTIONS} different emoji`, async () => {
const crowded = await send(ada, chat, { content: 'Popular' });
const emoji =
'😀 😁 😂 🤣 😃 😄 😅 😆 😉 😊 😋 😎 😍 😘 🥰 😗 😙 😚 🙂 🤗 🤩'.split(
' ',
);
expect(emoji).toHaveLength(MESSAGE_MAX_REACTIONS + 1);
for (const one of emoji.slice(0, MESSAGE_MAX_REACTIONS)) {
await ada.agent.put(reactionPath(chat, crowded.id, one)).expect(204);
}
await ben.agent
.put(reactionPath(chat, crowded.id, emoji[MESSAGE_MAX_REACTIONS]))
.expect(409);
// One that is there already still has room for more people.
await ben.agent.put(reactionPath(chat, crowded.id, emoji[0])).expect(204);
});
});
describe('unread counts', () => {
let first: Message;
let second: Message;
it('counts what other people posted since the reader last looked', async () => {
// Ben has posted nothing and read nothing so far.
const before = (await chatFor(ben)).unreadCount;
expect(before).toBeGreaterThan(0);
first = await send(ada, chat, { content: 'Unread one' });
second = await send(ada, chat, { content: 'Unread two' });
expect((await chatFor(ben)).unreadCount).toBe(before + 2);
// Posting counts as having read.
expect((await chatFor(ada)).unreadCount).toBe(0);
const listed: Conversation[] = (
await ben.agent.get('/conversations').expect(200)
).body;
expect(listed.find((item) => item.id === chat)?.unreadCount).toBe(
before + 2,
);
});
it('marks a conversation read up to a message, on every device', async () => {
const elsewhere = nextEvent(benSocket, 'conversation:read');
const read: ConversationRead = (
await ben.agent
.put(`/conversations/${chat}/read`)
.send({ messageId: first.id })
.expect(200)
).body;
expect(read).toEqual({
conversationId: chat,
realmId: null,
unreadCount: 1,
});
expect(await elsewhere).toEqual(read);
expect((await chatFor(ben)).unreadCount).toBe(1);
});
it('never moves the marker back', async () => {
await ben.agent
.put(`/conversations/${chat}/read`)
.send({ messageId: second.id })
.expect(200);
const read: ConversationRead = (
await ben.agent
.put(`/conversations/${chat}/read`)
.send({ messageId: first.id })
.expect(200)
).body;
expect(read.unreadCount).toBe(0);
expect((await chatFor(ben)).unreadCount).toBe(0);
});
it('answers 404 to outsiders and for a message from elsewhere', async () => {
await cy.agent
.put(`/conversations/${chat}/read`)
.send({ messageId: first.id })
.expect(404);
await ben.agent
.put(`/conversations/${chat}/read`)
.send({ messageId: chat })
.expect(404);
});
it("doesn't count a sender's own messages against them", async () => {
await send(ben, chat, { content: 'Reply' });
expect((await chatFor(ben)).unreadCount).toBe(0);
expect((await chatFor(ada)).unreadCount).toBe(1);
});
});
describe('in a realm', () => {
let realm: Realm;
let general: string;
let fileId: string;
async function realmFor(account: TestUser): Promise<Realm> {
return (await account.agent.get(`/realms/${realm.id}`).expect(200)).body;
}
async function listedFor(account: TestUser): Promise<RealmListItem> {
const realms: RealmListItem[] = (
await account.agent.get('/realms').expect(200)
).body;
const listed = realms.find((item) => item.id === realm.id);
if (!listed) throw new Error('The realm is not in the list.');
return listed;
}
beforeAll(async () => {
realm = (
await ada.agent.post('/realms').send({ name: 'Library' }).expect(201)
).body;
general = realm.cauldrons[0].id;
expect(realm.cauldrons[0].unreadCount).toBe(0);
fileId = await uploadFile(app, ada, NOTES, Buffer.from('for members'));
await send(ada, general, {
content: 'Before Ben',
attachmentIds: [fileId],
});
const invite: RealmInvite = (
await ada.agent.post(`/realms/${realm.id}/invites`).send({}).expect(201)
).body;
await ben.agent.post(`/invites/${invite.code}/accept`).expect(200);
});
it('starts a new member with nothing unread', async () => {
expect((await realmFor(ben)).cauldrons[0].unreadCount).toBe(0);
expect((await listedFor(ben)).hasUnread).toBe(false);
});
it('counts unread messages per cauldron and flags the realm', async () => {
const message = await send(ada, general, { content: 'After Ben' });
expect((await realmFor(ben)).cauldrons[0].unreadCount).toBe(1);
expect((await listedFor(ben)).hasUnread).toBe(true);
expect((await listedFor(ada)).hasUnread).toBe(false);
const read: ConversationRead = (
await ben.agent
.put(`/conversations/${general}/read`)
.send({ messageId: message.id })
.expect(200)
).body;
expect(read).toEqual({
conversationId: general,
realmId: realm.id,
unreadCount: 0,
});
expect((await listedFor(ben)).hasUnread).toBe(false);
});
it('lets members react, and tells the realm', async () => {
const message = (await historyFor(ben, general)).at(0);
if (!message) throw new Error('The cauldron is empty.');
const forAda = nextEvent(adaSocket, 'reaction:changed');
await ben.agent.put(reactionPath(general, message.id, '🔥')).expect(204);
expect(await forAda).toMatchObject({
emoji: '🔥',
count: 1,
added: true,
});
await cy.agent.put(reactionPath(general, message.id, '🔥')).expect(404);
});
it("serves a cauldron's files to members only", async () => {
expect((await download(ben, fileId)).body).toEqual(
Buffer.from('for members'),
);
await cy.agent.get(`/attachments/${fileId}`).expect(404);
await ben.agent
.delete(`/realms/${realm.id}/members/${ben.id}`)
.expect(204);
await ben.agent.get(`/attachments/${fileId}`).expect(404);
});
it('stops serving files once their realm is deleted', async () => {
await ada.agent.delete(`/realms/${realm.id}`).expect(204);
await ben.agent.get(`/attachments/${fileId}`).expect(404);
});
});
describe('after unfriending', () => {
it('keeps the history and its files readable, but not open to reactions', async () => {
const message = (await historyFor(ben, chat)).at(0);
if (!message) throw new Error('The chat is empty.');
await ada.agent.delete(`/friends/${ben.id}`).expect(204);
await ben.agent.put(reactionPath(chat, message.id, '👋')).expect(403);
await ben.agent
.put(`/conversations/${chat}/read`)
.send({ messageId: message.id })
.expect(200);
});
});
});
+396
View File
@@ -0,0 +1,396 @@
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);
});
});
});
+95
View File
@@ -0,0 +1,95 @@
import { ConfigService } from '@nestjs/config';
import type { Redis } from 'ioredis';
import request from 'supertest';
import type { Env } from '../src/config/env';
import { DEFAULT_LIMIT } from '../src/rate-limit/rate-limit.module';
import { REDIS } from '../src/redis/redis.module';
import { createTestApp, TestAccounts, type TestApp } from './helpers';
// The other specs run with the limits lifted; this one is about them. The
// setting is read when the app's modules load, which is before anything
// below this line would run.
vi.hoisted(() => {
process.env.RATE_LIMIT = 'true';
});
describe('Rate limits (e2e)', () => {
let app: TestApp;
let accounts: TestAccounts;
beforeAll(async () => {
app = await createTestApp();
// Sign-ins are counted per address, and every run comes from this
// machine: start from nothing, or a second run within the minute fails.
const redis = app.get<Redis>(REDIS);
const counted = await redis.keys('rate:*');
if (counted.length > 0) await redis.del(counted);
accounts = new TestAccounts(app, '@rate-limit-e2e.test');
await accounts.cleanup();
});
afterAll(async () => {
await accounts.cleanup();
await app.close();
});
it('counts per person and per route, and says when to come back', async () => {
const [ada, ben] = await Promise.all([
accounts.signUp('Ada'),
accounts.signUp('Ben'),
]);
// Creating a realm is allowed 5 times a minute.
for (let count = 1; count <= 5; count++) {
const made = await ada.agent
.post('/realms')
.send({ name: `Realm ${count}` })
.expect(201);
expect(made.headers['x-ratelimit-remaining']).toBe(String(5 - count));
}
const refused = await ada.agent
.post('/realms')
.send({ name: 'One too many' })
.expect(429);
const wait = Number(refused.headers['retry-after']);
expect(wait).toBeGreaterThan(0);
expect(wait).toBeLessThanOrEqual(60);
// Her other routes still answer, and so does the same route for Ben.
const listed = await ada.agent.get('/realms').expect(200);
expect(listed.body).toHaveLength(5);
expect(listed.headers['x-ratelimit-limit']).toBe(
String(DEFAULT_LIMIT.limit),
);
await ben.agent.post('/realms').send({ name: "Ben's" }).expect(201);
});
it('leaves the health checks alone', async () => {
const checked = await request(app.getHttpServer())
.get('/health')
.expect(200);
expect(checked.headers).not.toHaveProperty('x-ratelimit-limit');
});
it('slows down guessing a password', async () => {
const cal = await accounts.signUp('Cal');
const [origin] = app
.get<ConfigService<Env, true>>(ConfigService)
.getOrThrow('TRUSTED_ORIGINS', { infer: true });
const guess = () =>
request(app.getHttpServer())
.post('/api/auth/sign-in/username')
.set('Origin', origin)
.send({ username: cal.username, password: 'not-the-password' });
// Sign-in allows an address 10 tries a minute. Other specs' sign-ins
// don't count here: their limits are off, so nothing is recorded.
const answers: number[] = [];
for (let count = 0; count < 12; count++) {
answers.push((await guess()).status);
}
expect(answers.slice(0, 10)).toEqual(Array<number>(10).fill(401));
expect(answers.slice(10)).toEqual([429, 429]);
const refused = await guess();
expect(Number(refused.headers['x-retry-after'])).toBeGreaterThan(0);
});
});
+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);
});
});
+120
View File
@@ -0,0 +1,120 @@
import request from 'supertest';
import {
createTestApp,
TestAccounts,
type TestApp,
type TestUser,
} from './helpers';
describe('Users (e2e)', () => {
let app: TestApp;
let accounts: TestAccounts;
beforeAll(async () => {
app = await createTestApp();
accounts = new TestAccounts(app, '@users-e2e.test');
await accounts.cleanup();
});
afterAll(async () => {
await accounts.cleanup();
await app.close();
});
it('GET /users/me requires a session', () => {
return request(app.getHttpServer()).get('/users/me').expect(401);
});
it('refuses to sign up without a username', async () => {
const agent = request.agent(app.getHttpServer());
const response = await accounts.requestSignUp(agent, 'Nouser');
expect(response.status).toBe(400);
expect(response.body.message).toBe('Username is required.');
});
it('refuses to sign up with an invalid username', async () => {
const agent = request.agent(app.getHttpServer());
await accounts.requestSignUp(agent, 'Badname', 'not valid!').expect(400);
});
describe('with two accounts', () => {
let alice: TestUser;
let bob: TestUser;
beforeAll(async () => {
alice = await accounts.signUp('Alice');
bob = await accounts.signUp('Bob');
});
it('returns the own profile with a lower-cased username', async () => {
const response = await alice.agent.get('/users/me').expect(200);
expect(response.body).toEqual({
id: alice.id,
username: alice.username,
name: 'Alice',
bio: null,
image: null,
email: accounts.emailOf('Alice'),
createdAt: expect.any(String),
});
});
it('lower-cases a username on update', async () => {
const response = await bob.agent
.patch('/users/me')
.send({ username: bob.username.toUpperCase() })
.expect(200);
expect(response.body.username).toBe(bob.username);
});
it('updates only the fields sent', async () => {
const response = await alice.agent
.patch('/users/me')
.send({ bio: ' Brewing something. ' })
.expect(200);
expect(response.body).toMatchObject({
name: 'Alice',
bio: 'Brewing something.',
});
});
it('clears the bio when it is blank', async () => {
const response = await alice.agent
.patch('/users/me')
.send({ bio: ' ' })
.expect(200);
expect(response.body.bio).toBeNull();
});
it('rejects an invalid body', async () => {
await alice.agent.patch('/users/me').send({ name: '' }).expect(400);
await alice.agent
.patch('/users/me')
.send({ username: 'no spaces allowed' })
.expect(400);
});
it('answers 409 for a username someone else has', async () => {
const response = await bob.agent
.patch('/users/me')
.send({ username: alice.username })
.expect(409);
expect(response.body.message).toBe('Username is already taken.');
});
it('shows a public profile without the email', async () => {
const response = await bob.agent
.get(`/users/${alice.username}`)
.expect(200);
expect(response.body).toMatchObject({
username: alice.username,
name: 'Alice',
});
expect(response.body).not.toHaveProperty('email');
});
it('answers 404 for an unknown username', () => {
return bob.agent.get('/users/nobody_by_this_name').expect(404);
});
});
});