A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
test(api): cover message batches and mentions through routes
Hampus0163c7446e9e
diff --git a/fluxer_api/src/api/channel/services/message/MessageRetrievalService.test.ts b/fluxer_api/src/api/channel/services/message/MessageRetrievalService.test.tsdeleted file mode 100644index a1324e5d0..000000000--- a/fluxer_api/src/api/channel/services/message/MessageRetrievalService.test.ts+++ /dev/null@@ -1,212 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import type {AttachmentDecayService} from '@app/api/attachment/AttachmentDecayService';-import type {ChannelID, MessageID} from '@app/api/BrandedTypes';-import {createChannelID, createMessageID, createUserID} from '@app/api/BrandedTypes';-import type {ChannelRepository} from '@app/api/channel/ChannelRepository';-import type {AuthenticatedChannel} from '@app/api/channel/services/AuthenticatedChannel';-import type {MessageChannelAuthService} from '@app/api/channel/services/message/MessageChannelAuthService';-import type {MessageProcessingService} from '@app/api/channel/services/message/MessageProcessingService';-import {MessageRetrievalService} from '@app/api/channel/services/message/MessageRetrievalService';-import type {MessageSearchService} from '@app/api/channel/services/message/MessageSearchService';-import {SYSTEM_THREAD_VIEWER} from '@app/api/experiment/ChannelThreadsGate';-import type {UserCacheService} from '@app/api/infrastructure/UserCacheService';-import {Message} from '@app/api/models/Message';-import type {UserRepository} from '@app/api/user/repositories/UserRepository';-import {MessageTypes} from '@fluxer/constants/src/ChannelConstants';-import {createSnowflakeFromTimestamp} from '@fluxer/snowflake/src/Snowflake';-import {describe, expect, it} from 'vitest';--const CHANNEL_ID = createChannelID(10n);-const VIEWER_ID = createUserID(7n);-const CUTOFF = new Date('2026-01-10T00:00:00.000Z');--function makeMessageId(timestamp: Date, sequence: number): MessageID {- return createMessageID(createSnowflakeFromTimestamp(timestamp.getTime()) + BigInt(sequence));-}--function makeMessage(channelId: ChannelID, messageId: MessageID): Message {- return new Message({- channel_id: channelId,- bucket: 0,- message_id: messageId,- author_id: createUserID(3n),- type: MessageTypes.DEFAULT,- webhook_id: null,- webhook_name: null,- webhook_avatar_hash: null,- content: '',- edited_timestamp: null,- pinned_timestamp: null,- flags: 0,- mention_everyone: false,- mention_users: null,- mention_roles: null,- mention_channels: null,- attachments: null,- embeds: null,- sticker_items: null,- message_reference: null,- message_snapshots: null,- call: null,- has_reaction: null,- version: 1,- });-}--function createRetrievalService({- guilded,- canReadHistory,- messageHistoryCutoff = CUTOFF.toISOString(),- stored,-}: {- guilded: boolean;- canReadHistory: boolean;- messageHistoryCutoff?: string | null;- stored: Array<Message>;-}) {- const permissionChecks: Array<bigint> = [];- const authenticationCalls: Array<string> = [];- const storedById = new Map(stored.map((message) => [message.id.toString(), message] as const));- const channel = {id: CHANNEL_ID, guildId: guilded ? 20n : null};- const authChannel: AuthenticatedChannel = {- channel: channel as AuthenticatedChannel['channel'],- guild: guilded ? ({message_history_cutoff: messageHistoryCutoff} as AuthenticatedChannel['guild']) : null,- member: null,- hasPermission: async (permission: bigint) => {- permissionChecks.push(permission);- return canReadHistory;- },- checkPermission: async () => {},- };- const channelRepository = {- messages: {- getMessage: async (_channelId: ChannelID, messageId: MessageID) => storedById.get(messageId.toString()) ?? null,- },- } as unknown as ChannelRepository;- const channelAuthService = {- getChannelAuthenticated: async ({channelId}: {channelId: ChannelID}) => {- authenticationCalls.push(channelId.toString());- return authChannel;- },- } as unknown as MessageChannelAuthService;- const processingService = {- repairMentionsOnRead: async (message: Message) => message,- } as unknown as MessageProcessingService;- const attachmentDecayService = {- extendForAttachments: async () => {},- } as unknown as AttachmentDecayService;- const service = new MessageRetrievalService(- channelRepository,- {} as unknown as UserCacheService,- channelAuthService,- processingService,- {} as unknown as MessageSearchService,- {} as unknown as UserRepository,- attachmentDecayService,- );- return {service, permissionChecks, authenticationCalls};-}--describe('MessageRetrievalService.getMessagesByIds', () => {- it('authenticates the channel and checks message history once for the whole batch', async () => {- const messages = [- makeMessage(CHANNEL_ID, makeMessageId(new Date('2026-02-01T00:00:00.000Z'), 1)),- makeMessage(CHANNEL_ID, makeMessageId(new Date('2026-02-02T00:00:00.000Z'), 2)),- makeMessage(CHANNEL_ID, makeMessageId(new Date('2026-02-03T00:00:00.000Z'), 3)),- ];- const {service, permissionChecks, authenticationCalls} = createRetrievalService({- guilded: true,- canReadHistory: true,- stored: messages,- });-- const result = await service.getMessagesByIds({- viewer: SYSTEM_THREAD_VIEWER,- userId: VIEWER_ID,- channelId: CHANNEL_ID,- messageIds: messages.map((message) => message.id),- });-- expect(Array.from(result.keys())).toEqual(messages.map((message) => message.id.toString()));- expect(authenticationCalls).toEqual([CHANNEL_ID.toString()]);- expect(permissionChecks).toHaveLength(1);- });-- it('drops messages older than the history cutoff when history is not readable', async () => {- const beforeCutoff = makeMessage(CHANNEL_ID, makeMessageId(new Date('2026-01-05T00:00:00.000Z'), 1));- const afterCutoff = makeMessage(CHANNEL_ID, makeMessageId(new Date('2026-01-20T00:00:00.000Z'), 2));- const {service, permissionChecks} = createRetrievalService({- guilded: true,- canReadHistory: false,- stored: [beforeCutoff, afterCutoff],- });-- const result = await service.getMessagesByIds({- viewer: SYSTEM_THREAD_VIEWER,- userId: VIEWER_ID,- channelId: CHANNEL_ID,- messageIds: [beforeCutoff.id, afterCutoff.id],- });-- expect(Array.from(result.keys())).toEqual([afterCutoff.id.toString()]);- expect(permissionChecks).toHaveLength(1);- });-- it('drops every message when history is not readable and no cutoff is configured', async () => {- const message = makeMessage(CHANNEL_ID, makeMessageId(new Date('2026-02-01T00:00:00.000Z'), 1));- const {service} = createRetrievalService({- guilded: true,- canReadHistory: false,- messageHistoryCutoff: null,- stored: [message],- });-- const result = await service.getMessagesByIds({- viewer: SYSTEM_THREAD_VIEWER,- userId: VIEWER_ID,- channelId: CHANNEL_ID,- messageIds: [message.id],- });-- expect(result.size).toBe(0);- });-- it('skips the history permission check entirely for direct messages', async () => {- const message = makeMessage(CHANNEL_ID, makeMessageId(new Date('2026-02-01T00:00:00.000Z'), 1));- const {service, permissionChecks} = createRetrievalService({- guilded: false,- canReadHistory: false,- stored: [message],- });-- const result = await service.getMessagesByIds({- viewer: SYSTEM_THREAD_VIEWER,- userId: VIEWER_ID,- channelId: CHANNEL_ID,- messageIds: [message.id],- });-- expect(Array.from(result.keys())).toEqual([message.id.toString()]);- expect(permissionChecks).toEqual([]);- });-- it('omits messages that no longer exist instead of failing the batch', async () => {- const present = makeMessage(CHANNEL_ID, makeMessageId(new Date('2026-02-01T00:00:00.000Z'), 1));- const deleted = makeMessage(CHANNEL_ID, makeMessageId(new Date('2026-02-02T00:00:00.000Z'), 2));- const {service} = createRetrievalService({- guilded: true,- canReadHistory: true,- stored: [present],- });-- const result = await service.getMessagesByIds({- viewer: SYSTEM_THREAD_VIEWER,- userId: VIEWER_ID,- channelId: CHANNEL_ID,- messageIds: [present.id, deleted.id],- });-- expect(Array.from(result.keys())).toEqual([present.id.toString()]);- });-});diff --git a/fluxer_api/src/api/channel/tests/MessageAllowedMentions.test.ts b/fluxer_api/src/api/channel/tests/MessageAllowedMentions.test.tsnew file mode 100644index 000000000..21aef9b8b--- /dev/null+++ b/fluxer_api/src/api/channel/tests/MessageAllowedMentions.test.ts@@ -0,0 +1,76 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import assert from 'node:assert/strict';+import {createChannelID, createMessageID, createRoleID, createUserID} from '@app/api/BrandedTypes';+import {ChannelRepository} from '@app/api/channel/ChannelRepository';+import {createPermissionOverwrite, setupTestGuildWithMembers} from '@app/api/channel/tests/ChannelTestUtils';+import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';+import {createBuilder} from '@app/api/test/TestRequestBuilder';+import {Permissions} from '@fluxer/constants/src/ChannelConstants';+import type {MessageResponse} from '@fluxer/schema/src/domains/message/MessageResponseSchemas';+import type {AllowedMentionsRequest} from '@fluxer/schema/src/domains/message/SharedMessageSchemas';+import {afterAll, beforeAll, beforeEach, describe, expect, it} from 'vitest';+import type {z} from 'zod';++type AllowedMentionsInput = z.input<typeof AllowedMentionsRequest>;++describe('Message allowed mentions', () => {+ let harness: ApiTestHarness;++ beforeAll(async () => {+ harness = await createApiTestHarness();+ });++ beforeEach(async () => {+ await harness.reset();+ });++ afterAll(async () => {+ await harness.shutdown();+ });++ async function setup() {+ const {owner, members, systemChannel} = await setupTestGuildWithMembers(harness, 2);+ const [first, second] = members;+ assert(first && second, 'Expected two guild members');+ return {owner, first, second, systemChannel};+ }++ async function expectMentionState(+ message: MessageResponse,+ expected: {users: Array<string>; roles: Array<string>; everyone: boolean},+ ) {+ expect(message.mentions.map((user) => user.id)).toEqual(expected.users);+ expect(message.mention_roles).toEqual(expected.roles);+ expect(message.mention_everyone).toBe(expected.everyone);+ const stored = await new ChannelRepository().messages.getMessage(+ createChannelID(BigInt(message.channel_id)),+ createMessageID(BigInt(message.id)),+ );+ expect(stored?.mentionedUserIds).toEqual(new Set(expected.users.map((id) => createUserID(BigInt(id)))));+ expect(stored?.mentionedRoleIds).toEqual(new Set(expected.roles.map((id) => createRoleID(BigInt(id)))));+ expect(stored?.mentionEveryone).toBe(expected.everyone);+ }++ it.each(['@everyone', '@here'])('respects the permission boundary for %s', async (mention) => {+ const world = await setup();+ const content = `${mention} <@${world.second.userId}>`;+ const allowedMentions = {parse: ['users', 'everyone']} satisfies AllowedMentionsInput;+ const permitted = await createBuilder<MessageResponse>(harness, world.owner.token)+ .post(`/channels/${world.systemChannel.id}/messages`)+ .body({content, allowed_mentions: allowedMentions})+ .execute();+ await expectMentionState(permitted, {users: [world.second.userId], roles: [], everyone: true});+ await createPermissionOverwrite(harness, world.owner.token, world.systemChannel.id, world.first.userId, {+ type: 1,+ allow: Permissions.VIEW_CHANNEL.toString(),+ deny: Permissions.MENTION_EVERYONE.toString(),+ });+ const message = await createBuilder<MessageResponse>(harness, world.first.token)+ .post(`/channels/${world.systemChannel.id}/messages`)+ .body({content, allowed_mentions: allowedMentions})+ .execute();++ await expectMentionState(message, {users: [world.second.userId], roles: [], everyone: false});+ });+});diff --git a/fluxer_api/src/api/user/tests/UserRecentMentions.test.ts b/fluxer_api/src/api/user/tests/UserRecentMentions.test.tsindex f2390c702..de811c98f 100644--- a/fluxer_api/src/api/user/tests/UserRecentMentions.test.ts+++ b/fluxer_api/src/api/user/tests/UserRecentMentions.test.ts@@ -1,21 +1,22 @@// SPDX-License-Identifier: AGPL-3.0-or-later-import {createTestAccount} from '@app/api/auth/tests/AuthTestUtils';+import assert from 'node:assert/strict';import {createChannelID, createGuildID, createMessageID, createUserID} from '@app/api/BrandedTypes';-import {addMemberRole, createRole, removeMemberRole} from '@app/api/guild/tests/GuildTestUtils';import {- acceptInvite,- createChannelInvite,- createGuild,- sendMessage,- updateChannelPermissions,-} from '@app/api/message/tests/MessageTestUtils';+ createPermissionOverwrite,+ sendChannelMessage,+ setupTestGuildWithMembers,+ updateGuild,+} from '@app/api/channel/tests/ChannelTestUtils';+import {addMemberRole, createRole, removeMemberRole} from '@app/api/guild/tests/GuildTestUtils';+import {sendMessage, updateChannelPermissions} from '@app/api/message/tests/MessageTestUtils';import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';-import {HTTP_STATUS} from '@app/api/test/TestConstants';import {createBuilder} from '@app/api/test/TestRequestBuilder';import {UserRepository} from '@app/api/user/repositories/UserRepository';import {Permissions} from '@fluxer/constants/src/ChannelConstants';-import type {MessageListResponse} from '@fluxer/schema/src/domains/message/MessageResponseSchemas';+import {HttpStatus} from '@fluxer/constants/src/HttpConstants';+import type {MessageListResponse, MessageResponse} from '@fluxer/schema/src/domains/message/MessageResponseSchemas';+import {extractTimestamp} from '@fluxer/snowflake/src/SnowflakeUtils';import {afterEach, beforeEach, describe, expect, test} from 'vitest';describe('User recent mentions', () => {@@ -26,13 +27,36 @@ describe('User recent mentions', () => {afterEach(async () => {await harness?.shutdown();});++ async function recordMentions(userId: string, guildId: string, messages: Array<MessageResponse>) {+ await new UserRepository().createRecentMentions(+ messages.map((message) => ({+ user_id: createUserID(BigInt(userId)),+ channel_id: createChannelID(BigInt(message.channel_id)),+ message_id: createMessageID(BigInt(message.id)),+ guild_id: createGuildID(BigInt(guildId)),+ is_everyone: false,+ is_role: false,+ })),+ );+ }++ async function createMentionBatch() {+ const {owner, members, guild, systemChannel} = await setupTestGuildWithMembers(harness, 1);+ const [member] = members;+ assert(member, 'Expected a guild member');+ const older = await sendChannelMessage(harness, owner.token, systemChannel.id, `<@${member.userId}> before cutoff`);+ const boundary = await sendChannelMessage(harness, owner.token, systemChannel.id, `<@${member.userId}> at cutoff`);+ const newer = await sendChannelMessage(harness, owner.token, systemChannel.id, `<@${member.userId}> after cutoff`);+ await recordMentions(member.userId, guild.id, [older, boundary, newer]);+ return {owner, member, guild, systemChannel, older, boundary, newer};+ }+test('filters mentions from channels the user can no longer access', async () => {- const owner = await createTestAccount(harness);- const member = await createTestAccount(harness);- const guild = await createGuild(harness, owner.token, 'Recent Mentions Access Test');- const channelId = guild.system_channel_id!;- const invite = await createChannelInvite(harness, owner.token, channelId);- await acceptInvite(harness, member.token, invite.code);+ const {owner, members, guild, systemChannel} = await setupTestGuildWithMembers(harness, 1);+ const [member] = members;+ assert(member, 'Expected a guild member');+ const channelId = systemChannel.id;const accessRole = await createRole(harness, owner.token, guild.id, {name: 'Mention Channel Access',permissions: (Permissions.VIEW_CHANNEL | Permissions.READ_MESSAGE_HISTORY).toString(),@@ -47,66 +71,82 @@ describe('User recent mentions', () => {});await addMemberRole(harness, owner.token, guild.id, member.userId, accessRole.id);const message = await sendMessage(harness, owner.token, channelId, `<@${member.userId}> private ping`);- await new UserRepository().createRecentMentions([- {- user_id: createUserID(BigInt(member.userId)),- channel_id: createChannelID(BigInt(channelId)),- message_id: createMessageID(BigInt(message.id)),- guild_id: createGuildID(BigInt(guild.id)),- is_everyone: false,- is_role: false,- },- ]);+ await recordMentions(member.userId, guild.id, [message]);const visibleMentions = await createBuilder<MessageListResponse>(harness, member.token).get('/users/@me/mentions')- .expect(HTTP_STATUS.OK)+ .expect(HttpStatus.OK).execute();expect(visibleMentions.map((mention) => mention.id)).toContain(message.id);await removeMemberRole(harness, owner.token, guild.id, member.userId, accessRole.id);await createBuilder(harness, member.token).get(`/channels/${channelId}/messages/${message.id}`)- .expect(HTTP_STATUS.FORBIDDEN)+ .expect(HttpStatus.FORBIDDEN).execute();const filteredMentions = await createBuilder<MessageListResponse>(harness, member.token).get('/users/@me/mentions')- .expect(HTTP_STATUS.OK)+ .expect(HttpStatus.OK).execute();expect(filteredMentions.map((mention) => mention.id)).not.toContain(message.id);});test('marks several recent mentions read in one request', async () => {- const owner = await createTestAccount(harness);- const member = await createTestAccount(harness);- const guild = await createGuild(harness, owner.token, 'Recent Mentions Bulk Read Test');- const channelId = guild.system_channel_id!;- const invite = await createChannelInvite(harness, owner.token, channelId);- await acceptInvite(harness, member.token, invite.code);+ const {owner, members, guild, systemChannel} = await setupTestGuildWithMembers(harness, 1);+ const [member] = members;+ assert(member, 'Expected a guild member');+ const channelId = systemChannel.id;const firstMessage = await sendMessage(harness, owner.token, channelId, `<@${member.userId}> first ping`);const secondMessage = await sendMessage(harness, owner.token, channelId, `<@${member.userId}> second ping`);const thirdMessage = await sendMessage(harness, owner.token, channelId, `<@${member.userId}> third ping`);- const repository = new UserRepository();- for (const message of [firstMessage, secondMessage, thirdMessage]) {- await repository.createRecentMentions([- {- user_id: createUserID(BigInt(member.userId)),- channel_id: createChannelID(BigInt(channelId)),- message_id: createMessageID(BigInt(message.id)),- guild_id: createGuildID(BigInt(guild.id)),- is_everyone: false,- is_role: false,- },- ]);- }+ await recordMentions(member.userId, guild.id, [firstMessage, secondMessage, thirdMessage]);await createBuilder(harness, member.token).post('/users/@me/mentions/read').body({message_ids: [firstMessage.id, secondMessage.id]})- .expect(HTTP_STATUS.NO_CONTENT)+ .expect(HttpStatus.NO_CONTENT).execute();const remainingMentions = await createBuilder<MessageListResponse>(harness, member.token).get('/users/@me/mentions')- .expect(HTTP_STATUS.OK)+ .expect(HttpStatus.OK).execute();expect(remainingMentions.map((mention) => mention.id)).toEqual([thirdMessage.id]);});++ test.each([+ ['readable history', 0n, ['newer', 'boundary', 'older']],+ ['history restricted by cutoff', Permissions.READ_MESSAGE_HISTORY, ['newer', 'boundary']],+ ] as const)('returns a mention batch with %s', async (_name, denied, expected) => {+ const world = await createMentionBatch();+ const cutoffTimestamp = extractTimestamp(world.boundary.id);+ expect(extractTimestamp(world.older.id)).toBeLessThan(cutoffTimestamp);+ expect(extractTimestamp(world.newer.id)).toBeGreaterThan(cutoffTimestamp);+ await updateGuild(harness, world.owner.token, world.guild.id, {+ message_history_cutoff: new Date(cutoffTimestamp).toISOString(),+ });+ await createPermissionOverwrite(harness, world.owner.token, world.systemChannel.id, world.member.userId, {+ type: 1,+ allow: Permissions.VIEW_CHANNEL.toString(),+ deny: denied.toString(),+ });++ const mentions = await createBuilder<MessageListResponse>(harness, world.member.token)+ .get('/users/@me/mentions')+ .execute();++ expect(mentions.map((message) => message.id)).toEqual(expected.map((key) => world[key].id));+ });++ test('omits every guild mention when history is denied without a cutoff', async () => {+ const world = await createMentionBatch();+ await createPermissionOverwrite(harness, world.owner.token, world.systemChannel.id, world.member.userId, {+ type: 1,+ allow: Permissions.VIEW_CHANNEL.toString(),+ deny: Permissions.READ_MESSAGE_HISTORY.toString(),+ });++ const mentions = await createBuilder<MessageListResponse>(harness, world.member.token)+ .get('/users/@me/mentions')+ .execute();++ expect(mentions).toEqual([]);+ });test('continues scanning older rows when recent mentions are filtered out', async () => {const repository = new UserRepository();const userId = createUserID(10n);