Skip to content

A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.

TypeScript fluxerfluxerapp

test(api): trim community, infra, activity and report cases

Hampusd45ccd0330a7
diff --git a/fluxer_api/src/api/experiment/tests/ExperimentController.test.ts b/fluxer_api/src/api/experiment/tests/ExperimentController.test.ts
index 9e5162e12..3b3675e15 100644
--- a/fluxer_api/src/api/experiment/tests/ExperimentController.test.ts
+++ b/fluxer_api/src/api/experiment/tests/ExperimentController.test.ts
@@ -1,25 +1,16 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
-import {createTestAccount, setUserACLs} from '@app/api/auth/tests/AuthTestUtils';
+import {createTestAccount} from '@app/api/auth/tests/AuthTestUtils';
import {acceptInvite, createChannelInvite, createGuild, getChannel} from '@app/api/guild/tests/GuildTestUtils';
import {getInstanceConfigRepository} from '@app/api/middleware/ServiceSingletons';
import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
import {HTTP_STATUS} from '@app/api/test/TestConstants';
-import {createBuilder, createBuilderWithoutAuth} from '@app/api/test/TestRequestBuilder';
+import {createBuilder} from '@app/api/test/TestRequestBuilder';
import {grantPremium} from '@app/api/user/tests/UserTestUtils';
-import {AdminACLs} from '@fluxer/constants/src/AdminACLs';
import {UserPremiumTypes} from '@fluxer/constants/src/UserConstants';
-import {
- DEFAULT_DOMAIN_MIGRATION_CONFIG,
- INERT_DOMAIN_MIGRATION_ASSIGNMENT,
-} from '@fluxer/schema/src/domains/admin/DomainMigrationSchemas';
-import {DEFAULT_VOICE_P2P_CONFIG, INERT_VOICE_P2P_ASSIGNMENT} from '@fluxer/schema/src/domains/admin/VoiceP2pSchemas';
-import {
- DEFAULT_EXPERIMENT_POLL_INTERVAL_SECONDS,
- DEFAULT_EXPERIMENT_POLL_JITTER_PERCENT,
- type ExperimentAssignmentsResponse,
- type ExperimentDeliveryConfigResponse,
-} from '@fluxer/schema/src/domains/experiment/ExperimentSchemas';
+import {DEFAULT_DOMAIN_MIGRATION_CONFIG} from '@fluxer/schema/src/domains/admin/DomainMigrationSchemas';
+import {DEFAULT_VOICE_P2P_CONFIG} from '@fluxer/schema/src/domains/admin/VoiceP2pSchemas';
+import type {ExperimentAssignmentsResponse} from '@fluxer/schema/src/domains/experiment/ExperimentSchemas';
import type {GeoipResult} from '@pkgs/geoip/src/GeoipLookup';
import {afterAll, beforeAll, beforeEach, describe, expect, it, vi} from 'vitest';
@@ -62,24 +53,12 @@ describe('GET /experiments', () => {
await harness.shutdown();
});
- it('rejects an unauthenticated caller', async () => {
- await createBuilderWithoutAuth(harness).get(ENDPOINT).expect(HTTP_STATUS.UNAUTHORIZED).execute();
- });
-
- it('returns the default delivery cadence and the default assignments', async () => {
- const account = await createTestAccount(harness);
-
- const body = await createBuilder<ExperimentAssignmentsResponse>(harness, account.token).get(ENDPOINT).execute();
-
- expect(body).toEqual({
- poll_interval_seconds: DEFAULT_EXPERIMENT_POLL_INTERVAL_SECONDS,
- poll_jitter_percent: DEFAULT_EXPERIMENT_POLL_JITTER_PERCENT,
- assignments: {
- domain_migration: INERT_DOMAIN_MIGRATION_ASSIGNMENT,
- channel_threads: {active: true, config_version: 0},
- plutonium_page: {enabled: true},
- voice_p2p: INERT_VOICE_P2P_ASSIGNMENT,
- },
+ it('assigns guild visits only to people the switch includes', async () => {
+ const included = await createTestAccount(harness);
+ const other = await createTestAccount(harness);
+ await getInstanceConfigRepository().updateGuildVisitsConfig({
+ enabled: true,
+ included_user_ids: [included.userId],
});
});
@@ -239,31 +218,6 @@ describe('GET /experiments', () => {
}
});
- it('stores the guild ids, countries and premium switch an admin sets for each experiment', async () => {
- const admin = await setUserACLs(harness, await createTestAccount(harness), [
- AdminACLs.AUTHENTICATE,
- AdminACLs.INSTANCE_CONFIG_VIEW,
- AdminACLs.INSTANCE_CONFIG_UPDATE,
- ]);
- const guildIds = ['1500000000000000001', '1500000000000000002'];
- const countryCodes = ['SE', 'NO'];
- const section = {included_guild_ids: guildIds, include_premium_users: true, rollout_country_codes: countryCodes};
- const body = await createBuilder<
- Record<
- 'domain_migration' | 'voice_p2p',
- {included_guild_ids: Array<string>; include_premium_users: boolean; rollout_country_codes: Array<string>}
- >
- >(harness, admin.token)
- .patch('/admin/instance/config')
- .body({domain_migration: section, voice_p2p: section})
- .execute();
- for (const stored of [body.domain_migration, body.voice_p2p]) {
- expect(stored.included_guild_ids).toEqual(guildIds);
- expect(stored.include_premium_users).toBe(true);
- expect(stored.rollout_country_codes).toEqual(countryCodes);
- }
- });
-
it('revalidates with a strong etag and answers 304 when nothing changed', async () => {
const account = await createTestAccount(harness);
@@ -286,13 +240,6 @@ describe('GET /experiments', () => {
expect(revalidated.response.headers.get('vary')).toBe('Authorization, Origin');
});
- it('lets a cross-origin client send If-None-Match and read the etag back', async () => {
- const preflight = await harness.requestJson({path: ENDPOINT, method: 'OPTIONS'});
-
- expect(preflight.headers.get('access-control-allow-headers')).toContain('If-None-Match');
- expect(preflight.headers.get('access-control-expose-headers')).toContain('ETag');
- });
-
it('serves a fresh body once the domain migration config changes', async () => {
const account = await createTestAccount(harness);
@@ -339,100 +286,4 @@ describe('GET /experiments', () => {
expect(refreshed.json?.poll_interval_seconds).toBe(1800);
expect(refreshed.json?.poll_jitter_percent).toBe(5);
});
-
- it('bumps the domain migration config version on every admin update without the client sending one', async () => {
- const admin = await setUserACLs(harness, await createTestAccount(harness), [
- AdminACLs.AUTHENTICATE,
- AdminACLs.INSTANCE_CONFIG_VIEW,
- AdminACLs.INSTANCE_CONFIG_UPDATE,
- ]);
-
- const afterFirst = await createBuilder<{domain_migration: {config_version: number; enabled: boolean}}>(
- harness,
- admin.token,
- )
- .patch('/admin/instance/config')
- .body({domain_migration: {enabled: true, rollout_basis_points: 10000}})
- .execute();
- expect(afterFirst.domain_migration).toMatchObject({config_version: 1, enabled: true});
-
- const afterSecond = await createBuilder<{
- domain_migration: {config_version: number; enabled: boolean; anonymous_rollout_basis_points: number};
- }>(harness, admin.token)
- .patch('/admin/instance/config')
- .body({domain_migration: {anonymous_rollout_basis_points: 2500}})
- .execute();
- expect(afterSecond.domain_migration).toMatchObject({
- config_version: 2,
- enabled: true,
- anonymous_rollout_basis_points: 2500,
- });
-
- const afterEmpty = await createBuilder<{domain_migration: {config_version: number; enabled: boolean}}>(
- harness,
- admin.token,
- )
- .patch('/admin/instance/config')
- .body({domain_migration: {}})
- .execute();
- expect(afterEmpty.domain_migration).toMatchObject({config_version: 2, enabled: true});
-
- const body = await createBuilder<ExperimentAssignmentsResponse>(harness, admin.token).get(ENDPOINT).execute();
- expect(body.assignments.domain_migration).toEqual({enabled: true});
- });
-
- it('bumps the voice p2p config version on every admin update without the client sending one', async () => {
- const admin = await setUserACLs(harness, await createTestAccount(harness), [
- AdminACLs.AUTHENTICATE,
- AdminACLs.INSTANCE_CONFIG_VIEW,
- AdminACLs.INSTANCE_CONFIG_UPDATE,
- ]);
-
- const afterFirst = await createBuilder<{voice_p2p: {config_version: number; enabled: boolean}}>(
- harness,
- admin.token,
- )
- .patch('/admin/instance/config')
- .body({voice_p2p: {enabled: true, included_user_ids: [admin.userId]}})
- .execute();
- expect(afterFirst.voice_p2p).toMatchObject({config_version: 1, enabled: true});
-
- const afterSecond = await createBuilder<{
- voice_p2p: {config_version: number; rollout_basis_points: number};
- }>(harness, admin.token)
- .patch('/admin/instance/config')
- .body({voice_p2p: {rollout_basis_points: 2500, max_participants: 4}})
- .execute();
- expect(afterSecond.voice_p2p).toMatchObject({config_version: 2, rollout_basis_points: 2500, max_participants: 4});
-
- const afterEmpty = await createBuilder<{voice_p2p: {config_version: number}}>(harness, admin.token)
- .patch('/admin/instance/config')
- .body({voice_p2p: {}})
- .execute();
- expect(afterEmpty.voice_p2p).toMatchObject({config_version: 2});
-
- const body = await createBuilder<ExperimentAssignmentsResponse>(harness, admin.token).get(ENDPOINT).execute();
- expect(body.assignments.voice_p2p).toEqual({enabled: true, max_participants: 4});
- });
-
- it('serves the delivery cadence an admin set through the instance config', async () => {
- const admin = await setUserACLs(harness, await createTestAccount(harness), [
- AdminACLs.AUTHENTICATE,
- AdminACLs.INSTANCE_CONFIG_VIEW,
- AdminACLs.INSTANCE_CONFIG_UPDATE,
- ]);
-
- const updated = await createBuilder<{experiment_delivery: ExperimentDeliveryConfigResponse}>(harness, admin.token)
- .patch('/admin/instance/config')
- .body({experiment_delivery: {poll_interval_seconds: 3600}})
- .execute();
- expect(updated.experiment_delivery).toEqual({
- poll_interval_seconds: 3600,
- poll_jitter_percent: DEFAULT_EXPERIMENT_POLL_JITTER_PERCENT,
- });
-
- const body = await createBuilder<ExperimentAssignmentsResponse>(harness, admin.token).get(ENDPOINT).execute();
- expect(body.poll_interval_seconds).toBe(3600);
- expect(body.poll_jitter_percent).toBe(DEFAULT_EXPERIMENT_POLL_JITTER_PERCENT);
- });
});
diff --git a/fluxer_api/src/api/guild/services/ThreadPermissionBits.test.ts b/fluxer_api/src/api/guild/services/ThreadPermissionBits.test.ts
index f6fccd4cf..5bd21337c 100644
--- a/fluxer_api/src/api/guild/services/ThreadPermissionBits.test.ts
+++ b/fluxer_api/src/api/guild/services/ThreadPermissionBits.test.ts
@@ -1,171 +1,11 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
-import {createGuildID, createUserID} from '@app/api/BrandedTypes';
-import {clearChannelThreadsTaintCacheForTesting, isTainted} from '@app/api/experiment/ChannelThreadsGate';
-import {createGuildMfaEnforcer} from '@app/api/guild/services/GuildMfaEnforcement';
-import {
- maskGuildResponseThreadBits,
- maskUserGuildsThreadBits,
- resolveProtectedBitActor,
- shouldMaskThreadPermissionBits,
-} from '@app/api/guild/services/ThreadPermissionBits';
-import type {UserRepository} from '@app/api/user/repositories/UserRepository';
-import {
- applyProtectedOverwriteBits,
- applyProtectedRolePermissions,
- type ProtectedBitActor,
- permissionWriteMask,
- protectedThreadBits,
-} from '@app/api/utils/featureUtils';
-import {computePermissionsDiff} from '@app/api/utils/PermissionUtils';
import {seedThreadOverwriteBits, seedThreadOverwriteValue} from '@app/api/worker/tasks/SeedThreadPermissions';
import {Permissions} from '@fluxer/constants/src/ChannelConstants';
-import {GuildMFALevel} from '@fluxer/constants/src/GuildConstants';
-import {
- DEFAULT_THREAD_PERMISSIONS,
- THREAD_AWARE_ALL_PERMISSIONS,
- THREAD_PERMISSIONS,
- ThreadPermissionFlags,
-} from '@fluxer/constants/src/ThreadPermissionUtils';
-import {MfaNotEnabledError} from '@fluxer/errors/src/domains/auth/MfaNotEnabledError';
-import type {GuildResponse} from '@fluxer/schema/src/domains/guild/GuildResponseSchemas';
+import {DEFAULT_THREAD_PERMISSIONS, ThreadPermissionFlags} from '@fluxer/constants/src/ThreadPermissionUtils';
import {describe, expect, it} from 'vitest';
-const NONE: ReadonlySet<string> = new Set();
-const CAPABLE: ReadonlySet<string> = new Set(['channel_threads']);
const MANAGE_THREADS = ThreadPermissionFlags.MANAGE_THREADS;
-const VCM = Permissions.VIEW_CHANNEL_MEMBERS;
-
-function actor(opts: {bot?: boolean; features?: ReadonlySet<string>} = {}): ProtectedBitActor {
- return {
- clientFeatures: opts.features ?? NONE,
- threadBits: {mode: 'active', writer: opts.bot === true || (opts.features ?? NONE).has('channel_threads')},
- };
-}
-
-describe('thread bits in the protected permission helper', () => {
- it('lets bots and capable active users write, and restores for everyone else', () => {
- const writers = [actor({bot: true}), actor({features: CAPABLE})];
- for (const writer of writers) {
- expect(permissionWriteMask(writer)).toBe(THREAD_AWARE_ALL_PERMISSIONS);
- expect(protectedThreadBits(writer)).toBe(0n);
- expect(applyProtectedRolePermissions(DEFAULT_THREAD_PERMISSIONS, MANAGE_THREADS, writer)).toBe(
- DEFAULT_THREAD_PERMISSIONS,
- );
- }
- const readers = [actor({})];
- for (const reader of readers) {
- expect(protectedThreadBits(reader)).toBe(THREAD_PERMISSIONS);
- expect(applyProtectedRolePermissions(DEFAULT_THREAD_PERMISSIONS, MANAGE_THREADS, reader)).toBe(MANAGE_THREADS);
- expect(
- applyProtectedOverwriteBits(
- {allow: DEFAULT_THREAD_PERMISSIONS, deny: 0n},
- {allow: 0n, deny: MANAGE_THREADS},
- reader,
- ),
- ).toEqual({allow: 0n, deny: MANAGE_THREADS});
- }
- });
-
- it('keeps VIEW_CHANNEL_MEMBERS header-gated for bots', () => {
- expect(applyProtectedRolePermissions(VCM | MANAGE_THREADS, 0n, actor({bot: true}))).toBe(MANAGE_THREADS);
- });
-});
-
-describe('thread bit writers', () => {
- it('allows bots and capable viewers while refusing incapable viewers', async () => {
- const guildId = createGuildID(10n);
- const writer = async (userId: bigint, bot: boolean, capable: boolean) =>
- (
- await resolveProtectedBitActor({
- guildId,
- userId: createUserID(userId),
- clientFeatures: CAPABLE,
- viewer: {kind: 'user', userId: createUserID(userId), bot, capable},
- isBot: async () => bot,
- })
- ).threadBits?.writer;
- expect(await writer(2n, false, true)).toBe(true);
- expect(await writer(2n, false, false)).toBe(false);
- expect(await writer(2n, true, true)).toBe(true);
- });
-
- it('taints a guild on its first protected-bit write', async () => {
- clearChannelThreadsTaintCacheForTesting();
- const guildId = createGuildID(11n);
-
- expect(await isTainted(guildId)).toBe(false);
- await resolveProtectedBitActor({
- guildId,
- userId: createUserID(2n),
- clientFeatures: NONE,
- isBot: async () => true,
- });
- clearChannelThreadsTaintCacheForTesting();
- expect(await isTainted(guildId)).toBe(true);
- });
-
- it('masks thread bits for non-viewers of an active guild while a clean taint read is still cached', async () => {
- clearChannelThreadsTaintCacheForTesting();
- const guildId = createGuildID(13n);
-
- expect(await isTainted(guildId)).toBe(false);
- const bits = [Permissions.SEND_MESSAGES | DEFAULT_THREAD_PERMISSIONS];
- const control = {kind: 'user', userId: createUserID(3n), bot: false, capable: false} as const;
- const member = {kind: 'user', userId: createUserID(2n), bot: false, capable: true} as const;
- expect(await shouldMaskThreadPermissionBits(guildId, control, bits)).toBe(true);
- expect(await shouldMaskThreadPermissionBits(guildId, member, bits)).toBe(false);
- expect(await shouldMaskThreadPermissionBits(createGuildID(14n), control, bits)).toBe(true);
- const guild = {id: '13', roles: [{id: '13', permissions: bits[0]!.toString()}]} as unknown as GuildResponse;
- expect((await maskGuildResponseThreadBits(guildId, control, guild)).roles?.[0]?.permissions).toBe(
- Permissions.SEND_MESSAGES.toString(),
- );
- expect(await maskGuildResponseThreadBits(guildId, member, guild)).toBe(guild);
- });
-
- it('masks the computed guild list permissions for non-viewers only', async () => {
- clearChannelThreadsTaintCacheForTesting();
-
- const bits = (Permissions.SEND_MESSAGES | DEFAULT_THREAD_PERMISSIONS).toString();
- const guilds = [
- {id: '15', permissions: bits},
- {id: '16', permissions: bits},
- {id: '17'},
- ] as unknown as Array<GuildResponse>;
- const control = {kind: 'user', userId: createUserID(3n), bot: false, capable: false} as const;
- const member = {kind: 'user', userId: createUserID(2n), bot: false, capable: true} as const;
- expect((await maskUserGuildsThreadBits(control, guilds)).map((guild) => guild.permissions)).toEqual([
- Permissions.SEND_MESSAGES.toString(),
- Permissions.SEND_MESSAGES.toString(),
- undefined,
- ]);
- expect(await maskUserGuildsThreadBits(member, guilds)).toEqual(guilds);
- });
-});
-
-describe('thread permission audit naming', () => {
- it('names thread bits only outside control guilds', () => {
- const before = Permissions.SEND_MESSAGES;
- const after = Permissions.SEND_MESSAGES | MANAGE_THREADS;
- expect(computePermissionsDiff(before, after)).toEqual({added: [], removed: []});
- expect(computePermissionsDiff(before, after, {threads: true})).toEqual({added: ['MANAGE_THREADS'], removed: []});
- });
-});
-
-describe('guild MFA enforcement', () => {
- it('treats MANAGE_THREADS as elevated', async () => {
- const userRepository = {
- findUnique: async () => ({authenticatorTypes: new Set()}),
- } as unknown as UserRepository;
- const enforce = await createGuildMfaEnforcer({
- userRepository,
- guildData: {mfa_level: GuildMFALevel.ELEVATED, owner_id: '1'},
- userId: createUserID(2n),
- });
- expect(() => enforce(MANAGE_THREADS)).toThrow(MfaNotEnabledError);
- expect(() => enforce(ThreadPermissionFlags.CREATE_PUBLIC_THREADS)).not.toThrow();
- });
-});
describe('thread permission seeding rules', () => {
it('clears raw thread bits on overwrites without mirroring SEND_MESSAGES', () => {
diff --git a/fluxer_api/src/api/guild/tests/DiscoveryApplicationValidation.test.ts b/fluxer_api/src/api/guild/tests/DiscoveryApplicationValidation.test.ts
index 709c21560..acd9aa39a 100644
--- a/fluxer_api/src/api/guild/tests/DiscoveryApplicationValidation.test.ts
+++ b/fluxer_api/src/api/guild/tests/DiscoveryApplicationValidation.test.ts
@@ -1,7 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
-import {createTestAccount, setUserACLs} from '@app/api/auth/tests/AuthTestUtils';
-import {createGuild, setupTestGuildWithMembers} from '@app/api/guild/tests/GuildTestUtils';
+import {setupTestGuildWithMembers} 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';
@@ -25,57 +24,6 @@ describe('Discovery Application Validation', () => {
afterEach(async () => {
await harness?.shutdown();
});
- describe('member count requirements', () => {
- test('should reject application with 0 members', async () => {
- const owner = await createTestAccount(harness);
- const guild = await createGuild(harness, owner.token, 'Empty Guild');
- await setGuildMemberCount(harness, guild.id, 0);
- await createBuilder(harness, owner.token)
- .post(`/guilds/${guild.id}/discovery`)
- .body({description: 'No members yet', category_type: DiscoveryCategories.GAMING})
- .expect(HTTP_STATUS.BAD_REQUEST, APIErrorCodes.DISCOVERY_INSUFFICIENT_MEMBERS)
- .execute();
- });
- });
- describe('duplicate application', () => {
- test('should reject duplicate application when pending', async () => {
- const owner = await createTestAccount(harness);
- const guild = await createGuild(harness, owner.token, 'Dupe Pending Guild');
- await setGuildMemberCount(harness, guild.id, 1);
- await createBuilder<DiscoveryApplicationResponse>(harness, owner.token)
- .post(`/guilds/${guild.id}/discovery`)
- .body({description: 'First application attempt', category_type: DiscoveryCategories.GAMING})
- .expect(HTTP_STATUS.OK)
- .execute();
- await createBuilder(harness, owner.token)
- .post(`/guilds/${guild.id}/discovery`)
- .body({description: 'Second application attempt', category_type: DiscoveryCategories.GAMING})
- .expect(HTTP_STATUS.CONFLICT, APIErrorCodes.DISCOVERY_ALREADY_APPLIED)
- .execute();
- });
- test('should reject duplicate application when approved', async () => {
- const owner = await createTestAccount(harness);
- const guild = await createGuild(harness, owner.token, 'Dupe Approved Guild');
- await setGuildMemberCount(harness, guild.id, 1);
- const admin = await createTestAccount(harness);
- await setUserACLs(harness, admin, ['admin:authenticate', 'discovery:review']);
- await createBuilder<DiscoveryApplicationResponse>(harness, owner.token)
- .post(`/guilds/${guild.id}/discovery`)
- .body({description: 'Application to be approved', category_type: DiscoveryCategories.GAMING})
- .expect(HTTP_STATUS.OK)
- .execute();
- await createBuilder(harness, `${admin.token}`)
- .patch(`/admin/discovery/applications/${guild.id}`)
- .body({status: 'approved'})
- .expect(HTTP_STATUS.OK)
- .execute();
- await createBuilder(harness, owner.token)
- .post(`/guilds/${guild.id}/discovery`)
- .body({description: 'Trying to reapply while approved', category_type: DiscoveryCategories.GAMING})
- .expect(HTTP_STATUS.CONFLICT, APIErrorCodes.DISCOVERY_ALREADY_APPLIED)
- .execute();
- });
- });
describe('permission requirements', () => {
test('should require MANAGE_GUILD permission to apply', async () => {
const {members, guild} = await setupTestGuildWithMembers(harness, 1);
@@ -125,28 +73,4 @@ describe('Discovery Application Validation', () => {
.execute();
});
});
- describe('edit restrictions', () => {
- test('should not allow editing rejected application', async () => {
- const owner = await createTestAccount(harness);
- const guild = await createGuild(harness, owner.token, 'Rejected Edit Guild');
- await setGuildMemberCount(harness, guild.id, 1);
- const admin = await createTestAccount(harness);
- await setUserACLs(harness, admin, ['admin:authenticate', 'discovery:review']);
- await createBuilder<DiscoveryApplicationResponse>(harness, owner.token)
- .post(`/guilds/${guild.id}/discovery`)
- .body({description: 'To be rejected for edit test', category_type: DiscoveryCategories.GAMING})
- .expect(HTTP_STATUS.OK)
- .execute();
- await createBuilder(harness, `${admin.token}`)
- .patch(`/admin/discovery/applications/${guild.id}`)
- .body({status: 'rejected', reason: 'Not suitable'})
- .expect(HTTP_STATUS.OK)
- .execute();
- await createBuilder(harness, owner.token)
- .patch(`/guilds/${guild.id}/discovery`)
- .body({description: 'Trying to edit rejected'})
- .expect(HTTP_STATUS.CONFLICT, APIErrorCodes.DISCOVERY_APPLICATION_ALREADY_REVIEWED)
- .execute();
- });
- });
});
diff --git a/fluxer_api/src/api/guild/tests/GuildAuditLogEntryMapper.test.ts b/fluxer_api/src/api/guild/tests/GuildAuditLogEntryMapper.test.ts
index 7723939dc..639ed12a6 100644
--- a/fluxer_api/src/api/guild/tests/GuildAuditLogEntryMapper.test.ts
+++ b/fluxer_api/src/api/guild/tests/GuildAuditLogEntryMapper.test.ts
@@ -3,10 +3,8 @@
import {createGuildID, createUserID} from '@app/api/BrandedTypes';
import {
collectGuildAuditLogUserIds,
- GUILD_AUDIT_INTERNAL_CHANGE_KEYS,
isNoopGuildAuditLog,
mapGuildAuditLogEntry,
- maskThreadAuditLog,
} from '@app/api/guild/GuildAuditLogEntryMapper';
import type {GuildAuditLogChange} from '@app/api/guild/GuildAuditLogTypes';
import {GuildAuditLog} from '@app/api/models/GuildAuditLog';
@@ -57,60 +55,7 @@ function makeLog(params: {
});
}
-function userIdStrings(log: GuildAuditLog): Array<string> {
- return collectGuildAuditLogUserIds(log).map((id) => id.toString());
-}
-
describe('mapGuildAuditLogEntry', () => {
- it('types every schema option and drops unknown keys', () => {
- const entry = mapGuildAuditLogEntry(
- makeLog({
- actionType: AuditLogActionType.INVITE_DELETE,
- options: {
- channel_id: OTHER_ID,
- count: '3',
- delete_member_days: '7',
- delete_message_seconds: '3600',
- id: TARGET_ID,
- integration_type: '1',
- message_id: OTHER_ID,
- members_removed: '4',
- role_name: 'Moderators',
- type: '1',
- inviter_id: ACTOR_ID,
- max_age: '86400',
- max_uses: '10',
- temporary: 'true',
- uses: '2',
- name: 'raw name',
- new_owner_id: OTHER_ID,
- vanity_url_code: 'fluxer',
- role_id: OTHER_ID,
- action: 'add',
- timeout_reason: 'raw reason',
- communication_disabled_until: '2026-09-13T00:00:00.000Z',
- },
- }),
- );
- expect(entry.options).toEqual({
- channel_id: OTHER_ID,
- count: 3,
- delete_member_days: '7',
- delete_message_seconds: 3600,
- id: TARGET_ID,
- integration_type: 1,
- message_id: OTHER_ID,
- members_removed: 4,
- role_name: 'Moderators',
- type: 1,
- inviter_id: ACTOR_ID,
- max_age: 86400,
- max_uses: 10,
- temporary: true,
- uses: 2,
- });
- });
-
it('maps the legacy delete_message_days key onto delete_member_days', () => {
const legacyOnly = mapGuildAuditLogEntry(
makeLog({actionType: AuditLogActionType.MEMBER_BAN_ADD, options: {delete_message_days: '2'}}),
@@ -132,16 +77,6 @@ describe('mapGuildAuditLogEntry', () => {
expect(currentFirst.options).toEqual({delete_member_days: '5'});
});
- it('drops numeric options that do not parse', () => {
- const entry = mapGuildAuditLogEntry(
- makeLog({
- actionType: AuditLogActionType.MEMBER_BAN_ADD,
- options: {count: 'many', delete_message_seconds: 'NaN'},
- }),
- );
- expect(entry.options).toBeUndefined();
- });
-
it('scrubs ip changes', () => {
const entry = mapGuildAuditLogEntry(
makeLog({
@@ -167,87 +102,6 @@ describe('mapGuildAuditLogEntry', () => {
expect(mapGuildAuditLogEntry(makeLog({actionType: AuditLogActionType.MEMBER_KICK})).changes).toBeUndefined();
});
- it('keeps an explicit reason trimmed', () => {
- const entry = mapGuildAuditLogEntry(
- makeLog({actionType: AuditLogActionType.MEMBER_KICK, targetId: TARGET_ID, reason: ' spam '}),
- );
- expect(entry.reason).toBe('spam');
- });
-
- it('returns undefined for a blank reason', () => {
- const entry = mapGuildAuditLogEntry(
- makeLog({actionType: AuditLogActionType.MEMBER_KICK, targetId: TARGET_ID, reason: ' '}),
- );
- expect(entry.reason).toBeUndefined();
- });
-
- it('falls back to the ban change reason', () => {
- const entry = mapGuildAuditLogEntry(
- makeLog({
- actionType: AuditLogActionType.MEMBER_BAN_ADD,
- targetId: TARGET_ID,
- changes: [{key: 'reason', new_value: 'body reason'}],
- }),
- );
- expect(entry.reason).toBe('body reason');
- });
-
- it('prefers the explicit reason over the ban change reason', () => {
- const entry = mapGuildAuditLogEntry(
- makeLog({
- actionType: AuditLogActionType.MEMBER_BAN_ADD,
- targetId: TARGET_ID,
- reason: 'header reason',
- changes: [{key: 'reason', new_value: 'body reason'}],
- }),
- );
- expect(entry.reason).toBe('header reason');
- });
-
- it('ignores a blank ban change reason', () => {
- const entry = mapGuildAuditLogEntry(
- makeLog({
- actionType: AuditLogActionType.MEMBER_BAN_ADD,
- targetId: TARGET_ID,
- reason: ' ',
- changes: [{key: 'reason', new_value: ' '}],
- }),
- );
- expect(entry.reason).toBeUndefined();
- });
-
- it('falls back to the timeout_reason option for member updates', () => {
- const entry = mapGuildAuditLogEntry(
- makeLog({
- actionType: AuditLogActionType.MEMBER_UPDATE,
- targetId: TARGET_ID,
- options: {timeout_reason: 'cool off', communication_disabled_until: '2026-09-13T00:00:00.000Z'},
- changes: [{key: 'communication_disabled_until', new_value: '2026-09-13T00:00:00.000Z'}],
- }),
- );
- expect(entry.reason).toBe('cool off');
- expect(entry.options).toBeUndefined();
- });
-
- it('ignores a blank timeout_reason option', () => {
- const entry = mapGuildAuditLogEntry(
- makeLog({actionType: AuditLogActionType.MEMBER_UPDATE, targetId: TARGET_ID, options: {timeout_reason: ' '}}),
- );
- expect(entry.reason).toBeUndefined();
- });
-
- it('never falls back for other actions', () => {
- const entry = mapGuildAuditLogEntry(
- makeLog({
- actionType: AuditLogActionType.MEMBER_KICK,
- targetId: TARGET_ID,
- options: {timeout_reason: 'cool off'},
- changes: [{key: 'reason', new_value: 'body reason'}],
- }),
- );
- expect(entry.reason).toBeUndefined();
- });
-
it.each(ALL_ACTIONS)('maps action %i without throwing', (actionType) => {
const log = makeLog({
actionType,
@@ -264,128 +118,13 @@ describe('mapGuildAuditLogEntry', () => {
});
});
-describe('collectGuildAuditLogUserIds', () => {
- it('skips values that are not snowflakes', () => {
- expect(userIdStrings(makeLog({actionType: AuditLogActionType.MEMBER_KICK, targetId: 'not-a-snowflake'}))).toEqual([
- ACTOR_ID,
- ]);
- expect(userIdStrings(makeLog({actionType: AuditLogActionType.MEMBER_KICK, targetId: '-1'}))).toEqual([ACTOR_ID]);
- expect(
- userIdStrings(makeLog({actionType: AuditLogActionType.MEMBER_KICK, targetId: '99999999999999999999'})),
- ).toEqual([ACTOR_ID]);
- const numericOwner = makeLog({
- actionType: AuditLogActionType.GUILD_UPDATE,
- changes: [{key: 'owner_id', new_value: 1420}],
- });
- expect(userIdStrings(numericOwner)).toEqual([ACTOR_ID]);
- const missingCreator = makeLog({
- actionType: AuditLogActionType.EMOJI_DELETE,
- changes: [{key: 'creator_id', old_value: null}],
- });
- expect(userIdStrings(missingCreator)).toEqual([ACTOR_ID]);
- });
-});
-
describe('isNoopGuildAuditLog', () => {
- it.each(SKIPPABLE_ACTIONS)('treats action %i with empty or null changes as a no-op', (actionType) => {
- expect(isNoopGuildAuditLog(actionType, [])).toBe(true);
- expect(isNoopGuildAuditLog(actionType, null)).toBe(true);
- expect(isNoopGuildAuditLog(actionType, undefined)).toBe(true);
- });
-
it.each(SKIPPABLE_ACTIONS)('treats action %i with only an ip change as a no-op', (actionType) => {
expect(isNoopGuildAuditLog(actionType, [{key: 'ip', new_value: '203.0.113.1'}])).toBe(true);
});
- it.each(SKIPPABLE_ACTIONS)('keeps action %i with a real change', (actionType) => {
- expect(isNoopGuildAuditLog(actionType, [{key: 'name', old_value: 'a', new_value: 'b'}])).toBe(false);
- });
-
- it.each([...GUILD_AUDIT_INTERNAL_CHANGE_KEYS])('treats a guild update of only %s as a no-op', (key) => {
- expect(isNoopGuildAuditLog(AuditLogActionType.GUILD_UPDATE, [{key, old_value: 1, new_value: 2}])).toBe(true);
- });
-
- it('treats a dimension-only guild update as a no-op', () => {
- expect(
- isNoopGuildAuditLog(AuditLogActionType.GUILD_UPDATE, [
- {key: 'banner_width', old_value: 960, new_value: 1920},
- {key: 'banner_height', old_value: 540, new_value: 1080},
- {key: 'ip', new_value: '203.0.113.1'},
- ]),
- ).toBe(true);
- });
-
- it('keeps a guild update that renames the guild', () => {
- expect(
- isNoopGuildAuditLog(AuditLogActionType.GUILD_UPDATE, [
- {key: 'banner_width', old_value: 960, new_value: 1920},
- {key: 'name', old_value: 'Old', new_value: 'New'},
- ]),
- ).toBe(false);
- });
-
- it('only ignores internal keys for guild updates', () => {
- expect(
- isNoopGuildAuditLog(AuditLogActionType.MEMBER_UPDATE, [{key: 'banner_width', old_value: 1, new_value: 2}]),
- ).toBe(false);
- });
-
- it('treats a member move without changes as a no-op but keeps a disconnect', () => {
- expect(isNoopGuildAuditLog(AuditLogActionType.MEMBER_MOVE, null)).toBe(true);
- expect(isNoopGuildAuditLog(AuditLogActionType.MEMBER_DISCONNECT, null)).toBe(false);
- });
-
it.each(RECORDED_ACTIONS)('never treats action %i as a no-op', (actionType) => {
expect(isNoopGuildAuditLog(actionType, [])).toBe(false);
expect(isNoopGuildAuditLog(actionType, null)).toBe(false);
});
});
-
-describe('maskThreadAuditLog', () => {
- const MANAGE_THREADS = 1n << 34n;
- const SEND = 1n << 11n;
-
- it('strips thread bits from overwrite allow and deny', () => {
- const log = makeLog({
- actionType: AuditLogActionType.CHANNEL_OVERWRITE_UPDATE,
- targetId: TARGET_ID,
- changes: [
- {key: 'allow', old_value: '0', new_value: (SEND | MANAGE_THREADS).toString()},
- {key: 'deny', old_value: '0', new_value: MANAGE_THREADS.toString()},
- ],
- });
- expect(maskThreadAuditLog(log).changes).toEqual([{key: 'allow', old_value: '0', new_value: SEND.toString()}]);
- });
-
- it('drops thread-only role changes and thread names from the permissions diff', () => {
- const log = makeLog({
- actionType: AuditLogActionType.ROLE_UPDATE,
- targetId: TARGET_ID,
- changes: [
- {key: 'permissions', old_value: (SEND | MANAGE_THREADS).toString(), new_value: SEND.toString()},
- {key: 'permissions_diff', new_value: {added: [], removed: ['MANAGE_THREADS']}},
- ],
- });
- const masked = maskThreadAuditLog(log);
- expect(masked.changes).toBeNull();
- expect(isNoopGuildAuditLog(masked.actionType, masked.changes)).toBe(true);
- });
-
- it('drops thread surface keys from channel changes and leaves other entries untouched', () => {
- const channelLog = makeLog({
- actionType: AuditLogActionType.CHANNEL_UPDATE,
- targetId: TARGET_ID,
- changes: [
- {key: 'name', old_value: 'a', new_value: 'b'},
- {key: 'default_auto_archive_duration', old_value: 60, new_value: 1440},
- ],
- });
- expect(maskThreadAuditLog(channelLog).changes).toEqual([{key: 'name', old_value: 'a', new_value: 'b'}]);
- const memberLog = makeLog({
- actionType: AuditLogActionType.MEMBER_UPDATE,
- targetId: TARGET_ID,
- changes: [{key: 'flags', old_value: 0, new_value: 1}],
- });
- expect(maskThreadAuditLog(memberLog)).toBe(memberLog);
- });
-});
diff --git a/fluxer_api/src/api/guild/tests/GuildAuditLogService.test.ts b/fluxer_api/src/api/guild/tests/GuildAuditLogService.test.ts
index 559743ba4..9ad444a32 100644
--- a/fluxer_api/src/api/guild/tests/GuildAuditLogService.test.ts
+++ b/fluxer_api/src/api/guild/tests/GuildAuditLogService.test.ts
@@ -8,104 +8,49 @@ import {
type RoleID,
type UserID,
} from '@app/api/BrandedTypes';
-import type {GuildAuditLogRow} from '@app/api/database/types/GuildTypes';
-import {mapGuildAuditLogEntry} from '@app/api/guild/GuildAuditLogEntryMapper';
import {GuildAuditLogService} from '@app/api/guild/GuildAuditLogService';
-import type {GuildRepository} from '@app/api/guild/repositories/GuildRepository';
-import type {IGatewayService} from '@app/api/infrastructure/IGatewayService';
-import type {ISnowflakeService} from '@app/api/infrastructure/ISnowflakeService';
-import {ChannelPermissionOverwrite} from '@app/api/models/ChannelPermissionOverwrite';
-import {GuildAuditLog} from '@app/api/models/GuildAuditLog';
-import type {GuildRole} from '@app/api/models/GuildRole';
-import type {WorkerTaskName} from '@app/api/worker/WorkerLaneConfig';
+import {GuildRepository} from '@app/api/guild/repositories/GuildRepository';
+import {getSnowflakeService} from '@app/api/middleware/ServiceRegistry';
+import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
+import {NoopGatewayService} from '@app/api/test/NoopGatewayService';
+import {RecordingWorkerService} from '@app/api/test/RecordingWorkerService';
import {AuditLogActionType} from '@fluxer/constants/src/AuditLogActionType';
-import type {IWorkerService} from '@pkgs/worker/src/contracts/IWorkerService';
-import {describe, expect, it, vi} from 'vitest';
+import {afterEach, assert, beforeEach, describe, expect, it, vi} from 'vitest';
const GUILD_ID = createGuildID(1420000000000000000n);
const ACTOR_ID = createUserID(1420000000000000001n);
const MEMBER_ID = createUserID(1420000000000000002n);
-const ROLE_ID = createRoleID(1420000000000000003n);
-const CHANNEL_ID = createChannelID(1420000000000000004n);
-function createService(roleNames: Map<string, string> = new Map()) {
- let nextLogId = 1420000000000001000n;
- const createAuditLog = vi.fn(async (row: GuildAuditLogRow) => new GuildAuditLog(row));
- const batchDeleteAndCreateAuditLogs = vi.fn(
- async (_guildId: unknown, _logs: Array<GuildAuditLog>, row: GuildAuditLogRow) => new GuildAuditLog(row),
- );
- const getRole = vi.fn(async (roleId: RoleID) => {
- const name = roleNames.get(roleId.toString());
- return name === undefined ? null : ({id: roleId, name} as unknown as GuildRole);
- });
- const dispatchGuild = vi.fn().mockResolvedValue(undefined);
- const addJob = vi.fn().mockResolvedValue(undefined);
- const service = new GuildAuditLogService(
- {createAuditLog, batchDeleteAndCreateAuditLogs, getRole} as unknown as GuildRepository,
- {generate: vi.fn(async () => nextLogId++)} as unknown as ISnowflakeService,
- {addJob} as unknown as IWorkerService<WorkerTaskName>,
- {dispatchGuild} as unknown as IGatewayService,
- );
- return {service, createAuditLog, batchDeleteAndCreateAuditLogs, getRole, dispatchGuild, addJob};
-}
+type GuildDispatch = Parameters<NoopGatewayService['dispatchGuild']>[0];
-function overwrites(
- entries: Array<[RoleID | UserID, {type: number; allow: bigint; deny: bigint}]>,
-): Map<RoleID | UserID, ChannelPermissionOverwrite> {
- return new Map(
- entries.map(([id, overwrite]) => [
- id,
- new ChannelPermissionOverwrite({type: overwrite.type, allow_: overwrite.allow, deny_: overwrite.deny}),
- ]),
- );
-}
+class RecordingGateway extends NoopGatewayService {
+ readonly dispatches: Array<GuildDispatch> = [];
-function writtenRow(createAuditLog: ReturnType<typeof createService>['createAuditLog'], index = 0): GuildAuditLogRow {
- const call = createAuditLog.mock.calls[index];
- if (!call) {
- throw new Error(`expected audit log write ${index}`);
+ override async dispatchGuild(params: GuildDispatch): Promise<void> {
+ this.dispatches.push(params);
}
- return call[0];
}
-function writtenOptions(row: GuildAuditLogRow): Record<string, string> {
- return Object.fromEntries(row.options ?? []);
-}
+describe('Guild audit log service', () => {
+ let harness: ApiTestHarness;
+ let repository: GuildRepository;
+ let gateway: RecordingGateway;
+ let worker: RecordingWorkerService;
+ let service: GuildAuditLogService;
-describe('GuildAuditLogService dispatch', () => {
- it('dispatches the REST entry shape plus guild_id for an invite', async () => {
- const {service, dispatchGuild} = createService();
- const log = await service
- .createBuilder(GUILD_ID, ACTOR_ID)
- .withAction(AuditLogActionType.INVITE_CREATE, 'abcdef')
- .withMetadata({
- max_uses: '0',
- max_age: '604800',
- temporary: 'false',
- channel_id: CHANNEL_ID.toString(),
- inviter_id: ACTOR_ID.toString(),
- })
- .withChanges(service.computeChanges(null, {code: 'abcdef', uses: 0}))
- .commit();
- expect(log).not.toBeNull();
- expect(dispatchGuild).toHaveBeenCalledTimes(1);
- expect(dispatchGuild).toHaveBeenCalledWith({
- guildId: GUILD_ID,
- event: 'GUILD_AUDIT_LOG_ENTRY_CREATE',
- data: {...mapGuildAuditLogEntry(log!), guild_id: GUILD_ID.toString()},
- });
- const data = dispatchGuild.mock.calls[0]![0].data;
- expect(data.options).toEqual({
- max_uses: 0,
- max_age: 604800,
- temporary: false,
- channel_id: CHANNEL_ID.toString(),
- inviter_id: ACTOR_ID.toString(),
- });
+ beforeEach(async () => {
+ harness = await createApiTestHarness();
+ repository = new GuildRepository();
+ gateway = new RecordingGateway();
+ worker = new RecordingWorkerService();
+ service = new GuildAuditLogService(repository, getSnowflakeService(), worker, gateway);
+ });
+
+ afterEach(async () => {
+ await harness?.shutdown();
});
it('dispatches the resolved reason for a legacy ban row', async () => {
- const {service, dispatchGuild} = createService();
const log = await service
.createBuilder(GUILD_ID, ACTOR_ID)
.withAction(AuditLogActionType.MEMBER_BAN_ADD, MEMBER_ID.toString())
@@ -115,90 +60,37 @@ describe('GuildAuditLogService dispatch', () => {
{key: 'reason', new_value: 'spam'},
])
.commit();
- const data = dispatchGuild.mock.calls[0]![0].data;
- expect(data).toEqual({...mapGuildAuditLogEntry(log!), guild_id: GUILD_ID.toString()});
- expect(data.reason).toBe('spam');
- expect(data.options).toEqual({delete_member_days: '0'});
+ assert(log !== null);
+ expect(gateway.dispatches).toEqual([
+ {
+ guildId: GUILD_ID,
+ event: 'GUILD_AUDIT_LOG_ENTRY_CREATE',
+ data: {
+ id: log.logId.toString(),
+ action_type: AuditLogActionType.MEMBER_BAN_ADD,
+ user_id: ACTOR_ID.toString(),
+ target_id: MEMBER_ID.toString(),
+ reason: 'spam',
+ options: {delete_member_days: '0'},
+ changes: [
+ {key: 'user_id', new_value: MEMBER_ID.toString()},
+ {key: 'reason', new_value: 'spam'},
+ ],
+ guild_id: GUILD_ID.toString(),
+ },
+ },
+ ]);
});
- it('does not dispatch raw timeout options', async () => {
- const {service, dispatchGuild} = createService();
+ it('dispatches the timeout reason without raw timeout options', async () => {
await service
.createBuilder(GUILD_ID, ACTOR_ID)
.withAction(AuditLogActionType.MEMBER_UPDATE, MEMBER_ID.toString())
.withMetadata({timeout_reason: 'cool off', communication_disabled_until: '2026-09-13T00:00:00.000Z'})
.withChanges([{key: 'communication_disabled_until', new_value: '2026-09-13T00:00:00.000Z'}])
.commit();
- const data = dispatchGuild.mock.calls[0]![0].data;
- expect(data.options).toBeUndefined();
- expect(data.reason).toBe('cool off');
- });
-
- it('dispatches a batched bulk delete with a numeric count', async () => {
- const {service, dispatchGuild, batchDeleteAndCreateAuditLogs} = createService();
- const logs = [1420000000000000200n, 1420000000000000199n].map(
- (logId) =>
- new GuildAuditLog({
- guild_id: GUILD_ID,
- log_id: logId,
- user_id: ACTOR_ID,
- target_id: null,
- action_type: AuditLogActionType.MESSAGE_DELETE,
- reason: null,
- options: new Map([['channel_id', CHANNEL_ID.toString()]]),
- changes: null,
- }),
- );
- const result = await service.batchConsecutiveMessageDeleteLogs(GUILD_ID, logs);
- expect(batchDeleteAndCreateAuditLogs).toHaveBeenCalledTimes(1);
- expect(result.createdLogs).toHaveLength(1);
- expect(dispatchGuild).toHaveBeenCalledTimes(1);
- const data = dispatchGuild.mock.calls[0]![0].data;
- expect(data.action_type).toBe(AuditLogActionType.MESSAGE_BULK_DELETE);
- expect(data.guild_id).toBe(GUILD_ID.toString());
- expect(data.options).toEqual({channel_id: CHANNEL_ID.toString(), count: 2});
- });
-});
-
-describe('GuildAuditLogService.recordPermissionOverwriteDiff', () => {
- it('records the entry without role_name when the role lookup fails', async () => {
- const {service, createAuditLog, getRole} = createService(new Map([[ROLE_ID.toString(), 'Moderators']]));
- getRole.mockRejectedValueOnce(new Error('no host available'));
- await service.recordPermissionOverwriteDiff({
- guildId: GUILD_ID,
- userId: ACTOR_ID,
- channelId: CHANNEL_ID,
- previous: null,
- next: overwrites([[ROLE_ID, {type: 0, allow: 1024n, deny: 0n}]]),
- });
- expect(createAuditLog).toHaveBeenCalledTimes(1);
- expect(writtenOptions(writtenRow(createAuditLog))).toEqual({
- id: ROLE_ID.toString(),
- type: '0',
- channel_id: CHANNEL_ID.toString(),
- });
- });
-});
-
-describe('GuildAuditLogService.scheduleMessageDeleteBatchJob', () => {
- it('gives every delete in one 30 second window a single batch job that runs after the window closes, without a ledger row', async () => {
- vi.useFakeTimers({toFake: ['Date']});
- try {
- const {service, addJob} = createService();
- for (const at of ['2026-09-21T12:00:00.000Z', '2026-09-21T12:00:29.999Z', '2026-09-21T12:00:40.000Z']) {
- vi.setSystemTime(new Date(at));
- await service.scheduleMessageDeleteBatchJob(GUILD_ID);
- }
- const options = addJob.mock.calls.map((call) => call[2] as {jobKey: string; runAt: Date; skipLedger: boolean});
- expect(options.every((option) => option.skipLedger)).toBe(true);
- expect(options[0]!.jobKey).toBe(options[1]!.jobKey);
- expect(options[2]!.jobKey).not.toBe(options[1]!.jobKey);
- expect(options[0]!.runAt.getTime()).toBeGreaterThan(new Date('2026-09-21T12:00:29.999Z').getTime());
- expect(options[1]!.runAt).toEqual(options[0]!.runAt);
- expect(options[2]!.runAt).toEqual(new Date('2026-09-21T12:01:30.000Z'));
- expect(options[2]!.runAt.getTime() - options[0]!.runAt.getTime()).toBe(30_000);
- } finally {
- vi.useRealTimers();
- }
+ expect(gateway.dispatches.map(({data}) => data)).toEqual([
+ expect.objectContaining({options: undefined, reason: 'cool off'}),
+ ]);
});
});
diff --git a/fluxer_api/src/api/guild/tests/GuildDeletionJob.test.ts b/fluxer_api/src/api/guild/tests/GuildDeletionJob.test.ts
index 56c9a4bc9..ce3c4072a 100644
--- a/fluxer_api/src/api/guild/tests/GuildDeletionJob.test.ts
+++ b/fluxer_api/src/api/guild/tests/GuildDeletionJob.test.ts
@@ -1,8 +1,7 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
-import {createTestAccount, setUserACLs, type TestAccount} from '@app/api/auth/tests/AuthTestUtils';
-import {createGuildID, createUserID, type GuildID} from '@app/api/BrandedTypes';
-import {createTestGuildStack} from '@app/api/channel/tests/CrosspostTestUtils';
+import {createTestAccount, type TestAccount} from '@app/api/auth/tests/AuthTestUtils';
+import {createGuildID} from '@app/api/BrandedTypes';
import {processRecordedGuildDeletions, recordGuildDeletions} from '@app/api/guild/tests/GuildDeletionTestUtils';
import {acceptInvite, createChannelInvite, createGuild, getChannel} from '@app/api/guild/tests/GuildTestUtils';
import {getGuildRepository} from '@app/api/middleware/ServiceSingletons';
@@ -11,7 +10,6 @@ import {NoopGatewayService} from '@app/api/test/NoopGatewayService';
import type {RecordingWorkerService} from '@app/api/test/RecordingWorkerService';
import {HTTP_STATUS} from '@app/api/test/TestConstants';
import {createBuilder} from '@app/api/test/TestRequestBuilder';
-import {GuildFeatures} from '@fluxer/constants/src/GuildConstants';
import type {GuildResponse} from '@fluxer/schema/src/domains/guild/GuildResponseSchemas';
import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, test, vi} from 'vitest';
@@ -58,42 +56,6 @@ describe('Guild deletion job', () => {
return getGuildRepository().findUnique(createGuildID(BigInt(guildId)));
}
- test('the request hides the guild and leaves the purge to the worker', async () => {
- const {owner, member, guild} = await guildWithMember();
- const dispatched = vi.spyOn(NoopGatewayService.prototype, 'dispatchGuild');
- const leaves = vi.spyOn(NoopGatewayService.prototype, 'leaveGuild');
- await deleteAsOwner(owner, guild.id);
- const jobs = worker.byTask('guildProcessDeletion');
- expect(jobs).toHaveLength(1);
- expect(jobs[0]?.payload).toEqual({guildId: guild.id, copyMode: 'source_deleted'});
- expect(jobs[0]?.options?.jobKey).toBe(`guild-deletion-${guild.id}`);
- expect(dispatched).toHaveBeenCalledWith(expect.objectContaining({event: 'GUILD_DELETE'}));
- expect(leaves).not.toHaveBeenCalled();
- const pending = await storedGuild(guild.id);
- expect(pending?.features.has(GuildFeatures.UNAVAILABLE_FOR_EVERYONE)).toBe(true);
- expect(pending?.features.has(GuildFeatures.UNAVAILABLE_HIDDEN)).toBe(true);
- await createBuilder(harness, member.token).get(`/guilds/${guild.id}`).expect(HTTP_STATUS.FORBIDDEN).execute();
- await processRecordedGuildDeletions(worker);
- expect(await storedGuild(guild.id)).toBeNull();
- await createBuilder(harness, owner.token).get(`/guilds/${guild.id}`).expect(HTTP_STATUS.NOT_FOUND).execute();
- });
-
- test('an admin deletion enqueues a purge job', async () => {
- const admin = await createTestAccount(harness);
- await setUserACLs(harness, admin, ['admin:authenticate', 'guild:lookup', 'guild:delete']);
- const guild = await createGuild(harness, admin.token, 'Admin Deletion Guild');
- await createBuilder(harness, admin.token)
- .delete(`/admin/guilds/${guild.id}`)
- .body({basis: {type: 'holder_request'}})
- .expect(HTTP_STATUS.OK)
- .execute();
- expect(worker.byTask('guildProcessDeletion').map((job) => job.payload)).toEqual([
- {guildId: guild.id, copyMode: 'purge'},
- ]);
- await processRecordedGuildDeletions(worker);
- expect(await storedGuild(guild.id)).toBeNull();
- });
-
test('a purge interrupted by a gateway failure completes when retried', async () => {
const {owner, guild} = await guildWithMember();
await deleteAsOwner(owner, guild.id);
@@ -111,29 +73,4 @@ describe('Guild deletion job', () => {
await processRecordedGuildDeletions(worker);
expect(failing).toHaveBeenCalled();
});
-
- test('member teardown runs with bounded concurrency', async () => {
- const {owner, guild} = await guildWithMember();
- await deleteAsOwner(owner, guild.id);
- const guildId: GuildID = createGuildID(BigInt(guild.id));
- const repository = getGuildRepository();
- const realMembers = await repository.listMembers(guildId);
- const extraMembers = Array.from({length: 120}, (_, index) => ({
- ...realMembers[0]!,
- userId: createUserID(BigInt(realMembers[0]!.userId) + BigInt(index + 1)),
- }));
- vi.spyOn(Object.getPrototypeOf(repository), 'listMembers').mockResolvedValueOnce([...realMembers, ...extraMembers]);
- let inFlight = 0;
- let peak = 0;
- vi.spyOn(NoopGatewayService.prototype, 'leaveGuild').mockImplementation(async () => {
- inFlight += 1;
- peak = Math.max(peak, inFlight);
- await new Promise((resolve) => setTimeout(resolve, 1));
- inFlight -= 1;
- });
- await createTestGuildStack().guildService.data.operations.purgeGuild(guildId, 'source_deleted');
- expect(peak).toBeGreaterThan(1);
- expect(peak).toBeLessThanOrEqual(25);
- expect(await storedGuild(guild.id)).toBeNull();
- });
});
diff --git a/fluxer_api/src/api/guild/tests/GuildTemplateImport.test.ts b/fluxer_api/src/api/guild/tests/GuildTemplateImport.test.ts
index 673e3404a..7192d9559 100644
--- a/fluxer_api/src/api/guild/tests/GuildTemplateImport.test.ts
+++ b/fluxer_api/src/api/guild/tests/GuildTemplateImport.test.ts
@@ -1,16 +1,12 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import {createTestAccount} from '@app/api/auth/tests/AuthTestUtils';
-import {createGuildID} from '@app/api/BrandedTypes';
-import {fetchMany} from '@app/api/database/CassandraQueryExecution';
import {getGuildChannels, getRoles} from '@app/api/guild/tests/GuildTestUtils';
-import {ChannelsByGuild, ThreadOnlyChannelsByGuild} from '@app/api/Tables';
import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
import {createBuilder} from '@app/api/test/TestRequestBuilder';
import {ChannelTypes, Permissions} from '@fluxer/constants/src/ChannelConstants';
import {SystemChannelFlags} from '@fluxer/constants/src/GuildConstants';
-import {CHANNEL_TOPIC_MAX_LENGTH, VOICE_CHANNEL_USER_LIMIT_MAX} from '@fluxer/constants/src/LimitConstants';
-import {ChannelFlags, ForumLayoutTypes, ForumSortOrderTypes} from '@fluxer/constants/src/ThreadConstants';
+import {VOICE_CHANNEL_USER_LIMIT_MAX} from '@fluxer/constants/src/LimitConstants';
import type {ChannelResponse} from '@fluxer/schema/src/domains/channel/ChannelSchemas';
import type {GuildResponse} from '@fluxer/schema/src/domains/guild/GuildResponseSchemas';
import {afterAll, beforeAll, beforeEach, describe, expect, test} from 'vitest';
@@ -206,80 +202,6 @@ describe('Guild Template Import', () => {
expect(channels.find((channel) => channel.name === 'directory')).toBeUndefined();
expect(guild.system_channel_id).toBe(announcementsChannel?.id ?? null);
});
- test('accepts template roles and channels with empty names', async () => {
- const account = await createTestAccount(harness);
- const guild = await createBuilder<GuildResponse>(harness, account.token)
- .post('/guilds')
- .body({
- name: 'Empty Names Guild',
- template: {
- name: 'Template Source',
- description: null,
- verification_level: 0,
- default_message_notifications: 0,
- explicit_content_filter: 0,
- system_channel_id: 5001,
- afk_timeout: 300,
- system_channel_flags: 0,
- roles: [
- {id: 0, name: '@everyone', permissions: DEFAULT_EVERYONE_PERMISSIONS},
- {id: 5100, name: '', permissions: DEFAULT_EVERYONE_PERMISSIONS},
- ],
- channels: [
- {id: 5001, type: ChannelTypes.GUILD_TEXT, name: 'general', position: 0},
- {id: 5002, type: ChannelTypes.GUILD_TEXT, name: '', position: 1},
- ],
- },
- })
- .execute();
- const roles = await getRoles(harness, account.token, guild.id);
- const channels = await getGuildChannels(harness, account.token, guild.id);
- expect(roles.some((role) => role.name === '')).toBe(true);
- expect(channels.some((channel) => channel.name === '')).toBe(true);
- });
- test.each([
- ['a negative slowmode', {rate_limit_per_user: -1}],
- ['a slowmode above the channel maximum', {rate_limit_per_user: 1_000_000_000}],
- ['a fractional position', {position: 0.5}],
- ['a negative position', {position: -3}],
- ['a topic above the template maximum', {topic: 'x'.repeat(4097)}],
- ['a name above the channel maximum', {name: 'x'.repeat(101)}],
- ['a negative user limit', {type: ChannelTypes.GUILD_VOICE, user_limit: -1}],
- ['a voice connection limit above the maximum', {type: ChannelTypes.GUILD_VOICE, voice_connection_limit: 100_000}],
- ['a negative voice connection limit', {type: ChannelTypes.GUILD_VOICE, voice_connection_limit: -5}],
- ])('rejects a template channel with %s', async (_label, overrides) => {
- const account = await createTestAccount(harness);
- await createBuilder(harness, account.token)
- .post('/guilds')
- .body({
- name: 'Bounded Guild',
- template: buildMinimalTemplate({
- channels: [{id: 6001, type: ChannelTypes.GUILD_TEXT, name: 'general', position: 0, ...overrides}],
- }),
- })
- .expect(400, 'INVALID_FORM_BODY')
- .execute();
- });
- test.each([
- ['a negative colour', {color: -1}],
- ['a colour above 0xffffff', {color: 0x1000000}],
- ['a name above the role maximum', {name: 'x'.repeat(101)}],
- ])('rejects a template role with %s', async (_label, overrides) => {
- const account = await createTestAccount(harness);
- await createBuilder(harness, account.token)
- .post('/guilds')
- .body({
- name: 'Bounded Guild',
- template: buildMinimalTemplate({
- roles: [
- {id: 0, name: '@everyone', permissions: DEFAULT_EVERYONE_PERMISSIONS},
- {id: 6100, name: 'Role', permissions: '0', ...overrides},
- ],
- }),
- })
- .expect(400, 'INVALID_FORM_BODY')
- .execute();
- });
test('clamps imported voice user limits to the channel maximum and keeps channels readable', async () => {
const account = await createTestAccount(harness);
const guild = await createBuilder<GuildResponse>(harness, account.token)
@@ -300,138 +222,6 @@ describe('Guild Template Import', () => {
expect(channels.find((channel) => channel.name === 'town-hall')?.user_limit).toBe(VOICE_CHANNEL_USER_LIMIT_MAX);
expect(channels.find((channel) => channel.name === 'lounge')?.voice_connection_limit).toBe(100);
});
- test('accepts forum-length topics and shortens them only for non-forum channels', async () => {
- const account = await createTestAccount(harness);
- const longTopic = `${'a'.repeat(CHANNEL_TOPIC_MAX_LENGTH - 1)}\u{1F600}${'b'.repeat(300)}`;
- const guild = await createBuilder<GuildResponse>(harness, account.token)
- .post('/guilds')
- .body({
- name: 'Forum Guild',
- template: buildMinimalTemplate({
- channels: [
- {id: 6001, type: ChannelTypes.GUILD_TEXT, name: 'general', position: 0, topic: longTopic},
- {id: 6002, type: 15, name: 'projects', position: 1, topic: 'c'.repeat(1356)},
- ],
- }),
- })
- .execute();
- const channels = await listThreadAwareChannels(account.token, guild.id);
- const general = channels.find((channel) => channel.name === 'general');
- expect(general?.topic).toBe('a'.repeat(CHANNEL_TOPIC_MAX_LENGTH - 1));
- expect(channels.find((channel) => channel.name === 'projects')?.topic).toBe('c'.repeat(1356));
- });
- test('imports forum settings and drops values that cannot carry over', async () => {
- const account = await createTestAccount(harness);
- const guild = await createBuilder<GuildResponse>(harness, account.token)
- .post('/guilds')
- .body({
- name: 'Forum Settings Guild',
- template: buildMinimalTemplate({
- channels: [
- {id: 6001, type: ChannelTypes.GUILD_TEXT, name: 'general', position: 0},
- {
- id: 6002,
- type: ChannelTypes.GUILD_FORUM,
- name: 'support',
- position: 1,
- topic: 'Be kind',
- available_tags: [
- {id: 111, name: 'bug', moderated: false, emoji_id: null, emoji_name: '\u{1F41B}'},
- {id: 112, name: 'custom', moderated: false, emoji_id: '123456789', emoji_name: null},
- {id: 113, name: 'bug', moderated: true, emoji_id: null, emoji_name: null},
- {id: 114, name: 'staff', moderated: true, emoji_id: null, emoji_name: 'not-an-emoji'},
- ],
- default_reaction_emoji: {emoji_id: '987654321', emoji_name: null},
- default_sort_order: ForumSortOrderTypes.CREATION_TIME,
- default_forum_layout: ForumLayoutTypes.GRID,
- default_tag_setting: 'match_all',
- default_thread_rate_limit_per_user: 60,
- default_auto_archive_duration: 1440,
- flags: ChannelFlags.REQUIRE_TAG | ChannelFlags.HIDE_MEDIA_DOWNLOAD_OPTIONS,
- },
- {
- id: 6003,
- type: ChannelTypes.GUILD_MEDIA,
- name: 'gallery',
- position: 2,
- available_tags: Array.from({length: 25}, (_, index) => ({name: `tag-${index}`})),
- default_reaction_emoji: {emoji_id: null, emoji_name: '\u{1F525}'},
- default_forum_layout: ForumLayoutTypes.LIST,
- default_sort_order: 7,
- flags: ChannelFlags.HIDE_MEDIA_DOWNLOAD_OPTIONS,
- },
- {
- id: 6004,
- type: ChannelTypes.GUILD_FORUM,
- name: 'announcements-forum',
- position: 3,
- available_tags: [{name: 'staff', moderated: true}],
- flags: ChannelFlags.REQUIRE_TAG,
- },
- ],
- }),
- })
- .execute();
- const channels = await listThreadAwareChannels(account.token, guild.id);
- const forum = await getThreadAwareChannel(account.token, findChannelId(channels, 'support'));
- expect(forum.type).toBe(ChannelTypes.GUILD_FORUM);
- expect(forum.topic).toBe('Be kind');
- expect(
- forum.available_tags?.map(({name, moderated, emoji_id, emoji_name}) => ({name, moderated, emoji_id, emoji_name})),
- ).toEqual([
- {name: 'bug', moderated: false, emoji_id: null, emoji_name: '\u{1F41B}'},
- {name: 'custom', moderated: false, emoji_id: null, emoji_name: null},
- {name: 'staff', moderated: true, emoji_id: null, emoji_name: null},
- ]);
- expect(new Set(forum.available_tags?.map((tag) => tag.id)).size).toBe(3);
- expect(forum.available_tags?.some((tag) => ['111', '112', '113', '114'].includes(tag.id))).toBe(false);
- expect(forum.default_reaction_emoji).toBeNull();
- expect(forum.default_sort_order).toBe(ForumSortOrderTypes.CREATION_TIME);
- expect(forum.default_forum_layout).toBe(ForumLayoutTypes.GRID);
- expect(forum.default_tag_setting).toBe('match_all');
- expect(forum.default_thread_rate_limit_per_user).toBe(60);
- expect(forum.default_auto_archive_duration).toBe(1440);
- expect(forum.flags).toBe(ChannelFlags.REQUIRE_TAG);
- const media = await getThreadAwareChannel(account.token, findChannelId(channels, 'gallery'));
- expect(media.type).toBe(ChannelTypes.GUILD_MEDIA);
- expect(media.available_tags).toHaveLength(20);
- expect(media.default_reaction_emoji).toEqual({emoji_id: null, emoji_name: '\u{1F525}'});
- expect(media.default_forum_layout).toBeUndefined();
- expect(media.default_sort_order).toBeNull();
- expect(media.flags).toBe(ChannelFlags.HIDE_MEDIA_DOWNLOAD_OPTIONS);
- const moderatedOnly = await getThreadAwareChannel(account.token, findChannelId(channels, 'announcements-forum'));
- expect(moderatedOnly.flags).toBe(0);
- });
- test('indexes imported forum and media channels as thread-only channels', async () => {
- const account = await createTestAccount(harness);
- const guild = await createBuilder<GuildResponse>(harness, account.token)
- .post('/guilds')
- .body({
- name: 'Index Guild',
- template: buildMinimalTemplate({
- channels: [
- {id: 6001, type: ChannelTypes.GUILD_TEXT, name: 'general', position: 0},
- {id: 6002, type: ChannelTypes.GUILD_FORUM, name: 'forum', position: 1},
- {id: 6003, type: ChannelTypes.GUILD_MEDIA, name: 'media', position: 2},
- ],
- }),
- })
- .execute();
- const channels = await listThreadAwareChannels(account.token, guild.id);
- const threadOnlyIds = [findChannelId(channels, 'forum'), findChannelId(channels, 'media')];
- const guildId = createGuildID(BigInt(guild.id));
- const threadOnlyRows = await fetchMany<{channel_id: bigint}>(
- ThreadOnlyChannelsByGuild.selectCql({where: ThreadOnlyChannelsByGuild.where.eq('guild_id')}),
- {guild_id: guildId},
- );
- const regularRows = await fetchMany<{channel_id: bigint}>(
- ChannelsByGuild.selectCql({where: ChannelsByGuild.where.eq('guild_id')}),
- {guild_id: guildId},
- );
- expect(threadOnlyRows.map((row) => row.channel_id.toString()).sort()).toEqual([...threadOnlyIds].sort());
- expect(regularRows.some((row) => threadOnlyIds.includes(row.channel_id.toString()))).toBe(false);
- expect(regularRows.some((row) => row.channel_id.toString() === findChannelId(channels, 'general'))).toBe(true);
- });
test('accepts channels shaped like a full template export', async () => {
const account = await createTestAccount(harness);
const exported = {
@@ -490,24 +280,6 @@ describe('Guild Template Import', () => {
expect(channels.find((channel) => channel.name === 'ideas')?.parent_id).toBe(category?.id ?? null);
expect(guild.system_channel_id).toBe(rules?.id ?? null);
});
- test('hides imported forum channels from viewers outside the threads experiment', async () => {
- const account = await createTestAccount(harness);
- const guild = await createBuilder<GuildResponse>(harness, account.token)
- .post('/guilds')
- .body({
- name: 'Hidden Forum Guild',
- template: buildMinimalTemplate({
- channels: [
- {id: 6001, type: ChannelTypes.GUILD_TEXT, name: 'general', position: 0},
- {id: 6002, type: ChannelTypes.GUILD_FORUM, name: 'forum', position: 1},
- ],
- }),
- })
- .execute();
- const legacy = await getGuildChannels(harness, account.token, guild.id);
- expect(legacy.some((channel) => channel.name === 'forum')).toBe(false);
- expect(legacy.some((channel) => channel.name === 'general')).toBe(true);
- });
function listThreadAwareChannels(token: string, guildId: string): Promise<Array<ChannelResponse>> {
return createBuilder<Array<ChannelResponse>>(harness, token)
@@ -515,24 +287,11 @@ describe('Guild Template Import', () => {
.header(THREAD_FEATURES_HEADER, THREAD_FEATURES_CAPABLE)
.execute();
}
-
- function getThreadAwareChannel(token: string, channelId: string): Promise<ChannelResponse> {
- return createBuilder<ChannelResponse>(harness, token)
- .get(`/channels/${channelId}`)
- .header(THREAD_FEATURES_HEADER, THREAD_FEATURES_CAPABLE)
- .execute();
- }
});
const THREAD_FEATURES_HEADER = 'X-Fluxer-Features';
const THREAD_FEATURES_CAPABLE = 'channel_threads';
-function findChannelId(channels: Array<ChannelResponse>, name: string): string {
- const channel = channels.find((candidate) => candidate.name === name);
- if (!channel) throw new Error(`Missing channel ${name}`);
- return channel.id;
-}
-
const DEFAULT_EVERYONE_PERMISSIONS = Permissions.VIEW_CHANNEL.toString();
function buildMinimalTemplate(overrides: {channels?: Array<object>; roles?: Array<object>}) {
diff --git a/fluxer_api/src/api/infrastructure/ChangeFeedStorageService.test.ts b/fluxer_api/src/api/infrastructure/ChangeFeedStorageService.test.ts
index e68c98b4d..27c67fef0 100644
--- a/fluxer_api/src/api/infrastructure/ChangeFeedStorageService.test.ts
+++ b/fluxer_api/src/api/infrastructure/ChangeFeedStorageService.test.ts
@@ -40,55 +40,6 @@ function createHarness(options: {inner?: MockStorageService; sink?: StorageChang
const bytes = (length: number) => new Uint8Array(length).fill(7);
describe('ChangeFeedStorageService', () => {
- it('emits a put event after an upload lands', async () => {
- const {service, inner, feed, sink} = createHarness();
-
- await service.uploadObject({
- bucket: Config.s3.buckets.cdn,
- key: 'attachments/1/2/cat.png',
- body: bytes(5),
- contentType: 'image/png',
- });
- await feed.idle();
-
- expect(await inner.getObjectMetadata(Config.s3.buckets.cdn, 'attachments/1/2/cat.png')).not.toBeNull();
- expect(sink.events).toEqual([
- {
- subject: `storage.${Config.s3.buckets.cdn}.put`,
- bucket: Config.s3.buckets.cdn,
- key: 'attachments/1/2/cat.png',
- op: 'put',
- size: 5,
- etag: null,
- contentType: 'image/png',
- at: expect.any(String),
- },
- ]);
- });
-
- it('emits delete events for objects and avatars', async () => {
- const {service, feed, sink} = createHarness();
-
- await service.deleteObject(Config.s3.buckets.cdn, 'icons/1/a.webp');
- await service.deleteAvatar({prefix: 'avatars/9', key: 'hash'});
- await feed.idle();
-
- expect(sink.events.map(({subject, bucket, key, op}) => ({subject, bucket, key, op}))).toEqual([
- {
- subject: `storage.${Config.s3.buckets.cdn}.delete`,
- bucket: Config.s3.buckets.cdn,
- key: 'icons/1/a.webp',
- op: 'delete',
- },
- {
- subject: `storage.${Config.s3.buckets.cdn}.delete`,
- bucket: Config.s3.buckets.cdn,
- key: 'avatars/9/hash',
- op: 'delete',
- },
- ]);
- });
-
it('emits nothing for the uploads bucket but still reports promotions out of it', async () => {
const {service, inner, feed, sink} = createHarness();
const uploads = Config.s3.buckets.uploads;
@@ -109,17 +60,6 @@ describe('ChangeFeedStorageService', () => {
]);
});
- it('emits nothing when the storage call itself fails', async () => {
- const {service, feed, sink} = createHarness({inner: new MockStorageService({shouldFailUpload: true})});
-
- await expect(service.uploadObject({bucket: Config.s3.buckets.cdn, key: 'broken', body: bytes(1)})).rejects.toThrow(
- 'Mock storage upload failure',
- );
- await feed.idle();
-
- expect(sink.events).toEqual([]);
- });
-
it('does not let a failing publish reach the caller', async () => {
const sink: StorageChangeSink = {
publish: async () => {
diff --git a/fluxer_api/src/api/infrastructure/ControllerCachePurgeAdapter.test.ts b/fluxer_api/src/api/infrastructure/ControllerCachePurgeAdapter.test.ts
index 0b70270a5..722b21e42 100644
--- a/fluxer_api/src/api/infrastructure/ControllerCachePurgeAdapter.test.ts
+++ b/fluxer_api/src/api/infrastructure/ControllerCachePurgeAdapter.test.ts
@@ -16,33 +16,7 @@ function prefixes(count: number): Array<string> {
return Array.from({length: count}, (_, index) => `media.test/attachments/1/${index}/photo`);
}
-function sentPatterns(spy: MockInstance<typeof fetch>, call: number): Array<string> {
- const init = spy.mock.calls[call]![1]!;
- return JSON.parse(String(init.body)).patterns;
-}
-
describe('createControllerCachePurgeAdapter', () => {
- let fetchSpy: MockInstance<typeof fetch>;
-
- beforeEach(() => {
- fetchSpy = vi.spyOn(globalThis, 'fetch');
- });
-
- afterEach(() => {
- fetchSpy.mockRestore();
- });
-
- it('sends each prefix as a wildcard pattern with the bearer token', async () => {
- fetchSpy.mockResolvedValue(new Response(null, {status: 202}));
- const outcome = await createControllerCachePurgeAdapter(CONFIG).purge(['media.test/emojis/1']);
- expect(outcome).toEqual({kind: 'purged'});
- const [url, init] = fetchSpy.mock.calls[0]!;
- expect(url).toBe(ENDPOINT);
- expect(init!.method).toBe('POST');
- expect(new Headers(init!.headers).get('Authorization')).toBe('Bearer pak_test');
- expect(JSON.parse(String(init!.body))).toEqual({patterns: ['media.test/emojis/1*'], soft: false});
- });
-
it('splits a batch into requests of at most 30 patterns', async () => {
fetchSpy.mockImplementation(async () => new Response(null, {status: 202}));
const outcome = await createControllerCachePurgeAdapter(CONFIG).purge(prefixes(65));
@@ -61,22 +35,4 @@ describe('createControllerCachePurgeAdapter', () => {
expect(outcome).toEqual({kind: 'failed', status: 503, error: null});
expect(fetchSpy).toHaveBeenCalledTimes(2);
});
-
- it('reports a 400 as rejected', async () => {
- fetchSpy.mockResolvedValue(new Response(null, {status: 400}));
- expect(await createControllerCachePurgeAdapter(CONFIG).purge(prefixes(1))).toEqual({
- kind: 'rejected',
- status: 400,
- });
- });
-
- it('reports a network error as failed', async () => {
- const error = new TypeError('fetch failed');
- fetchSpy.mockRejectedValue(error);
- expect(await createControllerCachePurgeAdapter(CONFIG).purge(prefixes(1))).toEqual({
- kind: 'failed',
- status: null,
- error,
- });
- });
});
diff --git a/fluxer_api/src/api/infrastructure/KVBulkMessageDeletionQueueService.test.ts b/fluxer_api/src/api/infrastructure/KVBulkMessageDeletionQueueService.test.ts
index d82ccd885..373984674 100644
--- a/fluxer_api/src/api/infrastructure/KVBulkMessageDeletionQueueService.test.ts
+++ b/fluxer_api/src/api/infrastructure/KVBulkMessageDeletionQueueService.test.ts
@@ -8,7 +8,6 @@ import {createTestWorkerHelpers} from '@app/api/test/SyncTaskWorkerService';
import type {UserRepository} from '@app/api/user/repositories/UserRepository';
import processPendingBulkMessageDeletions from '@app/api/worker/tasks/ProcessPendingBulkMessageDeletions';
import {clearWorkerDependencies, setWorkerDependenciesForTest} from '@app/api/worker/WorkerContext';
-import type {WorkerDependencies} from '@app/api/worker/WorkerDependencies';
import {MockKVProvider} from '@pkgs/kv_client/src/testing/MockKVProvider';
import {afterEach, describe, expect, test, vi} from 'vitest';
@@ -48,7 +47,6 @@ function createHarness(users: Array<User>) {
describe('processPendingBulkMessageDeletions', () => {
afterEach(() => {
clearWorkerDependencies();
- vi.restoreAllMocks();
});
test('replaces the old sorted-set member when a user is rescheduled', async () => {
@@ -66,17 +64,6 @@ describe('processPendingBulkMessageDeletions', () => {
]);
});
- test('renews the rebuild lock with the acquired token before publishing the state version', async () => {
- const harness = createHarness([createUser(createUserID(1234n), new Date())]);
- const extendLock = vi.spyOn(harness.kvClient, 'extendLock');
- const token = await harness.bulkMessageDeletionQueueService.acquireRebuildLock();
- expect(token).not.toBeNull();
- await harness.bulkMessageDeletionQueueService.rebuildState(token);
-
- expect(extendLock).toHaveBeenCalledExactlyOnceWith('bulk_message_deletion_queue:rebuild_lock', token, 300);
- expect((await harness.kvClient.exists('bulk_message_deletion_queue:state_version')) === 1).toBe(true);
- });
-
test('rebuilds the queue from the users table when the state version is missing', async () => {
const userId = createUserID(1234n);
const scheduledAt = new Date(Date.now() - 60_000);
@@ -94,17 +81,6 @@ describe('processPendingBulkMessageDeletions', () => {
expect((await harness.kvClient.exists('bulk_message_deletion_queue:state_version')) === 1).toBe(true);
});
- test('does not scan the users table when the state version is fresh', async () => {
- const userId = createUserID(5678n);
- const harness = createHarness([createUser(userId, new Date(Date.now() - 60_000))]);
- await harness.kvClient.set('bulk_message_deletion_queue:state_version', Date.now().toString());
-
- await processPendingBulkMessageDeletions({}, createTestWorkerHelpers());
-
- expect(harness.scanCalls).toEqual([]);
- expect(harness.jobs).toEqual([]);
- });
-
test('skips the run when another worker holds the rebuild lock', async () => {
const userId = createUserID(9012n);
const harness = createHarness([createUser(userId, new Date(Date.now() - 60_000))]);
diff --git a/fluxer_api/src/api/infrastructure/SnowflakeService.test.ts b/fluxer_api/src/api/infrastructure/SnowflakeService.test.ts
index 48fc70c53..3246fcfba 100644
--- a/fluxer_api/src/api/infrastructure/SnowflakeService.test.ts
+++ b/fluxer_api/src/api/infrastructure/SnowflakeService.test.ts
@@ -52,30 +52,6 @@ describe('SnowflakeService', () => {
timeout: 1234,
});
});
- it('routes channel-scoped requests without consuming the buffered batch', async () => {
- const manager = createConnectionManager([['201', '202', '203', '204'], ['301']]);
- const service = track(
- new SnowflakeService({
- connectionManager: manager,
- batchSize: 4,
- lowWatermark: 0,
- }),
- );
- await service.initialize();
- expect(await service.generateForChannel('1510189013330296832')).toBe(301n);
- expect(manager.requests).toHaveLength(2);
- expect(manager.requests[1]).toEqual({
- subject: 'svc.snowflakes',
- body: {
- op: 'GenerateBatch',
- count: 1,
- routing_key: 'channel:1510189013330296832',
- },
- timeout: 6000,
- });
- expect(await service.generate()).toBe(201n);
- expect(manager.requests).toHaveLength(2);
- });
it('coalesces concurrent remote initialization and refill', async () => {
const manager = createConnectionManager([['201', '202', '203', '204']]);
const service = track(
@@ -89,45 +65,4 @@ describe('SnowflakeService', () => {
expect(ids).toEqual([201n, 202n, 203n]);
expect(manager.requests).toHaveLength(1);
});
- it('surfaces remote service errors', async () => {
- const manager = createConnectionManager([{error: 'shard_unavailable'}]);
- const service = track(
- new SnowflakeService({
- connectionManager: manager,
- batchSize: 4,
- lowWatermark: 0,
- }),
- );
- await expect(service.initialize()).rejects.toThrow('Snowflake service error: shard_unavailable');
- });
- it('discards stale buffered remote IDs after idle periods', async () => {
- const manager = createConnectionManager([
- ['401', '402', '403', '404'],
- ['501', '502', '503', '504'],
- ]);
- const service = track(
- new SnowflakeService({
- connectionManager: manager,
- batchSize: 4,
- lowWatermark: 0,
- maxBufferAgeMs: 1,
- }),
- );
- await service.initialize();
- await new Promise((resolve) => setTimeout(resolve, 5));
- expect(await service.generate()).toBe(501n);
- expect(manager.requests).toHaveLength(2);
- });
- it('drains the remote NATS connection on shutdown', async () => {
- const manager = createConnectionManager([['301', '302', '303', '304']]);
- const service = track(
- new SnowflakeService({
- connectionManager: manager,
- batchSize: 4,
- }),
- );
- await service.initialize();
- await service.shutdown();
- expect(manager.drained).toBe(true);
- });
});
diff --git a/fluxer_api/src/api/infrastructure/UsersServiceClient.test.ts b/fluxer_api/src/api/infrastructure/UsersServiceClient.test.ts
index 15f7e0fc9..461a32cda 100644
--- a/fluxer_api/src/api/infrastructure/UsersServiceClient.test.ts
+++ b/fluxer_api/src/api/infrastructure/UsersServiceClient.test.ts
@@ -2,6 +2,7 @@
import {createUserID} from '@app/api/BrandedTypes';
import {NatsUsersServiceClient} from '@app/api/infrastructure/UsersServiceClient';
+import {getInstanceProductName} from '@app/api/instance/ProductName';
import {FakeNatsConnectionManager} from '@app/api/test/mocks/FakeNatsConnectionManager';
import type {UserPartialResponse} from '@fluxer/schema/src/domains/user/UserResponseSchemas';
import {describe, expect, it} from 'vitest';
@@ -38,64 +39,11 @@ describe('NatsUsersServiceClient', () => {
body: {
op: 'GetApiPartialsByIds',
user_ids: ['9223372036854775807'],
+ instance_name: getInstanceProductName(),
},
timeout: 321,
},
]);
expect(result.get(userId)).toEqual(partial);
});
-
- it('sends invalidation requests with a string user id', async () => {
- const userId = createUserID(9007199254740993n);
- const manager = createConnectionManager(['Invalidated']);
- const client = new NatsUsersServiceClient(manager, 250, 'svc.users.test');
-
- await client.invalidateUserCache(userId);
-
- expect(manager.requests).toEqual([
- {
- subject: 'svc.users.test',
- body: {
- op: 'Invalidate',
- user_id: '9007199254740993',
- },
- timeout: 250,
- },
- ]);
- });
-
- it('coalesces concurrent overlapping partial lookups without retaining a completed cache entry', async () => {
- const userId = createUserID(9223372036854775807n);
- const secondUserId = createUserID(9223372036854775806n);
- const partial: UserPartialResponse = {
- id: userId.toString(),
- username: 'Cached',
- discriminator: '0001',
- global_name: null,
- avatar: null,
- avatar_color: null,
- flags: 0,
- };
- const secondPartial: UserPartialResponse = {
- ...partial,
- id: secondUserId.toString(),
- username: 'Second',
- };
- const manager = createConnectionManager([
- {FoundApiPartials: [secondPartial, partial]},
- {FoundApiPartials: [partial]},
- ]);
- const client = new NatsUsersServiceClient(manager, 250, 'svc.users.test', 100);
-
- const [first, second] = await Promise.all([
- client.getUserPartialResponses([secondUserId, userId, userId]),
- client.getUserPartialResponses([userId]),
- ]);
- await client.getUserPartialResponses([userId]);
-
- expect(manager.requests).toHaveLength(2);
- expect(first.get(userId)).toEqual(partial);
- expect(first.get(secondUserId)).toEqual(secondPartial);
- expect(second.get(userId)).toEqual(partial);
- });
});
diff --git a/fluxer_api/src/api/infrastructure/activity/tests/ActivityEvents.test.ts b/fluxer_api/src/api/infrastructure/activity/tests/ActivityEvents.test.ts
index acdb24e8d..8e505d87e 100644
--- a/fluxer_api/src/api/infrastructure/activity/tests/ActivityEvents.test.ts
+++ b/fluxer_api/src/api/infrastructure/activity/tests/ActivityEvents.test.ts
@@ -1,11 +1,9 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
-import {emitAccountChangedIfRelevant} from '@app/api/infrastructure/activity/AccountChangeEvents';
import {
activityCountForTests,
drainActivitySpoolNow,
emitActivity,
- idleActivityEvents,
resetActivityEventsForTests,
startActivityEvents,
} from '@app/api/infrastructure/activity/ActivityEvents';
@@ -39,8 +37,6 @@ class FakePublisher implements ActivityPublisher {
if (failure) throw failure;
}
}
-
-const LOGIN = {user_id: '1174109840998400001', ok: true, failure: null, mfa: false, new_ip: false};
const DELETED = {user_id: '1174109840998400001'};
async function spooled(kv: MockKVProvider): Promise<Array<ActivitySpoolEntry>> {
@@ -56,29 +52,6 @@ describe('activity events', () => {
resetActivityEventsForTests();
});
- it('publishes a fact with its natural id, ttl and envelope, and resolves after the ack', async () => {
- const publisher = new FakePublisher();
- const kv = new MockKVProvider();
- await startActivityEvents({publisher, kv});
- await emitActivity('account_deleted', DELETED.user_id, DELETED, workerMeta(), DELETED.user_id);
- expect(publisher.calls).toHaveLength(1);
- const [call] = publisher.calls;
- expect(call.subject).toBe(`evt.in.account_deleted.${DELETED.user_id}`);
- expect(call.options).toEqual({msgID: `account_deleted:${DELETED.user_id}`, ttl: 'never', spooled: false});
- const envelope = JSON.parse(call.payload);
- expect(envelope).toMatchObject({
- v: 1,
- id: `account_deleted:${DELETED.user_id}`,
- key: DELETED.user_id,
- kind: 'account_deleted',
- data: DELETED,
- meta: {channel: 'worker'},
- });
- expect(typeof envelope.at_ms).toBe('number');
- expect(await spooled(kv)).toEqual([]);
- expect(activityCountForTests('account_deleted', 'published')).toBe(1);
- });
-
it('retries a timed out publish with the same message id', async () => {
const publisher = new FakePublisher();
publisher.failures = [new TimeoutError(), new TimeoutError()];
@@ -107,47 +80,6 @@ describe('activity events', () => {
expect(activityCountForTests('account_deleted', 'spooled')).toBe(1);
});
- it('spools a rejected publish without retrying and counts it as rejected', async () => {
- const publisher = new FakePublisher();
- publisher.failures = [rejection()];
- const kv = new MockKVProvider();
- await startActivityEvents({publisher, kv});
- await emitActivity('account_deleted', DELETED.user_id, DELETED, workerMeta(), DELETED.user_id);
- expect(publisher.calls).toHaveLength(1);
- expect(await spooled(kv)).toHaveLength(1);
- expect(activityCountForTests('account_deleted', 'rejected')).toBe(1);
- });
-
- it('queues signals without blocking the caller and gives each a fresh id', async () => {
- const publisher = new FakePublisher();
- const kv = new MockKVProvider();
- await startActivityEvents({publisher, kv});
- void emitActivity('login', LOGIN.user_id, LOGIN, workerMeta());
- void emitActivity('login', LOGIN.user_id, LOGIN, workerMeta());
- await new Promise((resolve) => setImmediate(resolve));
- await idleActivityEvents();
- expect(publisher.calls).toHaveLength(2);
- const ids = publisher.calls.map((call) => call.options.msgID);
- expect(ids[0]).toMatch(/^login:\d+$/);
- expect(ids[0]).not.toBe(ids[1]);
- expect(publisher.calls[0].options.ttl).toBe('3024000');
- });
-
- it('keys a block by the blocked user so it lands with their other signals', async () => {
- const publisher = new FakePublisher();
- const kv = new MockKVProvider();
- await startActivityEvents({publisher, kv});
- const block = {blocker_id: '1174110260428800002', blocked_id: LOGIN.user_id};
- void emitActivity('user_blocked', block.blocked_id, block, workerMeta());
- await new Promise((resolve) => setImmediate(resolve));
- await idleActivityEvents();
- expect(publisher.calls).toHaveLength(1);
- const [call] = publisher.calls;
- expect(call.subject).toBe(`evt.in.user_blocked.${LOGIN.user_id}`);
- expect(call.options.ttl).toBe('259200');
- expect(JSON.parse(call.payload)).toMatchObject({kind: 'user_blocked', key: LOGIN.user_id, data: block});
- });
-
it('drains the spool in order with the original ids, marks them spooled and drops expired entries', async () => {
const failing = new FakePublisher();
failing.failures = [rejection(), rejection()];
@@ -189,81 +121,6 @@ describe('activity events', () => {
expect((await spooled(kv)).map((entry) => entry.id)).toEqual(['account_deleted:1', 'account_deleted:2']);
});
- it('gives two account changes written at the same version distinct ids', async () => {
- const publisher = new FakePublisher();
- await startActivityEvents({publisher, kv: new MockKVProvider()});
- const row = (flags: bigint) => ({user_id: 1174109840998400001n, version: 11, flags}) as never;
- await emitAccountChangedIfRelevant(row(0n), row(1n << 50n), 'admin');
- await emitAccountChangedIfRelevant(row(0n), row(1n << 43n), 'admin');
- await emitAccountChangedIfRelevant(row(0n), row(1n << 50n), 'admin');
- const ids = publisher.calls.map((call) => call.options.msgID);
- expect(ids).toHaveLength(3);
- expect(ids[0]).toMatch(/^account_changed:1174109840998400001:11:/u);
- expect(ids[0]).not.toBe(ids[1]);
- expect(ids[0]).toBe(ids[2]);
- });
-
- it('stays silent while the activity stream does not exist', async () => {
- const publisher = new FakePublisher();
- const kv = new MockKVProvider();
- await startActivityEvents({
- publisher,
- kv,
- jsm: {
- streams: {
- info: async () => {
- throw new JetStreamApiError({code: 404, err_code: 10059, description: 'stream not found'});
- },
- },
- } as never,
- });
- await emitActivity('account_deleted', DELETED.user_id, DELETED, workerMeta(), DELETED.user_id);
- expect(publisher.calls).toEqual([]);
- expect(await spooled(kv)).toEqual([]);
- expect(activityCountForTests('account_deleted', 'dropped')).toBe(1);
- });
-
- it('spools and counts rejected while the stream is missing when asked to', async () => {
- const publisher = new FakePublisher();
- const kv = new MockKVProvider();
- await startActivityEvents({
- publisher,
- kv,
- spoolWhileMissing: true,
- jsm: {
- streams: {
- info: async () => {
- throw new JetStreamApiError({code: 404, err_code: 10059, description: 'stream not found'});
- },
- },
- } as never,
- });
- await emitActivity('account_deleted', DELETED.user_id, DELETED, workerMeta(), DELETED.user_id);
- expect(publisher.calls).toEqual([]);
- expect((await spooled(kv)).map((entry) => entry.id)).toEqual([`account_deleted:${DELETED.user_id}`]);
- expect(activityCountForTests('account_deleted', 'rejected')).toBe(1);
- expect(await drainActivitySpoolNow()).toBeNull();
- });
-
- it('keeps publishing when the stream probe fails for a transient reason', async () => {
- const publisher = new FakePublisher();
- const kv = new MockKVProvider();
- await startActivityEvents({
- publisher,
- kv,
- jsm: {
- streams: {
- info: async () => {
- throw new TimeoutError();
- },
- },
- } as never,
- });
- await emitActivity('account_deleted', DELETED.user_id, DELETED, workerMeta(), DELETED.user_id);
- expect(publisher.calls.map((call) => call.options.msgID)).toEqual([`account_deleted:${DELETED.user_id}`]);
- expect(activityCountForTests('account_deleted', 'published')).toBe(1);
- });
-
it('stops a drain at its budget inside a batch and never trims after losing the lock', async () => {
const kv = new MockKVProvider();
for (const id of ['1', '2', '3']) {
diff --git a/fluxer_api/src/api/infrastructure/activity/tests/GuildEvents.test.ts b/fluxer_api/src/api/infrastructure/activity/tests/GuildEvents.test.ts
index c1370044c..b73de61de 100644
--- a/fluxer_api/src/api/infrastructure/activity/tests/GuildEvents.test.ts
+++ b/fluxer_api/src/api/infrastructure/activity/tests/GuildEvents.test.ts
@@ -3,20 +3,8 @@
import {createTestAccount, setUserACLs} from '@app/api/auth/tests/AuthTestUtils';
import {createGuildID} from '@app/api/BrandedTypes';
import {applyPauseGuildInvites, type GuildInvitePauseDeps} from '@app/api/guild/services/GuildInvitePauseApplier';
-import {
- acceptInvite,
- createChannelInvite,
- createGuild,
- deleteInvite,
- leaveGuild,
- setupTestGuildWithMembers,
- updateGuild,
-} from '@app/api/guild/tests/GuildTestUtils';
-import {
- idleActivityEvents,
- resetActivityEventsForTests,
- startActivityEvents,
-} from '@app/api/infrastructure/activity/ActivityEvents';
+import {acceptInvite, createChannelInvite, createGuild, updateGuild} from '@app/api/guild/tests/GuildTestUtils';
+import {resetActivityEventsForTests, startActivityEvents} from '@app/api/infrastructure/activity/ActivityEvents';
import type {ActivityPublisher} from '@app/api/infrastructure/activity/ActivitySpool';
import type {Event} from '@app/api/infrastructure/activity/Contract.generated';
import {getGatewayService, getKVClient} from '@app/api/middleware/ServiceRegistry';
@@ -24,7 +12,6 @@ import {getCacheService, getGuildAuditLogService, getGuildRepository} from '@app
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 type {GuildResponse} from '@fluxer/schema/src/domains/guild/GuildResponseSchemas';
import {MockKVProvider} from '@pkgs/kv_client/src/testing/MockKVProvider';
@@ -89,92 +76,6 @@ describe('guild activity events', () => {
await harness?.shutdown();
});
- test('creating a guild publishes who owns it', async () => {
- const owner = await createTestAccount(harness);
- const guild = await createGuild(harness, owner.token, 'Fresh guild');
- const [created] = publisher.of('guild_created');
- expect(created?.key).toBe(owner.userId);
- expect(created?.data).toEqual({guild_id: guild.id, owner_id: owner.userId, member_count: 1});
- });
-
- test('a member feature toggle publishes the actor and the member source', async () => {
- const owner = await createTestAccount(harness);
- const guild = await createGuild(harness, owner.token, 'Toggle guild');
- await updateGuild(harness, owner.token, guild.id, {features: [...guild.features, GuildFeatures.INVITES_DISABLED]});
- const [changed] = publisher.of('guild_features_changed');
- expect(changed?.key).toBe(`guild:${guild.id}`);
- expect(changed?.data).toEqual({
- guild_id: guild.id,
- actor_id: owner.userId,
- source: 'member',
- added: [GuildFeatures.INVITES_DISABLED],
- removed: [],
- invites_paused_until_ms: null,
- });
- });
-
- test('creating and deleting an invite publishes both with the invite settings', async () => {
- const owner = await createTestAccount(harness);
- const guild = await createGuild(harness, owner.token, 'Invite guild');
- const invite = await createChannelInvite(harness, owner.token, guild.system_channel_id!);
- await deleteInvite(harness, owner.token, invite.code);
- const [created] = publisher.of('invite_created');
- expect(created?.key).toBe(`guild:${guild.id}`);
- expect(created?.data).toEqual({
- guild_id: guild.id,
- channel_id: guild.system_channel_id,
- code: invite.code,
- inviter_id: owner.userId,
- max_uses: invite.max_uses,
- max_age_s: invite.max_age,
- temporary: false,
- });
- const [deleted] = publisher.of('invite_deleted');
- expect(deleted?.key).toBe(`guild:${guild.id}`);
- expect(deleted?.data).toEqual({guild_id: guild.id, code: invite.code});
- });
-
- test('leaving and being kicked publish the removal kind and actor', async () => {
- const {owner, members, guild} = await setupTestGuildWithMembers(harness, 2);
- const [leaver, kicked] = members;
- await leaveGuild(harness, leaver!.token, guild.id);
- await createBuilder(harness, owner.token)
- .delete(`/guilds/${guild.id}/members/${kicked!.userId}`)
- .expect(HTTP_STATUS.NO_CONTENT)
- .execute();
- await idleActivityEvents();
- expect(publisher.of('guild_member_removed').map((event) => [event.key, event.data])).toEqual([
- [leaver!.userId, {guild_id: guild.id, user_id: leaver!.userId, actor_id: null, kind: 'left'}],
- [kicked!.userId, {guild_id: guild.id, user_id: kicked!.userId, actor_id: owner.userId, kind: 'kicked'}],
- ]);
- });
-
- test('a join refused while invites are paused publishes the refusal only for non-members', async () => {
- const owner = await createTestAccount(harness);
- const joiner = await createTestAccount(harness);
- const guild = await createGuild(harness, owner.token, 'Paused guild');
- const invite = await createChannelInvite(harness, owner.token, guild.system_channel_id!);
- await pauseInvites(guild.id, Date.now() + HOUR_MS);
- for (const account of [owner, joiner]) {
- await createBuilder(harness, account.token)
- .post(`/invites/${invite.code}`)
- .body(null)
- .expect(HTTP_STATUS.FORBIDDEN, APIErrorCodes.INVITES_DISABLED)
- .execute();
- }
- await idleActivityEvents();
- const refusals = publisher.of('guild_join_refused');
- expect(refusals).toHaveLength(1);
- const [refused] = refusals;
- expect(refused?.key).toBe(joiner.userId);
- expect(refused?.data).toEqual({
- guild_id: guild.id,
- user_id: joiner.userId,
- cause: 'invites_paused',
- join_source: 'invite',
- });
- });
-
describe('managed invite pause', () => {
let owner: Awaited<ReturnType<typeof createTestAccount>>;
let guild: GuildResponse;
diff --git a/fluxer_api/src/api/infrastructure/activity/tests/ModerationEvents.test.ts b/fluxer_api/src/api/infrastructure/activity/tests/ModerationEvents.test.ts
index d5697742d..77ce53995 100644
--- a/fluxer_api/src/api/infrastructure/activity/tests/ModerationEvents.test.ts
+++ b/fluxer_api/src/api/infrastructure/activity/tests/ModerationEvents.test.ts
@@ -1,15 +1,12 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
-import {createTestAccount, setUserACLs, type TestAccount} from '@app/api/auth/tests/AuthTestUtils';
-import {decisionBody} from '@app/api/enforcement/tests/EnforcementTestUtils';
-import {addMemberRole, createGuild, createRole, setupTestGuildWithMembers} from '@app/api/guild/tests/GuildTestUtils';
+import {setupTestGuildWithMembers} from '@app/api/guild/tests/GuildTestUtils';
import {resetActivityEventsForTests, startActivityEvents} from '@app/api/infrastructure/activity/ActivityEvents';
import type {ActivityPublisher} from '@app/api/infrastructure/activity/ActivitySpool';
import type {Event} from '@app/api/infrastructure/activity/Contract.generated';
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 {Permissions} from '@fluxer/constants/src/ChannelConstants';
import {MockKVProvider} from '@pkgs/kv_client/src/testing/MockKVProvider';
import {afterEach, beforeEach, describe, expect, test} from 'vitest';
@@ -73,126 +70,4 @@ describe('moderation activity events', () => {
});
expect(unbanned?.meta.ip).toBeNull();
});
-
- test('banning a member who can moderate the guild marks the target as a moderator', async () => {
- const {owner, members, guild} = await setupTestGuildWithMembers(harness, 1);
- const target = members[0]!;
- const role = await createRole(harness, owner.token, guild.id, {
- name: 'Mods',
- permissions: Permissions.BAN_MEMBERS.toString(),
- });
- await addMemberRole(harness, owner.token, guild.id, target.userId, role.id);
- await ban(owner.token, `/guilds/${guild.id}/bans/${target.userId}`);
- expect(publisher.of('guild_member_banned')[0]?.data.target_moderator).toBe(true);
- });
-
- test('a staff ban says it came from staff', async () => {
- const admin = await setUserACLs(harness, await createTestAccount(harness), [
- 'admin:authenticate',
- 'guild:ban_member',
- ]);
- const target = await createTestAccount(harness);
- const guild = await createGuild(harness, admin.token, 'Staff ban guild');
- await ban(admin.token, `/admin/guilds/${guild.id}/bans/${target.userId}`);
- expect(publisher.of('guild_member_banned')[0]?.data).toMatchObject({
- user_id: target.userId,
- by: 'staff',
- target_moderator: false,
- });
- });
-
- describe('report resolution', () => {
- let admin: TestAccount;
-
- beforeEach(async () => {
- admin = await setUserACLs(harness, await createTestAccount(harness), [
- 'admin:authenticate',
- 'report:resolve',
- 'user:temp_ban',
- ]);
- });
-
- async function fileReport(): Promise<{reporter: TestAccount; reported: TestAccount; reportId: string}> {
- const reporter = await createTestAccount(harness);
- const reported = await createTestAccount(harness);
- const report = await createBuilder<{report_id: string}>(harness, reporter.token)
- .post('/reports/user')
- .body({user_id: reported.userId, category: 'harassment'})
- .execute();
- return {reporter, reported, reportId: report.report_id};
- }
-
- async function resolve(reportId: string, body: Record<string, unknown>): Promise<void> {
- await createBuilder(harness, admin.token)
- .patch(`/admin/reports/${reportId}`)
- .body({status: 'resolved', notify_reporter: false, ...body})
- .expect(HTTP_STATUS.OK)
- .execute();
- }
-
- test('a staff dismissal publishes the outcome staff chose', async () => {
- const {reporter, reported, reportId} = await fileReport();
- await resolve(reportId, {resolution: 'no_violation'});
- const [resolved] = publisher.of('report_resolved');
- expect(resolved?.key).toBe(reported.userId);
- expect(resolved?.data).toEqual({
- report_id: reportId,
- reporter_id: reporter.userId,
- category: 'harassment',
- target_type: 'user',
- reported_user_id: reported.userId,
- outcome: 'no_violation',
- resolved_by: 'staff',
- });
- expect(resolved?.meta.ip).toBeNull();
- });
-
- test.each(['actioned', 'no_violation', 'duplicate'] as const)(
- 'a staff resolve with %s publishes that outcome even when the account is under enforcement',
- async (resolution) => {
- const {reported, reportId} = await fileReport();
- await createBuilder(harness, admin.token)
- .put(`/admin/users/${reported.userId}/ban`)
- .header('X-Audit-Log-Reason', 'Test suspension')
- .body({
- duration_hours: 24,
- decision: decisionBody(),
- })
- .expect(HTTP_STATUS.OK)
- .execute();
- const {reportId: originalId} = await fileReport();
- await resolve(
- reportId,
- resolution === 'no_violation'
- ? {resolution}
- : resolution === 'duplicate'
- ? {resolution, duplicate_of: originalId}
- : {resolution, outcome: 'restricted'},
- );
- expect(publisher.of('report_resolved').map((event) => event.data)).toEqual([
- expect.objectContaining({report_id: reportId, outcome: resolution, resolved_by: 'staff'}),
- ]);
- },
- );
-
- test('a resolution is required', async () => {
- const {reportId} = await fileReport();
- await createBuilder(harness, admin.token)
- .patch(`/admin/reports/${reportId}`)
- .body({status: 'resolved'})
- .expect(HTTP_STATUS.BAD_REQUEST)
- .execute();
- expect(publisher.of('report_resolved')).toEqual([]);
- });
-
- test('an unknown resolution is rejected', async () => {
- const {reportId} = await fileReport();
- await createBuilder(harness, admin.token)
- .patch(`/admin/reports/${reportId}`)
- .body({status: 'resolved', resolution: 'maybe'})
- .expect(HTTP_STATUS.BAD_REQUEST)
- .execute();
- expect(publisher.of('report_resolved')).toEqual([]);
- });
- });
});
diff --git a/fluxer_api/src/api/infrastructure/tests/EmailDnsValidationService.test.ts b/fluxer_api/src/api/infrastructure/tests/EmailDnsValidationService.test.ts
index 9e7aa6831..0f2bf5b5d 100644
--- a/fluxer_api/src/api/infrastructure/tests/EmailDnsValidationService.test.ts
+++ b/fluxer_api/src/api/infrastructure/tests/EmailDnsValidationService.test.ts
@@ -1,8 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
-import {Config} from '@app/api/Config';
import {EmailDnsValidationService} from '@app/api/infrastructure/EmailDnsValidationService';
-import {getInstanceConfigRepository} from '@app/api/middleware/ServiceSingletons';
import {ms} from 'itty-time';
import {describe, expect, it} from 'vitest';
@@ -54,58 +52,6 @@ class FakeDnsResolver {
}
describe('EmailDnsValidationService', () => {
- it('skips the lookup when the instance sends no mail', async () => {
- const resolver = new FakeDnsResolver();
- resolver.mxErrorCode = 'ENOTFOUND';
- const service = new EmailDnsValidationService({
- resolver,
- enforceInTestMode: true,
- isEmailEnabled: async () => false,
- });
- expect(await service.hasValidDnsRecords('[email protected]')).toBe(true);
- expect(resolver.lookups).toEqual([]);
- });
-
- it('looks the domain up when the instance sends mail', async () => {
- const resolver = new FakeDnsResolver();
- const service = new EmailDnsValidationService({
- resolver,
- enforceInTestMode: true,
- isEmailEnabled: async () => true,
- });
- expect(await service.hasValidDnsRecords('[email protected]')).toBe(true);
- expect(resolver.lookups).toEqual(['mx:gmail.com']);
- });
-
- it('follows the env email flag when no gate is supplied and the operator set nothing', async () => {
- expect(Config.email.enabled).toBe(true);
- const resolver = new FakeDnsResolver();
- const service = new EmailDnsValidationService({resolver, enforceInTestMode: true});
- expect(await service.hasValidDnsRecords('[email protected]')).toBe(true);
- expect(resolver.lookups).toEqual(['mx:gmail.com']);
- });
-
- it('follows the runtime instance email setting over the env flag', async () => {
- expect(Config.email.enabled).toBe(true);
- await getInstanceConfigRepository().setInstanceIntegrationsConfig({email: {enabled: false}});
- const resolver = new FakeDnsResolver();
- resolver.mxErrorCode = 'ENOTFOUND';
- const service = new EmailDnsValidationService({resolver, enforceInTestMode: true});
- expect(await service.hasValidDnsRecords('[email protected]')).toBe(true);
- expect(resolver.lookups).toEqual([]);
- });
-
- it('still rejects a syntactically broken address when the instance sends no mail', async () => {
- const resolver = new FakeDnsResolver();
- const service = new EmailDnsValidationService({
- resolver,
- enforceInTestMode: true,
- isEmailEnabled: async () => false,
- });
- expect(await service.hasValidDnsRecords('probe@')).toBe(false);
- expect(resolver.lookups).toEqual([]);
- });
-
it('rejects a domain that does not exist', async () => {
const resolver = new FakeDnsResolver();
resolver.mxErrorCode = 'ENOTFOUND';
@@ -171,20 +117,6 @@ describe('EmailDnsValidationService', () => {
expect(resolver.lookups).toEqual(['mx:asdf.asdf', 'mx:asdf.asdf']);
});
- it('caches a verified domain for the positive ttl', async () => {
- const resolver = new FakeDnsResolver();
- const service = new EmailDnsValidationService({
- resolver,
- enforceInTestMode: true,
- isEmailEnabled: async () => true,
- positiveTtlMs: ms('30 minutes'),
- negativeTtlMs: 0,
- });
- expect(await service.hasValidDnsRecords('[email protected]')).toBe(true);
- expect(await service.hasValidDnsRecords('[email protected]')).toBe(true);
- expect(resolver.lookups).toEqual(['mx:gmail.com']);
- });
-
it('gives up on a stalled resolver instead of hanging', async () => {
const resolver = new FakeDnsResolver();
resolver.stall = true;
@@ -199,22 +131,4 @@ describe('EmailDnsValidationService', () => {
expect(Date.now() - startedAtMs).toBeLessThan(ms('5 seconds'));
expect(resolver.lookups).toEqual(['mx:stalled.test']);
});
-
- it('bounds the domain cache', async () => {
- const resolver = new FakeDnsResolver();
- resolver.mxErrorCode = 'ENOTFOUND';
- const service = new EmailDnsValidationService({
- resolver,
- enforceInTestMode: true,
- isEmailEnabled: async () => true,
- maxCachedDomains: 2,
- });
- expect(await service.hasValidDnsRecords('[email protected]')).toBe(false);
- expect(await service.hasValidDnsRecords('[email protected]')).toBe(false);
- expect(await service.hasValidDnsRecords('[email protected]')).toBe(false);
- expect(await service.hasValidDnsRecords('[email protected]')).toBe(false);
- expect(resolver.lookups).toEqual(['mx:first.test', 'mx:second.test', 'mx:third.test']);
- expect(await service.hasValidDnsRecords('[email protected]')).toBe(false);
- expect(resolver.lookups).toEqual(['mx:first.test', 'mx:second.test', 'mx:third.test', 'mx:first.test']);
- });
});
diff --git a/fluxer_api/src/api/infrastructure/tests/GatewayServiceErrorMapping.test.ts b/fluxer_api/src/api/infrastructure/tests/GatewayServiceErrorMapping.test.ts
index c7cfb9363..de2e26f6c 100644
--- a/fluxer_api/src/api/infrastructure/tests/GatewayServiceErrorMapping.test.ts
+++ b/fluxer_api/src/api/infrastructure/tests/GatewayServiceErrorMapping.test.ts
@@ -5,11 +5,7 @@ import type {GatewayRpcTransport} from '@app/api/infrastructure/GatewayRpcClient
import {GatewayRpcClient} from '@app/api/infrastructure/GatewayRpcClient';
import {GatewayRpcMethodError, GatewayRpcMethodErrorCodes} from '@app/api/infrastructure/GatewayRpcError';
import {GatewayService} from '@app/api/infrastructure/GatewayService';
-import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
-import {BadGatewayError} from '@fluxer/errors/src/domains/core/BadGatewayError';
-import {BadRequestError} from '@fluxer/errors/src/domains/core/BadRequestError';
import {ServiceUnavailableError} from '@fluxer/errors/src/domains/core/ServiceUnavailableError';
-import {UnknownGuildError} from '@fluxer/errors/src/domains/guild/UnknownGuildError';
import {afterEach, describe, expect, it} from 'vitest';
function failingTransport(code: string): GatewayRpcTransport {
@@ -31,47 +27,6 @@ describe('GatewayService gateway error mapping', () => {
await GatewayRpcClient.resetForTests();
});
- it('maps guild_not_found from guild.get_user_permissions to UnknownGuildError', async () => {
- const service = serviceRaising(GatewayRpcMethodErrorCodes.GUILD_NOT_FOUND);
- await expect(
- service.getUserPermissions({guildId: createGuildID(1n), userId: createUserID(2n)}),
- ).rejects.toBeInstanceOf(UnknownGuildError);
- });
-
- it('maps guild_not_found from guild.check_permission to UnknownGuildError', async () => {
- const service = serviceRaising(GatewayRpcMethodErrorCodes.GUILD_NOT_FOUND);
- await expect(
- service.checkPermission({guildId: createGuildID(1n), userId: createUserID(2n), permission: 1n}),
- ).rejects.toBeInstanceOf(UnknownGuildError);
- });
-
- it('maps an unrecognised gateway error from guild.check_permission to BadGatewayError', async () => {
- const service = serviceRaising('permission_check_error');
- await expect(
- service.checkPermission({guildId: createGuildID(1n), userId: createUserID(2n), permission: 1n}),
- ).rejects.toBeInstanceOf(BadGatewayError);
- });
-
- it('maps invalid_params to a 400 instead of an upstream failure', async () => {
- const service = serviceRaising(GatewayRpcMethodErrorCodes.INVALID_PARAMS);
- const error = await service
- .checkPermission({guildId: createGuildID(1n), userId: createUserID(2n), permission: 1n})
- .catch((raised: unknown) => raised);
- expect(error).toBeInstanceOf(BadRequestError);
- expect((error as BadRequestError).status).toBe(400);
- expect((error as BadRequestError).code).toBe(APIErrorCodes.INVALID_FORM_BODY);
- });
-
- it('maps batch_too_large to a 400 instead of an upstream failure', async () => {
- const service = serviceRaising(GatewayRpcMethodErrorCodes.BATCH_TOO_LARGE);
- const error = await service
- .getUserPermissionsBatch({guildIds: [createGuildID(1n)], userId: createUserID(2n)})
- .catch((raised: unknown) => raised);
- expect(error).toBeInstanceOf(BadRequestError);
- expect((error as BadRequestError).status).toBe(400);
- expect((error as BadRequestError).code).toBe(APIErrorCodes.INVALID_FORM_BODY);
- });
-
it('returns 503 with Retry-After for an overloaded guild', async () => {
const service = serviceRaising(GatewayRpcMethodErrorCodes.GUILD_OVERLOADED);
const error = await service
diff --git a/fluxer_api/src/api/infrastructure/tests/LiveKitWebhookService.test.ts b/fluxer_api/src/api/infrastructure/tests/LiveKitWebhookService.test.ts
index 1eb376455..d99582cfb 100644
--- a/fluxer_api/src/api/infrastructure/tests/LiveKitWebhookService.test.ts
+++ b/fluxer_api/src/api/infrastructure/tests/LiveKitWebhookService.test.ts
@@ -14,56 +14,6 @@ import {describe, expect, it, vi} from 'vitest';
const GUILD_ID = createGuildID(1n);
const CHANNEL_ID = createChannelID(2n);
-function roomFinished(name: string): WebhookEvent {
- return {
- event: 'room_finished',
- room: {name, sid: 'RM_test', emptyTimeout: 300, creationTime: 0n},
- } as unknown as WebhookEvent;
-}
-
-function harness(pinnedServerId: string | null) {
- const deleteRoomServer = vi.fn(async () => {});
- const voiceRoomStore = {
- getPinnedRoomServer: vi.fn(async () => (pinnedServerId ? {regionId: 'eu', serverId: pinnedServerId} : null)),
- deleteRoomServer,
- } as unknown as IVoiceRoomStore;
- const gatewayService = {} as unknown as IGatewayService;
- const liveKitService = {} as unknown as ILiveKitService;
- const service = new LiveKitWebhookService(
- voiceRoomStore,
- gatewayService,
- liveKitService,
- new VoiceTopology({} as unknown as VoiceRepository, null),
- );
- return {service, deleteRoomServer};
-}
-
-describe('LiveKitWebhookService room_finished', () => {
- it('clears the guild pin without disconnecting anybody', async () => {
- const {service, deleteRoomServer} = harness('eu-1');
-
- await service.handleRoomFinished(roomFinished(`guild_${GUILD_ID}_channel_${CHANNEL_ID}`), 'unknown-key');
-
- expect(deleteRoomServer).toHaveBeenCalledTimes(1);
- });
-
- it('clears the pin even when no server is pinned, and still disconnects nobody', async () => {
- const {service, deleteRoomServer} = harness(null);
-
- await service.handleRoomFinished(roomFinished(`guild_${GUILD_ID}_channel_${CHANNEL_ID}`), 'unknown-key');
-
- expect(deleteRoomServer).toHaveBeenCalledTimes(1);
- });
-
- it('ignores a room name it cannot parse', async () => {
- const {service, deleteRoomServer} = harness('eu-1');
-
- await service.handleRoomFinished(roomFinished('not_a_voice_room'), 'unknown-key');
-
- expect(deleteRoomServer).not.toHaveBeenCalled();
- });
-});
-
function trackPublished(source: TrackSource, attributes: Record<string, string>): WebhookEvent {
return {
event: 'track_published',
diff --git a/fluxer_api/src/api/report/tests/ContentReporting.test.ts b/fluxer_api/src/api/report/tests/ContentReporting.test.ts
index e94d230a2..7209027be 100644
--- a/fluxer_api/src/api/report/tests/ContentReporting.test.ts
+++ b/fluxer_api/src/api/report/tests/ContentReporting.test.ts
@@ -40,9 +40,10 @@ import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
import {Permissions} from '@fluxer/constants/src/ChannelConstants';
import {DELETED_USER_USERNAME} from '@fluxer/constants/src/UserConstants';
import type {GuildResponse} from '@fluxer/schema/src/domains/guild/GuildResponseSchemas';
+import {compareSnowflakes} from '@fluxer/snowflake/src/SnowflakeComparison';
import {extractTimestamp} from '@fluxer/snowflake/src/SnowflakeUtils';
-import {getEmailTemplate} from '@pkgs/email/src/email_i18n/EmailI18n';
-import {afterEach, beforeEach, describe, expect, test, vi} from 'vitest';
+import {emailLinkUrls, renderEmailTemplateText, reportResolvedSlots} from '@pkgs/email/src/EmailService';
+import {afterEach, beforeEach, describe, expect, test} from 'vitest';
interface ReportResponse {
report_id: string;
@@ -119,22 +120,10 @@ function embedStorageKey(url: string | null | undefined): string {
return unsigned.slice(`${Config.endpoints.media}/`.length);
}
-function refuseNextAllowanceSpend() {
- return vi.spyOn(getRateLimitService(), 'checkLimit').mockResolvedValueOnce({
- allowed: false,
- limit: 5,
- remaining: 0,
- resetTime: new Date(Date.now() + 1000),
- resetAfterDecimal: 1,
- retryAfter: 1,
- retryAfterDecimal: 1,
- });
-}
-
function contextIds(report: Awaited<ReturnType<typeof readReport>>): Array<string> {
return (report.messageContext ?? [])
.map((entry) => entry.messageId)
- .sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))
+ .sort(compareSnowflakes)
.map((id) => id.toString());
}
@@ -229,24 +218,19 @@ describe('Content Reporting', () => {
expect(email?.metadata['public_comment']).toBe(publicComment);
const systemMessages = await listSystemDmMessages(harness, reporter.token);
expect(systemMessages).toHaveLength(1);
- const template = getEmailTemplate(
+ const text = renderEmailTemplateText(
'report_resolved',
'fr',
+ {outcome: 'restricted', appeals_email: resolveContactEmails().appealsEmail},
+ getInstanceProductName(),
+ (template) => reportResolvedSlots(template, report.report_id, publicComment),
{
- username: reporter.username!,
- reportId: report.report_id,
- publicComment,
- hasComment: 'yes',
- outcome: 'restricted',
- appeals_email: resolveContactEmails().appealsEmail,
+ format: 'markdown',
+ urls: emailLinkUrls({appBaseUrl: Config.endpoints.webApp, marketingBaseUrl: Config.endpoints.marketing}),
},
- getInstanceProductName(),
);
- expect(template.ok).toBe(true);
- if (!template.ok) {
- throw new Error('Failed to resolve expected report_resolved email template');
- }
- expect(systemMessages[0]?.content).toBe(systemDmBody(template.value.body));
+ expect(text).not.toBeNull();
+ expect(systemMessages[0]?.content).toBe(systemDmBody(text ?? ''));
expect(systemMessages[0]?.content).not.toContain(reporter.username!);
const systemDmChannel = (await listSystemDmChannels(harness, reporter.token))[0];
expect(systemDmChannel?.id).toBeTruthy();
@@ -750,46 +734,6 @@ describe('Content Reporting', () => {
}
});
});
- describe('Reservations', () => {
- test('a user report refused when the allowance is spent keeps no reservation', async () => {
- const reporter = await createTestAccount(harness);
- const targetUser = await createTestAccount(harness);
- const spend = refuseNextAllowanceSpend();
- await reportUser(harness, reporter.token, targetUser.userId).expect(429, APIErrorCodes.RATE_LIMITED).execute();
- expect(spend).toHaveBeenCalledTimes(1);
- spend.mockRestore();
- expect(await countReports()).toBe(0);
- await reportUser(harness, reporter.token, targetUser.userId).expect(HTTP_STATUS.OK).execute();
- expect(await countReports()).toBe(1);
- });
- test('a guild report refused when the allowance is spent keeps no reservation', async () => {
- const {members, guild} = await setupTestGuildWithMembers(harness, 1);
- const reporter = members[0];
- const spend = refuseNextAllowanceSpend();
- await reportGuild(harness, reporter.token, guild.id).expect(429, APIErrorCodes.RATE_LIMITED).execute();
- expect(spend).toHaveBeenCalledTimes(1);
- spend.mockRestore();
- expect(await countReports()).toBe(0);
- await reportGuild(harness, reporter.token, guild.id).expect(HTTP_STATUS.OK).execute();
- await reportGuild(harness, reporter.token, guild.id)
- .expect(HTTP_STATUS.CONFLICT, APIErrorCodes.CONFLICT)
- .execute();
- expect(await countReports()).toBe(1);
- });
- test('a message report refused when the allowance is spent keeps no reservation', async () => {
- const {owner, members, systemChannel} = await setupTestGuildWithMembers(harness, 1);
- const message = await sendChannelMessage(harness, members[0].token, systemChannel.id, 'Reported');
- const spend = refuseNextAllowanceSpend();
- await reportMessage(harness, owner.token, systemChannel.id, message.id)
- .expect(429, APIErrorCodes.RATE_LIMITED)
- .execute();
- expect(spend).toHaveBeenCalledTimes(1);
- spend.mockRestore();
- expect(await countReports()).toBe(0);
- await reportMessage(harness, owner.token, systemChannel.id, message.id).expect(HTTP_STATUS.OK).execute();
- expect(await countReports()).toBe(1);
- });
- });
describe('DSA Report Flow', () => {
test('should reject DSA message report with a non-numeric message link segment', async () => {
await clearTestEmails(harness);
diff --git a/fluxer_api/src/api/report/tests/ReportFlowAdmin.test.ts b/fluxer_api/src/api/report/tests/ReportFlowAdmin.test.ts
index 06c883688..1c532382a 100644
--- a/fluxer_api/src/api/report/tests/ReportFlowAdmin.test.ts
+++ b/fluxer_api/src/api/report/tests/ReportFlowAdmin.test.ts
@@ -2,9 +2,8 @@
import {createTestAccount, setUserACLs, type TestAccount} from '@app/api/auth/tests/AuthTestUtils';
import {Config} from '@app/api/Config';
-import {getChannel, sendChannelMessage, setupTestGuildWithMembers} from '@app/api/channel/tests/ChannelTestUtils';
+import {setupTestGuildWithMembers} from '@app/api/channel/tests/ChannelTestUtils';
import type {IARMessageContextRow, IARSubmissionRow} from '@app/api/database/types/ReportTypes';
-import {getReportFlowVariant, type ReportFlowStepInput} from '@app/api/report/flows/ReportFlowRegistry';
import {ReportRepository} from '@app/api/report/ReportRepository';
import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
import {HTTP_STATUS} from '@app/api/test/TestConstants';
@@ -12,7 +11,6 @@ import {createBuilder, createBuilderWithoutAuth} from '@app/api/test/TestRequest
import {deleteAccount, setPendingDeletionAt} from '@app/api/user/tests/UserTestUtils';
import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
import {ReportAdminResponseSchema} from '@fluxer/schema/src/domains/admin/AdminSchemas';
-import type {ReportFlowSurface, ReportFlowTargetType} from '@fluxer/schema/src/domains/report/ReportFlowSchemas';
import {
type ReportProfileSnapshot,
serializeReportProfileSnapshot,
@@ -33,63 +31,6 @@ interface AdminReportList {
limit: number;
}
-interface MessageTargets {
- reporter: TestAccount;
- channelId: string;
- messageIds: Array<string>;
-}
-
-const MESSAGE_CSAM_WALK: ReadonlyArray<ReportFlowStepInput> = [
- {screen_id: 'root_message', option_id: 'abuse'},
- {screen_id: 'abuse', option_id: 'sexual'},
- {screen_id: 'sexual', option_id: 'minor_sexual'},
- {screen_id: 'minor_sexual', option_id: 'csam'},
-];
-
-function currentHash(target: ReportFlowTargetType, surface: ReportFlowSurface = 'in_app'): string {
- return getReportFlowVariant(target, surface).revisionHash;
-}
-
-async function setupMessages(harness: ApiTestHarness, count: number): Promise<MessageTargets> {
- const {owner, members, guild} = await setupTestGuildWithMembers(harness, 1);
- const channel = await getChannel(harness, owner.token, guild.system_channel_id!);
- const messageIds: Array<string> = [];
- for (let index = 0; index < count; index++) {
- messageIds.push((await sendChannelMessage(harness, members[0].token, channel.id, `Reported ${index}`)).id);
- }
- return {reporter: owner, channelId: channel.id, messageIds};
-}
-
-async function submitMessageFlow(
- harness: ApiTestHarness,
- targets: MessageTargets,
- index: number,
- steps: ReadonlyArray<ReportFlowStepInput>,
- locale?: string,
-): Promise<string> {
- const result = await createBuilder<ReportResponse>(harness, targets.reporter.token)
- .post('/reports/flows/message/submissions')
- .body({
- channel_id: targets.channelId,
- message_id: targets.messageIds[index],
- revision_hash: currentHash('message'),
- steps,
- ...(locale ? {locale} : {}),
- })
- .expect(HTTP_STATUS.OK)
- .execute();
- return result.report_id;
-}
-
-async function submitLegacyMessage(harness: ApiTestHarness, targets: MessageTargets, index: number): Promise<string> {
- const result = await createBuilder<ReportResponse>(harness, targets.reporter.token)
- .post('/reports/message')
- .body({channel_id: targets.channelId, message_id: targets.messageIds[index], category: 'child_safety'})
- .expect(HTTP_STATUS.OK)
- .execute();
- return result.report_id;
-}
-
async function submitLegacyUser(harness: ApiTestHarness, reporter: TestAccount, userId: string): Promise<string> {
const result = await createBuilder<ReportResponse>(harness, reporter.token)
.post('/reports/user')
@@ -117,10 +58,6 @@ function getAdminReport(harness: ApiTestHarness, admin: TestAccount, reportId: s
.execute();
}
-function reportIds(list: AdminReportList): Array<string> {
- return list.reports.map((report) => report.report_id).sort();
-}
-
let seedSequence = 8_000_000_000_000_000_000n;
function nextSeedId(): bigint {
@@ -230,19 +167,6 @@ describe('Report flow admin', () => {
await harness?.shutdown();
});
- describe('Search', () => {
- test('a status filter with a reason uses the search index', async () => {
- const messages = await setupMessages(harness, 2);
- const messageCsam = await submitMessageFlow(harness, messages, 0, MESSAGE_CSAM_WALK);
- await submitLegacyMessage(harness, messages, 1);
- const admin = await createReportAdmin(harness);
- expect(reportIds(await listReports(harness, admin, 'status=pending'))).toHaveLength(2);
- const filtered = await listReports(harness, admin, 'status=pending&reason=csam');
- expect(reportIds(filtered)).toEqual([messageCsam]);
- expect(filtered.total).toBe(1);
- });
- });
-
describe('Stored evidence', () => {
test('a context message with no channel is left out and the detail still parses', async () => {
const {owner, guild} = await setupTestGuildWithMembers(harness, 0);
diff --git a/fluxer_api/src/api/rpc/tests/RpcGuildCollectionMembers.test.ts b/fluxer_api/src/api/rpc/tests/RpcGuildCollectionMembers.test.ts
index 4d405414c..60292215e 100644
--- a/fluxer_api/src/api/rpc/tests/RpcGuildCollectionMembers.test.ts
+++ b/fluxer_api/src/api/rpc/tests/RpcGuildCollectionMembers.test.ts
@@ -1,12 +1,11 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import {setupTestGuildWithMembers} from '@app/api/guild/tests/GuildTestUtils';
-import {createUsersServiceClient} from '@app/api/infrastructure/UsersServiceClient';
import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
import {HTTP_STATUS, TEST_IDS} from '@app/api/test/TestConstants';
import {createBuilder} from '@app/api/test/TestRequestBuilder';
import {RpcRequest} from '@fluxer/schema/src/domains/rpc/RpcSchemas';
-import {afterEach, beforeEach, describe, expect, test, vi} from 'vitest';
+import {afterEach, beforeEach, describe, expect, test} from 'vitest';
interface RpcGuildCollectionMembersResponse {
type: 'guild_collection';
@@ -70,34 +69,6 @@ describe('RpcService guild member collection pagination', () => {
expect(seenIds.slice().sort()).toStrictEqual(expectedIds.slice().sort());
});
- test('looks up every member user on a page in one users service request', async () => {
- const {owner, members, guild} = await setupTestGuildWithMembers(harness, 3);
- const memberIds = [owner.userId, ...members.map((member) => member.userId)].sort();
- const lookups = vi.spyOn(createUsersServiceClient(), 'getUserPartialResponses');
- try {
- const data = await fetchMemberPage(harness, guild.id, 1000);
- expect(data.members.map((member) => member.user.id).sort()).toStrictEqual(memberIds);
- const memberLookups = lookups.mock.calls
- .map(([userIds]) => userIds.map(String).sort())
- .filter((userIds) => userIds.some((userId) => memberIds.includes(userId)));
- expect(memberLookups).toStrictEqual([memberIds]);
- } finally {
- lookups.mockRestore();
- }
- });
-
- test('rejects an unknown guild on the first member page', async () => {
- await createBuilder(harness, '')
- .post('/test/rpc-session-init')
- .body({
- type: 'guild_collection',
- guild_id: TEST_IDS.NONEXISTENT_GUILD,
- collection: 'members',
- })
- .expect(HTTP_STATUS.NOT_FOUND)
- .execute();
- });
-
test('accepts the member page size the gateway requests', () => {
const atCeiling = RpcRequest.safeParse({
type: 'guild_collection',
diff --git a/fluxer_api/src/api/rpc/tests/RpcUserBatchFanout.test.ts b/fluxer_api/src/api/rpc/tests/RpcUserBatchFanout.test.ts
index b5c0293c4..ef8d901c9 100644
--- a/fluxer_api/src/api/rpc/tests/RpcUserBatchFanout.test.ts
+++ b/fluxer_api/src/api/rpc/tests/RpcUserBatchFanout.test.ts
@@ -6,7 +6,6 @@ import {HTTP_STATUS} from '@app/api/test/TestConstants';
import {createBuilder} from '@app/api/test/TestRequestBuilder';
import {blockUser} from '@app/api/user/tests/RelationshipTestUtils';
import {UserNotificationSettings} from '@fluxer/constants/src/UserConstants';
-import {RpcRequest} from '@fluxer/schema/src/domains/rpc/RpcSchemas';
import {afterEach, beforeEach, describe, expect, test} from 'vitest';
interface RpcUserGuildSettingsResponse {
@@ -70,23 +69,6 @@ describe('RpcService user batch fanout', () => {
).toStrictEqual(requested.map((entry) => entry.expected));
});
- test('rejects user batch requests above the schema bound', () => {
- for (const type of ['get_user_guild_settings', 'get_user_blocked_ids']) {
- const withinBound = RpcRequest.safeParse({
- type,
- user_ids: Array.from({length: 1000}, () => UNKNOWN_USER_ID),
- guild_id: '0',
- });
- expect(withinBound.success).toBe(true);
- const aboveBound = RpcRequest.safeParse({
- type,
- user_ids: Array.from({length: 1001}, () => UNKNOWN_USER_ID),
- guild_id: '0',
- });
- expect(aboveBound.success).toBe(false);
- }
- });
-
test('returns blocked ids per user for get_user_blocked_ids', async () => {
const blocker = await createTestAccount(harness);
const blockedFirst = await createTestAccount(harness);