A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
test(api): delete restated channel, community and user suites
Hampus953f565286eb
diff --git a/fluxer_api/src/api/channel/services/message/MessageProcessingService.test.ts b/fluxer_api/src/api/channel/services/message/MessageProcessingService.test.tsdeleted file mode 100644index d69272d54..000000000--- a/fluxer_api/src/api/channel/services/message/MessageProcessingService.test.ts+++ /dev/null@@ -1,109 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {- type ChannelID,- createChannelID,- createMessageID,- createUserID,- type MessageID,- type UserID,-} from '@app/api/BrandedTypes';-import {MessageProcessingService} from '@app/api/channel/services/message/MessageProcessingService';-import type {ChannelRow} from '@app/api/database/types/ChannelTypes';-import type {IGatewayService} from '@app/api/infrastructure/IGatewayService';-import type {UserCacheService} from '@app/api/infrastructure/UserCacheService';-import type {RequestCache} from '@app/api/middleware/RequestCacheMiddleware';-import {Channel} from '@app/api/models/Channel';-import type {UserRepository} from '@app/api/user/repositories/UserRepository';-import {ChannelTypes} from '@fluxer/constants/src/ChannelConstants';-import {describe, expect, it} from 'vitest';--const CHANNEL_ID = createChannelID(1532860318772891648n);-const AUTHOR_ID = createUserID(1471426754353995881n);-const RECIPIENT_ID = createUserID(1485344055661987728n);-const MESSAGE_ID = createMessageID(1546325276953149440n);--function dmChannelRow(lastMessageId: MessageID | null): ChannelRow {- return {- channel_id: CHANNEL_ID,- guild_id: null,- type: ChannelTypes.DM,- name: null,- topic: null,- icon_hash: null,- url: null,- parent_id: null,- position: null,- owner_id: null,- recipient_ids: new Set<UserID>([AUTHOR_ID, RECIPIENT_ID]),- nsfw: null,- content_warning_level: null,- content_warning_text: null,- rate_limit_per_user: null,- bitrate: null,- user_limit: null,- voice_connection_limit: null,- rtc_region: null,- rtc_p2p: null,- last_message_id: lastMessageId,- last_pin_timestamp: null,- permission_overwrites: null,- nicks: null,- soft_deleted: false,- indexed_at: null,- version: 0,- };-}--function buildService(): {service: MessageProcessingService; opened: Array<Channel>} {- const opened: Array<Channel> = [];- const userRepository = {- isDmChannelOpen: async (userId: UserID, _channelId: ChannelID) => userId === AUTHOR_ID,- openPrivateChannelForUser: async (_userId: UserID, channel: Channel) => {- opened.push(channel);- },- } as unknown as UserRepository;- const userCacheService = {- getUserPartialResponses: async (userIds: Array<UserID>) =>- new Map(userIds.map((userId) => [userId, {id: userId.toString()}])),- } as unknown as UserCacheService;- const gatewayService = {- dispatchPresence: async () => {},- } as unknown as IGatewayService;- const service = new MessageProcessingService(- undefined as never,- userRepository,- userCacheService,- gatewayService,- undefined as never,- undefined as never,- );- return {service, opened};-}--describe('MessageProcessingService.updateDMRecipients', () => {- it('snapshots the new message id when the in-request channel is stale', async () => {- const {service, opened} = buildService();- await service.updateDMRecipients({- channel: new Channel(dmChannelRow(null)),- channelId: CHANNEL_ID,- messageId: MESSAGE_ID,- requestCache: {} as RequestCache,- });- expect(opened).toHaveLength(1);- expect(opened[0].lastMessageId).toBe(MESSAGE_ID);- });-- it('keeps a newer last message id already present on the channel', async () => {- const {service, opened} = buildService();- const newer = createMessageID(MESSAGE_ID + 10n);- await service.updateDMRecipients({- channel: new Channel(dmChannelRow(newer)),- channelId: CHANNEL_ID,- messageId: MESSAGE_ID,- requestCache: {} as RequestCache,- });- expect(opened).toHaveLength(1);- expect(opened[0].lastMessageId).toBe(newer);- });-});diff --git a/fluxer_api/src/api/channel/services/message/MessageRequestService.test.ts b/fluxer_api/src/api/channel/services/message/MessageRequestService.test.tsdeleted file mode 100644index 34d0495a7..000000000--- a/fluxer_api/src/api/channel/services/message/MessageRequestService.test.ts+++ /dev/null@@ -1,155 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {createChannelID, createGuildID, createMessageID, createUserID} from '@app/api/BrandedTypes';-import type {ChannelService} from '@app/api/channel/services/ChannelService';-import type {CrosspostSourceService} from '@app/api/channel/services/message/CrosspostSourceService';-import {MessageRequestService} from '@app/api/channel/services/message/MessageRequestService';-import type {MessageResponseDataService} from '@app/api/channel/services/message/MessageResponseDataService';-import {setCassandraQueryExecutorForTesting, upsertOne} from '@app/api/database/CassandraQueryExecution';-import type {CassandraParams, PreparedQuery} from '@app/api/database/CassandraTypes';-import {clearChannelThreadsTaintCacheForTesting, type ThreadViewer} from '@app/api/experiment/ChannelThreadsGate';-import type {RequestCache} from '@app/api/middleware/RequestCacheMiddleware';-import {GuildThreadState} from '@app/api/Tables';-import {InMemoryCassandraQueryExecutor} from '@app/api/test/InMemoryCassandraQueryExecutor';-import {ChannelTypes, MessageTypes} from '@fluxer/constants/src/ChannelConstants';-import {ServerMessageFlags} from '@fluxer/constants/src/ThreadConstants';-import type {MessageResponse} from '@fluxer/schema/src/domains/message/MessageResponseSchemas';-import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';--class MarkerCountingExecutor extends InMemoryCassandraQueryExecutor {- markerReads = 0;-- override async executeQuery<T = Record<string, unknown>, P extends CassandraParams = CassandraParams>(- query: PreparedQuery<P>,- ): Promise<Array<T>> {- if (query.cql.trimStart().toUpperCase().startsWith('SELECT') && query.cql.includes('guild_thread_state')) {- this.markerReads++;- }- return super.executeQuery<T>(query);- }-}--const GUILD = createGuildID(100n);-const CHANNEL = createChannelID(200n);-const USER = createUserID(10n);-const VIEWER: ThreadViewer = {kind: 'user', userId: USER, bot: false, capable: false};--function message(overrides: Partial<MessageResponse> = {}): MessageResponse {- return {- id: '300',- channel_id: CHANNEL.toString(),- type: MessageTypes.DEFAULT,- flags: 0,- content: 'hello',- mentions: [],- mention_roles: [],- ...overrides,- } as MessageResponse;-}--function build(responses: Array<MessageResponse>) {- const listMessages = vi.fn(async (_params: {threadsMask?: boolean}) => responses);- const getMessage = vi.fn(async (_params: {threadsMask?: boolean}) => responses[0] ?? null);- const channelService = {- messages: {- retrieval: {- getResponseAccess: async () => ({- access: {sourceGuildId: GUILD, messageHistoryCutoff: null, canReadMessageHistory: true},- authChannel: {channel: {guildId: GUILD, isThreadOnly: () => false}},- }),- threadResponses: {- shape: async (params: {responses: Array<MessageResponse>}) => params.responses,- getStarter: async () => null,- },- },- },- } as unknown as ChannelService;- const service = new MessageRequestService(- channelService,- {listMessages, getMessage} as unknown as MessageResponseDataService,- {} as CrosspostSourceService,- );- return {service, listMessages, getMessage};-}--function list(service: MessageRequestService) {- return service.listMessages({- userId: USER,- viewer: VIEWER,- channelId: CHANNEL,- query: {limit: 50},- requestCache: {} as RequestCache,- });-}--function get(service: MessageRequestService) {- return service.getMessage({- userId: USER,- viewer: VIEWER,- channelId: CHANNEL,- messageId: createMessageID(300n),- requestCache: {} as RequestCache,- });-}--async function taint(): Promise<void> {- await upsertOne(- GuildThreadState.upsertAll({- guild_id: GUILD,- first_active_at: new Date(),- perms_seeded_at: null,- search_backfilled_at: null,- }),- );-}--describe('MessageRequestService thread masking', () => {- let executor: MarkerCountingExecutor;-- beforeEach(() => {- executor = new MarkerCountingExecutor();- setCassandraQueryExecutorForTesting(executor);- clearChannelThreadsTaintCacheForTesting();- });-- afterEach(() => {- setCassandraQueryExecutorForTesting(null);- });-- it('never reads the marker for a page without thread data', async () => {- const {service, listMessages, getMessage} = build([message()]);- await list(service);- await get(service);- expect(executor.markerReads).toBe(0);- expect(listMessages).toHaveBeenCalledTimes(1);- expect(listMessages.mock.calls[0]![0].threadsMask).toBeUndefined();- expect(getMessage).toHaveBeenCalledTimes(1);- expect(getMessage.mock.calls[0]![0].threadsMask).toBeUndefined();- });-- it('refetches masked when a tainted guild page carries thread data', async () => {- await taint();- const {service, listMessages, getMessage} = build([message({flags: ServerMessageFlags.HAS_THREAD})]);- await list(service);- await get(service);- expect(executor.markerReads).toBe(1);- expect(listMessages.mock.calls.map(([params]) => params.threadsMask)).toEqual([undefined, true]);- expect(getMessage.mock.calls.map(([params]) => params.threadsMask)).toEqual([undefined, true]);- });-- it('treats a mentioned forum as thread data', async () => {- await taint();- const {service, listMessages} = build([- message({mention_channels: [{id: '400', name: 'forum', type: ChannelTypes.GUILD_FORUM}]}),- ]);- await list(service);- expect(listMessages.mock.calls.map(([params]) => params.threadsMask)).toEqual([undefined, true]);- });-- it('keeps raw data in an untainted guild', async () => {- const {service, listMessages} = build([message({flags: ServerMessageFlags.HAS_THREAD})]);- await list(service);- expect(executor.markerReads).toBe(1);- expect(listMessages).toHaveBeenCalledTimes(1);- });-});diff --git a/fluxer_api/src/api/channel/services/message/MessageValidationService.test.ts b/fluxer_api/src/api/channel/services/message/MessageValidationService.test.tsdeleted file mode 100644index e97b68fb9..000000000--- a/fluxer_api/src/api/channel/services/message/MessageValidationService.test.ts+++ /dev/null@@ -1,102 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {createUserID} from '@app/api/BrandedTypes';-import {MessageValidationService} from '@app/api/channel/services/message/MessageValidationService';-import {createDefaultLimitConfig} from '@app/api/constants/LimitConfig';-import {EMPTY_USER_ROW} from '@app/api/database/types/UserTypes';-import {User} from '@app/api/models/User';-import {MAX_MESSAGE_LENGTH_NON_PREMIUM, MAX_MESSAGE_LENGTH_PREMIUM} from '@fluxer/constants/src/LimitConstants';-import {ValidationErrorCodes} from '@fluxer/constants/src/ValidationErrorCodes';-import {CannotSendEmptyMessageError} from '@fluxer/errors/src/domains/channel/CannotSendEmptyMessageError';-import {InputValidationError} from '@fluxer/errors/src/domains/core/InputValidationError';-import {describe, expect, it} from 'vitest';--function createValidationService(): MessageValidationService {- return new MessageValidationService(- {} as never,- {- getConfigSnapshot: () => createDefaultLimitConfig({selfHosted: false}),- } as never,- );-}--function createUser(params?: {isBot?: boolean}): User {- return new User({- ...EMPTY_USER_ROW,- user_id: createUserID(params?.isBot ? 2n : 1n),- username: params?.isBot ? 'bot-user' : 'regular-user',- discriminator: 1234,- bot: params?.isBot ?? false,- version: 1,- });-}--function expectContentLengthError(run: () => void, maxLength: number): void {- try {- run();- throw new Error('Expected content length validation to fail');- } catch (error) {- expect(error).toBeInstanceOf(InputValidationError);- expect((error as InputValidationError).getLocalizedErrors()).toEqual([- {- path: 'content',- code: ValidationErrorCodes.CONTENT_EXCEEDS_MAX_LENGTH,- variables: {maxLength},- },- ]);- }-}--describe('MessageValidationService.validateMessageContent', () => {- it('rejects content with no visible characters', () => {- const service = createValidationService();- for (const content of [' ', '\u200e \u200b', '\u2800\u3164\u{e0100}']) {- expect(() => service.validateMessageContent({content} as never, null)).toThrow(CannotSendEmptyMessageError);- }- });-- it('accepts visible message content', () => {- const service = createValidationService();- expect(() => service.validateMessageContent({content: '\u200e hello'} as never, null)).not.toThrow();- });-- it('limits regular users to the non-premium message length', () => {- const service = createValidationService();- const user = createUser();- expect(() =>- service.validateMessageContent({content: 'x'.repeat(MAX_MESSAGE_LENGTH_NON_PREMIUM)} as never, user),- ).not.toThrow();- expectContentLengthError(- () => service.validateMessageContent({content: 'x'.repeat(MAX_MESSAGE_LENGTH_NON_PREMIUM + 1)} as never, user),- MAX_MESSAGE_LENGTH_NON_PREMIUM,- );- });-- it('allows bot users to send premium-length message content', () => {- const service = createValidationService();- const bot = createUser({isBot: true});- expect(() =>- service.validateMessageContent({content: 'x'.repeat(MAX_MESSAGE_LENGTH_PREMIUM)} as never, bot),- ).not.toThrow();- expectContentLengthError(- () => service.validateMessageContent({content: 'x'.repeat(MAX_MESSAGE_LENGTH_PREMIUM + 1)} as never, bot),- MAX_MESSAGE_LENGTH_PREMIUM,- );- });-- it('allows webhooks to send premium-length message content', () => {- const service = createValidationService();- expect(() =>- service.validateMessageContent({content: 'x'.repeat(MAX_MESSAGE_LENGTH_PREMIUM)} as never, null, {- messageAuthorType: 'webhook',- }),- ).not.toThrow();- expectContentLengthError(- () =>- service.validateMessageContent({content: 'x'.repeat(MAX_MESSAGE_LENGTH_PREMIUM + 1)} as never, null, {- messageAuthorType: 'webhook',- }),- MAX_MESSAGE_LENGTH_PREMIUM,- );- });-});diff --git a/fluxer_api/src/api/channel/services/tests/ChannelAuthThreadGate.test.ts b/fluxer_api/src/api/channel/services/tests/ChannelAuthThreadGate.test.tsdeleted file mode 100644index 9a11c3774..000000000--- a/fluxer_api/src/api/channel/services/tests/ChannelAuthThreadGate.test.ts+++ /dev/null@@ -1,84 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {createChannelID, createGuildID, createUserID} from '@app/api/BrandedTypes';-import type {ChannelRepository} from '@app/api/channel/ChannelRepository';-import {ChannelAuthService} from '@app/api/channel/services/channel_data/ChannelAuthService';-import {SYSTEM_THREAD_VIEWER, type ThreadViewer} from '@app/api/experiment/ChannelThreadsGate';-import type {GuildRepository} from '@app/api/guild/repositories/GuildRepository';-import type {IGatewayService} from '@app/api/infrastructure/IGatewayService';-import type {Channel} from '@app/api/models/Channel';-import type {UserRepository} from '@app/api/user/repositories/UserRepository';-import {ChannelTypes} from '@fluxer/constants/src/ChannelConstants';-import {UnknownChannelError} from '@fluxer/errors/src/domains/channel/UnknownChannelError';-import {describe, expect, it} from 'vitest';--const GUILD_ID = createGuildID(100n);-const CHANNEL_ID = createChannelID(300n);-const USER_ID = createUserID(10n);-const REACHED_GATEWAY = new Error('reached the gateway permission lookup');--function createService(type: number): ChannelAuthService {- const channel = {id: CHANNEL_ID, type, guildId: GUILD_ID, parentId: createChannelID(200n)} as unknown as Channel;- const channelRepository = {- channelData: {findUnique: async () => channel},- threads: {getState: async () => null, getMember: async () => null},- } as unknown as ChannelRepository;- const gatewayService = {- getGuildAuthContext: async () => {- throw REACHED_GATEWAY;- },- getGuildMember: async () => {- throw REACHED_GATEWAY;- },- } as unknown as IGatewayService;- return new ChannelAuthService(channelRepository, {} as UserRepository, {} as GuildRepository, gatewayService);-}--const capableViewer: ThreadViewer = {kind: 'user', userId: USER_ID, bot: false, capable: true};--describe('getChannelAuthenticated thread gate', () => {- it('never consults the gate for control channel types', async () => {- await expect(- createService(ChannelTypes.GUILD_TEXT).getChannelAuthenticated({- userId: USER_ID,- channelId: CHANNEL_ID,- viewer: {...capableViewer, capable: false},- }),- ).rejects.toBe(REACHED_GATEWAY);- });-- it.each([- ChannelTypes.PUBLIC_THREAD,- ChannelTypes.PRIVATE_THREAD,- ChannelTypes.GUILD_FORUM,- ChannelTypes.GUILD_MEDIA,- ])('hides channel type %i as unknown from incapable viewers', async (type) => {- await expect(- createService(type).getChannelAuthenticated({- userId: USER_ID,- channelId: CHANNEL_ID,- viewer: {...capableViewer, capable: false},- }),- ).rejects.toBeInstanceOf(UnknownChannelError);- });-- it('hides a thread when the client lacks the capability', async () => {- await expect(- createService(ChannelTypes.PUBLIC_THREAD).getChannelAuthenticated({- userId: USER_ID,- channelId: CHANNEL_ID,- viewer: {...capableViewer, capable: false},- }),- ).rejects.toBeInstanceOf(UnknownChannelError);- });-- it('lets an active viewer and the system through to the permission checks', async () => {- const service = createService(ChannelTypes.PUBLIC_THREAD);- await expect(- service.getChannelAuthenticated({userId: USER_ID, channelId: CHANNEL_ID, viewer: capableViewer}),- ).rejects.toBe(REACHED_GATEWAY);- await expect(- service.getChannelAuthenticated({userId: USER_ID, channelId: CHANNEL_ID, viewer: SYSTEM_THREAD_VIEWER}),- ).rejects.toBe(REACHED_GATEWAY);- });-});diff --git a/fluxer_api/src/api/channel/tests/ChannelPinsResponseShape.test.ts b/fluxer_api/src/api/channel/tests/ChannelPinsResponseShape.test.tsdeleted file mode 100644index ba7066853..000000000--- a/fluxer_api/src/api/channel/tests/ChannelPinsResponseShape.test.ts+++ /dev/null@@ -1,49 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {createTestAccount} from '@app/api/auth/tests/AuthTestUtils';-import {Config} from '@app/api/Config';-import {createGuild} from '@app/api/guild/tests/GuildTestUtils';-import {pinMessage, sendMessage} 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 {afterEach, beforeEach, describe, expect, test} from 'vitest';--describe('Channel Pins Response Shape', () => {- let harness: ApiTestHarness;- beforeEach(async () => {- harness = await createApiTestHarness();- });- afterEach(async () => {- Config.dev.validateResponses = true;- await harness.shutdown();- });- test('omits referenced_message and reactions from pinned messages when response validation is disabled', async () => {- const account = await createTestAccount(harness);- const guild = await createGuild(harness, account.token, 'Pins Shape Guild');- const channelId = guild.system_channel_id!;- const target = await sendMessage(harness, account.token, channelId, 'pin target');- const reply = await createBuilder<{id: string}>(harness, account.token)- .post(`/channels/${channelId}/messages`)- .body({- content: 'pin reply',- message_reference: {channel_id: channelId, guild_id: guild.id, message_id: target.id},- })- .expect(HTTP_STATUS.OK)- .execute();- await createBuilder(harness, account.token)- .put(`/channels/${channelId}/messages/${reply.id}/reactions/${encodeURIComponent('👍')}/@me`)- .body(null)- .expect(HTTP_STATUS.NO_CONTENT)- .execute();- await pinMessage(harness, account.token, channelId, reply.id);- Config.dev.validateResponses = false;- const pins = await createBuilder<{items: Array<{message: Record<string, unknown>}>}>(harness, account.token)- .get(`/channels/${channelId}/messages/pins`)- .expect(HTTP_STATUS.OK)- .execute();- expect(pins.items).toHaveLength(1);- expect(pins.items[0]!.message).not.toHaveProperty('referenced_message');- expect(pins.items[0]!.message).not.toHaveProperty('reactions');- });-});diff --git a/fluxer_api/src/api/channel/tests/DMEveryoneMention.test.ts b/fluxer_api/src/api/channel/tests/DMEveryoneMention.test.tsdeleted file mode 100644index 0e0ff0475..000000000--- a/fluxer_api/src/api/channel/tests/DMEveryoneMention.test.ts+++ /dev/null@@ -1,44 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {createTestAccount} from '@app/api/auth/tests/AuthTestUtils';-import {- createDmChannel,- createFriendship,- createGroupDmChannel,- sendChannelMessage,-} from '@app/api/channel/tests/ChannelTestUtils';-import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';-import {afterAll, beforeAll, beforeEach, describe, expect, it} from 'vitest';--describe('DM everyone mention', () => {- let harness: ApiTestHarness;- beforeAll(async () => {- harness = await createApiTestHarness();- });- beforeEach(async () => {- await harness.reset();- });- afterAll(async () => {- await harness?.shutdown();- });- it('does not mention everyone in a one-to-one DM', async () => {- const user1 = await createTestAccount(harness);- const user2 = await createTestAccount(harness);- await createFriendship(harness, user1, user2);- const dm = await createDmChannel(harness, user1.token, user2.userId);- const everyone = await sendChannelMessage(harness, user1.token, dm.id, '@everyone test');- const here = await sendChannelMessage(harness, user1.token, dm.id, '@here test');- expect(everyone.mention_everyone).toBe(false);- expect(here.mention_everyone).toBe(false);- });- it('still mentions everyone in a group DM', async () => {- const user1 = await createTestAccount(harness);- const user2 = await createTestAccount(harness);- const user3 = await createTestAccount(harness);- await createFriendship(harness, user1, user2);- await createFriendship(harness, user1, user3);- const groupDm = await createGroupDmChannel(harness, user1.token, [user2.userId, user3.userId]);- const message = await sendChannelMessage(harness, user1.token, groupDm.id, '@everyone test');- expect(message.mention_everyone).toBe(true);- });-});diff --git a/fluxer_api/src/api/channel/tests/GroupDmLimit.test.ts b/fluxer_api/src/api/channel/tests/GroupDmLimit.test.tsindex 533732607..e9d4ba8bd 100644--- a/fluxer_api/src/api/channel/tests/GroupDmLimit.test.ts+++ b/fluxer_api/src/api/channel/tests/GroupDmLimit.test.ts@@ -1,15 +1,13 @@// SPDX-License-Identifier: AGPL-3.0-or-laterimport {createTestAccount} from '@app/api/auth/tests/AuthTestUtils';-import {createFriendship, seedPrivateChannels} from '@app/api/channel/tests/ChannelTestUtils';+import {createFriendship, createGroupDmChannel} from '@app/api/channel/tests/ChannelTestUtils';import {ensureSessionStarted} from '@app/api/message/tests/MessageTestUtils';import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';+import {setLimitOverride} from '@app/api/test/LimitTestUtils';import {HTTP_STATUS} from '@app/api/test/TestConstants';import {createBuilder} from '@app/api/test/TestRequestBuilder';-import {afterAll, beforeAll, beforeEach, describe, expect, it} from 'vitest';--const MAX_GROUP_DM_LIMIT = 150;-const MAX_GROUP_DMS_ERROR_CODE = 'MAX_GROUP_DMS';+import {afterAll, beforeAll, beforeEach, describe, it} from 'vitest';describe('Group DM recipient limit', () => {let harness: ApiTestHarness;@@ -22,29 +20,28 @@ describe('Group DM recipient limit', () => {afterAll(async () => {await harness?.shutdown();});- it('rejects creating group DM when user has reached the limit', async () => {+ it('counts a recipient’s open group DMs against the cap', async () => {const creator = await createTestAccount(harness);const target = await createTestAccount(harness);- const recipient = await createTestAccount(harness);const helper = await createTestAccount(harness);- await ensureSessionStarted(harness, creator.token);- await ensureSessionStarted(harness, target.token);- await ensureSessionStarted(harness, recipient.token);- await ensureSessionStarted(harness, helper.token);+ const other = await createTestAccount(harness);+ for (const account of [creator, target, helper, other]) {+ await ensureSessionStarted(harness, account.token);+ }+ await createFriendship(harness, helper, target);+ await createFriendship(harness, helper, other);await createFriendship(harness, creator, target);- await createFriendship(harness, creator, recipient);- const seedResult = await seedPrivateChannels(harness, target.token, target.userId, {- group_dm_count: MAX_GROUP_DM_LIMIT,- recipients: [helper.userId, recipient.userId],- clear_existing: true,- });- expect(seedResult.group_dms.length).toBe(MAX_GROUP_DM_LIMIT);- await createBuilder(harness, creator.token)- .post('/users/@me/channels')- .body({- recipients: [helper.userId, target.userId],- })- .expect(HTTP_STATUS.BAD_REQUEST, MAX_GROUP_DMS_ERROR_CODE)- .execute();+ await createFriendship(harness, creator, helper);+ const restore = await setLimitOverride(harness, {max_group_dms_per_user: 1});+ try {+ await createGroupDmChannel(harness, helper.token, [target.userId, other.userId]);+ await createBuilder(harness, creator.token)+ .post('/users/@me/channels')+ .body({recipients: [helper.userId, target.userId]})+ .expect(HTTP_STATUS.BAD_REQUEST, 'MAX_GROUP_DMS')+ .execute();+ } finally {+ await restore();+ }});});diff --git a/fluxer_api/src/api/channel/tests/MessagePinsList.test.ts b/fluxer_api/src/api/channel/tests/MessagePinsList.test.tsdeleted file mode 100644index 65ee5b4dc..000000000--- a/fluxer_api/src/api/channel/tests/MessagePinsList.test.ts+++ /dev/null@@ -1,94 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {createMessageResponseDataService} from '@app/api/channel/services/message/MessageResponseDataService';-import {- createPermissionOverwrite,- pinMessage,- sendChannelMessage,- setupTestGuildWithMembers,- updateGuild,-} 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 {ChannelPinsResponse} from '@fluxer/schema/src/domains/message/MessageResponseSchemas';-import {extractTimestamp} from '@fluxer/snowflake/src/SnowflakeUtils';-import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi} from 'vitest';--describe('Channel pins listing', () => {- let harness: ApiTestHarness;-- beforeAll(async () => {- harness = await createApiTestHarness();- });-- beforeEach(async () => {- await harness.reset();- });-- afterEach(() => {- vi.restoreAllMocks();- });-- afterAll(async () => {- await harness?.shutdown();- });-- it('builds a full page of pins with a single batched request', async () => {- const {owner, systemChannel} = await setupTestGuildWithMembers(harness, 0);- const pinnedIds: Array<string> = [];- for (let index = 0; index < 6; index++) {- const message = await sendChannelMessage(harness, owner.token, systemChannel.id, `pinned ${index}`);- await pinMessage(harness, owner.token, systemChannel.id, message.id);- pinnedIds.push(message.id);- }- const responseDataService = createMessageResponseDataService();- const buildMessages = vi.spyOn(responseDataService, 'buildMessages');- const getMessage = vi.spyOn(responseDataService, 'getMessage');- const before = encodeURIComponent(new Date(Date.now() + 60_000).toISOString());-- const pins = await createBuilder<ChannelPinsResponse>(harness, owner.token)- .get(`/channels/${systemChannel.id}/messages/pins?limit=5&before=${before}`)- .execute();-- expect(pins.has_more).toBe(true);- expect(pins.items).toHaveLength(5);- for (const item of pins.items) {- expect(pinnedIds).toContain(item.message.id);- expect(item.message.pinned).toBe(true);- expect(item.pinned_at).toEqual(expect.any(String));- }- expect(getMessage).not.toHaveBeenCalled();- expect(buildMessages).toHaveBeenCalledTimes(1);- expect(buildMessages.mock.calls[0]![0].messages).toHaveLength(5);- });-- it('applies message history access filtering to every pin in the batch', async () => {- const {owner, members, guild, systemChannel} = await setupTestGuildWithMembers(harness, 1);- const member = members[0]!;- const oldMessage = await sendChannelMessage(harness, owner.token, systemChannel.id, 'old pin');- const newMessage = await sendChannelMessage(harness, owner.token, systemChannel.id, 'new pin');- await pinMessage(harness, owner.token, systemChannel.id, oldMessage.id);- await pinMessage(harness, owner.token, systemChannel.id, newMessage.id);- const cutoff = new Date(extractTimestamp(newMessage.id)).toISOString();- await updateGuild(harness, owner.token, guild.id, {message_history_cutoff: cutoff});- await createPermissionOverwrite(harness, owner.token, systemChannel.id, member.userId, {- type: 1,- allow: Permissions.VIEW_CHANNEL.toString(),- deny: Permissions.READ_MESSAGE_HISTORY.toString(),- });- const responseDataService = createMessageResponseDataService();- const buildMessages = vi.spyOn(responseDataService, 'buildMessages');-- const pins = await createBuilder<ChannelPinsResponse>(harness, member.token)- .get(`/channels/${systemChannel.id}/messages/pins`)- .execute();-- expect(pins.items.map((item) => item.message.id)).toEqual([newMessage.id]);- expect(buildMessages).toHaveBeenCalledTimes(1);- const batch = buildMessages.mock.calls[0]![0];- expect(batch.messages.map((message) => message.id.toString())).toEqual([newMessage.id]);- expect(batch.access.canReadMessageHistory).toBe(false);- expect(batch.access.messageHistoryCutoff).toBe(cutoff);- });-});diff --git a/fluxer_api/src/api/channel/tests/ReactionUsersPagination.test.ts b/fluxer_api/src/api/channel/tests/ReactionUsersPagination.test.tsdeleted file mode 100644index d35eee6c1..000000000--- a/fluxer_api/src/api/channel/tests/ReactionUsersPagination.test.ts+++ /dev/null@@ -1,72 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {sendChannelMessage, setupTestGuildWithMembers} from '@app/api/channel/tests/ChannelTestUtils';-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 {afterAll, beforeAll, beforeEach, describe, expect, it} from 'vitest';--const EMOJI = encodeURIComponent('👍');--interface ReactionUsersPage {- items: Array<{id: string}>;- has_more: boolean;- next_after: string | null;-}--describe('Reaction users pagination', () => {- let harness: ApiTestHarness;-- beforeAll(async () => {- harness = await createApiTestHarness();- });-- beforeEach(async () => {- await harness.reset();- });-- afterAll(async () => {- await harness?.shutdown();- });-- async function setupReactedMessage(): Promise<{token: string; channelId: string; messageId: string}> {- const {owner, members, systemChannel} = await setupTestGuildWithMembers(harness, 2);- const message = await sendChannelMessage(harness, owner.token, systemChannel.id, 'react to me');- for (const account of [owner, ...members]) {- await createBuilder(harness, account.token)- .put(`/channels/${systemChannel.id}/messages/${message.id}/reactions/${EMOJI}/@me`)- .body(null)- .expect(HTTP_STATUS.NO_CONTENT)- .execute();- }- return {token: owner.token, channelId: systemChannel.id, messageId: message.id};- }-- it('sends the pagination signal of the page in headers', async () => {- const {token, channelId, messageId} = await setupReactedMessage();-- const legacy = await createBuilder<Array<{id: string}>>(harness, token)- .get(`/channels/${channelId}/messages/${messageId}/reactions/${EMOJI}?limit=2`)- .executeWithResponse();- const page = await createBuilder<ReactionUsersPage>(harness, token)- .get(`/channels/${channelId}/messages/${messageId}/reactions/${EMOJI}/users?limit=2`)- .execute();-- expect(legacy.json.map((user) => user.id)).toEqual(page.items.map((user) => user.id));- expect(page.has_more).toBe(true);- expect(legacy.response.headers.get('X-Has-More')).toBe('true');- expect(legacy.response.headers.get('X-Next-After')).toBe(page.next_after);- });-- it('omits the cursor header on the final page', async () => {- const {token, channelId, messageId} = await setupReactedMessage();-- const legacy = await createBuilder<Array<{id: string}>>(harness, token)- .get(`/channels/${channelId}/messages/${messageId}/reactions/${EMOJI}?limit=3`)- .executeWithResponse();-- expect(legacy.json).toHaveLength(3);- expect(legacy.response.headers.get('X-Has-More')).toBe('false');- expect(legacy.response.headers.get('X-Next-After')).toBeNull();- });-});diff --git a/fluxer_api/src/api/channel/tests/ThreadAuditVisibility.test.ts b/fluxer_api/src/api/channel/tests/ThreadAuditVisibility.test.tsdeleted file mode 100644index 18775e2af..000000000--- a/fluxer_api/src/api/channel/tests/ThreadAuditVisibility.test.ts+++ /dev/null@@ -1,83 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {createTestAccount, type TestAccount} from '@app/api/auth/tests/AuthTestUtils';-import {createChannel, createGuild} from '@app/api/channel/tests/ChannelTestUtils';-import {threadsRequest} from '@app/api/channel/tests/ThreadTestUtils';-import {clearChannelThreadsTaintCacheForTesting} from '@app/api/experiment/ChannelThreadsGate';-import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';-import {AuditLogActionType} from '@fluxer/constants/src/AuditLogActionType';-import {ChannelTypes, Permissions} from '@fluxer/constants/src/ChannelConstants';-import {THREAD_PERMISSIONS, ThreadPermissionFlags} from '@fluxer/constants/src/ThreadPermissionUtils';-import type {ThreadChannelResponse} from '@fluxer/schema/src/domains/channel/ThreadRequestSchemas';-import type {GuildAuditLogListResponse} from '@fluxer/schema/src/domains/guild/GuildAuditLogSchemas';-import type {GuildRoleResponse} from '@fluxer/schema/src/domains/guild/GuildRoleSchemas';-import {afterAll, beforeAll, beforeEach, describe, expect, test} from 'vitest';--interface Setup {- owner: TestAccount;- guildId: string;- channelId: string;- thread: ThreadChannelResponse;- role: GuildRoleResponse;-}--describe('thread audit visibility', () => {- let harness: ApiTestHarness;-- beforeAll(async () => {- harness = await createApiTestHarness();- });-- beforeEach(async () => {- await harness.reset();- clearChannelThreadsTaintCacheForTesting();- });-- afterAll(async () => {- clearChannelThreadsTaintCacheForTesting();- await harness.shutdown();- });-- async function setup(): Promise<Setup> {- const owner = await createTestAccount(harness);- const guild = await createGuild(harness, owner.token, 'kill switch');- const channel = await createChannel(harness, owner.token, guild.id, 'general');- const thread = await threadsRequest<ThreadChannelResponse>(harness, owner.token)- .post(`/channels/${channel.id}/threads`)- .body({name: 'topic', type: ChannelTypes.PUBLIC_THREAD})- .expect(201)- .execute();- const role = await threadsRequest<GuildRoleResponse>(harness, owner.token)- .post(`/guilds/${guild.id}/roles`)- .body({name: 'mods', permissions: (Permissions.SEND_MESSAGES | ThreadPermissionFlags.MANAGE_THREADS).toString()})- .execute();- await threadsRequest(harness, owner.token)- .patch(`/guilds/${guild.id}/roles/${role.id}`)- .body({permissions: Permissions.SEND_MESSAGES.toString()})- .execute();- return {owner, guildId: guild.id, channelId: channel.id, thread, role};- }-- async function auditLog(s: Setup): Promise<GuildAuditLogListResponse> {- return threadsRequest<GuildAuditLogListResponse>(harness, s.owner.token)- .get(`/guilds/${s.guildId}/audit-logs`)- .execute();- }-- function roleEntries(log: GuildAuditLogListResponse, roleId: string, action: AuditLogActionType) {- return log.audit_log_entries.filter((entry) => entry.target_id === roleId && entry.action_type === action);- }-- function permissionsChange(entry: GuildAuditLogListResponse['audit_log_entries'][number] | undefined) {- return entry?.changes?.find((change) => change.key === 'permissions');- }-- test('viewers see thread entries and thread bits while the guild is active', async () => {- const s = await setup();- const log = await auditLog(s);- expect(log.audit_log_entries.map((entry) => entry.action_type)).toContain(AuditLogActionType.THREAD_CREATE);- const created = permissionsChange(roleEntries(log, s.role.id, AuditLogActionType.ROLE_CREATE)[0]);- expect(BigInt(created?.new_value as string) & THREAD_PERMISSIONS).toBe(ThreadPermissionFlags.MANAGE_THREADS);- expect(roleEntries(log, s.role.id, AuditLogActionType.ROLE_UPDATE)).toHaveLength(1);- });-});diff --git a/fluxer_api/src/api/channel/tests/ThreadCrossCuttingHelpers.test.ts b/fluxer_api/src/api/channel/tests/ThreadCrossCuttingHelpers.test.tsdeleted file mode 100644index 9bfaba96c..000000000--- a/fluxer_api/src/api/channel/tests/ThreadCrossCuttingHelpers.test.ts+++ /dev/null@@ -1,51 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {maskThreadArtifacts} from '@app/api/channel/services/message/ThreadMessageResponses';-import {MessageTypes} from '@fluxer/constants/src/ChannelConstants';-import {ServerMessageFlags} from '@fluxer/constants/src/ThreadConstants';-import type {MessageResponse} from '@fluxer/schema/src/domains/message/MessageResponseSchemas';-import {describe, expect, it} from 'vitest';--function message(overrides: Partial<MessageResponse>): MessageResponse {- return {- id: '10',- channel_id: '1',- author: {- id: '2',- username: 'a',- discriminator: '0001',- global_name: null,- avatar: null,- avatar_color: null,- flags: 0,- },- type: MessageTypes.DEFAULT,- flags: 0,- content: '',- timestamp: new Date(0).toISOString(),- pinned: false,- mention_everyone: false,- tts: false,- mentions: [],- mention_roles: [],- ...overrides,- };-}--describe('thread artifact masking', () => {- it('drops thread created messages and clears thread bits including nested ones', () => {- const masked = maskThreadArtifacts([- message({id: '1', type: MessageTypes.THREAD_CREATED}),- message({- id: '2',- flags: ServerMessageFlags.HAS_THREAD,- referenced_message: message({id: '3', flags: ServerMessageFlags.FAILED_TO_MENTION_SOME_ROLES_IN_THREAD}),- }),- message({id: '4', referenced_message: message({id: '5', type: MessageTypes.THREAD_CREATED})}),- ]);- expect(masked.map((m) => m.id)).toEqual(['2', '4']);- expect(masked[0]?.flags).toBe(0);- expect(masked[0]?.referenced_message?.flags).toBe(0);- expect(masked[1]?.referenced_message).toBeNull();- });-});diff --git a/fluxer_api/src/api/channel/threads/tests/GatedJsonValidator.test.ts b/fluxer_api/src/api/channel/threads/tests/GatedJsonValidator.test.tsdeleted file mode 100644index fceb84641..000000000--- a/fluxer_api/src/api/channel/threads/tests/GatedJsonValidator.test.ts+++ /dev/null@@ -1,58 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {GatedJsonValidator} from '@app/api/channel/threads/GatedJsonValidator';-import type {HonoEnv} from '@app/api/types/HonoEnv';-import {Validator} from '@app/api/Validator';-import {AppErrorHandler} from '@fluxer/errors/src/domains/core/ErrorHandlers';-import {Hono} from 'hono';-import {describe, expect, it} from 'vitest';-import {z} from 'zod';--const Control = z.object({name: z.string().max(10)});-const Gated = Control.extend({default_auto_archive_duration: z.number().int()});--function touchesGate(body: unknown): boolean {- return typeof body === 'object' && body !== null && 'default_auto_archive_duration' in body;-}--function createApp(active: boolean): Hono<HonoEnv> {- const app = new Hono<HonoEnv>();- app.onError(AppErrorHandler);- app.post('/control', Validator('json', Control), (ctx) => ctx.json(ctx.req.valid('json')));- app.post('/gated', GatedJsonValidator(Control, Gated, {touchesGate, active: () => active}), (ctx) =>- ctx.json(ctx.req.valid('json')),- );- return app;-}--async function post(app: Hono<HonoEnv>, path: string, body: string): Promise<{status: number; text: string}> {- const response = await app.request(path, {method: 'POST', headers: {'content-type': 'application/json'}, body});- return {status: response.status, text: await response.text()};-}--describe('GatedJsonValidator', () => {- const bodies = [- '{"name":"general","default_auto_archive_duration":60}',- '{"name":"general"}',- '{"name":"far too long for the control schema","default_auto_archive_duration":60}',- '{"name":',- '{"default_auto_archive_duration":"soon"}',- ];-- it('behaves exactly like the control schema while inactive', async () => {- const app = createApp(false);- for (const body of bodies) {- expect(await post(app, '/gated', body)).toEqual(await post(app, '/control', body));- }- });-- it('keeps gated keys when the body touches the gate and the caller is active', async () => {- const app = createApp(true);- expect(await post(app, '/gated', bodies[0]!)).toEqual({- status: 200,- text: '{"name":"general","default_auto_archive_duration":60}',- });- expect((await post(app, '/gated', bodies[4]!)).status).toBe(400);- expect(await post(app, '/gated', bodies[1]!)).toEqual(await post(app, '/control', bodies[1]!));- });-});diff --git a/fluxer_api/src/api/guild/ExpressionSourceGuild.test.ts b/fluxer_api/src/api/guild/ExpressionSourceGuild.test.tsindex 9a7b8836d..b3f97c58a 100644--- a/fluxer_api/src/api/guild/ExpressionSourceGuild.test.ts+++ b/fluxer_api/src/api/guild/ExpressionSourceGuild.test.ts@@ -2,71 +2,24 @@import {resolveExpressionSourceGuild} from '@app/api/guild/ExpressionSourceGuild';import {GuildFeatures} from '@fluxer/constants/src/GuildConstants';-import {UnknownGuildError} from '@fluxer/errors/src/domains/guild/UnknownGuildError';import type {GuildResponse} from '@fluxer/schema/src/domains/guild/GuildResponseSchemas';-import {describe, expect, it, vi} from 'vitest';--function guild(features: Array<string>, icon: string | null = null): GuildResponse {- return {id: '20', name: 'Blob Club', icon, features} as unknown as GuildResponse;-}+import {describe, expect, it} from 'vitest';describe('resolveExpressionSourceGuild', () => {- it('hides a community the gateway reports as unavailable without checking membership', async () => {- const isMember = vi.fn(() => Promise.resolve(true));- await expect(- resolveExpressionSourceGuild({loadGuild: () => Promise.reject(new UnknownGuildError()), isMember}),- ).rejects.toBeInstanceOf(UnknownGuildError);- expect(isMember).not.toHaveBeenCalled();- });-- it('propagates other gateway failures instead of reporting the community as unavailable', async () => {- const failure = new Error('gateway timeout');- const isMember = vi.fn(() => Promise.resolve(true));- await expect(resolveExpressionSourceGuild({loadGuild: () => Promise.reject(failure), isMember})).rejects.toBe(- failure,- );- expect(isMember).not.toHaveBeenCalled();- });-- it('reveals a discoverable community without checking membership', async () => {- const isMember = vi.fn(() => Promise.resolve(false));- const community = await resolveExpressionSourceGuild({- loadGuild: () => Promise.resolve(guild([GuildFeatures.DISCOVERABLE])),- isMember,- });- expect(community).toEqual({id: '20', name: 'Blob Club', icon: null, features: [GuildFeatures.DISCOVERABLE]});- expect(isMember).not.toHaveBeenCalled();- });-- it('reveals a private community to a member', async () => {- const community = await resolveExpressionSourceGuild({- loadGuild: () => Promise.resolve(guild([])),- isMember: () => Promise.resolve(true),- });- expect(community.id).toBe('20');- expect(community.features).toEqual([]);- });-- it('hides a private community from a non-member', async () => {- await expect(- resolveExpressionSourceGuild({- loadGuild: () => Promise.resolve(guild([])),- isMember: () => Promise.resolve(false),- }),- ).rejects.toBeInstanceOf(UnknownGuildError);- });-it('limits features to the badge flags', async () => {const community = await resolveExpressionSourceGuild({loadGuild: () =>- Promise.resolve(- guild([+ Promise.resolve({+ id: '20',+ name: 'Blob Club',+ icon: null,+ features: [GuildFeatures.DISCOVERABLE,GuildFeatures.VERIFIED,GuildFeatures.INVITES_DISABLED,GuildFeatures.CLONE_EMOJI_ENABLED,- ]),- ),+ ],+ } as unknown as GuildResponse),isMember: () => Promise.resolve(false),});expect(community.features).toEqual(expect.arrayContaining([GuildFeatures.DISCOVERABLE, GuildFeatures.VERIFIED]));diff --git a/fluxer_api/src/api/guild/tests/GuildChannelPositionsThreadGate.test.ts b/fluxer_api/src/api/guild/tests/GuildChannelPositionsThreadGate.test.tsdeleted file mode 100644index 5e70ef172..000000000--- a/fluxer_api/src/api/guild/tests/GuildChannelPositionsThreadGate.test.ts+++ /dev/null@@ -1,94 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {createTestAccount} from '@app/api/auth/tests/AuthTestUtils';-import {createChannel, createGuild} from '@app/api/channel/tests/ChannelTestUtils';-import {threadsRequest} from '@app/api/channel/tests/ThreadTestUtils';-import {clearChannelThreadsTaintCacheForTesting} from '@app/api/experiment/ChannelThreadsGate';-import {ensureSessionStarted} 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 {ChannelTypes} from '@fluxer/constants/src/ChannelConstants';-import {ValidationErrorCodes} from '@fluxer/constants/src/ValidationErrorCodes';-import type {ChannelResponse} from '@fluxer/schema/src/domains/channel/ChannelSchemas';-import {afterAll, beforeAll, beforeEach, describe, expect, test} from 'vitest';--interface ValidationResponse {- code: string;- errors: Array<{path: string; code: string}>;-}--describe('guild channel positions with thread-only channels', () => {- let harness: ApiTestHarness;-- beforeAll(async () => {- harness = await createApiTestHarness();- });-- beforeEach(async () => {- await harness.reset();- clearChannelThreadsTaintCacheForTesting();- });-- afterAll(async () => {- clearChannelThreadsTaintCacheForTesting();- await harness.shutdown();- });-- async function setup() {- const owner = await createTestAccount(harness);- await ensureSessionStarted(harness, owner.token);- const guild = await createGuild(harness, owner.token, 'positions');- const category = await createChannel(harness, owner.token, guild.id, 'cat', ChannelTypes.GUILD_CATEGORY);- const text = await createChannel(harness, owner.token, guild.id, 'text');- const forum = await threadsRequest<ChannelResponse>(harness, owner.token)- .post(`/guilds/${guild.id}/channels`)- .body({name: 'forum', type: ChannelTypes.GUILD_FORUM})- .execute();- return {owner, guildId: guild.id, categoryId: category.id, textId: text.id, forumId: forum.id};- }-- async function rejected(token: string, guildId: string, body: Array<Record<string, unknown>>) {- const response = await createBuilder<ValidationResponse>(harness, token)- .patch(`/guilds/${guildId}/channels`)- .body(body)- .expect(HTTP_STATUS.BAD_REQUEST)- .execute();- return response.errors[0];- }-- test('a non-viewer naming a forum id gets the same errors as an unknown id', async () => {- const s = await setup();- const unknownId = '1';- const asId = await rejected(s.owner.token, s.guildId, [- {id: s.forumId, parent_id: s.categoryId, lock_permissions: true},- ]);- const unknownAsId = await rejected(s.owner.token, s.guildId, [- {id: unknownId, parent_id: s.categoryId, lock_permissions: true},- ]);- expect(asId).toEqual(unknownAsId);- expect(asId?.code).toBe(ValidationErrorCodes.CHANNEL_NOT_FOUND);-- const asParent = await rejected(s.owner.token, s.guildId, [{id: s.textId, parent_id: s.forumId}]);- expect(asParent).toEqual(await rejected(s.owner.token, s.guildId, [{id: s.textId, parent_id: unknownId}]));- expect(asParent?.code).toBe(ValidationErrorCodes.INVALID_PARENT_CHANNEL);-- const asSibling = await rejected(s.owner.token, s.guildId, [{id: s.textId, preceding_sibling_id: s.forumId}]);- expect(asSibling?.path).toBe('preceding_sibling_id');- expect(asSibling?.code).toBe(ValidationErrorCodes.INVALID_CHANNEL_ID);-- const forum = await threadsRequest<ChannelResponse>(harness, s.owner.token).get(`/channels/${s.forumId}`).execute();- expect(forum.parent_id ?? null).toBeNull();- });-- test('a viewer can still move a forum', async () => {- const s = await setup();- await threadsRequest(harness, s.owner.token)- .patch(`/guilds/${s.guildId}/channels`)- .body([{id: s.forumId, parent_id: s.categoryId}])- .expect(HTTP_STATUS.NO_CONTENT)- .execute();- const forum = await threadsRequest<ChannelResponse>(harness, s.owner.token).get(`/channels/${s.forumId}`).execute();- expect(forum.parent_id).toBe(s.categoryId);- });-});diff --git a/fluxer_api/src/api/guild/tests/GuildFolderOperations.test.ts b/fluxer_api/src/api/guild/tests/GuildFolderOperations.test.tsdeleted file mode 100644index e1e634bc2..000000000--- a/fluxer_api/src/api/guild/tests/GuildFolderOperations.test.ts+++ /dev/null@@ -1,143 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {createTestAccount} from '@app/api/auth/tests/AuthTestUtils';-import {processRecordedGuildDeletions, recordGuildDeletions} from '@app/api/guild/tests/GuildDeletionTestUtils';-import {acceptInvite, createChannelInvite, createGuild, getChannel} from '@app/api/guild/tests/GuildTestUtils';-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 {UNCATEGORIZED_FOLDER_ID} from '@fluxer/constants/src/UserConstants';-import type {UserSettingsResponse} from '@fluxer/schema/src/domains/user/UserResponseSchemas';-import {afterEach, beforeEach, describe, expect, test} from 'vitest';--describe('Guild Folder Operations', () => {- let harness: ApiTestHarness;- beforeEach(async () => {- harness = await createApiTestHarness();- });- afterEach(async () => {- await harness?.shutdown();- });- test('should remove guild from all folders when leaving', async () => {- const owner = await createTestAccount(harness);- const member = await createTestAccount(harness);- const guild1 = await createGuild(harness, owner.token, 'Guild 1');- const channel1 = await getChannel(harness, owner.token, guild1.system_channel_id!);- const invite1 = await createChannelInvite(harness, owner.token, channel1.id);- const guild2 = await createGuild(harness, owner.token, 'Guild 2');- const channel2 = await getChannel(harness, owner.token, guild2.system_channel_id!);- const invite2 = await createChannelInvite(harness, owner.token, channel2.id);- await acceptInvite(harness, member.token, invite1.code);- await acceptInvite(harness, member.token, invite2.code);- await createBuilder(harness, member.token)- .patch('/users/@me/settings')- .body({- guild_folders: [- {- id: 1,- name: 'My Folder',- guild_ids: [guild1.id],- },- {- id: UNCATEGORIZED_FOLDER_ID,- guild_ids: [guild2.id],- },- ],- })- .expect(HTTP_STATUS.OK)- .executeWithResponse();- await createBuilder(harness, member.token)- .delete(`/users/@me/guilds/${guild1.id}`)- .expect(HTTP_STATUS.NO_CONTENT)- .executeWithResponse();- const {json: settings} = await createBuilder<UserSettingsResponse>(harness, member.token)- .get('/users/@me/settings')- .expect(HTTP_STATUS.OK)- .executeWithResponse();- const customFolder = settings.guild_folders?.find((folder) => folder.id === 1);- expect(customFolder).toBeUndefined();- const uncategorizedFolder = settings.guild_folders?.find((folder) => folder.id === UNCATEGORIZED_FOLDER_ID);- expect(uncategorizedFolder?.guild_ids).toEqual([guild2.id]);- });- test('should remove guild from folders across multiple custom folders', async () => {- const owner = await createTestAccount(harness);- const member = await createTestAccount(harness);- const guild1 = await createGuild(harness, owner.token, 'Guild 1');- const channel1 = await getChannel(harness, owner.token, guild1.system_channel_id!);- const invite1 = await createChannelInvite(harness, owner.token, channel1.id);- const guild2 = await createGuild(harness, owner.token, 'Guild 2');- const channel2 = await getChannel(harness, owner.token, guild2.system_channel_id!);- const invite2 = await createChannelInvite(harness, owner.token, channel2.id);- const guild3 = await createGuild(harness, owner.token, 'Guild 3');- const channel3 = await getChannel(harness, owner.token, guild3.system_channel_id!);- const invite3 = await createChannelInvite(harness, owner.token, channel3.id);- await acceptInvite(harness, member.token, invite1.code);- await acceptInvite(harness, member.token, invite2.code);- await acceptInvite(harness, member.token, invite3.code);- await createBuilder(harness, member.token)- .patch('/users/@me/settings')- .body({- guild_folders: [- {- id: 1,- name: 'Folder 1',- guild_ids: [guild1.id, guild2.id],- },- {- id: 2,- name: 'Folder 2',- guild_ids: [guild3.id],- },- ],- })- .expect(HTTP_STATUS.OK)- .executeWithResponse();- await createBuilder(harness, member.token)- .delete(`/users/@me/guilds/${guild2.id}`)- .expect(HTTP_STATUS.NO_CONTENT)- .executeWithResponse();- const {json: settings} = await createBuilder<UserSettingsResponse>(harness, member.token)- .get('/users/@me/settings')- .expect(HTTP_STATUS.OK)- .executeWithResponse();- const folder1 = settings.guild_folders?.find((folder) => folder.id === 1);- expect(folder1?.guild_ids).toEqual([guild1.id]);- const folder2 = settings.guild_folders?.find((folder) => folder.id === 2);- expect(folder2?.guild_ids).toEqual([guild3.id]);- });- test('should remove guild from all members folders when guild is deleted', async () => {- const owner = await createTestAccount(harness);- const member1 = await createTestAccount(harness);- const member2 = await createTestAccount(harness);- const guild = await createGuild(harness, owner.token, 'Test Guild');- const channel = await getChannel(harness, owner.token, guild.system_channel_id!);- const invite = await createChannelInvite(harness, owner.token, channel.id);- await acceptInvite(harness, member1.token, invite.code);- await acceptInvite(harness, member2.token, invite.code);- const worker = recordGuildDeletions();- await createBuilder(harness, owner.token)- .post(`/guilds/${guild.id}/delete`)- .body({password: owner.password})- .expect(HTTP_STATUS.NO_CONTENT)- .executeWithResponse();- await processRecordedGuildDeletions(worker);- const {json: ownerSettings} = await createBuilder<UserSettingsResponse>(harness, owner.token)- .get('/users/@me/settings')- .expect(HTTP_STATUS.OK)- .executeWithResponse();- const {json: member1Settings} = await createBuilder<UserSettingsResponse>(harness, member1.token)- .get('/users/@me/settings')- .expect(HTTP_STATUS.OK)- .executeWithResponse();- const {json: member2Settings} = await createBuilder<UserSettingsResponse>(harness, member2.token)- .get('/users/@me/settings')- .expect(HTTP_STATUS.OK)- .executeWithResponse();- const ownerUncategorized = ownerSettings.guild_folders?.find((folder) => folder.id === UNCATEGORIZED_FOLDER_ID);- const member1Uncategorized = member1Settings.guild_folders?.find((folder) => folder.id === UNCATEGORIZED_FOLDER_ID);- const member2Uncategorized = member2Settings.guild_folders?.find((folder) => folder.id === UNCATEGORIZED_FOLDER_ID);- expect(ownerUncategorized?.guild_ids ?? []).not.toContain(guild.id);- expect(member1Uncategorized?.guild_ids ?? []).not.toContain(guild.id);- expect(member2Uncategorized?.guild_ids ?? []).not.toContain(guild.id);- });-});diff --git a/fluxer_api/src/api/guild/tests/UserGuildsThreadsActive.test.ts b/fluxer_api/src/api/guild/tests/UserGuildsThreadsActive.test.tsdeleted file mode 100644index 0f221c061..000000000--- a/fluxer_api/src/api/guild/tests/UserGuildsThreadsActive.test.ts+++ /dev/null@@ -1,77 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {createTestAccount, type TestAccount} from '@app/api/auth/tests/AuthTestUtils';-import {clearChannelThreadsTaintCacheForTesting} from '@app/api/experiment/ChannelThreadsGate';-import {acceptInvite, createChannelInvite, createGuild} from '@app/api/guild/tests/GuildTestUtils';-import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';-import {createBuilder} from '@app/api/test/TestRequestBuilder';-import type {GuildResponse} from '@fluxer/schema/src/domains/guild/GuildResponseSchemas';-import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, test, vi} from 'vitest';--const FEATURES = 'X-Fluxer-Features';-const CAPABLE = 'channel_threads';--describe('threads_active on GET /users/@me/guilds', () => {- let harness: ApiTestHarness;-- beforeAll(async () => {- harness = await createApiTestHarness();- });-- beforeEach(async () => {- await harness.reset();- clearChannelThreadsTaintCacheForTesting();- });-- afterEach(() => {- vi.restoreAllMocks();- clearChannelThreadsTaintCacheForTesting();- });-- afterAll(async () => {- await harness?.shutdown();- });-- async function listGuilds(token: string, capable: boolean): Promise<Array<GuildResponse>> {- const builder = createBuilder<Array<GuildResponse>>(harness, token).get('/users/@me/guilds');- return (capable ? builder.header(FEATURES, CAPABLE) : builder).execute();- }-- async function setup(): Promise<{- owner: TestAccount;- member: TestAccount;- enrolled: GuildResponse;- plain: GuildResponse;- ownerBaseline: Array<GuildResponse>;- memberBaseline: Array<GuildResponse>;- }> {- const owner = await createTestAccount(harness);- const member = await createTestAccount(harness);- const enrolled = await createGuild(harness, owner.token, 'Enrolled');- const plain = await createGuild(harness, owner.token, 'Plain');- const invite = await createChannelInvite(harness, owner.token, enrolled.system_channel_id!);- await acceptInvite(harness, member.token, invite.code);- return {- owner,- member,- enrolled,- plain,- ownerBaseline: await listGuilds(owner.token, true),- memberBaseline: await listGuilds(member.token, true),- };- }-- test('flags every guild for a capable viewer and hides the key from incapable clients', async () => {- const {owner, enrolled, plain, ownerBaseline} = await setup();- const guilds = await listGuilds(owner.token, true);- const byId = new Map(guilds.map((guild) => [guild.id, guild]));- const baseline = new Map(ownerBaseline.map((guild) => [guild.id, guild]));- expect(byId.get(enrolled.id)).toEqual({...baseline.get(enrolled.id), threads_active: true});- expect(byId.get(plain.id)).toEqual({...baseline.get(plain.id), threads_active: true});- const incapable = await listGuilds(owner.token, false);- expect(incapable.map(({threads_active: _active, ...rest}) => rest)).toEqual(- ownerBaseline.map(({threads_active: _active, ...rest}) => rest),- );- for (const entry of incapable) expect(entry).not.toHaveProperty('threads_active');- });-});diff --git a/fluxer_api/src/api/invite/tests/InviteGuildMemberLimit.test.ts b/fluxer_api/src/api/invite/tests/InviteGuildMemberLimit.test.tsdeleted file mode 100644index 061c6299a..000000000--- a/fluxer_api/src/api/invite/tests/InviteGuildMemberLimit.test.ts+++ /dev/null@@ -1,102 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {createTestAccount} from '@app/api/auth/tests/AuthTestUtils';-import {createGuild} from '@app/api/channel/tests/ChannelTestUtils';-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 {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';-import {GuildFeatures} from '@fluxer/constants/src/GuildConstants';-import {MAX_GUILD_MEMBERS, MAX_GUILD_MEMBERS_VERY_LARGE_GUILD} from '@fluxer/constants/src/LimitConstants';-import {afterAll, beforeAll, beforeEach, describe, expect, it} from 'vitest';--interface InviteResponse {- code: string;-}--interface InviteAcceptResponse {- guild: {- id: string;- };-}--async function createGuildInvite(harness: ApiTestHarness, token: string, channelId: string): Promise<string> {- const invite = await createBuilder<InviteResponse>(harness, token)- .post(`/channels/${channelId}/invites`)- .body({})- .execute();- return invite.code;-}--async function addGuildFeatureForTesting(harness: ApiTestHarness, guildId: string, feature: string): Promise<void> {- await createBuilder<{- success: boolean;- }>(harness, '')- .post(`/test/guilds/${guildId}/features`)- .body({add_features: [feature]})- .execute();-}--async function setGuildMemberCountForTesting(- harness: ApiTestHarness,- guildId: string,- memberCount: number,-): Promise<void> {- await createBuilder<{- success: boolean;- }>(harness, '')- .post(`/test/guilds/${guildId}/member-count`)- .body({member_count: memberCount})- .execute();-}--describe('Invite guild member limit', () => {- let harness: ApiTestHarness;- beforeAll(async () => {- harness = await createApiTestHarness();- });- afterAll(async () => {- await harness?.shutdown();- });- beforeEach(async () => {- await harness.reset();- });- it('rejects joining when guild reaches the default cap', async () => {- const owner = await createTestAccount(harness);- const joiner = await createTestAccount(harness);- const guild = await createGuild(harness, owner.token, 'Default cap guild');- if (!guild.system_channel_id) {- throw new Error('Guild system channel is missing');- }- const inviteCode = await createGuildInvite(harness, owner.token, guild.system_channel_id);- await setGuildMemberCountForTesting(harness, guild.id, MAX_GUILD_MEMBERS);- await createBuilder(harness, joiner.token)- .post(`/invites/${inviteCode}`)- .body(null)- .expect(HTTP_STATUS.BAD_REQUEST, APIErrorCodes.MAX_GUILD_MEMBERS)- .execute();- });- it('raises guild member cap to 10000 when VERY_LARGE_GUILD is enabled', async () => {- const owner = await createTestAccount(harness);- const firstJoiner = await createTestAccount(harness);- const secondJoiner = await createTestAccount(harness);- const guild = await createGuild(harness, owner.token, 'Very large guild');- if (!guild.system_channel_id) {- throw new Error('Guild system channel is missing');- }- const inviteCode = await createGuildInvite(harness, owner.token, guild.system_channel_id);- await addGuildFeatureForTesting(harness, guild.id, GuildFeatures.VERY_LARGE_GUILD);- await setGuildMemberCountForTesting(harness, guild.id, MAX_GUILD_MEMBERS);- const accepted = await createBuilder<InviteAcceptResponse>(harness, firstJoiner.token)- .post(`/invites/${inviteCode}`)- .body(null)- .execute();- expect(accepted.guild.id).toBe(guild.id);- await setGuildMemberCountForTesting(harness, guild.id, MAX_GUILD_MEMBERS_VERY_LARGE_GUILD);- await createBuilder(harness, secondJoiner.token)- .post(`/invites/${inviteCode}`)- .body(null)- .expect(HTTP_STATUS.BAD_REQUEST, APIErrorCodes.MAX_GUILD_MEMBERS)- .execute();- });-});diff --git a/fluxer_api/src/api/read_state/ClearChannelReadState.test.ts b/fluxer_api/src/api/read_state/ClearChannelReadState.test.tsdeleted file mode 100644index 7d23645f5..000000000--- a/fluxer_api/src/api/read_state/ClearChannelReadState.test.ts+++ /dev/null@@ -1,48 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {createTestAccount} from '@app/api/auth/tests/AuthTestUtils';-import {createChannel, createGuild} from '@app/api/guild/tests/GuildTestUtils';-import {sendMessage} 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 {afterEach, beforeEach, describe, expect, test} from 'vitest';--interface AckResponse {- read_states: Array<{- id: string;- last_message_id: string | null;- }>;-}--describe('DELETE /channels/:channel_id/messages/ack', () => {- let harness: ApiTestHarness;- beforeEach(async () => {- harness = await createApiTestHarness();- });- afterEach(async () => {- await harness?.shutdown();- });- test('leaves the read state untouched', async () => {- const account = await createTestAccount(harness);- const guild = await createGuild(harness, account.token, 'Read State Guild');- const channel = await createChannel(harness, account.token, guild.id, 'read-state-channel');- const older = await sendMessage(harness, account.token, channel.id, 'older');- const newer = await sendMessage(harness, account.token, channel.id, 'newer');- await createBuilder<AckResponse>(harness, account.token)- .post('/read-states/ack')- .body({read_states: [{channel_id: channel.id, message_id: newer.id}]})- .expect(HTTP_STATUS.OK)- .execute();- await createBuilder(harness, account.token)- .delete(`/channels/${channel.id}/messages/ack`)- .expect(HTTP_STATUS.NO_CONTENT)- .execute();- const response = await createBuilder<AckResponse>(harness, account.token)- .post('/read-states/ack')- .body({read_states: [{channel_id: channel.id, message_id: older.id}]})- .expect(HTTP_STATUS.OK)- .execute();- expect(response.read_states[0]?.last_message_id).toBe(newer.id);- });-});diff --git a/fluxer_api/src/api/read_state/ReadStateService.test.ts b/fluxer_api/src/api/read_state/ReadStateService.test.tsdeleted file mode 100644index cd4ae4a05..000000000--- a/fluxer_api/src/api/read_state/ReadStateService.test.ts+++ /dev/null@@ -1,228 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {- type ChannelID,- createChannelID,- createMessageID,- createUserID,- type MessageID,- type UserID,-} from '@app/api/BrandedTypes';-import type {IGatewayService} from '@app/api/infrastructure/IGatewayService';-import {ReadState} from '@app/api/models/ReadState';-import type {ReadStateRepository} from '@app/api/read_state/ReadStateRepository';-import {ReadStateService} from '@app/api/read_state/ReadStateService';-import {BadGatewayError} from '@fluxer/errors/src/domains/core/BadGatewayError';-import {describe, expect, it, vi} from 'vitest';--const USER_ID = createUserID(20n);-const CHANNEL_ID = createChannelID(21n);-const MESSAGE_ID = createMessageID(22n);--function makeReadState(channelId: ChannelID, messageId: MessageID, mentionCount = 0): ReadState {- return new ReadState({- user_id: USER_ID,- channel_id: channelId,- message_id: messageId,- mention_count: mentionCount,- last_pin_timestamp: null,- version: 5n,- });-}--describe('ReadStateService gateway side effects after the write', () => {- it('returns the committed read state when clearing push notifications fails', async () => {- const stored: Array<{channelId: ChannelID; messageId: MessageID}> = [];- const repository = {- upsertReadState: vi.fn(async (_userId: UserID, channelId: ChannelID, messageId: MessageID) => {- stored.push({channelId, messageId});- return {readState: makeReadState(channelId, messageId), previous: null};- }),- } as unknown as ReadStateRepository;- const gatewayService = {- clearPushChannelNotifications: vi.fn().mockRejectedValue(new BadGatewayError()),- dispatchPresence: vi.fn().mockResolvedValue(undefined),- } as unknown as IGatewayService;- const service = new ReadStateService(repository, gatewayService);-- const readState = await service.ackMessage({- userId: USER_ID,- channelId: CHANNEL_ID,- messageId: MESSAGE_ID,- mentionCount: 0,- });-- expect(readState.channelId).toBe(CHANNEL_ID);- expect(readState.lastMessageId).toBe(MESSAGE_ID);- expect(stored).toEqual([{channelId: CHANNEL_ID, messageId: MESSAGE_ID}]);- expect(gatewayService.dispatchPresence).toHaveBeenCalledTimes(1);- });-- it('acknowledges the message when the MESSAGE_ACK dispatch fails', async () => {- const repository = {- upsertReadState: vi.fn(async (_userId: UserID, channelId: ChannelID, messageId: MessageID) => ({- readState: makeReadState(channelId, messageId),- previous: null,- })),- } as unknown as ReadStateRepository;- const gatewayService = {- clearPushChannelNotifications: vi.fn().mockResolvedValue(undefined),- dispatchPresence: vi.fn().mockRejectedValue(new BadGatewayError()),- } as unknown as IGatewayService;- const service = new ReadStateService(repository, gatewayService);-- const readState = await service.ackMessage({- userId: USER_ID,- channelId: CHANNEL_ID,- messageId: MESSAGE_ID,- mentionCount: 0,- });-- expect(readState.lastMessageId).toBe(MESSAGE_ID);- });-- it('returns every entry of the entry-by-entry path when the dispatch fails', async () => {- const stored: Array<string> = [];- const repository = {- upsertReadState: vi.fn(async (_userId: UserID, channelId: ChannelID, messageId: MessageID) => {- stored.push(channelId.toString());- return {readState: makeReadState(channelId, messageId, 1), previous: null};- }),- } as unknown as ReadStateRepository;- const gatewayService = {- clearPushChannelNotifications: vi.fn().mockResolvedValue(undefined),- dispatchPresence: vi.fn().mockRejectedValue(new BadGatewayError()),- } as unknown as IGatewayService;- const service = new ReadStateService(repository, gatewayService);-- const readStates = await service.ackReadStates({- userId: USER_ID,- readStates: [- {channelId: CHANNEL_ID, messageId: MESSAGE_ID, manual: true},- {channelId: createChannelID(23n), messageId: createMessageID(24n), manual: true},- ],- });-- expect(readStates.map((readState) => readState.channelId.toString())).toEqual(['21', '23']);- expect(stored).toEqual(['21', '23']);- });-- it('returns the bulk acknowledged states when clearing push notifications fails', async () => {- const updated = [makeReadState(CHANNEL_ID, MESSAGE_ID)];- const repository = {- bulkAckMessages: vi.fn().mockResolvedValue(updated),- } as unknown as ReadStateRepository;- const gatewayService = {- clearPushChannelNotifications: vi.fn().mockRejectedValue(new BadGatewayError()),- dispatchPresence: vi.fn().mockResolvedValue(undefined),- } as unknown as IGatewayService;- const service = new ReadStateService(repository, gatewayService);-- const readStates = await service.bulkAckMessages({- userId: USER_ID,- readStates: [{channelId: CHANNEL_ID, messageId: MESSAGE_ID}],- });-- expect(readStates).toBe(updated);- });-});--describe('ReadStateService implicit acknowledgements', () => {- async function implicitAck(params: {- previous: ReadState | null;- messageId: MessageID;- unreadThrough: MessageID | null;- }): Promise<Array<MessageID>> {- const repository = {- upsertReadState: vi.fn(async (_userId: UserID, channelId: ChannelID, messageId: MessageID) => ({- readState: makeReadState(channelId, messageId),- previous: params.previous,- })),- } as unknown as ReadStateRepository;- const clearPushChannelNotifications = vi.fn().mockResolvedValue(undefined);- const gatewayService = {- clearPushChannelNotifications,- dispatchPresence: vi.fn().mockResolvedValue(undefined),- } as unknown as IGatewayService;- await new ReadStateService(repository, gatewayService).ackMessage({- userId: USER_ID,- channelId: CHANNEL_ID,- messageId: params.messageId,- mentionCount: 0,- implicit: {unreadThrough: params.unreadThrough},- emitGateway: false,- });- return clearPushChannelNotifications.mock.calls.map(([call]) => call.messageId);- }-- it('clears when the previous read state lagged the latest earlier message', async () => {- const cleared = await implicitAck({- previous: makeReadState(CHANNEL_ID, createMessageID(30n)),- messageId: createMessageID(40n),- unreadThrough: createMessageID(35n),- });- expect(cleared).toEqual([createMessageID(40n)]);- });-- it('does not clear when the previous read state already covered the latest earlier message', async () => {- const cleared = await implicitAck({- previous: makeReadState(CHANNEL_ID, createMessageID(35n)),- messageId: createMessageID(40n),- unreadThrough: createMessageID(35n),- });- expect(cleared).toEqual([]);- });-- it('clears when unread mentions remained', async () => {- const cleared = await implicitAck({- previous: makeReadState(CHANNEL_ID, createMessageID(35n), 2),- messageId: createMessageID(40n),- unreadThrough: createMessageID(35n),- });- expect(cleared).toEqual([createMessageID(40n)]);- });-- it('does not clear when the read state was already past the acknowledged message', async () => {- const cleared = await implicitAck({- previous: makeReadState(CHANNEL_ID, createMessageID(50n), 2),- messageId: createMessageID(40n),- unreadThrough: createMessageID(40n),- });- expect(cleared).toEqual([]);- });-- it('clears when there was no read state and the channel had earlier messages', async () => {- const cleared = await implicitAck({- previous: null,- messageId: createMessageID(40n),- unreadThrough: createMessageID(35n),- });- expect(cleared).toEqual([createMessageID(40n)]);- });-- it('does not clear when there was no read state and no earlier message', async () => {- const cleared = await implicitAck({previous: null, messageId: createMessageID(40n), unreadThrough: null});- expect(cleared).toEqual([]);- });-- it('does not wait for the push clear to finish', async () => {- const repository = {- upsertReadState: vi.fn(async (_userId: UserID, channelId: ChannelID, messageId: MessageID) => ({- readState: makeReadState(channelId, messageId),- previous: makeReadState(channelId, createMessageID(30n), 1),- })),- } as unknown as ReadStateRepository;- const clearPushChannelNotifications = vi.fn(() => new Promise<void>(() => {}));- const gatewayService = {clearPushChannelNotifications} as unknown as IGatewayService;- const readState = await new ReadStateService(repository, gatewayService).ackMessage({- userId: USER_ID,- channelId: CHANNEL_ID,- messageId: createMessageID(40n),- mentionCount: 0,- implicit: {unreadThrough: createMessageID(35n)},- emitGateway: false,- });- expect(readState.lastMessageId).toBe(createMessageID(40n));- expect(clearPushChannelNotifications).toHaveBeenCalledTimes(1);- });-});diff --git a/fluxer_api/src/api/rpc/tests/RpcGuildThreadSeedTrigger.test.ts b/fluxer_api/src/api/rpc/tests/RpcGuildThreadSeedTrigger.test.tsdeleted file mode 100644index 83116526d..000000000--- a/fluxer_api/src/api/rpc/tests/RpcGuildThreadSeedTrigger.test.ts+++ /dev/null@@ -1,99 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {createTestAccount} from '@app/api/auth/tests/AuthTestUtils';-import {createChannelID, createGuildID} from '@app/api/BrandedTypes';-import {deleteOneOrMany, fetchOne} from '@app/api/database/CassandraQueryExecution';-import type {GuildThreadStateRow} from '@app/api/database/types/ThreadTypes';-import {clearChannelThreadsTaintCacheForTesting} from '@app/api/experiment/ChannelThreadsGate';-import {GuildRepository} from '@app/api/guild/repositories/GuildRepository';-import {createGuild} from '@app/api/guild/tests/GuildTestUtils';-import {getWorkerService} from '@app/api/middleware/ServiceRegistry';-import {getChannelRepository} from '@app/api/middleware/ServiceSingletons';-import {GuildThreadState} from '@app/api/Tables';-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 {ChannelTypes} from '@fluxer/constants/src/ChannelConstants';-import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, test, vi} from 'vitest';--const FETCH_MARKER = GuildThreadState.selectCql({where: GuildThreadState.where.eq('guild_id'), limit: 1});--describe('RpcService guild load thread permission seeding', () => {- let harness: ApiTestHarness;-- beforeAll(async () => {- harness = await createApiTestHarness();- });-- beforeEach(async () => {- await harness.reset();- clearChannelThreadsTaintCacheForTesting();- });-- afterEach(() => {- vi.restoreAllMocks();- clearChannelThreadsTaintCacheForTesting();- });-- afterAll(async () => {- await harness?.shutdown();- });-- const loadCollection = (guildId: string, collection: 'guild' | 'channels') =>- createBuilder(harness, '')- .post('/test/rpc-session-init')- .body({type: 'guild_collection', guild_id: guildId, collection})- .expect(HTTP_STATUS.OK)- .execute();- const loadGuild = (guildId: string) => loadCollection(guildId, 'guild');- test('marks and seeds a guild on its first load and skips later seeded loads', async () => {- const owner = await createTestAccount(harness);- const guild = await createGuild(harness, owner.token, 'Bucketed');- const guildId = createGuildID(BigInt(guild.id));- await deleteOneOrMany(GuildThreadState.deleteByPk({guild_id: guildId}));- clearChannelThreadsTaintCacheForTesting();- const addJob = vi.spyOn(getWorkerService(), 'addJob');-- await loadGuild(guild.id);- const marker = await fetchOne<GuildThreadStateRow>(FETCH_MARKER, {guild_id: guildId});- expect(marker?.first_active_at).toBeInstanceOf(Date);- expect(marker?.perms_seeded_at).toBeNull();- expect(addJob).toHaveBeenCalledWith(- 'seedThreadPermissions',- {guildId: guild.id},- {jobKey: `seed-thread-permissions-${guild.id}`},- );-- await getChannelRepository().threads.markGuildPermsSeeded(guildId, new Date());- addJob.mockClear();- await loadGuild(guild.id);- await loadGuild(guild.id);- expect(addJob).not.toHaveBeenCalled();- });- test('channel loads preserve existing references and clear dangling references', async () => {- const owner = await createTestAccount(harness);- const guild = await createGuild(harness, owner.token, 'Retired');- const guildId = createGuildID(BigInt(guild.id));- const channelRepository = getChannelRepository();- const source = (await channelRepository.channelData.findUnique(createChannelID(BigInt(guild.system_channel_id!))))!;- const forumId = createChannelID(BigInt(source.id) + 1n);- await channelRepository.channelData.upsert({- ...source.toRow(),- channel_id: forumId,- type: ChannelTypes.GUILD_FORUM,- name: 'f',- });- const guildRepository = new GuildRepository();- const stored = (await guildRepository.findUnique(guildId))!;- const missingId = createChannelID(BigInt(source.id) + 2n);- await guildRepository.upsertPartial(- guildId,- {system_channel_id: forumId, rules_channel_id: missingId},- stored.toRow(),- );- await loadCollection(guild.id, 'channels');- const repaired = (await guildRepository.findUnique(guildId))!;- expect(repaired.systemChannelId).toBe(forumId);- expect(repaired.rulesChannelId).toBeNull();- });-});diff --git a/fluxer_api/src/api/rpc/tests/RpcSessionGeoipCountry.test.ts b/fluxer_api/src/api/rpc/tests/RpcSessionGeoipCountry.test.tsdeleted file mode 100644index 87454601c..000000000--- a/fluxer_api/src/api/rpc/tests/RpcSessionGeoipCountry.test.ts+++ /dev/null@@ -1,35 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {createTestAccount} from '@app/api/auth/tests/AuthTestUtils';-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 {afterEach, beforeEach, describe, expect, test} from 'vitest';--interface RpcSessionResponse {- type: 'session';- data: {- country_code: string;- geoip_country_code: string | null;- };-}--describe('RpcService session geoip country', () => {- let harness: ApiTestHarness;- beforeEach(async () => {- harness = await createApiTestHarness();- });- afterEach(async () => {- await harness?.shutdown();- });- test('reports an unknown country as null without the country_code default', async () => {- const account = await createTestAccount(harness);- const response = await createBuilder<RpcSessionResponse>(harness, '')- .post('/test/rpc-session-init')- .body({type: 'session', token: account.token, version: 1, ip: '127.0.0.1'})- .expect(HTTP_STATUS.OK)- .execute();- expect(response.data.geoip_country_code).toBeNull();- expect(response.data.country_code).toBe('US');- });-});diff --git a/fluxer_api/src/api/rpc/tests/RpcSessionPaymentReconciliation.test.ts b/fluxer_api/src/api/rpc/tests/RpcSessionPaymentReconciliation.test.tsdeleted file mode 100644index 932d0aa4a..000000000--- a/fluxer_api/src/api/rpc/tests/RpcSessionPaymentReconciliation.test.ts+++ /dev/null@@ -1,37 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {createTestUserWithPremium} from '@app/api/stripe/tests/StripeWebhookTestUtils';-import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';-import {NoopWorkerService} from '@app/api/test/NoopWorkerService';-import {HTTP_STATUS} from '@app/api/test/TestConstants';-import {createBuilder} from '@app/api/test/TestRequestBuilder';-import {UserPremiumTypes} from '@fluxer/constants/src/UserConstants';-import {afterEach, beforeEach, describe, expect, test, vi} from 'vitest';--describe('RpcService session payment reconciliation', () => {- let harness: ApiTestHarness;- beforeEach(async () => {- harness = await createApiTestHarness();- });- afterEach(async () => {- await harness?.shutdown();- });- test('queues payment reconciliation without a job record', async () => {- const account = await createTestUserWithPremium(harness, UserPremiumTypes.SUBSCRIPTION, {- stripeCustomerId: 'cus_rpc_session_reconcile',- });- const addJob = vi.spyOn(NoopWorkerService.prototype, 'addJob');- try {- await createBuilder(harness, '')- .post('/test/rpc-session-init')- .body({type: 'session', token: account.token, version: 1, ip: '127.0.0.1'})- .expect(HTTP_STATUS.OK)- .execute();- await vi.waitFor(() =>- expect(addJob).toHaveBeenCalledWith('reconcileUserPayments', {userId: account.userId}, {skipLedger: true}),- );- } finally {- addJob.mockRestore();- }- });-});diff --git a/fluxer_api/src/api/search/tests/GuildSearchThreadScope.test.ts b/fluxer_api/src/api/search/tests/GuildSearchThreadScope.test.tsdeleted file mode 100644index 513f57914..000000000--- a/fluxer_api/src/api/search/tests/GuildSearchThreadScope.test.ts+++ /dev/null@@ -1,84 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {createTestAccount, type TestAccount} from '@app/api/auth/tests/AuthTestUtils';-import {createChannel, createGuild} from '@app/api/channel/tests/ChannelTestUtils';-import {threadsRequest} from '@app/api/channel/tests/ThreadTestUtils';-import {clearChannelThreadsTaintCacheForTesting} from '@app/api/experiment/ChannelThreadsGate';-import {ensureSessionStarted, markGuildChannelsAsIndexed} from '@app/api/message/tests/MessageTestUtils';-import {getWorkerService} from '@app/api/middleware/ServiceRegistry';-import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';-import {ChannelTypes} from '@fluxer/constants/src/ChannelConstants';-import type {ThreadChannelResponse} from '@fluxer/schema/src/domains/channel/ThreadRequestSchemas';-import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi} from 'vitest';--vi.mock('@fluxer/constants/src/ThreadConstants', async (importOriginal) => ({- ...(await importOriginal<typeof import('@fluxer/constants/src/ThreadConstants')>()),- SEARCH_INDEX_ENQUEUE_MAX: 1,-}));--describe('guild search thread scope', () => {- let harness: ApiTestHarness;-- beforeAll(async () => {- harness = await createApiTestHarness({search: 'enabled'});- });-- beforeEach(async () => {- await harness.reset();- clearChannelThreadsTaintCacheForTesting();- });-- afterEach(() => {- vi.restoreAllMocks();- });-- afterAll(async () => {- clearChannelThreadsTaintCacheForTesting();- await harness.shutdown();- });-- async function setup() {- const owner = await createTestAccount(harness);- await ensureSessionStarted(harness, owner.token);- const guild = await createGuild(harness, owner.token, 'search');- const first = await createChannel(harness, owner.token, guild.id, 'first');- await createChannel(harness, owner.token, guild.id, 'second');- return {owner, guildId: guild.id, channelId: first.id};- }-- function search(account: TestAccount, body: Record<string, unknown>) {- return threadsRequest<{indexing?: boolean}>(harness, account.token)- .post('/search/messages')- .body({content: 'needle', ...body})- .expect(200)- .execute();- }-- function spyIndexJobs() {- const addJob = vi.spyOn(getWorkerService(), 'addJob');- return () => addJob.mock.calls.filter(([task]) => task === 'indexChannelMessages');- }-- it('caps index enqueues per search in an active guild', async () => {- const s = await setup();- const indexJobs = spyIndexJobs();- expect(await search(s.owner, {context_guild_id: s.guildId})).toEqual({indexing: true});- expect(indexJobs()).toHaveLength(1);- });-- it('never reports indexing for threads', async () => {- const s = await setup();- await markGuildChannelsAsIndexed(harness, s.owner.token, s.guildId);- const thread = await threadsRequest<ThreadChannelResponse>(harness, s.owner.token)- .post(`/channels/${s.channelId}/threads`)- .body({name: 'topic', type: ChannelTypes.PUBLIC_THREAD})- .expect(201)- .execute();- const indexJobs = spyIndexJobs();- expect(await search(s.owner, {context_guild_id: s.guildId})).not.toHaveProperty('indexing');- expect(await search(s.owner, {context_guild_id: s.guildId, channel_ids: [thread.id]})).not.toHaveProperty(- 'indexing',- );- expect(indexJobs()).toHaveLength(0);- });-});diff --git a/fluxer_api/src/api/search/tests/ThreadSearchScopeCap.test.ts b/fluxer_api/src/api/search/tests/ThreadSearchScopeCap.test.tsdeleted file mode 100644index a6beac093..000000000--- a/fluxer_api/src/api/search/tests/ThreadSearchScopeCap.test.ts+++ /dev/null@@ -1,144 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {createTestAccount} from '@app/api/auth/tests/AuthTestUtils';-import {createChannel, createGuild} from '@app/api/channel/tests/ChannelTestUtils';-import {threadsRequest} from '@app/api/channel/tests/ThreadTestUtils';-import {clearChannelThreadsTaintCacheForTesting} from '@app/api/experiment/ChannelThreadsGate';-import {ensureSessionStarted, markGuildChannelsAsIndexed, sendMessage} from '@app/api/message/tests/MessageTestUtils';-import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';-import {TEST_TIMEOUTS, wait} from '@app/api/test/TestConstants';-import {ChannelTypes} from '@fluxer/constants/src/ChannelConstants';-import type {ThreadChannelResponse} from '@fluxer/schema/src/domains/channel/ThreadRequestSchemas';-import {afterAll, beforeAll, beforeEach, describe, expect, it, vi} from 'vitest';--vi.mock('@fluxer/constants/src/ThreadConstants', async (importOriginal) => ({- ...(await importOriginal<typeof import('@fluxer/constants/src/ThreadConstants')>()),- THREAD_SCOPE_MAX: 1,-}));--interface SearchResult {- messages: Array<{channel_id: string}>;-}--describe('thread search scope cap', () => {- let harness: ApiTestHarness;-- beforeAll(async () => {- harness = await createApiTestHarness({search: 'enabled'});- });-- beforeEach(async () => {- await harness.reset();- clearChannelThreadsTaintCacheForTesting();- });-- afterAll(async () => {- clearChannelThreadsTaintCacheForTesting();- await harness.shutdown();- });-- it('caps the thread scope across every guild of a global search', async () => {- const owner = await createTestAccount(harness);- await ensureSessionStarted(harness, owner.token);- const channelIds = new Set<string>();- const threadIds = new Set<string>();- for (const name of ['first', 'second']) {- const guild = await createGuild(harness, owner.token, name);- const channel = await createChannel(harness, owner.token, guild.id, 'general');- await markGuildChannelsAsIndexed(harness, owner.token, guild.id);- const thread = await threadsRequest<ThreadChannelResponse>(harness, owner.token)- .post(`/channels/${channel.id}/threads`)- .body({name: 'topic', type: ChannelTypes.PUBLIC_THREAD})- .expect(201)- .execute();- await sendMessage(harness, owner.token, channel.id, 'needle channel');- await threadsRequest(harness, owner.token)- .post(`/channels/${thread.id}/messages`)- .body({content: 'needle thread'})- .execute();- channelIds.add(channel.id);- threadIds.add(thread.id);- }- let result: SearchResult = {messages: []};- for (let attempt = 0; attempt < 20; attempt++) {- result = await threadsRequest<SearchResult>(harness, owner.token)- .post('/search/messages')- .body({content: 'needle', scope: 'all_guilds'})- .expect(200)- .execute();- if (result.messages.length >= 3) break;- await wait(TEST_TIMEOUTS.QUICK);- }- const searched = new Set(result.messages.map((message) => message.channel_id));- expect([...channelIds].every((id) => searched.has(id))).toBe(true);- expect([...threadIds].filter((id) => searched.has(id))).toEqual([[...threadIds][1]]);- });-- it('keeps the newest thread of the guild when the cap drops older ones in earlier channels', async () => {- const owner = await createTestAccount(harness);- await ensureSessionStarted(harness, owner.token);- const guild = await createGuild(harness, owner.token, 'spread');- const first = await createChannel(harness, owner.token, guild.id, 'first');- const second = await createChannel(harness, owner.token, guild.id, 'second');- await markGuildChannelsAsIndexed(harness, owner.token, guild.id);- const threadIds: Array<string> = [];- for (const channel of [first, second]) {- const thread = await threadsRequest<ThreadChannelResponse>(harness, owner.token)- .post(`/channels/${channel.id}/threads`)- .body({name: 'topic', type: ChannelTypes.PUBLIC_THREAD})- .expect(201)- .execute();- await threadsRequest(harness, owner.token)- .post(`/channels/${thread.id}/messages`)- .body({content: 'needle thread'})- .execute();- threadIds.push(thread.id);- }- let result: SearchResult = {messages: []};- for (let attempt = 0; attempt < 20; attempt++) {- result = await threadsRequest<SearchResult>(harness, owner.token)- .post('/search/messages')- .body({content: 'needle', context_guild_id: guild.id})- .expect(200)- .execute();- if (result.messages.length >= 1) break;- await wait(TEST_TIMEOUTS.QUICK);- }- expect(result.messages.map((message) => message.channel_id)).toEqual([threadIds[1]]);- });-- it.each([- ['guild', (guildId: string) => ({context_guild_id: guildId})],- ['all_guilds', () => ({scope: 'all_guilds'})],- ['all', () => ({scope: 'all'})],- ] as const)('searches an explicitly named older thread past the scope cap in %s search', async (_scope, body) => {- const owner = await createTestAccount(harness);- await ensureSessionStarted(harness, owner.token);- const guild = await createGuild(harness, owner.token, 'capped');- const channel = await createChannel(harness, owner.token, guild.id, 'general');- await markGuildChannelsAsIndexed(harness, owner.token, guild.id);- const startThread = (type: number) =>- threadsRequest<ThreadChannelResponse>(harness, owner.token)- .post(`/channels/${channel.id}/threads`)- .body({name: 'topic', type})- .expect(201)- .execute();- const older = await startThread(ChannelTypes.PRIVATE_THREAD);- await startThread(ChannelTypes.PUBLIC_THREAD);- await threadsRequest(harness, owner.token)- .post(`/channels/${older.id}/messages`)- .body({content: 'needle older'})- .execute();- let result: SearchResult = {messages: []};- for (let attempt = 0; attempt < 20; attempt++) {- result = await threadsRequest<SearchResult>(harness, owner.token)- .post('/search/messages')- .body({content: 'needle', ...body(guild.id), channel_ids: [older.id]})- .expect(200)- .execute();- if (result.messages.length >= 1) break;- await wait(TEST_TIMEOUTS.QUICK);- }- expect(result.messages.map((message) => message.channel_id)).toEqual([older.id]);- });-});diff --git a/fluxer_api/src/api/unfurl/tests/UnfurlController.test.ts b/fluxer_api/src/api/unfurl/tests/UnfurlController.test.tsdeleted file mode 100644index 42ce8c7c6..000000000--- a/fluxer_api/src/api/unfurl/tests/UnfurlController.test.ts+++ /dev/null@@ -1,23 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {setInjectedUnfurlerService} from '@app/api/middleware/ServiceSingletons';-import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';-import {createBuilderWithoutAuth} from '@app/api/test/TestRequestBuilder';-import {afterEach, beforeEach, describe, it} from 'vitest';--describe('UnfurlController', () => {- let harness: ApiTestHarness;-- beforeEach(async () => {- harness = await createApiTestHarness();- });-- afterEach(async () => {- setInjectedUnfurlerService(undefined);- await harness.shutdown();- });-- it('requires authentication', async () => {- await createBuilderWithoutAuth(harness).post('/unfurl').body({url: 'https://example.com'}).expect(401).execute();- });-});diff --git a/fluxer_api/src/api/user/repositories/PushSubscriptionRepository.test.ts b/fluxer_api/src/api/user/repositories/PushSubscriptionRepository.test.tsdeleted file mode 100644index e13f60ed2..000000000--- a/fluxer_api/src/api/user/repositories/PushSubscriptionRepository.test.ts+++ /dev/null@@ -1,64 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {createUserID} from '@app/api/BrandedTypes';-import {setCassandraQueryExecutorForTesting} from '@app/api/database/CassandraQueryExecution';-import type {PreparedQuery} from '@app/api/database/CassandraTypes';-import type {PushSubscriptionRow} from '@app/api/database/types/UserTypes';-import {InMemoryCassandraQueryExecutor} from '@app/api/test/InMemoryCassandraQueryExecutor';-import {PushSubscriptionRepository} from '@app/api/user/repositories/PushSubscriptionRepository';-import {afterEach, beforeEach, describe, expect, it} from 'vitest';--const USER_ID = createUserID(1000000000000000000n);--class CountingExecutor extends InMemoryCassandraQueryExecutor {- selects = 0;-- override async executeQuery<T>(query: PreparedQuery): Promise<Array<T>> {- if (/^\s*SELECT/i.test(query.cql)) this.selects++;- return super.executeQuery<T>(query);- }-}--let executor: CountingExecutor;--function row(threadChannels?: boolean): PushSubscriptionRow {- return {- user_id: USER_ID,- subscription_id: 'device',- auth_session_id_hash: null,- endpoint: 'fcm:token',- p256dh_key: null,- auth_key: null,- user_agent: null,- platform: 'android_fcm',- app_id: null,- provider_environment: null,- ...(threadChannels === undefined ? {} : {thread_channels: threadChannels}),- };-}--async function storedCapability(repository: PushSubscriptionRepository) {- const [subscription] = await repository.listPushSubscriptions(USER_ID);- return subscription?.threadChannels;-}--describe('PushSubscriptionRepository.createPushSubscription', () => {- beforeEach(() => {- executor = new CountingExecutor();- setCassandraQueryExecutorForTesting(executor);- });- afterEach(() => {- executor.reset();- setCassandraQueryExecutorForTesting(null);- });-- it('does no read when registration explicitly advertises its capability', async () => {- const repository = new PushSubscriptionRepository();- await repository.createPushSubscription(row(true));- expect(executor.selects).toBe(0);- executor.selects = 0;- await repository.createPushSubscription(row(false));- expect(executor.selects).toBe(0);- expect(await storedCapability(repository)).toBe(false);- });-});diff --git a/fluxer_api/src/api/user/repositories/SavedMessageRepository.test.ts b/fluxer_api/src/api/user/repositories/SavedMessageRepository.test.tsdeleted file mode 100644index 75b0b8f88..000000000--- a/fluxer_api/src/api/user/repositories/SavedMessageRepository.test.ts+++ /dev/null@@ -1,56 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {createChannelID, createMessageID, createUserID, type UserID} from '@app/api/BrandedTypes';-import {setCassandraQueryExecutorForTesting} from '@app/api/database/CassandraQueryExecution';-import {InMemoryCassandraQueryExecutor} from '@app/api/test/InMemoryCassandraQueryExecutor';-import {SavedMessageRepository} from '@app/api/user/repositories/SavedMessageRepository';-import {afterEach, beforeEach, describe, expect, it} from 'vitest';--const CHANNEL_ID = createChannelID(10n);--let executor: InMemoryCassandraQueryExecutor;--async function seedSavedMessages(repository: SavedMessageRepository, userId: UserID, count: number) {- for (let index = 0; index < count; index++) {- await repository.createSavedMessage(userId, CHANNEL_ID, createMessageID(BigInt(1000 + index)));- }-}--describe('SavedMessageRepository.countSavedMessages', () => {- beforeEach(() => {- executor = new InMemoryCassandraQueryExecutor();- setCassandraQueryExecutorForTesting(executor);- });- afterEach(() => {- executor.reset();- setCassandraQueryExecutorForTesting(null);- });-- it('returns zero when the user has saved nothing', async () => {- const repository = new SavedMessageRepository();- expect(await repository.countSavedMessages(createUserID(1n))).toBe(0);- });-- it('counts past the ceiling a listing page can report', async () => {- const repository = new SavedMessageRepository();- const userId = createUserID(1n);- await seedSavedMessages(repository, userId, 1200);- expect(await repository.listSavedMessages(userId, 1000)).toHaveLength(1000);- expect(await repository.countSavedMessages(userId)).toBe(1200);- });-- it('follows creates and deletes and stays scoped to one user', async () => {- const repository = new SavedMessageRepository();- const userId = createUserID(1n);- const otherUserId = createUserID(2n);- await seedSavedMessages(repository, userId, 3);- await seedSavedMessages(repository, otherUserId, 7);- expect(await repository.countSavedMessages(userId)).toBe(3);- await repository.deleteSavedMessage(userId, createMessageID(1001n));- expect(await repository.countSavedMessages(userId)).toBe(2);- expect(await repository.countSavedMessages(otherUserId)).toBe(7);- await repository.deleteAllSavedMessages(userId);- expect(await repository.countSavedMessages(userId)).toBe(0);- expect(await repository.countSavedMessages(otherUserId)).toBe(7);- });-});diff --git a/fluxer_api/src/api/user/tests/HarvestRetryClearsFailure.test.ts b/fluxer_api/src/api/user/tests/HarvestRetryClearsFailure.test.tsdeleted file mode 100644index 5f3b5a12c..000000000--- a/fluxer_api/src/api/user/tests/HarvestRetryClearsFailure.test.ts+++ /dev/null@@ -1,48 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {createTestAccount} from '@app/api/auth/tests/AuthTestUtils';-import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';-import {- expectHarvestDownloadFailsWithError,- fetchHarvestDownload,- findHarvest,- markHarvestCompleted,- markHarvestFailed,- markHarvestStarted,- requestHarvest,-} from '@app/api/user/tests/HarvestTestUtils';-import {beforeEach, describe, expect, test} from 'vitest';--describe('Harvest Retry Clears Failure', () => {- let harness: ApiTestHarness;- beforeEach(async () => {- harness = await createApiTestHarness();- });- test('a retry clears the previous failure and a completed retry reports completed', async () => {- const account = await createTestAccount(harness);- const {harvest_id} = await requestHarvest(harness, account.token);- await markHarvestFailed(account.userId, harvest_id, 'harvest exploded');- const failed = await findHarvest(account.userId, harvest_id);- expect(failed?.getStatus()).toBe('failed');- expect(failed?.errorMessage).toBe('harvest exploded');- await markHarvestStarted(account.userId, harvest_id);- const retrying = await findHarvest(account.userId, harvest_id);- expect(retrying?.getStatus()).toBe('processing');- expect(retrying?.failedAt).toBeNull();- expect(retrying?.errorMessage).toBeNull();- const validTime = new Date(Date.now() + 6 * 24 * 60 * 60 * 1000);- await markHarvestCompleted(account.userId, harvest_id, validTime);- const completed = await findHarvest(account.userId, harvest_id);- expect(completed?.getStatus()).toBe('completed');- expect(completed?.failedAt).toBeNull();- expect(completed?.errorMessage).toBeNull();- const download = await fetchHarvestDownload(harness, account.token, harvest_id);- expect(download.download_url).not.toBe('');- });- test('download reports the failure rather than unreadiness when the latest attempt failed', async () => {- const account = await createTestAccount(harness);- const {harvest_id} = await requestHarvest(harness, account.token);- await markHarvestFailed(account.userId, harvest_id, 'harvest exploded');- await expectHarvestDownloadFailsWithError(harness, account.token, harvest_id, 'HARVEST_FAILED');- });-});diff --git a/fluxer_api/src/api/user/tests/ListEndpointUserPartialPrefetch.test.ts b/fluxer_api/src/api/user/tests/ListEndpointUserPartialPrefetch.test.tsdeleted file mode 100644index 5aed830ac..000000000--- a/fluxer_api/src/api/user/tests/ListEndpointUserPartialPrefetch.test.ts+++ /dev/null@@ -1,192 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {type ChannelID, createChannelID, createUserID, type UserID} from '@app/api/BrandedTypes';-import type {ChannelRow} from '@app/api/database/types/ChannelTypes';-import type {RelationshipRow} from '@app/api/database/types/UserTypes';-import {UserCacheService} from '@app/api/infrastructure/UserCacheService';-import type {IUsersServiceClient} from '@app/api/infrastructure/UsersServiceClient';-import {createRequestCache} from '@app/api/middleware/RequestCacheMiddleware';-import {Channel} from '@app/api/models/Channel';-import {Relationship} from '@app/api/models/Relationship';-import {UserChannelRequestService} from '@app/api/user/services/UserChannelRequestService';-import type {UserChannelService} from '@app/api/user/services/UserChannelService';-import {UserRelationshipRequestService} from '@app/api/user/services/UserRelationshipRequestService';-import type {UserRelationshipService} from '@app/api/user/services/UserRelationshipService';-import {ChannelTypes} from '@fluxer/constants/src/ChannelConstants';-import {DELETED_USER_GLOBAL_NAME, DELETED_USER_USERNAME, RelationshipTypes} from '@fluxer/constants/src/UserConstants';-import type {UserPartialResponse} from '@fluxer/schema/src/domains/user/UserResponseSchemas';-import {describe, expect, test} from 'vitest';--class RecordingUsersServiceClient implements IUsersServiceClient {- readonly requests: Array<Array<UserID>> = [];-- constructor(private readonly partialsById: Map<UserID, UserPartialResponse>) {}-- async getUserPartialResponses(userIds: Array<UserID>): Promise<Map<UserID, UserPartialResponse>> {- this.requests.push([...userIds]);- const result = new Map<UserID, UserPartialResponse>();- for (const userId of userIds) {- const partial = this.partialsById.get(userId);- if (partial) {- result.set(userId, partial);- }- }- return result;- }-- async invalidateUserCache(_userId: UserID): Promise<void> {}-}--function createPartial(userId: UserID, username: string): UserPartialResponse {- return {- id: userId.toString(),- username,- discriminator: '0001',- global_name: null,- avatar: null,- avatar_color: null,- flags: 0,- };-}--function createPartials(userIds: Array<UserID>): Map<UserID, UserPartialResponse> {- return new Map(userIds.map((userId, index) => [userId, createPartial(userId, `Partial${index}`)]));-}--function createRelationship(sourceUserId: UserID, targetUserId: UserID, shareVoiceActivity: boolean): Relationship {- return new Relationship({- source_user_id: sourceUserId,- target_user_id: targetUserId,- type: RelationshipTypes.FRIEND,- nickname: null,- since: null,- share_voice_activity: shareVoiceActivity,- version: 1,- } satisfies RelationshipRow);-}--function createPrivateChannel(channelId: ChannelID, type: number, recipientIds: Set<UserID>): Channel {- return new Channel({- channel_id: channelId,- guild_id: null,- type,- name: null,- topic: null,- icon_hash: null,- url: null,- parent_id: null,- position: null,- owner_id: null,- recipient_ids: recipientIds,- nsfw: null,- content_warning_level: null,- content_warning_text: null,- rate_limit_per_user: null,- bitrate: null,- user_limit: null,- voice_connection_limit: null,- rtc_region: null,- rtc_p2p: null,- last_message_id: null,- last_pin_timestamp: null,- permission_overwrites: null,- nicks: null,- soft_deleted: false,- indexed_at: null,- version: 1,- } satisfies ChannelRow);-}--function createRelationshipRequestService(- relationships: Array<Relationship>,- inverseRelationships: Map<UserID, Relationship>,- userCacheService: UserCacheService,-): UserRelationshipRequestService {- return new UserRelationshipRequestService(- {- getRelationships: async () => relationships,- getRelationship: async (params: {userId: UserID}) => inverseRelationships.get(params.userId) ?? null,- } as unknown as UserRelationshipService,- {} as UserChannelService,- userCacheService,- );-}--describe('list endpoint user partial prefetch', () => {- test('resolves every relationship from a single batched user partial fetch', async () => {- const viewerId = createUserID(9000n);- const targetIds = [createUserID(9001n), createUserID(9002n), createUserID(9003n), createUserID(9004n)];- const partials = createPartials(targetIds);- const usersServiceClient = new RecordingUsersServiceClient(partials);- const relationships = targetIds.map((targetId) => createRelationship(viewerId, targetId, true));- const inverseRelationships = new Map(- targetIds.map((targetId) => [targetId, createRelationship(targetId, viewerId, false)]),- );- const service = createRelationshipRequestService(- relationships,- inverseRelationships,- new UserCacheService(usersServiceClient),- );-- const response = await service.listRelationships({userId: viewerId, requestCache: createRequestCache()});-- expect(usersServiceClient.requests).toEqual([targetIds]);- expect(response).toEqual(- targetIds.map((targetId) => ({- id: targetId.toString(),- type: RelationshipTypes.FRIEND,- user: partials.get(targetId),- nickname: null,- share_voice_activity: true,- friend_shares_voice_activity: false,- })),- );- });-- test('keeps the deleted-user fallback for relationship targets the users service drops', async () => {- const viewerId = createUserID(9100n);- const knownId = createUserID(9101n);- const missingId = createUserID(9102n);- const usersServiceClient = new RecordingUsersServiceClient(createPartials([knownId]));- const relationships = [createRelationship(viewerId, knownId, true), createRelationship(viewerId, missingId, true)];- const service = createRelationshipRequestService(- relationships,- new Map(),- new UserCacheService(usersServiceClient),- );-- const response = await service.listRelationships({userId: viewerId, requestCache: createRequestCache()});-- expect(usersServiceClient.requests).toEqual([[knownId, missingId]]);- expect(response[1]?.user).toMatchObject({- id: missingId.toString(),- username: DELETED_USER_USERNAME,- global_name: DELETED_USER_GLOBAL_NAME,- });- expect(response[1]?.friend_shares_voice_activity).toBe(true);- });-- test('resolves every private channel recipient from a single batched user partial fetch', async () => {- const viewerId = createUserID(9200n);- const friendId = createUserID(9201n);- const groupMemberId = createUserID(9202n);- const partials = createPartials([friendId, groupMemberId]);- const usersServiceClient = new RecordingUsersServiceClient(partials);- const channels = [- createPrivateChannel(createChannelID(9300n), ChannelTypes.DM, new Set([viewerId, friendId])),- createPrivateChannel(createChannelID(9301n), ChannelTypes.GROUP_DM, new Set([viewerId, friendId, groupMemberId])),- createPrivateChannel(createChannelID(9302n), ChannelTypes.DM_PERSONAL_NOTES, new Set([viewerId])),- ];- const service = new UserChannelRequestService(- {getPrivateChannels: async () => channels} as unknown as UserChannelService,- new UserCacheService(usersServiceClient),- );-- const response = await service.listPrivateChannels({userId: viewerId, requestCache: createRequestCache()});-- expect(usersServiceClient.requests).toEqual([[friendId, groupMemberId]]);- expect(response[0]?.recipients).toEqual([partials.get(friendId)]);- expect(response[1]?.recipients).toEqual([partials.get(friendId), partials.get(groupMemberId)]);- expect(response[2]?.recipients).toBeUndefined();- });-});diff --git a/fluxer_api/src/api/user/tests/ProfileCustomizationEmailVerificationRequired.test.ts b/fluxer_api/src/api/user/tests/ProfileCustomizationEmailVerificationRequired.test.tsdeleted file mode 100644index 0c6d1e1fd..000000000--- a/fluxer_api/src/api/user/tests/ProfileCustomizationEmailVerificationRequired.test.ts+++ /dev/null@@ -1,72 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {createAuthHarness, createTestAccount} from '@app/api/auth/tests/AuthTestUtils';-import {acceptInvite, createChannelInvite, createGuild, getChannel} from '@app/api/channel/tests/ChannelTestUtils';-import type {ApiTestHarness} from '@app/api/test/ApiTestHarness';-import {createBuilder} from '@app/api/test/TestRequestBuilder';-import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';-import {afterAll, beforeAll, beforeEach, describe, expect, it} from 'vitest';--interface ErrorResponse {- code: string;- message: string;-}--async function setEmailVerified(harness: ApiTestHarness, userId: string, emailVerified: boolean): Promise<void> {- await createBuilder(harness, '')- .post(`/test/users/${userId}/security-flags`)- .body({- email_verified: emailVerified,- })- .execute();-}--describe('Profile customization requires verified email', () => {- let harness: ApiTestHarness;- beforeAll(async () => {- harness = await createAuthHarness();- });- beforeEach(async () => {- await harness.reset();- });- afterAll(async () => {- await harness?.shutdown();- });- it('rejects global profile customization for unverified accounts', async () => {- const account = await createTestAccount(harness);- await setEmailVerified(harness, account.userId, false);- const {json} = await createBuilder<ErrorResponse>(harness, account.token)- .patch('/users/@me')- .body({bio: 'blocked'})- .expect(403)- .executeWithResponse();- expect(json.code).toBe(APIErrorCodes.PROFILE_EMAIL_VERIFICATION_REQUIRED);- });- it('still allows non-profile account flags for unverified accounts', async () => {- const account = await createTestAccount(harness);- await setEmailVerified(harness, account.userId, false);- const updated = await createBuilder<{- has_dismissed_premium_onboarding: boolean;- }>(harness, account.token)- .patch('/users/@me')- .body({has_dismissed_premium_onboarding: true})- .expect(200)- .execute();- expect(updated.has_dismissed_premium_onboarding).toBeDefined();- });- it('rejects community profile customization for unverified accounts', async () => {- const owner = await createTestAccount(harness);- const member = await createTestAccount(harness);- const guild = await createGuild(harness, owner.token, 'Profile Lock Guild');- const channel = await getChannel(harness, owner.token, guild.system_channel_id!);- const invite = await createChannelInvite(harness, owner.token, channel.id);- await acceptInvite(harness, member.token, invite.code);- await setEmailVerified(harness, member.userId, false);- const {json} = await createBuilder<ErrorResponse>(harness, member.token)- .patch(`/guilds/${guild.id}/members/@me`)- .body({nick: 'blocked'})- .expect(403)- .executeWithResponse();- expect(json.code).toBe(APIErrorCodes.PROFILE_EMAIL_VERIFICATION_REQUIRED);- });-});diff --git a/fluxer_api/src/api/user/tests/UserAccountAndSettings.test.ts b/fluxer_api/src/api/user/tests/UserAccountAndSettings.test.tsdeleted file mode 100644index 5d0231bc4..000000000--- a/fluxer_api/src/api/user/tests/UserAccountAndSettings.test.ts+++ /dev/null@@ -1,30 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {createTestAccount} from '@app/api/auth/tests/AuthTestUtils';-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 {sendFriendRequest} from '@app/api/user/tests/RelationshipTestUtils';-import {fetchUserProfile} from '@app/api/user/tests/UserTestUtils';-import {afterEach, beforeEach, describe, expect, test} from 'vitest';--describe('User Account And Settings', () => {- let harness: ApiTestHarness;- beforeEach(async () => {- harness = await createApiTestHarness();- });- afterEach(async () => {- await harness?.shutdown();- });- test('pending outgoing friend request allows viewing target profile', async () => {- const requester = await createTestAccount(harness);- const target = await createTestAccount(harness);- await createBuilder(harness, requester.token)- .get(`/users/${target.userId}/profile`)- .expect(HTTP_STATUS.FORBIDDEN, 'MISSING_ACCESS')- .execute();- await sendFriendRequest(harness, requester.token, target.userId);- const profile = await fetchUserProfile(harness, target.userId, requester.token);- expect(profile.json.user.id).toBe(target.userId);- });-});diff --git a/fluxer_api/src/api/user/tests/UserSettingsGuildFolders.test.ts b/fluxer_api/src/api/user/tests/UserSettingsGuildFolders.test.tsdeleted file mode 100644index b374533c4..000000000--- a/fluxer_api/src/api/user/tests/UserSettingsGuildFolders.test.ts+++ /dev/null@@ -1,55 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {createTestAccount} from '@app/api/auth/tests/AuthTestUtils';-import {createGuild} from '@app/api/guild/tests/GuildTestUtils';-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 {beforeEach, describe, expect, test} from 'vitest';--describe('UserSettings guild_folders validation', () => {- let harness: ApiTestHarness;- beforeEach(async () => {- harness = await createApiTestHarness();- });- test('preserves guild folders in database after unrelated settings update', async () => {- const account = await createTestAccount(harness);- const guild = await createGuild(harness, account.token, 'Persist Guild');- type SettingsResponse = {- guild_folders: Array<{- id: number;- name: string | null;- color: number | null;- guild_ids: Array<string>;- }>;- };- await createBuilder(harness, account.token)- .patch('/users/@me/settings')- .body({- guild_folders: [- {- id: 42,- name: 'Persist Folder',- color: 0x00ff00,- guild_ids: [guild.id],- },- ],- })- .expect(HTTP_STATUS.OK)- .execute();- await createBuilder(harness, account.token)- .patch('/users/@me/settings')- .body({developer_mode: true})- .expect(HTTP_STATUS.OK)- .execute();- const {json} = await createBuilder<SettingsResponse>(harness, account.token)- .get('/users/@me/settings')- .expect(HTTP_STATUS.OK)- .executeWithResponse();- const folder = json.guild_folders.find((entry) => entry.id === 42);- expect(folder).toBeDefined();- expect(folder?.name).toBe('Persist Folder');- expect(folder?.color).toBe(0x00ff00);- expect(folder?.guild_ids).toContain(guild.id);- });-});diff --git a/fluxer_api/src/api/voice/tests/VoiceP2pConnectionReports.test.ts b/fluxer_api/src/api/voice/tests/VoiceP2pConnectionReports.test.tsdeleted file mode 100644index bd9ad02fe..000000000--- a/fluxer_api/src/api/voice/tests/VoiceP2pConnectionReports.test.ts+++ /dev/null@@ -1,205 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {createUniqueEmail, createUniqueUsername} from '@app/api/auth/tests/AuthTestUtils';-import {createUserID} from '@app/api/BrandedTypes';-import {createTestBotAccount} from '@app/api/bot/tests/BotTestUtils';-import {fetchMany} from '@app/api/database/CassandraQueryExecution';-import {- VOICE_P2P_CONNECTION_REPORT_COLUMNS,- type VoiceP2pConnectionReportRow,-} from '@app/api/database/types/VoiceTypes';-import {getInstanceProductName} from '@app/api/instance/ProductName';-import {getInstanceConfigRepository} from '@app/api/middleware/ServiceSingletons';-import {VoiceP2pConnectionReports} from '@app/api/Tables';-import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';-import {HTTP_STATUS, TEST_CREDENTIALS, TEST_USER_DATA} from '@app/api/test/TestConstants';-import {createBuilder, createBuilderWithoutAuth} from '@app/api/test/TestRequestBuilder';-import {DEFAULT_VOICE_P2P_CONFIG} from '@fluxer/schema/src/domains/admin/VoiceP2pSchemas';-import type {GeoipResult} from '@pkgs/geoip/src/GeoipLookup';-import {afterAll, beforeAll, beforeEach, describe, expect, it, vi} from 'vitest';--const {lookupGeoipMock} = vi.hoisted(() => ({- lookupGeoipMock: vi.fn(),-}));--vi.mock('@app/api/utils/IpUtils', async (importOriginal) => ({- ...(await importOriginal<typeof import('@app/api/utils/IpUtils')>()),- lookupGeoip: lookupGeoipMock,-}));--const ENDPOINT = '/voice/p2p/connection-reports';-const CLIENT_IP = '203.0.113.10';-const ANDROID_USER_AGENT = 'Fluxer Android/1.4.0';--const LIST_REPORTS = VoiceP2pConnectionReports.select({where: VoiceP2pConnectionReports.where.eq('user_id')});--function geoipCountry(countryCode: string | null): GeoipResult {- return {countryCode, normalizedIp: CLIENT_IP, city: 'São Paulo', region: 'SP', countryName: 'Brazil'};-}--function connectedReport(overrides: Record<string, unknown> = {}): Record<string, unknown> {- return {- channel_id: '1189375284394692610',- guild_id: null,- participant_count: 2,- outcome: 'connected',- local_candidate_type: 'srflx',- remote_candidate_type: 'host',- ip_family: 'ipv6',- protocol: 'udp',- setup_ms: 840,- ice_restarted: false,- ...overrides,- };-}--async function registerAndroidAccount(harness: ApiTestHarness): Promise<{userId: string; token: string}> {- const registration = await createBuilder<{user_id: string; token: string}>(harness, '')- .post('/auth/register')- .header('user-agent', ANDROID_USER_AGENT)- .header('x-forwarded-for', CLIENT_IP)- .body({- email: createUniqueEmail('p2p-report'),- username: createUniqueUsername('p2preport'),- global_name: TEST_USER_DATA.DEFAULT_GLOBAL_NAME,- password: TEST_CREDENTIALS.STRONG_PASSWORD,- date_of_birth: TEST_USER_DATA.DEFAULT_DATE_OF_BIRTH,- consent: true,- })- .execute();- return {userId: registration.user_id, token: registration.token};-}--async function listReports(userId: string): Promise<Array<VoiceP2pConnectionReportRow>> {- return fetchMany<VoiceP2pConnectionReportRow>(LIST_REPORTS.bind({user_id: createUserID(BigInt(userId))}));-}--describe('POST /voice/p2p/connection-reports', () => {- let harness: ApiTestHarness;-- beforeAll(async () => {- harness = await createApiTestHarness();- });-- beforeEach(async () => {- await harness.reset();- lookupGeoipMock.mockReset();- lookupGeoipMock.mockResolvedValue(geoipCountry('BR'));- await getInstanceConfigRepository().setVoiceP2pConfig({...DEFAULT_VOICE_P2P_CONFIG, enabled: true});- });-- afterAll(async () => {- await harness.shutdown();- });-- it('rejects an unauthenticated caller', async () => {- await createBuilderWithoutAuth(harness)- .post(ENDPOINT)- .body({reports: [connectedReport()]})- .expect(HTTP_STATUS.UNAUTHORIZED)- .execute();- });-- it('rejects a bot', async () => {- const bot = await createTestBotAccount(harness);- await createBuilder(harness, `Bot ${bot.botToken}`)- .post(ENDPOINT)- .body({reports: [connectedReport()]})- .expect(HTTP_STATUS.FORBIDDEN)- .execute();- });-- it('stores each report with the server-derived fields and the request address', async () => {- const account = await registerAndroidAccount(harness);-- await createBuilder(harness, account.token)- .post(ENDPOINT)- .header('x-forwarded-for', CLIENT_IP)- .body({- reports: [- connectedReport(),- connectedReport({- guild_id: '1189375284394692608',- participant_count: 3,- outcome: 'failed',- local_candidate_type: null,- remote_candidate_type: null,- ip_family: null,- protocol: null,- setup_ms: null,- ice_restarted: true,- }),- ],- })- .expect(HTTP_STATUS.NO_CONTENT)- .execute();-- const rows = await listReports(account.userId);- expect(rows).toHaveLength(2);- const shared = {- user_id: BigInt(account.userId),- channel_id: 1189375284394692610n,- country: 'BR',- client_platform: `${getInstanceProductName()} Android`,- client_os: 'Android',- };- const connected = rows.find((row) => row.outcome === 'connected');- const failed = rows.find((row) => row.outcome === 'failed');- expect(connected).toMatchObject({- ...shared,- guild_id: null,- participant_count: 2,- local_candidate_type: 'srflx',- remote_candidate_type: 'host',- ip_family: 'ipv6',- protocol: 'udp',- setup_ms: 840,- ice_restarted: false,- });- expect(failed).toMatchObject({- ...shared,- guild_id: 1189375284394692608n,- participant_count: 3,- local_candidate_type: null,- remote_candidate_type: null,- ip_family: null,- protocol: null,- setup_ms: null,- ice_restarted: true,- });- for (const row of rows) {- expect(Object.keys(row).sort()).toEqual([...VOICE_P2P_CONNECTION_REPORT_COLUMNS].sort());- expect(row.reported_at).toBeInstanceOf(Date);- expect(row.ip).toBe(CLIENT_IP);- }- expect(connected?.report_id).not.toEqual(failed?.report_id);- });-- it('accepts and drops reports while the experiment is disabled', async () => {- await getInstanceConfigRepository().setVoiceP2pConfig(DEFAULT_VOICE_P2P_CONFIG);- const account = await registerAndroidAccount(harness);-- await createBuilder(harness, account.token)- .post(ENDPOINT)- .body({reports: [connectedReport()]})- .expect(HTTP_STATUS.NO_CONTENT)- .execute();-- expect(await listReports(account.userId)).toEqual([]);- });-- it.each([{name: 'more than 8 reports', body: {reports: Array.from({length: 9}, () => connectedReport())}}])(- 'rejects $name and stores nothing',- async ({body}) => {- const account = await registerAndroidAccount(harness);-- await createBuilder(harness, account.token)- .post(ENDPOINT)- .body(body)- .expect(HTTP_STATUS.BAD_REQUEST, 'INVALID_FORM_BODY')- .execute();-- expect(await listReports(account.userId)).toEqual([]);- },- );-});diff --git a/fluxer_api/src/api/voice/tests/VoiceServerLoad.test.ts b/fluxer_api/src/api/voice/tests/VoiceServerLoad.test.tsdeleted file mode 100644index f250e6e9f..000000000--- a/fluxer_api/src/api/voice/tests/VoiceServerLoad.test.ts+++ /dev/null@@ -1,87 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import type {GatewayVoiceStateCounts, IGatewayService} from '@app/api/infrastructure/IGatewayService';-import {VoiceServerLoadTracker} from '@app/api/voice/VoiceServerLoad';-import {describe, expect, it} from 'vitest';--function createGatewayService(respond: () => Promise<GatewayVoiceStateCounts>): {- gatewayService: IGatewayService;- callCount: () => number;-} {- let calls = 0;- const gatewayService = {- getVoiceStateCounts: () => {- calls += 1;- return respond();- },- } as IGatewayService;- return {gatewayService, callCount: () => calls};-}--function counts(servers: Array<{server_id: string; voice_state_count: number}>): GatewayVoiceStateCounts {- return {- total_voice_states: servers.reduce((total, server) => total + server.voice_state_count, 0),- regions: [],- servers,- };-}--describe('VoiceServerLoadTracker', () => {- it('reports no counts until the first refresh resolves', () => {- const {gatewayService} = createGatewayService(async () => counts([{server_id: 'server-1', voice_state_count: 7}]));- const tracker = new VoiceServerLoadTracker({gatewayService});- expect(tracker.getConnectionCounts().size).toBe(0);- });- it('reports the counts the gateway returned', async () => {- const {gatewayService} = createGatewayService(async () => counts([{server_id: 'server-1', voice_state_count: 7}]));- const tracker = new VoiceServerLoadTracker({gatewayService});- await tracker.refresh();- expect(tracker.getConnectionCounts().get('server-1')).toBe(7);- });- it('keeps the last counts when a refresh fails', async () => {- let shouldFail = false;- const {gatewayService} = createGatewayService(async () => {- if (shouldFail) {- throw new Error('gateway unavailable');- }- return counts([{server_id: 'server-1', voice_state_count: 7}]);- });- const tracker = new VoiceServerLoadTracker({gatewayService});- await tracker.refresh();- shouldFail = true;- await tracker.refresh();- expect(tracker.getConnectionCounts().get('server-1')).toBe(7);- });- it('refreshes no more often than the refresh interval', async () => {- let currentTime = 1000;- const {gatewayService, callCount} = createGatewayService(async () =>- counts([{server_id: 'server-1', voice_state_count: 7}]),- );- const tracker = new VoiceServerLoadTracker({- gatewayService,- refreshIntervalMs: 5000,- now: () => currentTime,- });- await tracker.refresh();- tracker.getConnectionCounts();- currentTime += 4999;- tracker.getConnectionCounts();- expect(callCount()).toBe(1);- currentTime += 1;- tracker.getConnectionCounts();- expect(callCount()).toBe(2);- });- it('drops counts that are too old to place against', async () => {- let currentTime = 1000;- const {gatewayService} = createGatewayService(async () => counts([{server_id: 'server-1', voice_state_count: 7}]));- const tracker = new VoiceServerLoadTracker({- gatewayService,- refreshIntervalMs: 5000,- now: () => currentTime,- });- await tracker.refresh();- expect(tracker.getConnectionCounts().get('server-1')).toBe(7);- currentTime += 20001;- expect(tracker.getConnectionCounts().size).toBe(0);- });-});diff --git a/fluxer_api/src/api/webhook/WebhookRepository.test.ts b/fluxer_api/src/api/webhook/WebhookRepository.test.tsdeleted file mode 100644index 4cb4322af..000000000--- a/fluxer_api/src/api/webhook/WebhookRepository.test.ts+++ /dev/null@@ -1,137 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {- type ChannelID,- createChannelID,- createGuildID,- createUserID,- createWebhookID,- createWebhookToken,- type GuildID,- type WebhookID,-} from '@app/api/BrandedTypes';-import {setCassandraQueryExecutorForTesting} from '@app/api/database/CassandraQueryExecution';-import {InMemoryCassandraQueryExecutor} from '@app/api/test/InMemoryCassandraQueryExecutor';-import {WebhookRepository} from '@app/api/webhook/WebhookRepository';-import {WebhookTypes} from '@fluxer/constants/src/ChannelConstants';-import {afterEach, beforeEach, describe, expect, it} from 'vitest';--const SOURCE_GUILD = createGuildID(1n);-const SOURCE_CHANNEL = createChannelID(10n);--let executor: InMemoryCassandraQueryExecutor;-let repository: WebhookRepository;--async function createFollower(- webhookId: WebhookID,- guildId: GuildID,- channelId: ChannelID,- sourceChannelId: ChannelID = SOURCE_CHANNEL,-) {- return repository.create({- webhookId,- token: createWebhookToken(`token-${webhookId}`),- type: WebhookTypes.CHANNEL_FOLLOWER,- guildId,- channelId,- creatorId: createUserID(7n),- name: 'Source #news',- avatarHash: null,- sourceGuildId: SOURCE_GUILD,- sourceChannelId,- });-}--describe('WebhookRepository source channel index', () => {- beforeEach(() => {- executor = new InMemoryCassandraQueryExecutor();- setCassandraQueryExecutorForTesting(executor);- repository = new WebhookRepository();- });- afterEach(() => {- executor.reset();- setCassandraQueryExecutorForTesting(null);- });-- it('stores and returns the source columns of a follower webhook', async () => {- const created = await createFollower(createWebhookID(100n), createGuildID(2n), createChannelID(20n));- expect(created.sourceGuildId).toBe(1n);- expect(created.sourceChannelId).toBe(10n);- expect(created.type).toBe(WebhookTypes.CHANNEL_FOLLOWER);- const found = await repository.findUnique(createWebhookID(100n));- expect(found?.sourceGuildId).toBe(1n);- expect(found?.sourceChannelId).toBe(10n);- expect(found?.toRow().source_channel_id).toBe(10n);- });-- it('leaves incoming webhooks out of the index with null source columns', async () => {- const created = await repository.create({- webhookId: createWebhookID(101n),- token: createWebhookToken('incoming'),- type: WebhookTypes.INCOMING,- guildId: createGuildID(2n),- channelId: SOURCE_CHANNEL,- creatorId: createUserID(7n),- name: 'Incoming',- avatarHash: null,- });- expect(created.sourceGuildId).toBeNull();- expect(created.sourceChannelId).toBeNull();- expect(await repository.listIdsBySourceChannel(SOURCE_CHANNEL, {limit: 10})).toEqual([]);- expect(await repository.countBySourceChannel(SOURCE_CHANNEL)).toEqual({channelCount: 0, guildCount: 0});- });-- it('keeps the source columns across an update and a move', async () => {- await createFollower(createWebhookID(100n), createGuildID(2n), createChannelID(20n));- const updated = await repository.update(createWebhookID(100n), {- name: 'Renamed',- channelId: createChannelID(21n),- });- expect(updated?.name).toBe('Renamed');- expect(updated?.sourceGuildId).toBe(1n);- expect(updated?.sourceChannelId).toBe(10n);- const found = await repository.findUnique(createWebhookID(100n));- expect(found?.channelId).toBe(21n);- expect(found?.sourceChannelId).toBe(10n);- expect(await repository.listIdsBySourceChannel(SOURCE_CHANNEL, {limit: 10})).toEqual([- {webhookId: 100n, guildId: 2n},- ]);- });-- it('pages follower ids by source channel in webhook id order', async () => {- await createFollower(createWebhookID(104n), createGuildID(3n), createChannelID(30n));- await createFollower(createWebhookID(101n), createGuildID(2n), createChannelID(20n));- await createFollower(createWebhookID(103n), createGuildID(2n), createChannelID(21n));- await createFollower(createWebhookID(102n), createGuildID(4n), createChannelID(40n));- await createFollower(createWebhookID(105n), createGuildID(2n), createChannelID(22n), createChannelID(11n));- const first = await repository.listIdsBySourceChannel(SOURCE_CHANNEL, {limit: 3});- expect(first).toEqual([- {webhookId: 101n, guildId: 2n},- {webhookId: 102n, guildId: 4n},- {webhookId: 103n, guildId: 2n},- ]);- const second = await repository.listIdsBySourceChannel(SOURCE_CHANNEL, {- afterWebhookId: first[first.length - 1]!.webhookId,- limit: 3,- });- expect(second).toEqual([{webhookId: 104n, guildId: 3n}]);- });-- it('counts follower channels and distinct target guilds', async () => {- await createFollower(createWebhookID(101n), createGuildID(2n), createChannelID(20n));- await createFollower(createWebhookID(102n), createGuildID(2n), createChannelID(21n));- await createFollower(createWebhookID(103n), createGuildID(3n), createChannelID(30n));- expect(await repository.countBySourceChannel(SOURCE_CHANNEL)).toEqual({channelCount: 3, guildCount: 2});- });-- it('removes the index row when a follower webhook is deleted', async () => {- await createFollower(createWebhookID(101n), createGuildID(2n), createChannelID(20n));- await createFollower(createWebhookID(102n), createGuildID(3n), createChannelID(30n));- await repository.delete(createWebhookID(101n));- expect(await repository.findUnique(createWebhookID(101n))).toBeNull();- expect(await repository.listIdsBySourceChannel(SOURCE_CHANNEL, {limit: 10})).toEqual([- {webhookId: 102n, guildId: 3n},- ]);- expect(await repository.countBySourceChannel(SOURCE_CHANNEL)).toEqual({channelCount: 1, guildCount: 1});- });-});diff --git a/fluxer_api/src/api/webhook/tests/WebhookExecutionAdvanced.test.ts b/fluxer_api/src/api/webhook/tests/WebhookExecutionAdvanced.test.tsdeleted file mode 100644index c43aea099..000000000--- a/fluxer_api/src/api/webhook/tests/WebhookExecutionAdvanced.test.ts+++ /dev/null@@ -1,72 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {createTestAccount} from '@app/api/auth/tests/AuthTestUtils';-import {createGuild} from '@app/api/guild/tests/GuildTestUtils';-import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';-import {HTTP_STATUS} from '@app/api/test/TestConstants';-import {createBuilderWithoutAuth} from '@app/api/test/TestRequestBuilder';-import {createWebhook, deleteWebhook} from '@app/api/webhook/tests/WebhookTestUtils';-import type {MessageResponse} from '@fluxer/schema/src/domains/message/MessageResponseSchemas';-import {afterEach, beforeEach, describe, expect, it} from 'vitest';--describe('Webhook execution advanced', () => {- let harness: ApiTestHarness;- beforeEach(async () => {- harness = await createApiTestHarness();- });- afterEach(async () => {- await harness?.shutdown();- });- describe('Message content', () => {- it('executes webhook with an empty embed title', async () => {- const owner = await createTestAccount(harness);- const guild = await createGuild(harness, owner.token, 'Webhook Empty Embed Title Guild');- const channelId = guild.system_channel_id!;- const webhook = await createWebhook(harness, channelId, owner.token, 'Empty Embed Title Webhook');- const result = await createBuilderWithoutAuth<MessageResponse>(harness)- .post(`/webhooks/${webhook.id}/${webhook.token}?wait=true`)- .body({- embeds: [{title: '', description: 'Description with intentionally empty title'}],- })- .expect(HTTP_STATUS.OK)- .execute();- expect(result.embeds).toHaveLength(1);- expect(result.embeds?.[0]?.title).toBe('');- expect(result.embeds?.[0]?.description).toBe('Description with intentionally empty title');- await deleteWebhook(harness, webhook.id, owner.token);- });- it('executes webhook with an empty embed description', async () => {- const owner = await createTestAccount(harness);- const guild = await createGuild(harness, owner.token, 'Webhook Empty Embed Description Guild');- const channelId = guild.system_channel_id!;- const webhook = await createWebhook(harness, channelId, owner.token, 'Empty Embed Description Webhook');- const result = await createBuilderWithoutAuth<MessageResponse>(harness)- .post(`/webhooks/${webhook.id}/${webhook.token}?wait=true`)- .body({- embeds: [{title: 'Workflow run', description: ''}],- })- .expect(HTTP_STATUS.OK)- .execute();- expect(result.embeds).toHaveLength(1);- expect(result.embeds?.[0]?.title).toBe('Workflow run');- expect(result.embeds?.[0]?.description).toBeNull();- await deleteWebhook(harness, webhook.id, owner.token);- });- });- describe('Slack compatible endpoint', () => {- it('executes slack compatible webhook', async () => {- const owner = await createTestAccount(harness);- const guild = await createGuild(harness, owner.token, 'Slack Webhook Guild');- const channelId = guild.system_channel_id!;- const webhook = await createWebhook(harness, channelId, owner.token, 'Slack Compatible Webhook');- const {response, text} = await createBuilderWithoutAuth(harness)- .post(`/webhooks/${webhook.id}/${webhook.token}/slack`)- .body({text: 'Hello from Slack format'})- .expect(HTTP_STATUS.OK)- .executeRaw();- expect(response.status).toBe(HTTP_STATUS.OK);- expect(text).toBe('ok');- await deleteWebhook(harness, webhook.id, owner.token);- });- });-});diff --git a/fluxer_api/src/api/webhook/tests/WebhookLimits.test.ts b/fluxer_api/src/api/webhook/tests/WebhookLimits.test.tsdeleted file mode 100644index 5df54daf0..000000000--- a/fluxer_api/src/api/webhook/tests/WebhookLimits.test.ts+++ /dev/null@@ -1,64 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {createTestAccount} from '@app/api/auth/tests/AuthTestUtils';-import {createChannel, createGuild} from '@app/api/guild/tests/GuildTestUtils';-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 {createWebhook, deleteWebhook} from '@app/api/webhook/tests/WebhookTestUtils';-import {MAX_WEBHOOKS_PER_CHANNEL} from '@fluxer/constants/src/LimitConstants';-import type {WebhookResponse} from '@fluxer/schema/src/domains/webhook/WebhookSchemas';-import {afterEach, beforeEach, describe, it} from 'vitest';--describe('Webhook limits', () => {- let harness: ApiTestHarness;- beforeEach(async () => {- harness = await createApiTestHarness();- });- afterEach(async () => {- await harness?.shutdown();- });- describe('Channel webhook limits', () => {- it('enforces max webhooks per channel limit', async () => {- const owner = await createTestAccount(harness);- const guild = await createGuild(harness, owner.token, 'Webhook Limit Guild');- const channelId = guild.system_channel_id!;- const createdWebhooks: Array<WebhookResponse> = [];- for (let i = 0; i < MAX_WEBHOOKS_PER_CHANNEL; i++) {- const webhook = await createWebhook(harness, channelId, owner.token, `Webhook ${i + 1}`);- createdWebhooks.push(webhook);- }- await createBuilder(harness, owner.token)- .post(`/channels/${channelId}/webhooks`)- .body({name: 'One Too Many'})- .expect(HTTP_STATUS.BAD_REQUEST, 'MAX_WEBHOOKS_PER_CHANNEL')- .execute();- for (const webhook of createdWebhooks) {- await deleteWebhook(harness, webhook.id, owner.token);- }- });- });- describe('Channel move limits', () => {- it('rejects moving webhook to channel at limit', async () => {- const owner = await createTestAccount(harness);- const guild = await createGuild(harness, owner.token, 'Webhook Move Limit Guild');- const channel1 = guild.system_channel_id!;- const channel2 = (await createChannel(harness, owner.token, guild.id, 'full-channel')).id;- const channel2Webhooks: Array<WebhookResponse> = [];- for (let i = 0; i < MAX_WEBHOOKS_PER_CHANNEL; i++) {- const webhook = await createWebhook(harness, channel2, owner.token, `Ch2 Webhook ${i + 1}`);- channel2Webhooks.push(webhook);- }- const movingWebhook = await createWebhook(harness, channel1, owner.token, 'Moving Webhook');- await createBuilder(harness, owner.token)- .patch(`/webhooks/${movingWebhook.id}`)- .body({channel_id: channel2})- .expect(HTTP_STATUS.BAD_REQUEST, 'MAX_WEBHOOKS_PER_CHANNEL')- .execute();- await deleteWebhook(harness, movingWebhook.id, owner.token);- for (const webhook of channel2Webhooks) {- await deleteWebhook(harness, webhook.id, owner.token);- }- });- });-});diff --git a/fluxer_api/src/api/webhook/tests/WebhookMultipartAttachmentUploads.test.ts b/fluxer_api/src/api/webhook/tests/WebhookMultipartAttachmentUploads.test.tsdeleted file mode 100644index 2128145a2..000000000--- a/fluxer_api/src/api/webhook/tests/WebhookMultipartAttachmentUploads.test.ts+++ /dev/null@@ -1,148 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {createTestAccount} from '@app/api/auth/tests/AuthTestUtils';-import {loadFixture} from '@app/api/channel/tests/AttachmentTestUtils';-import {createPermissionOverwrite} from '@app/api/channel/tests/ChannelTestUtils';-import {acceptInvite, addMemberRole, createGuild, createRole} from '@app/api/guild/tests/GuildTestUtils';-import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';-import {HTTP_STATUS} from '@app/api/test/TestConstants';-import {- createChannelInvite,- createWebhook,- deleteWebhook,- executeWebhookWithAttachments,-} from '@app/api/webhook/tests/WebhookTestUtils';-import {Permissions} from '@fluxer/constants/src/ChannelConstants';-import {afterEach, beforeEach, describe, expect, it} from 'vitest';--describe('Webhook multipart attachment uploads', () => {- let harness: ApiTestHarness;- beforeEach(async () => {- harness = await createApiTestHarness();- });- afterEach(async () => {- await harness?.shutdown();- });- it('executes webhook with attachment-only multipart payload', async () => {- const owner = await createTestAccount(harness);- const guild = await createGuild(harness, owner.token, 'Webhook multipart upload guild');- const channelId = guild.system_channel_id!;- const webhook = await createWebhook(harness, channelId, owner.token, 'Multipart Upload Webhook');- const {response, json} = await executeWebhookWithAttachments(harness, {- webhookId: webhook.id,- webhookToken: webhook.token,- payload: {- attachments: [{id: 0, filename: 'webhook_upload.png'}],- },- files: [{index: 0, filename: 'webhook_upload.png', data: loadFixture('yeah.png')}],- });- expect(response.status).toBe(HTTP_STATUS.OK);- expect(json).not.toBeNull();- expect(json?.webhook_id).toBe(webhook.id);- expect(json?.attachments).toBeDefined();- expect(json?.attachments?.length).toBe(1);- expect(json?.attachments?.[0].filename).toBe('webhook_upload.png');- await deleteWebhook(harness, webhook.id, owner.token);- });- it('executes webhook multipart payload with content and username overrides', async () => {- const owner = await createTestAccount(harness);- const guild = await createGuild(harness, owner.token, 'Webhook multipart override guild');- const channelId = guild.system_channel_id!;- const webhook = await createWebhook(harness, channelId, owner.token, 'Multipart Override Webhook');- const {response, json} = await executeWebhookWithAttachments(harness, {- webhookId: webhook.id,- webhookToken: webhook.token,- payload: {- content: 'Webhook with uploaded file',- username: 'Upload Bot',- attachments: [{id: 0, filename: 'upload.txt'}],- },- files: [{index: 0, filename: 'upload.txt', data: Buffer.from('uploaded through webhook')}],- });- expect(response.status).toBe(HTTP_STATUS.OK);- expect(json).not.toBeNull();- expect(json?.content).toBe('Webhook with uploaded file');- expect(json?.attachments).toBeDefined();- expect(json?.attachments?.length).toBe(1);- expect(json?.attachments?.[0].filename).toBe('upload.txt');- await deleteWebhook(harness, webhook.id, owner.token);- });- it('executes multipart webhook requests with files but no attachment metadata', async () => {- const owner = await createTestAccount(harness);- const guild = await createGuild(harness, owner.token, 'Webhook multipart metadata required guild');- const channelId = guild.system_channel_id!;- const webhook = await createWebhook(harness, channelId, owner.token, 'Metadata Required Webhook');- const {response} = await executeWebhookWithAttachments(harness, {- webhookId: webhook.id,- webhookToken: webhook.token,- payload: {- content: 'missing metadata',- },- files: [{index: 0, filename: 'missing-metadata.png', data: loadFixture('yeah.png')}],- });- expect(response.status).toBe(HTTP_STATUS.OK);- await deleteWebhook(harness, webhook.id, owner.token);- });- it('rejects multipart webhook requests with attachment metadata but no file upload', async () => {- const owner = await createTestAccount(harness);- const guild = await createGuild(harness, owner.token, 'Webhook multipart missing file guild');- const channelId = guild.system_channel_id!;- const webhook = await createWebhook(harness, channelId, owner.token, 'Missing File Webhook');- const {response} = await executeWebhookWithAttachments(harness, {- webhookId: webhook.id,- webhookToken: webhook.token,- payload: {- attachments: [{id: 0, filename: 'missing.png'}],- },- files: [],- });- expect(response.status).toBe(HTTP_STATUS.BAD_REQUEST);- await deleteWebhook(harness, webhook.id, owner.token);- });- it('executes multipart webhook requests when the creator is denied attach files', async () => {- const owner = await createTestAccount(harness);- const creator = await createTestAccount(harness);- const guild = await createGuild(harness, owner.token, 'Webhook creator denied attach files guild');- const channelId = guild.system_channel_id!;- const invite = await createChannelInvite(harness, owner.token, channelId);- await acceptInvite(harness, creator.token, invite.code);- const webhookManagerRole = await createRole(harness, owner.token, guild.id, {- name: 'Webhook Manager',- permissions: Permissions.MANAGE_WEBHOOKS.toString(),- });- await addMemberRole(harness, owner.token, guild.id, creator.userId, webhookManagerRole.id);- const webhook = await createWebhook(harness, channelId, creator.token, 'Denied Creator Webhook');- await createPermissionOverwrite(harness, owner.token, channelId, creator.userId, {- type: 1,- allow: '0',- deny: Permissions.ATTACH_FILES.toString(),- });- const {response, json} = await executeWebhookWithAttachments(harness, {- webhookId: webhook.id,- webhookToken: webhook.token,- payload: {- attachments: [{id: 0, filename: 'denied_creator.png'}],- },- files: [{index: 0, filename: 'denied_creator.png', data: loadFixture('yeah.png')}],- });- expect(response.status).toBe(HTTP_STATUS.OK);- expect(json?.attachments?.length).toBe(1);- await deleteWebhook(harness, webhook.id, owner.token);- });- it('rejects multipart webhook requests when file indices do not match metadata IDs', async () => {- const owner = await createTestAccount(harness);- const guild = await createGuild(harness, owner.token, 'Webhook multipart id mismatch guild');- const channelId = guild.system_channel_id!;- const webhook = await createWebhook(harness, channelId, owner.token, 'ID Mismatch Webhook');- const {response} = await executeWebhookWithAttachments(harness, {- webhookId: webhook.id,- webhookToken: webhook.token,- payload: {- attachments: [{id: 2, filename: 'mismatch.png'}],- },- files: [{index: 0, filename: 'mismatch.png', data: loadFixture('yeah.png')}],- });- expect(response.status).toBe(HTTP_STATUS.BAD_REQUEST);- await deleteWebhook(harness, webhook.id, owner.token);- });-});