572 lines
20 KiB
TypeScript
572 lines
20 KiB
TypeScript
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);
|
|
});
|
|
});
|
|
});
|