A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
test(api): delete restated infra, worker and admin suites
Hampus1b26b110efb1
diff --git a/fluxer_api/src/api/admin/tests/GatewayAdminController.test.ts b/fluxer_api/src/api/admin/tests/GatewayAdminController.test.tsdeleted file mode 100644index 6a5a60884..000000000--- a/fluxer_api/src/api/admin/tests/GatewayAdminController.test.ts+++ /dev/null@@ -1,33 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {createAdminWithAcls} from '@app/api/admin/tests/AdminTestUtils';-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 {AdminACLs} from '@fluxer/constants/src/AdminACLs';-import {afterEach, beforeEach, describe, test} from 'vitest';--describe('GatewayAdminController', () => {- let harness: ApiTestHarness;- beforeEach(async () => {- harness = await createApiTestHarness();- });- afterEach(async () => {- await harness?.shutdown();- });- test('requires the gateway memory stats acl for guild memory statistics', async () => {- const admin = await createAdminWithAcls(harness, []);- await createBuilder(harness, `${admin.token}`)- .get('/admin/gateway/memory-stats')- .expect(HTTP_STATUS.FORBIDDEN)- .execute();- });- test('requires the gateway reload acl for reloads', async () => {- const admin = await createAdminWithAcls(harness, [AdminACLs.GATEWAY_MEMORY_STATS]);- await createBuilder(harness, `${admin.token}`)- .post('/admin/gateway/reloads')- .body({guild_ids: []})- .expect(HTTP_STATUS.FORBIDDEN)- .execute();- });-});diff --git a/fluxer_api/src/api/admin/tests/InstanceConfigLegalUrls.test.ts b/fluxer_api/src/api/admin/tests/InstanceConfigLegalUrls.test.tsdeleted file mode 100644index 5b4517f0e..000000000--- a/fluxer_api/src/api/admin/tests/InstanceConfigLegalUrls.test.ts+++ /dev/null@@ -1,143 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import type {TestAccount} from '@app/api/auth/tests/AuthTestUtils';-import {createTestAccount, setUserACLs} from '@app/api/auth/tests/AuthTestUtils';-import {getConfig} from '@app/api/Config';-import {setCachedConfiguredLegalUrls} from '@app/api/instance/LegalUrls';-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 {AdminACLs} from '@fluxer/constants/src/AdminACLs';-import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';-import type {InstanceConfigResponse} from '@fluxer/schema/src/domains/admin/AdminSchemas';-import type {WellKnownFluxerResponse} from '@fluxer/schema/src/domains/instance/InstanceSchemas';-import type {ReportFlowResponse} from '@fluxer/schema/src/domains/report/ReportFlowSchemas';-import {afterAll, beforeAll, beforeEach, describe, expect, it} from 'vitest';--const RULES_URL = 'https://rules.example.org/community';--function useInstanceHarness(selfHosted: boolean) {- const context: {harness: ApiTestHarness} = {harness: undefined as unknown as ApiTestHarness};- let originalSelfHosted: boolean;- beforeAll(async () => {- originalSelfHosted = getConfig().instance.selfHosted;- getConfig().instance.selfHosted = selfHosted;- context.harness = await createApiTestHarness();- });- beforeEach(async () => {- await context.harness.reset();- setCachedConfiguredLegalUrls({terms_url: null, guidelines_url: null});- });- afterAll(async () => {- await context.harness.shutdown();- getConfig().instance.selfHosted = originalSelfHosted;- setCachedConfiguredLegalUrls({terms_url: null, guidelines_url: null});- });- return context;-}--async function createAdmin(harness: ApiTestHarness): Promise<TestAccount> {- return await setUserACLs(harness, await createTestAccount(harness), [- AdminACLs.AUTHENTICATE,- AdminACLs.INSTANCE_CONFIG_VIEW,- AdminACLs.INSTANCE_CONFIG_UPDATE,- ]);-}--function patchLegal(harness: ApiTestHarness, admin: TestAccount, legal: Record<string, unknown>) {- return createBuilder<InstanceConfigResponse>(harness, admin.token)- .patch('/admin/instance/config')- .body({app_public: {legal}});-}--function getUserFlow(harness: ApiTestHarness): Promise<ReportFlowResponse> {- return createBuilderWithoutAuth<ReportFlowResponse>(harness)- .get('/reports/flows/user?surface=in_app&locale=en-US')- .expect(HTTP_STATUS.OK)- .execute();-}--describe('community guidelines URL on a self-hosted instance', () => {- const context = useInstanceHarness(true);-- it('is unset by default, so no guidelines link is offered', async () => {- const admin = await createAdmin(context.harness);- const config = await createBuilder<InstanceConfigResponse>(context.harness, admin.token)- .get('/admin/instance/config')- .execute();- expect(config.app_public.legal.guidelines_url).toBeNull();- const flow = await getUserFlow(context.harness);- expect(flow.guidelines_url).toBeNull();- expect(flow.screens[0].options).toEqual([]);- });-- it('round-trips through the admin API and reaches discovery and the report flow', async () => {- const admin = await createAdmin(context.harness);- const before = await getUserFlow(context.harness);- const updated = await patchLegal(context.harness, admin, {guidelines_url: ` ${RULES_URL} `}).execute();- expect(updated.app_public.legal).toEqual({terms_url: null, privacy_url: null, guidelines_url: RULES_URL});- const reread = await createBuilder<InstanceConfigResponse>(context.harness, admin.token)- .get('/admin/instance/config')- .execute();- expect(reread.app_public.legal.guidelines_url).toBe(RULES_URL);- const discovery = await createBuilderWithoutAuth<WellKnownFluxerResponse>(context.harness)- .get('/.well-known/fluxer')- .execute();- expect(discovery.app_public.legal.guidelines_url).toBe(RULES_URL);- const flow = await getUserFlow(context.harness);- expect(flow.guidelines_url).toBe(RULES_URL);- expect(flow.screens[0].options.map((option) => option.outcome.url)).toEqual([RULES_URL]);- expect(flow.revision_hash).not.toBe(before.revision_hash);- expect(flow.screens.find((screen) => screen.id === 'root_user')?.options.map((option) => option.id)).not.toContain(- 'dsa',- );- await patchLegal(context.harness, admin, {terms_url: 'https://rules.example.org/tos'}).execute();- expect((await getUserFlow(context.harness)).guidelines_url).toBe(RULES_URL);- const cleared = await patchLegal(context.harness, admin, {guidelines_url: null}).execute();- expect(cleared.app_public.legal.guidelines_url).toBeNull();- expect(cleared.app_public.legal.terms_url).toBe('https://rules.example.org/tos');- const after = await getUserFlow(context.harness);- expect(after.guidelines_url).toBeNull();- expect(after.revision_hash).toBe(before.revision_hash);- });-- it('clears every legal URL at once, and an empty string clears like null', async () => {- const admin = await createAdmin(context.harness);- await patchLegal(context.harness, admin, {- terms_url: 'https://rules.example.org/tos',- privacy_url: 'https://rules.example.org/privacy',- guidelines_url: RULES_URL,- }).execute();- const cleared = await patchLegal(context.harness, admin, {- terms_url: null,- privacy_url: '',- guidelines_url: '',- }).execute();- expect(cleared.app_public.legal).toEqual({terms_url: null, privacy_url: null, guidelines_url: null});- expect((await getUserFlow(context.harness)).guidelines_url).toBeNull();- });-- it.each(['rules.example.org', 'javascript:alert(1)', 'ftp://rules.example.org', '/guidelines'])(- 'rejects %j as a guidelines URL',- async (value) => {- const admin = await createAdmin(context.harness);- await patchLegal(context.harness, admin, {guidelines_url: value})- .expect(HTTP_STATUS.BAD_REQUEST, APIErrorCodes.INVALID_FORM_BODY)- .execute();- },- );-});--describe('community guidelines URL on a hosted instance', () => {- const context = useInstanceHarness(false);-- it('defaults to the marketing page and can be overridden', async () => {- const admin = await createAdmin(context.harness);- const hosted = await getUserFlow(context.harness);- expect(hosted.guidelines_url).toBe(`${getConfig().endpoints.marketing}/guidelines`);- await patchLegal(context.harness, admin, {guidelines_url: RULES_URL}).execute();- const flow = await getUserFlow(context.harness);- expect(flow.guidelines_url).toBe(RULES_URL);- expect(flow.revision_hash).toBe(hosted.revision_hash);- });-});diff --git a/fluxer_api/src/api/admin/tests/LimitConfigAllowedRange.test.ts b/fluxer_api/src/api/admin/tests/LimitConfigAllowedRange.test.tsdeleted file mode 100644index 9e337007c..000000000--- a/fluxer_api/src/api/admin/tests/LimitConfigAllowedRange.test.ts+++ /dev/null@@ -1,101 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import type {TestAccount} from '@app/api/auth/tests/AuthTestUtils';-import {createTestAccount, setUserACLs} from '@app/api/auth/tests/AuthTestUtils';-import {getInstanceConfigRepository, getLimitConfigService} from '@app/api/middleware/ServiceSingletons';-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 {AdminACLs} from '@fluxer/constants/src/AdminACLs';-import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';-import {- MAX_BIO_LENGTH,- MAX_SCREEN_SHARE_BITRATE_CEILING,- MIN_SCREEN_SHARE_BITRATE_CEILING,-} from '@fluxer/constants/src/LimitConstants';-import type {LimitConfigGetResponse} from '@fluxer/schema/src/domains/admin/AdminSchemas';-import {afterAll, beforeAll, beforeEach, describe, expect, it} from 'vitest';-import type {z} from 'zod';--type LimitConfigResponse = z.infer<typeof LimitConfigGetResponse>;--describe('limit config allowed ranges', () => {- let harness: ApiTestHarness;-- beforeAll(async () => {- harness = await createApiTestHarness();- });-- beforeEach(async () => {- await harness.reset();- });-- afterAll(async () => {- await harness.shutdown();- });-- async function createAdmin(): Promise<TestAccount> {- return await setUserACLs(harness, await createTestAccount(harness), [- AdminACLs.AUTHENTICATE,- AdminACLs.INSTANCE_LIMIT_CONFIG_VIEW,- AdminACLs.INSTANCE_LIMIT_CONFIG_UPDATE,- ]);- }-- function vipRule(maxBioLength: number) {- return {id: 'vip', filters: {traits: ['vip']}, limits: {max_bio_length: maxBioLength}};- }-- it('refuses a bio length above what a profile can hold', async () => {- const admin = await createAdmin();- await createBuilder(harness, admin.token)- .put('/admin/limit-config')- .body({limit_config: {traitDefinitions: ['vip'], rules: [vipRule(MAX_BIO_LENGTH + 1)]}})- .expect(HTTP_STATUS.BAD_REQUEST, APIErrorCodes.INVALID_FORM_BODY)- .execute();- const saved = await createBuilder<LimitConfigResponse>(harness, admin.token)- .put('/admin/limit-config')- .body({limit_config: {traitDefinitions: ['vip'], rules: [vipRule(MAX_BIO_LENGTH)]}})- .execute();- expect(saved.limit_config.rules.find((rule) => rule.id === 'vip')?.limits).toEqual({- max_bio_length: MAX_BIO_LENGTH,- });- expect(saved.metadata.max_bio_length).toMatchObject({min: 0, max: MAX_BIO_LENGTH});- });-- it('keeps a screen share bitrate ceiling inside its allowed range', async () => {- const admin = await createAdmin();- const rule = (bitrate: number) => ({- id: 'vip',- filters: {traits: ['vip']},- limits: {max_screen_share_bitrate: bitrate},- });- for (const bitrate of [MIN_SCREEN_SHARE_BITRATE_CEILING - 1, MAX_SCREEN_SHARE_BITRATE_CEILING + 1]) {- await createBuilder(harness, admin.token)- .put('/admin/limit-config')- .body({limit_config: {traitDefinitions: ['vip'], rules: [rule(bitrate)]}})- .expect(HTTP_STATUS.BAD_REQUEST, APIErrorCodes.INVALID_FORM_BODY)- .execute();- }- const saved = await createBuilder<LimitConfigResponse>(harness, admin.token)- .put('/admin/limit-config')- .body({limit_config: {traitDefinitions: ['vip'], rules: [rule(25_000_000)]}})- .execute();- expect(saved.limit_config.rules.find((entry) => entry.id === 'vip')?.limits).toEqual({- max_screen_share_bitrate: 25_000_000,- });- expect(saved.defaults.default?.max_screen_share_bitrate).toBe(9_000_000);- });-- it('reads a stored bio length above the profile maximum as the maximum', async () => {- const admin = await createAdmin();- await getInstanceConfigRepository().setLimitConfig({traitDefinitions: ['vip'], rules: [vipRule(1000)]});- await getLimitConfigService().refreshCache();- const response = await createBuilder<LimitConfigResponse>(harness, admin.token)- .get('/admin/limit-config')- .execute();- expect(response.limit_config.rules.find((rule) => rule.id === 'vip')?.limits).toEqual({- max_bio_length: MAX_BIO_LENGTH,- });- });-});diff --git a/fluxer_api/src/api/database/CassandraParamGuard.test.ts b/fluxer_api/src/api/database/CassandraParamGuard.test.tsdeleted file mode 100644index b05e4f890..000000000--- a/fluxer_api/src/api/database/CassandraParamGuard.test.ts+++ /dev/null@@ -1,64 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {assertNoUndefinedParams} from '@app/api/database/CassandraTypes';-import {describe, expect, it} from 'vitest';--function messageFor(path: string): string {- return `Undefined value at "${path}". This project forbids undefined in Cassandra params; use null explicitly or omit the column via PATCH.`;-}--function guardError(params: Record<string, unknown>): string {- try {- assertNoUndefinedParams(params);- } catch (error) {- return (error as Error).message;- }- throw new Error('Expected assertNoUndefinedParams to throw');-}--describe('assertNoUndefinedParams', () => {- it('accepts a realistic message row without throwing', () => {- expect(() =>- assertNoUndefinedParams({- message_id: 123n,- channel_id: 456n,- content: 'hello',- edited_at: null,- pinned: false,- created_at: new Date(0),- blob: Buffer.from('x'),- mention_users: [1n, 2n, 3n],- mention_roles: new Set(['a', 'b']),- reactions: new Map([['a', 1]]),- embeds: {title: 'a', fields: [{name: 'n', value: 'v'}], footer: {text: null}},- }),- ).not.toThrow();- });-- it('reports the dotted path of a top level undefined param', () => {- expect(guardError({user_id: undefined})).toBe(messageFor(':user_id'));- });-- it('reports the dotted path of an undefined map key', () => {- expect(guardError({reactions: new Map([['a', 1] as const, [undefined, 2] as const])})).toBe(- messageFor(':reactions{mapKey:1}'),- );- });-- it('reports the dotted path of an undefined map value', () => {- expect(- guardError({- reactions: new Map([- ['a', 1],- ['b', undefined],- ]),- }),- ).toBe(messageFor(':reactions{mapVal:1}'));- });-- it('reports the dotted path of an undefined value nested through mixed containers', () => {- expect(guardError({embeds: [{fields: new Set([new Map([['inline', undefined]])])}]})).toBe(- messageFor(':embeds[0].fields{set:0}{mapVal:0}'),- );- });-});diff --git a/fluxer_api/src/api/database/CassandraTypes.test.ts b/fluxer_api/src/api/database/CassandraTypes.test.tsdeleted file mode 100644index a6a986f3e..000000000--- a/fluxer_api/src/api/database/CassandraTypes.test.ts+++ /dev/null@@ -1,49 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {BatchBuilder, executeQuery, fetchPage} from '@app/api/database/CassandraQueryExecution';-import {getStatementMeta, normalizeInParams} from '@app/api/database/CassandraTypes';-import {describe, expect, it} from 'vitest';--describe('getStatementMeta', () => {- it('flags SELECT * statements as unsafe', () => {- expect(getStatementMeta('SELECT * FROM messages WHERE channel_id = :channel_id').unsafe).toBe(true);- expect(getStatementMeta(' select * FROM messages').unsafe).toBe(true);- expect(getStatementMeta('SELECT\n\t*\nFROM messages').unsafe).toBe(true);- });-- it('does not flag projected selects or other statements as unsafe', () => {- expect(getStatementMeta('SELECT id, content FROM messages WHERE id = :id').unsafe).toBe(false);- expect(getStatementMeta('SELECT count(*) FROM messages').unsafe).toBe(false);- expect(getStatementMeta('UPDATE messages SET content = :content WHERE id = :id').unsafe).toBe(false);- expect(getStatementMeta('SELECT').unsafe).toBe(false);- expect(getStatementMeta('').unsafe).toBe(false);- });-});--describe('normalizeInParams', () => {- it('expands Set values bound to IN parameters into arrays', () => {- const meta = getStatementMeta('SELECT id FROM messages WHERE id IN :ids');- const params = {ids: new Set(['a', 'b'])};- const normalized = normalizeInParams(meta, params);- expect(normalized).not.toBe(params);- expect(normalized.ids).toEqual(['a', 'b']);- });-- it('returns the original params when there is nothing to expand', () => {- const withoutIn = getStatementMeta('SELECT id FROM messages WHERE id = :id');- const params = {id: 'a'};- expect(normalizeInParams(withoutIn, params)).toBe(params);- const withIn = getStatementMeta('SELECT id FROM messages WHERE id IN :ids');- const arrayParams = {ids: ['a', 'b']};- expect(normalizeInParams(withIn, arrayParams)).toBe(arrayParams);- });-});--describe('unsafe statement guard', () => {- it('rejects SELECT * through every execution entrypoint', async () => {- const message = 'Cannot prepare a statement that looks like `SELECT *`';- await expect(executeQuery('SELECT * FROM messages', {})).rejects.toThrow(message);- await expect(fetchPage('SELECT * FROM messages', {}, {pageSize: 1})).rejects.toThrow(message);- await expect(new BatchBuilder().add('SELECT * FROM messages', {}).execute()).rejects.toThrow(message);- });-});diff --git a/fluxer_api/src/api/database/PostgresKvLoggerSafety.test.ts b/fluxer_api/src/api/database/PostgresKvLoggerSafety.test.tsdeleted file mode 100644index 345997e17..000000000--- a/fluxer_api/src/api/database/PostgresKvLoggerSafety.test.ts+++ /dev/null@@ -1,49 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {defineTable} from '@app/api/database/CassandraTableDsl';-import type {KvQueryMeta} from '@app/api/database/CassandraTypes';-import {describe, expect, it, vi} from 'vitest';--vi.mock('@app/api/Logger', () => ({- Logger: new Proxy(- {},- {- get() {- throw new Error('Logger has not been initialized. Call initializeLogger() first.');- },- },- ),-}));--type Row = Record<string, unknown>;--const Probe = defineTable<{k: string; v: string}, 'k'>({- name: 'kv_logger_probe',- columns: ['k', 'v'],- primaryKey: ['k'],-});--const client = {- async query() {- return {rows: [], rowCount: 0};- },- async connect() {},- async shutdown() {},- async transaction(fn: (db: unknown) => Promise<unknown>) {- return fn(client);- },- kvTable() {- return 'kv_logger_probe_table';- },-} as never;--describe('PostgresKvQueryExecutor logging safety', () => {- it('runs full scan queries in a process whose logger was never initialized', async () => {- const {PostgresKvQueryExecutor} = await import('@app/api/database/PostgresKvQueryExecutor');- const executor = new PostgresKvQueryExecutor(client);- for (const action of ['select', 'count', 'delete'] as const) {- const meta = {action, table: Probe, where: [], columns: ['k', 'v']} as unknown as KvQueryMeta<Row>;- await expect(executor.executeQuery({cql: `__probe_${action}`, params: {}, kvMeta: meta})).resolves.toBeDefined();- }- });-});diff --git a/fluxer_api/src/api/database/PostgresKvUnorderedScan.test.ts b/fluxer_api/src/api/database/PostgresKvUnorderedScan.test.tsdeleted file mode 100644index b870364de..000000000--- a/fluxer_api/src/api/database/PostgresKvUnorderedScan.test.ts+++ /dev/null@@ -1,69 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import type {KvQueryMeta, KvTableSpec} from '@app/api/database/CassandraTypes';-import {PostgresKvQueryExecutor} from '@app/api/database/PostgresKvQueryExecutor';-import type {IPostgresClient} from '@pkgs/postgres/src/Client';-import {describe, expect, it} from 'vitest';--type Row = Record<string, unknown>;--const Probe: KvTableSpec<Row> = {- name: 'kv_unordered_probe',- columns: ['user_id', 'username'],- primaryKey: ['user_id'],- partitionKey: ['user_id'],-};--function recordingClient(statements: Array<{text: string; values: Array<unknown> | undefined}>): IPostgresClient {- const client = {- async query(text: string, values?: Array<unknown>) {- statements.push({text, values});- const rows = [- {row_key: 'a', row_data: {user_id: '2', username: 'second'}},- {row_key: 'b', row_data: {user_id: '1', username: 'first'}},- ];- return {rows, rowCount: rows.length};- },- async connect() {},- async shutdown() {},- async transaction(fn: (db: unknown) => Promise<unknown>) {- return fn(client);- },- kvTable() {- return 'kv_unordered_table';- },- } as never;- return client;-}--function selectMeta(extra: Row): KvQueryMeta<Row> {- return {action: 'select', table: Probe, where: [], columns: ['user_id'], ...extra} as unknown as KvQueryMeta<Row>;-}--describe('Postgres KV unordered scan', () => {- it('pushes the limit into SQL for an unordered scan without filters', async () => {- const statements: Array<{text: string; values: Array<unknown> | undefined}> = [];- const executor = new PostgresKvQueryExecutor(recordingClient(statements));- const rows = await executor.executeQuery({- cql: '__unordered_probe',- params: {},- kvMeta: selectMeta({limit: 1, unordered: true}),- });- expect(statements).toHaveLength(1);- expect(statements[0]!.text).toMatch(/LIMIT \$2$/);- expect(statements[0]!.values).toEqual([Probe.name, 1]);- expect(rows).toEqual([{user_id: '2'}, {user_id: '1'}]);- });-- it('keeps the sorted full scan when the order cannot be walked by key', async () => {- const statements: Array<{text: string; values: Array<unknown> | undefined}> = [];- const executor = new PostgresKvQueryExecutor(recordingClient(statements));- const rows = await executor.executeQuery({- cql: '__ordered_probe',- params: {},- kvMeta: selectMeta({limit: 1, orderBy: {col: 'user_id', direction: 'DESC'}}),- });- expect(statements[0]!.text).not.toContain('LIMIT');- expect(rows).toEqual([{user_id: '2'}]);- });-});diff --git a/fluxer_api/src/api/download/tests/DownloadRedirects.test.ts b/fluxer_api/src/api/download/tests/DownloadRedirects.test.tsdeleted file mode 100644index c6285c830..000000000--- a/fluxer_api/src/api/download/tests/DownloadRedirects.test.ts+++ /dev/null@@ -1,12 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {resolveDownloadObjectPath} from '@app/api/download/DownloadRedirects';-import {describe, expect, it} from 'vitest';--describe('download object paths', () => {- it('refuses a traversal attempt rather than pointing at another prefix', () => {- expect(resolveDownloadObjectPath('/dl/desktop/../harvests/dump.zip')).toBeNull();- expect(resolveDownloadObjectPath('/dl/../desktop/stable/linux/x64/latest')).toBeNull();- expect(resolveDownloadObjectPath('/dl/desktop/stable/linux/x64/lat\0est')).toBeNull();- });-});diff --git a/fluxer_api/src/api/email/EmailProviderFactory.test.ts b/fluxer_api/src/api/email/EmailProviderFactory.test.tsdeleted file mode 100644index b1b8c9526..000000000--- a/fluxer_api/src/api/email/EmailProviderFactory.test.ts+++ /dev/null@@ -1,56 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import type {APIConfig} from '@app/api/config/APIConfig';-import {createEmailProvider} from '@app/api/email/EmailProviderFactory';-import {DomainRoutedEmailProvider} from '@pkgs/email/src/DomainRoutedEmailProvider';-import {SmtpEmailProvider} from '@pkgs/email/src/SmtpEmailProvider';-import nodemailer, {type Transporter} from 'nodemailer';-import {describe, expect, it, vi} from 'vitest';--const smtp = {host: 'smtp.example.com', port: 587, username: 'user', password: 'pass', tlsMode: null};--function emailConfig(overrides: Partial<APIConfig['email']> = {}): APIConfig['email'] {- return {- enabled: true,- provider: 'smtp',- fromEmail: '[email protected]',- fromName: 'Example',- replyToEmail: '',- appBaseUrl: 'https://example.com',- smtp,- ...overrides,- };-}--describe('createEmailProvider', () => {- it('returns the plain SMTP provider without a fallback', () => {- expect(createEmailProvider(emailConfig())).toBeInstanceOf(SmtpEmailProvider);- });-- it('routes by domain when a fallback is set', () => {- const provider = createEmailProvider(- emailConfig({fallback: {domains: ['gmail.com'], smtp: {...smtp, host: 'smtp.sendgrid.net'}}}),- );- expect(provider).toBeInstanceOf(DomainRoutedEmailProvider);- });-- it('adds the fallback headers only to mail through the fallback', async () => {- const sendMail = vi.fn();- vi.spyOn(nodemailer, 'createTransport').mockReturnValue({sendMail} as unknown as Transporter);- const headers = {'X-Tracking': '{"enable":0}'};- const provider = createEmailProvider(emailConfig({fallback: {domains: ['gmail.com'], smtp: {...smtp, headers}}}));- const from = {email: '[email protected]', name: 'Example'};- await provider?.sendEmail({to: '[email protected]', from, subject: 'Hi', text: 'Body'});- await provider?.sendEmail({to: '[email protected]', from, subject: 'Hi', text: 'Body'});- expect(sendMail.mock.calls[0][0].headers).toEqual({'X-Tracking': {prepared: true, value: '{"enable":0}'}});- expect(sendMail.mock.calls[1][0]).not.toHaveProperty('headers');- });-- it.each([{enabled: false}, {provider: 'none' as const}, {smtp: undefined}])(- 'returns no provider for %j even with a fallback',- (overrides) => {- const fallback = {domains: ['gmail.com'], smtp};- expect(createEmailProvider(emailConfig({fallback, ...overrides}))).toBeNull();- },- );-});diff --git a/fluxer_api/src/api/enforcement/tests/EnforcementCopy.test.ts b/fluxer_api/src/api/enforcement/tests/EnforcementCopy.test.tsdeleted file mode 100644index d4c44a30c..000000000--- a/fluxer_api/src/api/enforcement/tests/EnforcementCopy.test.ts+++ /dev/null@@ -1,82 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {CONTENT_I18N_MESSAGES} from '@app/api/content_i18n/ContentI18nMessages';-import {ERROR_I18N_MESSAGES} from '@fluxer/errors/src/i18n/ErrorI18nMessages';-import {EMAIL_I18N_MESSAGES} from '@pkgs/email/src/email_i18n/EmailI18nMessages';-import {describe, expect, it} from 'vitest';--const FORBIDDEN = [- /[–—]/,- /;/,- /\b(carry|carries|carried|matters|sitting)\b/i,- /\bservers?\b/i,- /platform admin/i,- /self-?bot|modified client|unofficial client/i,- /@fluxer\.app/i,-];--const ENFORCEMENT_EMAILS = new Set(['account_deletion_scheduled_requested', 'report_resolved', 'dsa_report_resolved']);--const ENFORCEMENT_ERRORS = new Set([- 'admin_and_system.moderation_basis_required',- 'moderation_and_reports.report_outcome_invalid',- 'moderation_and_reports.ip_ban_linked_to_decision',- 'permissions.global_ip_banned',- 'permissions.global_ip_temporarily_banned',-]);--const SERVER_CATALOG_TEXT: Array<[string, string]> = [- ...Object.entries(CONTENT_I18N_MESSAGES),- ...Object.entries(ERROR_I18N_MESSAGES),- ...Object.entries(EMAIL_I18N_MESSAGES).map(([key, template]): [string, string] => [- key,- `${template.subject}\n${template.body}`,- ]),-];--const ENFORCEMENT_COPY: Array<[string, string]> = [- ...Object.entries(CONTENT_I18N_MESSAGES).filter(([key]) => key.startsWith('enforcement.')),- ...Object.entries(EMAIL_I18N_MESSAGES)- .filter(([key]) => key.startsWith('enforcement_') || ENFORCEMENT_EMAILS.has(key))- .flatMap(- ([key, template]): Array<[string, string]> => [- [`${key}.subject`, template.subject],- [`${key}.body`, template.body],- ],- ),- ...Object.entries(ERROR_I18N_MESSAGES).filter(([key]) => key.includes('enforcement') || ENFORCEMENT_ERRORS.has(key)),-];--describe('enforcement copy', () => {- it('covers every catalog', () => {- expect(ENFORCEMENT_COPY.length).toBeGreaterThan(100);- });-- it.each(ENFORCEMENT_COPY)('%s follows the house style', (_key, text) => {- for (const pattern of FORBIDDEN) {- expect(text).not.toMatch(pattern);- }- });-- it('no server catalog blames platform administrators', () => {- expect(SERVER_CATALOG_TEXT.filter(([, text]) => /platform admin/i.test(text)).map(([key]) => key)).toEqual([]);- });-- it.each(['permissions.global_ip_banned', 'permissions.global_ip_temporarily_banned'] as const)(- '%s never says the reader did something or should sign in',- (key) => {- expect(ERROR_I18N_MESSAGES[key]).not.toMatch(/\byou (did|broke|violated)\b|sign in/i);- expect(ERROR_I18N_MESSAGES[key]).toContain('this block may have nothing to do with you');- },- );-- it.each(['report_resolved', 'dsa_report_resolved'] as const)(- '%s states the decision about the item instead of a generic review line',- (key) => {- const {subject, body} = EMAIL_I18N_MESSAGES[key];- expect(body).toContain('{outcome, select, removed {');- expect(body).toContain('} action_taken {We found that what you reported broke our rules, and we took action. ');- expect(`${subject}\n${body}`).not.toMatch(/already reviewed|take all reports seriously/i);- },- );-});diff --git a/fluxer_api/src/api/experiment/tests/ChannelThreadsGate.test.ts b/fluxer_api/src/api/experiment/tests/ChannelThreadsGate.test.tsdeleted file mode 100644index 02e7506f7..000000000--- a/fluxer_api/src/api/experiment/tests/ChannelThreadsGate.test.ts+++ /dev/null@@ -1,109 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {createGuildID, createUserID} from '@app/api/BrandedTypes';-import {setCassandraQueryExecutorForTesting, upsertOne} from '@app/api/database/CassandraQueryExecution';-import type {CassandraParams, PreparedQuery} from '@app/api/database/CassandraTypes';-import {- clearChannelThreadsTaintCacheForTesting,- isTainted,- noteGuildThreadMarker,-} from '@app/api/experiment/ChannelThreadsGate';-import {GuildRepository} from '@app/api/guild/repositories/GuildRepository';-import {setInjectedWorkerService} from '@app/api/middleware/ServiceRegistry';-import {GuildThreadState} from '@app/api/Tables';-import {InMemoryCassandraQueryExecutor} from '@app/api/test/InMemoryCassandraQueryExecutor';-import {NoopWorkerService} from '@app/api/test/NoopWorkerService';-import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';--class CountingExecutor extends InMemoryCassandraQueryExecutor {- reads = 0;- markerReads = 0;-- override async executeQuery<T = Record<string, unknown>, P extends CassandraParams = CassandraParams>(- query: PreparedQuery<P>,- ): Promise<Array<T>> {- if (query.cql.trimStart().toUpperCase().startsWith('SELECT')) this.reads++;- if (query.cql.includes('guild_thread_state')) this.markerReads++;- return super.executeQuery<T>(query);- }-}--const GUILD = createGuildID(100n);-const OTHER_GUILD = createGuildID(200n);-const USER = createUserID(10n);--describe('ChannelThreadsGate', () => {- let executor: CountingExecutor;-- beforeEach(() => {- executor = new CountingExecutor();- setCassandraQueryExecutorForTesting(executor);- clearChannelThreadsTaintCacheForTesting();- });-- afterEach(() => {- setCassandraQueryExecutorForTesting(null);- });-- it('reads the marker once per guild and remembers the answer', async () => {- await upsertOne(- GuildThreadState.upsertAll({- guild_id: GUILD,- first_active_at: new Date(),- perms_seeded_at: null,- search_backfilled_at: null,- }),- );- expect(await isTainted(GUILD)).toBe(true);- expect(await isTainted(GUILD)).toBe(true);- expect(await isTainted(OTHER_GUILD)).toBe(false);- expect(executor.reads).toBe(2);- noteGuildThreadMarker(OTHER_GUILD);- expect(await isTainted(OTHER_GUILD)).toBe(true);- expect(executor.reads).toBe(2);- });-- it('rereads a remembered clean answer for fresh checks and trusts a remembered taint', async () => {- expect(await isTainted(GUILD)).toBe(false);- await upsertOne(- GuildThreadState.upsertAll({- guild_id: GUILD,- first_active_at: new Date(),- perms_seeded_at: null,- search_backfilled_at: null,- }),- );- expect(await isTainted(GUILD)).toBe(false);- expect(executor.reads).toBe(1);- expect(await isTainted(GUILD, {fresh: true})).toBe(true);- expect(executor.reads).toBe(2);- expect(await isTainted(GUILD, {fresh: true})).toBe(true);- expect(await isTainted(GUILD)).toBe(true);- expect(executor.reads).toBe(2);- });-- it('enqueues thread membership cleanup on member removal despite a remembered clean answer', async () => {- const worker = new NoopWorkerService();- const addJob = vi.spyOn(worker, 'addJob');- setInjectedWorkerService(worker);- try {- expect(await isTainted(GUILD)).toBe(false);- await upsertOne(- GuildThreadState.upsertAll({- guild_id: GUILD,- first_active_at: new Date(),- perms_seeded_at: null,- search_backfilled_at: null,- }),- );- await new GuildRepository().deleteMember(GUILD, USER);- expect(addJob).toHaveBeenCalledWith(- 'removeThreadMembershipsForGuildMember',- {guildId: GUILD.toString(), userId: USER.toString()},- {jobKey: `remove-thread-memberships-${GUILD}-${USER}`},- );- } finally {- setInjectedWorkerService(undefined);- }- });-});diff --git a/fluxer_api/src/api/infrastructure/NatsUnfurlerService.test.ts b/fluxer_api/src/api/infrastructure/NatsUnfurlerService.test.tsdeleted file mode 100644index f9a616a64..000000000--- a/fluxer_api/src/api/infrastructure/NatsUnfurlerService.test.ts+++ /dev/null@@ -1,67 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {NatsUnfurlerService} from '@app/api/infrastructure/NatsUnfurlerService';-import {FakeNatsConnectionManager} from '@app/api/test/mocks/FakeNatsConnectionManager';-import {BadGatewayError} from '@fluxer/errors/src/domains/core/BadGatewayError';-import {ServiceUnavailableError} from '@fluxer/errors/src/domains/core/ServiceUnavailableError';-import {NoRespondersError, RequestError} from '@nats-io/transport-node';-import {describe, expect, it} from 'vitest';--const RESOLVED_REPLY = JSON.stringify({Resolved: {embeds: [], cache_ttl_seconds: null}});--describe('NatsUnfurlerService', () => {- it('does not send media proxy configuration in unfurl requests', async () => {- const manager = new FakeNatsConnectionManager(() => RESOLVED_REPLY);- const service = new NatsUnfurlerService(manager);-- await service.unfurlWithCachePolicy('https://fxtwitter.com/example/status/1', 'flag', {- bypassCache: true,- cacheOnly: false,- });-- expect(manager.connectCalls).toBe(1);- expect(manager.requests).toEqual([- {- subject: 'svc.unfurl',- body: {- op: 'Unfurl',- url: 'https://fxtwitter.com/example/status/1',- nsfw_mode: 'flag',- bypass_cache: true,- cache_only: false,- youtube_api_key: null,- klipy_api_key: null,- },- timeout: 12000,- },- ]);- expect(manager.requests[0]?.body).not.toHaveProperty('media_endpoint');- expect(manager.requests[0]?.body).not.toHaveProperty('media_proxy_endpoint');- expect(manager.requests[0]?.body).not.toHaveProperty('media_proxy_secret_key');- });-- it('rejects with a bad gateway error when the reply payload is unreadable', async () => {- const manager = new FakeNatsConnectionManager(() => 'not json');- const service = new NatsUnfurlerService(manager);-- await expect(service.unfurlWithCachePolicy('https://example.com')).rejects.toEqual(- new BadGatewayError({message: '[nats-unfurl] invalid response payload'}),- );- });-- it('rejects with a service unavailable error when no responders answer', async () => {- const manager = new FakeNatsConnectionManager(- () => new RequestError("no responders: 'svc.unfurl'", {cause: new NoRespondersError('svc.unfurl')}),- );- const service = new NatsUnfurlerService(manager);-- await expect(service.unfurlWithCachePolicy('https://example.com')).rejects.toBeInstanceOf(ServiceUnavailableError);- });-- it('rejects with a service unavailable error when the shard rejects the request', async () => {- const manager = new FakeNatsConnectionManager(() => JSON.stringify({error: 'overloaded'}));- const service = new NatsUnfurlerService(manager);-- await expect(service.unfurlWithCachePolicy('https://example.com')).rejects.toBeInstanceOf(ServiceUnavailableError);- });-});diff --git a/fluxer_api/src/api/infrastructure/SearchProvider.test.ts b/fluxer_api/src/api/infrastructure/SearchProvider.test.tsdeleted file mode 100644index 9e18f3e55..000000000--- a/fluxer_api/src/api/infrastructure/SearchProvider.test.ts+++ /dev/null@@ -1,53 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {SearchProvider, type SearchServices} from '@app/api/infrastructure/SearchProvider';-import {InMemorySearchProvider} from '@app/api/test/search/InMemorySearchProvider';-import {describe, expect, it, vi} from 'vitest';--function createServices(): SearchServices {- const provider = new InMemorySearchProvider();- const lifecycle = () => ({initialize: vi.fn(async () => {}), shutdown: vi.fn(async () => {})});- return {- message: Object.assign(provider.getMessageSearchService(), lifecycle()),- guild: Object.assign(provider.getGuildSearchService(), lifecycle()),- user: Object.assign(provider.getUserSearchService(), lifecycle()),- report: Object.assign(provider.getReportSearchService(), lifecycle()),- auditLog: Object.assign(provider.getAuditLogSearchService(), lifecycle()),- guildMember: Object.assign(provider.getGuildMemberSearchService(), lifecycle()),- thread: Object.assign(provider.getThreadSearchService(), {shutdown: vi.fn(async () => {})}),- };-}--describe('SearchProvider lifecycle', () => {- it('keeps all services available for cleanup after a partial initialization failure', async () => {- const services = createServices();- const failure = new Error('index creation failed');- vi.mocked(services.guild.initialize).mockRejectedValueOnce(failure);- const initialized = vi.fn();- const provider = new SearchProvider(async () => services, initialized);-- await expect(provider.initialize()).rejects.toBe(failure);- expect(provider.getMessageSearchService()).toBe(services.message);- expect(provider.getThreadSearchService()).toBe(services.thread);- expect(initialized).not.toHaveBeenCalled();- await provider.shutdown();-- for (const service of Object.values(services)) expect(service.shutdown).toHaveBeenCalledOnce();- expect(provider.getMessageSearchService()).toBeNull();- expect(provider.getThreadSearchService()).toBeNull();- });-- it('retains service references until shutdown succeeds so a failed shutdown can be retried', async () => {- const services = createServices();- const failure = new Error('adapter shutdown failed');- vi.mocked(services.thread.shutdown).mockRejectedValueOnce(failure);- const provider = new SearchProvider(async () => services);- await provider.initialize();-- await expect(provider.shutdown()).rejects.toBe(failure);- expect(provider.getThreadSearchService()).toBe(services.thread);- await provider.shutdown();- expect(services.thread.shutdown).toHaveBeenCalledTimes(2);- expect(provider.getThreadSearchService()).toBeNull();- });-});diff --git a/fluxer_api/src/api/infrastructure/StorageChangeFeed.test.ts b/fluxer_api/src/api/infrastructure/StorageChangeFeed.test.tsdeleted file mode 100644index da92c035b..000000000--- a/fluxer_api/src/api/infrastructure/StorageChangeFeed.test.ts+++ /dev/null@@ -1,158 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {- type StorageChangeEvent,- StorageChangeFeed,- type StorageChangeSink,-} from '@app/api/infrastructure/StorageChangeFeed';-import {describe, expect, it} from 'vitest';--interface PublishCall {- subject: string;- body: string;- msgID: string;-}--class ScriptedSink implements StorageChangeSink {- readonly calls: Array<PublishCall> = [];- closed = false;- private readonly outcomes: Array<() => Promise<void>>;-- constructor(outcomes: Array<() => Promise<void>> = []) {- this.outcomes = outcomes;- }-- async publish(subject: string, body: string, msgID: string): Promise<void> {- this.calls.push({subject, body, msgID});- const next = this.outcomes.shift();- if (next) await next();- }-- async close(): Promise<void> {- this.closed = true;- }-}--function change(key: string, overrides: Partial<StorageChangeEvent> = {}): StorageChangeEvent {- return {- bucket: 'fluxer',- key,- op: 'put',- size: 12,- etag: null,- contentType: 'image/png',- at: '2026-09-14T12:00:00.000Z',- ...overrides,- };-}--describe('StorageChangeFeed', () => {- it('publishes metadata to the bucket and operation subject with a dedupe id', async () => {- const sink = new ScriptedSink();- const feed = new StorageChangeFeed(sink);-- feed.record(change('attachments/1/2/cat.png'));- feed.record(change('avatars/3/abc', {bucket: 'fluxer.static', op: 'delete', etag: '"abc"'}));- await feed.idle();-- expect(sink.calls.map(({subject, msgID}) => ({subject, msgID}))).toEqual([- {subject: 'storage.fluxer.put', msgID: 'fluxer:attachments/1/2/cat.png:2026-09-14T12:00:00.000Z'},- {subject: 'storage.fluxer_static.delete', msgID: 'fluxer.static:avatars/3/abc:"abc"'},- ]);- expect(JSON.parse(sink.calls[0].body)).toEqual(change('attachments/1/2/cat.png'));- expect(feed.stats()).toEqual({queued: 0, published: 2, dropped: 0, failed: 0});- });-- it('does not publish before the caller has moved on', () => {- const sink = new ScriptedSink();- const feed = new StorageChangeFeed(sink);-- feed.record(change('attachments/1/2/cat.png'));-- expect(sink.calls).toEqual([]);- expect(feed.stats().queued).toBe(1);- });-- it('drops and counts events once the queue is full', async () => {- const gate = Promise.withResolvers<void>();- const sink = new ScriptedSink([() => gate.promise]);- const feed = new StorageChangeFeed(sink, {capacity: 2, concurrency: 1});-- for (const key of ['a', 'b', 'c', 'd', 'e']) {- feed.record(change(key));- }-- expect(feed.stats()).toEqual({queued: 2, published: 0, dropped: 3, failed: 0});- gate.resolve();- await feed.idle();- expect(sink.calls.map(({msgID}) => msgID.split(':')[1])).toEqual(['a', 'b']);- expect(feed.stats()).toEqual({queued: 0, published: 2, dropped: 3, failed: 0});- });-- it('retries a failed publish with the same dedupe id', async () => {- const sink = new ScriptedSink([() => Promise.reject(new Error('no responders'))]);- const feed = new StorageChangeFeed(sink, {retryDelayMs: 0});-- feed.record(change('attachments/1/2/cat.png'));- await feed.idle();-- expect(sink.calls).toHaveLength(2);- expect(sink.calls[0].msgID).toBe(sink.calls[1].msgID);- expect(feed.stats()).toEqual({queued: 0, published: 1, dropped: 0, failed: 0});- });-- it('counts an event as failed once its attempts run out and keeps going', async () => {- const reject = () => Promise.reject(new Error('stream offline'));- const sink = new ScriptedSink([reject, reject]);- const feed = new StorageChangeFeed(sink, {maxAttempts: 2, retryDelayMs: 0, concurrency: 1});-- feed.record(change('lost'));- feed.record(change('kept'));- await feed.idle();-- expect(sink.calls.map(({msgID}) => msgID.split(':')[1])).toEqual(['lost', 'lost', 'kept']);- expect(feed.stats()).toEqual({queued: 0, published: 1, dropped: 0, failed: 1});- });-- it('survives a sink that throws synchronously', async () => {- const sink: StorageChangeSink = {- publish: () => {- throw new Error('NATS connection is not established. Call connect() first.');- },- close: async () => undefined,- };- const feed = new StorageChangeFeed(sink, {maxAttempts: 1, retryDelayMs: 0});-- expect(() => feed.record(change('attachments/1/2/cat.png'))).not.toThrow();- await feed.idle();-- expect(feed.stats()).toEqual({queued: 0, published: 0, dropped: 0, failed: 1});- });-- it('flushes queued events on close, then closes the sink and drops later events', async () => {- const sink = new ScriptedSink();- const feed = new StorageChangeFeed(sink);-- feed.record(change('before-close'));- await feed.close(1000);- feed.record(change('after-close'));-- expect(sink.calls.map(({msgID}) => msgID.split(':')[1])).toEqual(['before-close']);- expect(sink.closed).toBe(true);- expect(feed.stats()).toEqual({queued: 0, published: 1, dropped: 1, failed: 0});- });-- it('stops waiting for a stuck publish when close runs out of time', async () => {- const sink = new ScriptedSink([() => new Promise<void>(() => undefined)]);- const feed = new StorageChangeFeed(sink, {concurrency: 1});-- feed.record(change('stuck'));- feed.record(change('waiting'));- await new Promise((resolve) => setImmediate(resolve));- await feed.close(10);-- expect(sink.calls.map(({msgID}) => msgID.split(':')[1])).toEqual(['stuck']);- expect(sink.closed).toBe(true);- expect(feed.stats()).toEqual({queued: 0, published: 0, dropped: 1, failed: 0});- });-});diff --git a/fluxer_api/src/api/infrastructure/UserCacheService.test.ts b/fluxer_api/src/api/infrastructure/UserCacheService.test.tsdeleted file mode 100644index 6f9225c00..000000000--- a/fluxer_api/src/api/infrastructure/UserCacheService.test.ts+++ /dev/null@@ -1,150 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {createUserID, type UserID} from '@app/api/BrandedTypes';-import {EMPTY_USER_ROW, type UserRow} from '@app/api/database/types/UserTypes';-import {UserCacheService} from '@app/api/infrastructure/UserCacheService';-import type {IUsersServiceClient} from '@app/api/infrastructure/UsersServiceClient';-import {createRequestCache} from '@app/api/middleware/RequestCacheMiddleware';-import {User} from '@app/api/models/User';-import {DELETED_USER_GLOBAL_NAME, DELETED_USER_USERNAME} from '@fluxer/constants/src/UserConstants';-import type {UserPartialResponse} from '@fluxer/schema/src/domains/user/UserResponseSchemas';-import {describe, expect, it} from 'vitest';--class FakeUsersServiceClient implements IUsersServiceClient {- readonly requests: Array<Array<UserID>> = [];- readonly invalidated: Array<UserID> = [];- shouldFail = false;-- constructor(private readonly partialsById = new Map<UserID, UserPartialResponse>()) {}-- async getUserPartialResponses(userIds: Array<UserID>): Promise<Map<UserID, UserPartialResponse>> {- this.requests.push([...userIds]);- if (this.shouldFail) {- throw new Error('user partial source unavailable');- }- const result = new Map<UserID, UserPartialResponse>();- for (const userId of userIds) {- const partial = this.partialsById.get(userId);- if (partial) {- result.set(userId, partial);- }- }- return result;- }-- async invalidateUserCache(userId: UserID): Promise<void> {- this.invalidated.push(userId);- }-}--function createPartial(userId: UserID, username: string): UserPartialResponse {- return {- id: userId.toString(),- username,- discriminator: '0001',- global_name: null,- avatar: null,- avatar_color: null,- flags: 0,- };-}--function createUser(userId: UserID, username: string): User {- return new User({- ...EMPTY_USER_ROW,- user_id: userId,- username,- discriminator: 42,- global_name: `${username} Global`,- bot: true,- flags: 0n,- version: 1,- } satisfies UserRow);-}--describe('UserCacheService', () => {- it('uses the users service for request-cache misses in one bulk call', async () => {- const userId1 = createUserID(1001n);- const userId2 = createUserID(1002n);- const partial1 = createPartial(userId1, 'CacheOne');- const partial2 = createPartial(userId2, 'CacheTwo');- const usersServiceClient = new FakeUsersServiceClient(- new Map([- [userId1, partial1],- [userId2, partial2],- ]),- );- const service = new UserCacheService(usersServiceClient);- const requestCache = createRequestCache();-- const result = await service.getUserPartialResponses([userId1, userId2, userId1], requestCache);-- expect(usersServiceClient.requests).toEqual([[userId1, userId2]]);- expect(result.get(userId1)).toBe(partial1);- expect(result.get(userId2)).toBe(partial2);- expect(requestCache.userPartials.get(userId1)).toBe(partial1);-- await service.getUserPartialResponses([userId1, userId2], requestCache);- expect(usersServiceClient.requests).toHaveLength(1);- });-- it('returns deleted-user partials for users the service reports as missing', async () => {- const serviceHitId = createUserID(2001n);- const missingId = createUserID(2002n);- const servicePartial = createPartial(serviceHitId, 'FromUsersService');- const usersServiceClient = new FakeUsersServiceClient(new Map([[serviceHitId, servicePartial]]));- const service = new UserCacheService(usersServiceClient);-- const result = await service.getUserPartialResponses([serviceHitId, missingId], createRequestCache());-- expect(usersServiceClient.requests).toEqual([[serviceHitId, missingId]]);- expect(result.get(serviceHitId)).toBe(servicePartial);- expect(result.get(missingId)).toMatchObject({- id: missingId.toString(),- username: DELETED_USER_USERNAME,- global_name: DELETED_USER_GLOBAL_NAME,- flags: 0,- });- });-- it('surfaces user partial source failures', async () => {- const userId = createUserID(3001n);- const usersServiceClient = new FakeUsersServiceClient();- usersServiceClient.shouldFail = true;- const service = new UserCacheService(usersServiceClient);-- await expect(service.getUserPartialResponse(userId, createRequestCache())).rejects.toThrow(- 'user partial source unavailable',- );- expect(usersServiceClient.requests).toEqual([[userId]]);- });-- it('seeds only the request cache when mapping a user on a read path', () => {- const userId = createUserID(4501n);- const usersServiceClient = new FakeUsersServiceClient();- const service = new UserCacheService(usersServiceClient);- const user = createUser(userId, 'ReadUser');- const requestCache = createRequestCache();-- const partial = service.setUserPartialResponseFromUserInRequestCache(user, requestCache);-- expect(partial.username).toBe('ReadUser');- expect(requestCache.userPartials.get(userId)).toBe(partial);- expect(usersServiceClient.invalidated).toEqual([]);- expect(usersServiceClient.requests).toEqual([]);- });-- it('invalidates the users service cache when seeding a partial from a user update', async () => {- const userId = createUserID(4001n);- const usersServiceClient = new FakeUsersServiceClient();- const service = new UserCacheService(usersServiceClient);- const user = createUser(userId, 'UpdatedUser');- const requestCache = createRequestCache();-- const partial = await service.setUserPartialResponseFromUser(user, requestCache);-- expect(partial.username).toBe('UpdatedUser');- expect(requestCache.userPartials.get(userId)).toBe(partial);- expect(usersServiceClient.invalidated).toEqual([userId]);- });-});diff --git a/fluxer_api/src/api/infrastructure/tests/AssetFormatPolicyParity.test.ts b/fluxer_api/src/api/infrastructure/tests/AssetFormatPolicyParity.test.tsdeleted file mode 100644index e73a64bee..000000000--- a/fluxer_api/src/api/infrastructure/tests/AssetFormatPolicyParity.test.ts+++ /dev/null@@ -1,31 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import fs from 'node:fs';-import path from 'node:path';-import {fileURLToPath} from 'node:url';-import {ASSET_FORMAT_POLICY} from '@fluxer/constants/src/AssetFormatPolicy';-import {describe, expect, it} from 'vitest';--const THIS_DIR = path.dirname(fileURLToPath(import.meta.url));-const REPO_ROOT = path.resolve(THIS_DIR, '../../../../..');--function parseRustAssetExtensionFunction(source: string, functionName: 'name' | 'mime'): Map<string, string> {- const regex = new RegExp(`pub fn ${functionName}\\(self\\)[^{]+\\{\\s*match self \\{([\\s\\S]*?)\\n\\s*\\}`, 'm');- const match = regex.exec(source);- expect(match, `missing Rust AssetExtension.${functionName}() match block`).not.toBeNull();- const block = match?.[1] ?? '';- return new Map([...block.matchAll(/Self::([A-Za-z]+)\s*=>\s*"([^"]+)"/g)].map((entry) => [entry[1], entry[2]]));-}--describe('AssetFormatPolicy parity', () => {- it('matches the media proxy extension MIME table', () => {- const rustSource = fs.readFileSync(path.join(REPO_ROOT, 'fluxer_media_proxy/src/constants.rs'), 'utf8');- const rustNames = parseRustAssetExtensionFunction(rustSource, 'name');- const rustMimes = parseRustAssetExtensionFunction(rustSource, 'mime');- const rustMimesByExtension = new Map(- [...rustNames.entries()].map(([variantName, extension]) => [extension, rustMimes.get(variantName)]),- );- expect([...rustMimesByExtension.keys()]).toEqual(ASSET_FORMAT_POLICY.attachment.upload);- expect(Object.fromEntries(rustMimesByExtension.entries())).toEqual(ASSET_FORMAT_POLICY.attachment.mimes);- });-});diff --git a/fluxer_api/src/api/infrastructure/tests/CallRpcCallerParams.test.ts b/fluxer_api/src/api/infrastructure/tests/CallRpcCallerParams.test.tsdeleted file mode 100644index ab5ea6674..000000000--- a/fluxer_api/src/api/infrastructure/tests/CallRpcCallerParams.test.ts+++ /dev/null@@ -1,86 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {createChannelID} from '@app/api/BrandedTypes';-import type {GatewayRpcTransport} from '@app/api/infrastructure/GatewayRpcClient';-import {GatewayRpcClient} from '@app/api/infrastructure/GatewayRpcClient';-import {GatewayService} from '@app/api/infrastructure/GatewayService';-import {afterEach, describe, expect, it} from 'vitest';--const CHANNEL_ID = createChannelID(12n);--interface RecordedCall {- method: string;- params: Record<string, unknown>;-}--function recordingService(recorded: Array<RecordedCall>): GatewayService {- const transport: GatewayRpcTransport = {- async call(method: string, params: Record<string, unknown>): Promise<unknown> {- recorded.push({method, params});- return null;- },- async destroy(): Promise<void> {},- };- GatewayRpcClient.createForTests(transport);- return new GatewayService();-}--describe('call rpc caller params', () => {- afterEach(async () => {- await GatewayRpcClient.resetForTests();- });-- it('sends the caller to call.create as caller_id, caller_name and caller_avatar', async () => {- const recorded: Array<RecordedCall> = [];- const service = recordingService(recorded);- await service.createCall(CHANNEL_ID, '99', 'automatic', ['2'], ['1', '2'], {- id: '1',- name: 'Elias',- avatar: 'a1b2c3d4',- });- expect(recorded).toHaveLength(1);- expect(recorded[0].method).toBe('call.create');- expect(recorded[0].params.caller_id).toBe('1');- expect(recorded[0].params.caller_name).toBe('Elias');- expect(recorded[0].params.caller_avatar).toBe('a1b2c3d4');- });-- it('sends the caller to call.ring as caller_id, caller_name and caller_avatar', async () => {- const recorded: Array<RecordedCall> = [];- const service = recordingService(recorded);- await service.ringCallRecipients(CHANNEL_ID, ['2'], {id: '1', name: 'Elias', avatar: 'a1b2c3d4'});- expect(recorded).toHaveLength(1);- expect(recorded[0].method).toBe('call.ring');- expect(recorded[0].params.caller_id).toBe('1');- expect(recorded[0].params.caller_name).toBe('Elias');- expect(recorded[0].params.caller_avatar).toBe('a1b2c3d4');- });-- it('sends caller_avatar as null when the caller has no avatar', async () => {- const recorded: Array<RecordedCall> = [];- const service = recordingService(recorded);- await service.ringCallRecipients(CHANNEL_ID, ['2'], {id: '1', name: 'Elias', avatar: null});- expect(recorded[0].params.caller_avatar).toBeNull();- expect(Object.hasOwn(recorded[0].params, 'caller_avatar')).toBe(true);- });-- it('omits every caller key from call.create when no caller was resolved', async () => {- const recorded: Array<RecordedCall> = [];- const service = recordingService(recorded);- await service.createCall(CHANNEL_ID, '99', 'automatic', ['2'], ['1', '2']);- expect(recorded[0].params).toEqual({- channel_id: '12',- message_id: '99',- region: 'automatic',- ringing: ['2'],- recipients: ['1', '2'],- });- });-- it('omits every caller key from call.ring when no caller was resolved', async () => {- const recorded: Array<RecordedCall> = [];- const service = recordingService(recorded);- await service.ringCallRecipients(CHANNEL_ID, ['2']);- expect(recorded[0].params).toEqual({channel_id: '12', recipients: ['2']});- });-});diff --git a/fluxer_api/src/api/infrastructure/tests/KVActivityTrackerFanout.test.ts b/fluxer_api/src/api/infrastructure/tests/KVActivityTrackerFanout.test.tsdeleted file mode 100644index 5f9cafb16..000000000--- a/fluxer_api/src/api/infrastructure/tests/KVActivityTrackerFanout.test.ts+++ /dev/null@@ -1,63 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {createUserID} from '@app/api/BrandedTypes';-import {KVActivityTracker} from '@app/api/infrastructure/KVActivityTracker';-import type {User} from '@app/api/models/User';-import {UserRepository} from '@app/api/user/repositories/UserRepository';-import {FanoutRecordingKVProvider} from '@pkgs/kv_client/src/testing/FanoutRecordingKVProvider';-import {afterEach, describe, expect, it, vi} from 'vitest';--const REBUILD_KV_BATCH_SIZE = 1000;-const MAX_CONCURRENT_ROUND_TRIPS = 16;--function mockUserPage(count: number): Array<User> {- const lastActiveAt = new Date('2026-06-01T00:00:00.000Z');- const users = Array.from(- {length: count},- (_unused, index) => ({id: createUserID(BigInt(index + 1)), lastActiveAt}) as unknown as User,- );- vi.spyOn(UserRepository.prototype, 'scanAllUsersPage').mockResolvedValue({users, pageState: null});- return users;-}--describe('KVActivityTracker rebuild fan out', () => {- afterEach(() => {- vi.restoreAllMocks();- });-- it('writes a full rebuild batch in one round trip outside cluster mode', async () => {- const kvClient = new FanoutRecordingKVProvider();- kvClient.clustered = false;- mockUserPage(REBUILD_KV_BATCH_SIZE);-- await new KVActivityTracker(kvClient).rebuildActivities();-- expect(kvClient.batches.map((batch) => batch.keys.length)).toEqual([REBUILD_KV_BATCH_SIZE, 1]);- expect(kvClient.batches[1]?.keys).toEqual(['activity_tracker:state_version']);- expect(kvClient.peakInFlight).toBe(1);- });-- it('bounds concurrent round trips when a rebuild batch spans hash slots', async () => {- const kvClient = new FanoutRecordingKVProvider();- const users = mockUserPage(REBUILD_KV_BATCH_SIZE);-- await new KVActivityTracker(kvClient).rebuildActivities();-- expect(kvClient.peakInFlight).toBeLessThanOrEqual(MAX_CONCURRENT_ROUND_TRIPS);- expect(kvClient.crossSlotBatches()).toEqual([]);- expect(- kvClient.batches.flatMap((batch) => batch.keys).filter((key) => key.startsWith('user_activity:')).length,- ).toBe(REBUILD_KV_BATCH_SIZE);- expect(kvClient.batches.at(-1)?.keys).toEqual(['activity_tracker:state_version']);- expect(await kvClient.get(`user_activity:${users[0].id}`)).toBe(users[0].lastActiveAt?.getTime().toString());- });-- it('fails the rebuild when a batched write fails', async () => {- const kvClient = new FanoutRecordingKVProvider();- const users = mockUserPage(REBUILD_KV_BATCH_SIZE);- kvClient.failingKey = `user_activity:${users[0].id}`;-- await expect(new KVActivityTracker(kvClient).rebuildActivities()).rejects.toThrow('write rejected');- expect(await kvClient.get('activity_tracker:state_version')).toBeNull();- });-});diff --git a/fluxer_api/src/api/infrastructure/tests/SvcErrorReply.test.ts b/fluxer_api/src/api/infrastructure/tests/SvcErrorReply.test.tsdeleted file mode 100644index b652535bc..000000000--- a/fluxer_api/src/api/infrastructure/tests/SvcErrorReply.test.ts+++ /dev/null@@ -1,34 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {svcErrorReplyReason, throwForSvcErrorReply} from '@app/api/infrastructure/SvcErrorReply';-import {ServiceUnavailableError} from '@fluxer/errors/src/domains/core/ServiceUnavailableError';-import {describe, expect, it} from 'vitest';--describe('SvcErrorReply', () => {- it('recognises the shard overload reply', () => {- expect(svcErrorReplyReason({error: 'overloaded'})).toBe('overloaded');- });-- it('maps an overload reply to a retryable service unavailable error', () => {- try {- throwForSvcErrorReply('users-service', {error: 'overloaded'});- expect.unreachable('should have thrown');- } catch (error) {- expect(error).toBeInstanceOf(ServiceUnavailableError);- expect((error as ServiceUnavailableError).status).toBe(503);- expect((error as ServiceUnavailableError).headers?.['Retry-After']).toBe('1');- }- });-- it('maps any other structured error reply to service unavailable', () => {- expect(() => throwForSvcErrorReply('users-service', {error: 'shard_unavailable'})).toThrow(ServiceUnavailableError);- });-- it('ignores a reply that is not a structured error', () => {- expect(svcErrorReplyReason({user: {id: '1'}})).toBeNull();- expect(svcErrorReplyReason(null)).toBeNull();- expect(svcErrorReplyReason('overloaded')).toBeNull();- expect(svcErrorReplyReason({error: ''})).toBeNull();- expect(() => throwForSvcErrorReply('users-service', {user: {id: '1'}})).not.toThrow();- });-});diff --git a/fluxer_api/src/api/instance/ProductName.test.ts b/fluxer_api/src/api/instance/ProductName.test.tsdeleted file mode 100644index ca522ea52..000000000--- a/fluxer_api/src/api/instance/ProductName.test.ts+++ /dev/null@@ -1,85 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {getConfig} from '@app/api/Config';-import {setCassandraQueryExecutorForTesting} from '@app/api/database/CassandraQueryExecution';-import {InstanceConfigRepository} from '@app/api/instance/InstanceConfigRepository';-import {getInstanceProductName, setCachedProductName} from '@app/api/instance/ProductName';-import {InMemoryCassandraQueryExecutor} from '@app/api/test/InMemoryCassandraQueryExecutor';-import {MockKVProvider} from '@pkgs/kv_client/src/testing/MockKVProvider';-import {afterEach, beforeEach, describe, expect, it} from 'vitest';--const WEB_APP_HOST = 'chat.example.org';--describe('getInstanceProductName', () => {- const config = getConfig();- const original = {- selfHosted: config.instance.selfHosted,- productName: config.instance.branding.productName,- webApp: config.endpoints.webApp,- };-- beforeEach(() => {- config.endpoints.webApp = `https://${WEB_APP_HOST}:8443/app`;- config.instance.branding.productName = '';- });-- afterEach(() => {- config.instance.selfHosted = original.selfHosted;- config.instance.branding.productName = original.productName;- config.endpoints.webApp = original.webApp;- setCachedProductName(null);- });-- describe('hosted', () => {- beforeEach(() => {- config.instance.selfHosted = false;- });-- it.each([- [null, 'Fluxer'],- ['Fluxer', 'Fluxer'],- ['Example Chat', 'Example Chat'],- ])('resolves %j to %j', (cached, expected) => {- setCachedProductName(cached);- expect(getInstanceProductName()).toBe(expected);- });- });-- describe('self-hosted', () => {- beforeEach(() => {- config.instance.selfHosted = true;- });-- it.each([null, '', ' ', 'Fluxer', ' fluxer ', 'FLUXER'])('resolves %j to the web app host', (cached) => {- setCachedProductName(cached);- expect(getInstanceProductName()).toBe(WEB_APP_HOST);- });-- it('resolves a configured default of Fluxer to the web app host', () => {- config.instance.branding.productName = 'Fluxer';- expect(getInstanceProductName()).toBe(WEB_APP_HOST);- });-- it.each(['Fluxer Community', 'Example Chat'])('leaves %j alone', (cached) => {- setCachedProductName(cached);- expect(getInstanceProductName()).toBe(cached);- });-- it('resolves a persisted Fluxer name to the web app host', async () => {- setCassandraQueryExecutorForTesting(new InMemoryCassandraQueryExecutor());- const kvProvider = new MockKVProvider();- const writer = new InstanceConfigRepository(kvProvider);- const reader = new InstanceConfigRepository(kvProvider);- try {- await writer.setConfig('app_public_config', JSON.stringify({branding: {product_name: 'Fluxer'}}));- setCachedProductName('Example Chat');- await reader.initialize();- expect((await reader.getAppPublicConfig()).branding.product_name).toBe('Fluxer');- expect(getInstanceProductName()).toBe(WEB_APP_HOST);- } finally {- writer.shutdown();- reader.shutdown();- }- });- });-});diff --git a/fluxer_api/src/api/middleware/tests/BlocklistRefreshRecovery.test.ts b/fluxer_api/src/api/middleware/tests/BlocklistRefreshRecovery.test.tsdeleted file mode 100644index 494f12ab5..000000000--- a/fluxer_api/src/api/middleware/tests/BlocklistRefreshRecovery.test.ts+++ /dev/null@@ -1,51 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {AdminRepository} from '@app/api/admin/AdminRepository';-import {IP_BAN_REFRESH_CHANNEL} from '@app/api/constants/IpBan';-import {Logger} from '@app/api/Logger';-import {ipBanCache} from '@app/api/middleware/IpBanMiddleware';-import {MockKVProvider} from '@pkgs/kv_client/src/testing/MockKVProvider';-import {afterEach, expect, it, vi} from 'vitest';--afterEach(async () => {- await ipBanCache.shutdown();- ipBanCache.setRefreshSubscriber(null);- ipBanCache.resetCaches();- vi.restoreAllMocks();- vi.unstubAllEnvs();- vi.useRealTimers();-});--it('keeps periodic failures at warn and resets notification escalation after a direct admin refresh', async () => {- await ipBanCache.shutdown();- vi.useFakeTimers({toFake: ['setInterval', 'clearInterval']});- vi.stubEnv('FLUXER_IP_BAN_REFRESH_INTERVAL_MS', '10');- const load = vi.spyOn(AdminRepository.prototype, 'loadAllBannedIpEntries').mockResolvedValue([]);- const logger = Logger.child({});- const warn = vi.spyOn(logger, 'warn').mockImplementation(() => {});- const error = vi.spyOn(logger, 'error').mockImplementation(() => {});- const provider = new MockKVProvider();- ipBanCache.setRefreshSubscriber(provider);- await ipBanCache.initialize();- load.mockRejectedValue(new Error('database unavailable'));-- for (let count = 1; count <= 4; count++) {- await provider.publish(IP_BAN_REFRESH_CHANNEL, 'changed');- await new Promise<void>((resolve) => setImmediate(resolve));- expect(warn).toHaveBeenCalledTimes(count);- }- await vi.advanceTimersByTimeAsync(10);- expect(warn).toHaveBeenLastCalledWith({error: 'database unavailable'}, 'Periodic IP ban cache refresh failed');- expect(error).not.toHaveBeenCalled();-- await provider.publish(IP_BAN_REFRESH_CHANNEL, 'changed');- await new Promise<void>((resolve) => setImmediate(resolve));- expect(error).toHaveBeenCalledTimes(1);- load.mockResolvedValue([]);- await ipBanCache.refresh();- load.mockRejectedValue(new Error('database unavailable'));- await provider.publish(IP_BAN_REFRESH_CHANNEL, 'changed');- await new Promise<void>((resolve) => setImmediate(resolve));- expect(warn).toHaveBeenCalledTimes(6);- expect(error).toHaveBeenCalledTimes(1);-});diff --git a/fluxer_api/src/api/middleware/tests/LazyServiceProvider.test.ts b/fluxer_api/src/api/middleware/tests/LazyServiceProvider.test.tsdeleted file mode 100644index 8154d9042..000000000--- a/fluxer_api/src/api/middleware/tests/LazyServiceProvider.test.ts+++ /dev/null@@ -1,46 +0,0 @@-import {ServiceMiddleware} from '@app/api/middleware/ServiceMiddleware';-import type {ApiTestHarness} from '@app/api/test/ApiTestHarness';-import {createApiTestHarness} from '@app/api/test/ApiTestHarness';-import type {HonoEnv} from '@app/api/types/HonoEnv';-import {Hono} from 'hono';-import {afterAll, beforeAll, describe, expect, it} from 'vitest';--const NO_CONTENT = 204;--describe('ServiceMiddleware lazy request services', () => {- let harness: ApiTestHarness;- beforeAll(async () => {- harness = await createApiTestHarness();- });- afterAll(async () => {- await harness?.shutdown();- });-- it('shares stateless services across requests and rebuilds request-scoped ones', async () => {- const reads: Array<Record<string, unknown>> = [];- const app = new Hono<HonoEnv>();- app.use(ServiceMiddleware);- app.get('/probe', (ctx) => {- reads.push({- guildService: ctx.get('guildService'),- guildServiceAgain: ctx.get('guildService'),- channelService: ctx.get('channelService'),- userCacheService: ctx.get('userCacheService'),- userRepository: ctx.get('userRepository'),- readStateRequestService: ctx.get('readStateRequestService'),- });- return ctx.body(null, NO_CONTENT);- });-- await app.request('/probe');- await app.request('/probe');-- const [first, second] = reads;- expect(first.guildService).toBe(first.guildServiceAgain);- expect(first.guildService).not.toBe(second.guildService);- expect(first.channelService).not.toBe(second.channelService);- expect(first.userCacheService).toBe(second.userCacheService);- expect(first.userRepository).toBe(second.userRepository);- expect(first.readStateRequestService).toBe(second.readStateRequestService);- });-});diff --git a/fluxer_api/src/api/models/GiftCodeGeneration.test.ts b/fluxer_api/src/api/models/GiftCodeGeneration.test.tsdeleted file mode 100644index 73d015151..000000000--- a/fluxer_api/src/api/models/GiftCodeGeneration.test.ts+++ /dev/null@@ -1,11 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {generateUniqueGiftCode} from '@app/api/models/GiftCode';-import {expect, it, vi} from 'vitest';--it('bounds repeated gift-code collisions so reconciliation cannot loop forever', async () => {- const findGiftCode = vi.fn(async (_code: string) => ({}));- await expect(generateUniqueGiftCode(findGiftCode)).rejects.toThrow('after 100 attempts');- expect(findGiftCode).toHaveBeenCalledTimes(100);- for (const [code] of findGiftCode.mock.calls) expect(code).toHaveLength(32);-});diff --git a/fluxer_api/src/api/oauth/tests/OAuth2OpenAPIScopeSurface.test.ts b/fluxer_api/src/api/oauth/tests/OAuth2OpenAPIScopeSurface.test.tsdeleted file mode 100644index e565e683d..000000000--- a/fluxer_api/src/api/oauth/tests/OAuth2OpenAPIScopeSurface.test.ts+++ /dev/null@@ -1,97 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import * as fs from 'node:fs';-import * as path from 'node:path';-import {fileURLToPath} from 'node:url';-import {describe, expect, test} from 'vitest';--interface OpenAPIOperation {- operationId?: string;- security?: Array<Record<string, Array<string>>>;-}--interface OpenAPISpec {- paths: Record<string, Record<string, OpenAPIOperation>>;-}--const SPEC_PATH = path.join(path.dirname(fileURLToPath(import.meta.url)), '../../openapi/openapi.json');--function readPublicOpenAPISpec(): OpenAPISpec {- return JSON.parse(fs.readFileSync(SPEC_PATH, 'utf-8')) as OpenAPISpec;-}--describe('OAuth2 OpenAPI scope surface', () => {- test('documents exactly the routes that accept OAuth2 bearer tokens', () => {- const spec = readPublicOpenAPISpec();- const actual: Array<{- method: string;- path: string;- operationId: string;- oauth2: Array<Array<string>>;- }> = [];- const methods = ['get', 'post', 'put', 'patch', 'delete'] as const;- for (const [routePath, pathItem] of Object.entries(spec.paths)) {- for (const method of methods) {- const operation = pathItem[method];- if (!operation) continue;- const oauth2 = (operation.security ?? [])- .filter((entry) => entry.oauth2Token !== undefined)- .map((entry) => [...entry.oauth2Token].sort());- const bearer = (operation.security ?? []).filter((entry) => entry.bearerToken !== undefined);- expect(bearer, `${method.toUpperCase()} ${routePath} should use oauth2Token, not bearerToken`).toEqual([]);- if (oauth2.length === 0) continue;- actual.push({- method: method.toUpperCase(),- path: routePath,- operationId: operation.operationId ?? '',- oauth2,- });- }- }- actual.sort((a, b) => `${a.method} ${a.path}`.localeCompare(`${b.method} ${b.path}`));- expect(actual).toEqual([- {- method: 'GET',- path: '/guilds/{guild_id}',- operationId: 'get_guild',- oauth2: [['guilds']],- },- {- method: 'GET',- path: '/guilds/{guild_id}/roles',- operationId: 'list_guild_roles',- oauth2: [['guilds']],- },- {- method: 'GET',- path: '/oauth2/@me',- operationId: 'get_current_user_oauth2',- oauth2: [[]],- },- {- method: 'GET',- path: '/oauth2/userinfo',- operationId: 'get_oauth2_userinfo',- oauth2: [['identify']],- },- {- method: 'GET',- path: '/users/@me',- operationId: 'get_current_user',- oauth2: [['identify']],- },- {- method: 'GET',- path: '/users/@me/connections',- operationId: 'list_connections',- oauth2: [['connections']],- },- {- method: 'GET',- path: '/users/@me/guilds',- operationId: 'list_guilds',- oauth2: [['guilds']],- },- ]);- });-});diff --git a/fluxer_api/src/api/report/tests/ReportTablesTtl.test.ts b/fluxer_api/src/api/report/tests/ReportTablesTtl.test.tsdeleted file mode 100644index 2447e98e9..000000000--- a/fluxer_api/src/api/report/tests/ReportTablesTtl.test.ts+++ /dev/null@@ -1,78 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import fs from 'node:fs';-import path from 'node:path';-import {fileURLToPath} from 'node:url';-import {clearTestEmails, createUniqueEmail, findLastTestEmail, listTestEmails} from '@app/api/auth/tests/AuthTestUtils';-import {ReportRepository} from '@app/api/report/ReportRepository';-import {DSAReportEmailVerifications, DSAReportTickets, IARReportNotes, IARSubmissions} from '@app/api/Tables';-import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';-import {HTTP_STATUS} from '@app/api/test/TestConstants';-import {createBuilderWithoutAuth} from '@app/api/test/TestRequestBuilder';-import {afterEach, beforeEach, describe, expect, it} from 'vitest';--const THIS_DIR = path.dirname(fileURLToPath(import.meta.url));-const REPO_ROOT = path.resolve(THIS_DIR, '../../../../..');--const SCHEMA = JSON.parse(fs.readFileSync(path.join(REPO_ROOT, 'tools/dev/cassandra_target_schema.json'), 'utf8')) as {- tables: Array<{name: string; options: string}>;-};--function schemaOptions(name: string): string {- const table = SCHEMA.tables.find((entry) => entry.name === name);- expect(table).toBeDefined();- return table!.options;-}--describe('report table TTLs', () => {- it('keeps reports without a table TTL', () => {- expect(IARSubmissions.defaultTtlSeconds).toBeUndefined();- expect(schemaOptions(IARSubmissions.name)).not.toContain('default_time_to_live');- });-- it('keeps report notes without a table TTL, so they go only with the report', () => {- expect(IARReportNotes.defaultTtlSeconds).toBeUndefined();- expect(schemaOptions(IARReportNotes.name)).not.toContain('default_time_to_live');- });-});--describe('report table TTLs cover the service windows', () => {- let harness: ApiTestHarness;-- beforeEach(async () => {- harness = await createApiTestHarness();- });-- afterEach(async () => {- await harness?.shutdown();- });-- it('a verification code and its ticket expire in the service before their rows do', async () => {- const repository = new ReportRepository();- await clearTestEmails(harness);- const email = createUniqueEmail('dsa-ttl');- await createBuilderWithoutAuth(harness)- .post('/reports/dsa/email/send')- .body({email})- .expect(HTTP_STATUS.OK)- .execute();- const verification = await repository.getDsaEmailVerification(email.toLowerCase());- expect(verification).not.toBeNull();- const codeWindow = verification!.expires_at.getTime() - verification!.last_sent_at.getTime();- expect(codeWindow).toBeLessThanOrEqual(DSAReportEmailVerifications.defaultTtlSeconds! * 1000);- expect(codeWindow).toBeGreaterThan(DSAReportEmailVerifications.defaultTtlSeconds! * 1000 - 60_000);-- const code = findLastTestEmail(await listTestEmails(harness), 'dsa_report_verification')?.metadata.code;- expect(typeof code).toBe('string');- const {ticket} = await createBuilderWithoutAuth<{ticket: string}>(harness)- .post('/reports/dsa/email/verify')- .body({email, code})- .expect(HTTP_STATUS.OK)- .execute();- const ticketRow = await repository.getDsaTicket(ticket);- expect(ticketRow).not.toBeNull();- const ticketWindow = ticketRow!.expires_at.getTime() - ticketRow!.created_at.getTime();- expect(ticketWindow).toBeLessThanOrEqual(DSAReportTickets.defaultTtlSeconds! * 1000);- expect(ticketWindow).toBeGreaterThan(DSAReportTickets.defaultTtlSeconds! * 1000 - 60_000);- });-});diff --git a/fluxer_api/src/api/worker/tests/BlocklistFeedStartup.test.ts b/fluxer_api/src/api/worker/tests/BlocklistFeedStartup.test.tsdeleted file mode 100644index 44044b802..000000000--- a/fluxer_api/src/api/worker/tests/BlocklistFeedStartup.test.ts+++ /dev/null@@ -1,84 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {queueBlocklistFeedStartupJobs} from '@app/api/worker/BlocklistFeedStartup';-import type {WorkerTaskName} from '@app/api/worker/WorkerLaneConfig';-import {WorkerQueueOverflowError} from '@app/api/worker/WorkerQueueOverflowError';-import {MockKVProvider} from '@pkgs/kv_client/src/testing/MockKVProvider';-import type {WorkerJobPayload} from '@pkgs/worker/src/contracts/WorkerTypes';-import {describe, expect, it, vi} from 'vitest';--const INITIAL_SYNC_KEY = 'sync:email_domains:initialized';-const FEED_TASKS = ['syncUrlBlocklists', 'syncFileShaBlocklists'];--function createWorkerService() {- return {addJob: vi.fn(async (_task: WorkerTaskName, _payload: WorkerJobPayload) => 1n)};-}--function queuedTasks(workerService: ReturnType<typeof createWorkerService>): Array<string> {- return workerService.addJob.mock.calls.map(([task]) => task);-}--describe('queueBlocklistFeedStartupJobs', () => {- it('with feeds on, a start queues nothing and marks the feeds as enabled for six hours', async () => {- const kv = new MockKVProvider();- const workerService = createWorkerService();-- await queueBlocklistFeedStartupJobs(kv, workerService, true);-- expect(workerService.addJob).not.toHaveBeenCalled();- expect(kv.setnxSpy.mock.calls).toEqual([[INITIAL_SYNC_KEY, '1', 21600]]);- expect(kv.delSpy).not.toHaveBeenCalled();- });-- it('with feeds off, the first start queues all three feed tasks and a second start queues none', async () => {- const kv = new MockKVProvider();- const workerService = createWorkerService();-- await queueBlocklistFeedStartupJobs(kv, workerService, false);- expect(workerService.addJob.mock.calls).toEqual(FEED_TASKS.map((task) => [task, {}]));-- await queueBlocklistFeedStartupJobs(kv, workerService, false);- expect(queuedTasks(workerService)).toEqual(FEED_TASKS);- });-- it('with feeds off, a start after a feeds-on start cleans up again inside the claim', async () => {- const kv = new MockKVProvider();- const workerService = createWorkerService();-- await queueBlocklistFeedStartupJobs(kv, workerService, false);- await queueBlocklistFeedStartupJobs(kv, workerService, true);- await queueBlocklistFeedStartupJobs(kv, workerService, false);-- expect(queuedTasks(workerService)).toEqual([...FEED_TASKS, ...FEED_TASKS]);- expect(await kv.exists(INITIAL_SYNC_KEY)).toBe(0);- });-- it('a legacy enabled marker without expiry is cleared when feeds are off', async () => {- const kv = new MockKVProvider();- await kv.set(INITIAL_SYNC_KEY, '1');- expect(await kv.ttl(INITIAL_SYNC_KEY)).toBe(-1);-- await queueBlocklistFeedStartupJobs(kv, createWorkerService(), false);- expect(await kv.exists(INITIAL_SYNC_KEY)).toBe(0);-- await queueBlocklistFeedStartupJobs(kv, createWorkerService(), true);- const ttl = await kv.ttl(INITIAL_SYNC_KEY);- expect(ttl).toBeGreaterThanOrEqual(21599);- expect(ttl).toBeLessThanOrEqual(21600);- });-- it('a full jobs stream drops the job without failing startup', async () => {- const overflowing = createWorkerService();- overflowing.addJob.mockImplementation(async (task) => {- throw new WorkerQueueOverflowError(task, 'maximum messages exceeded');- });- await expect(queueBlocklistFeedStartupJobs(new MockKVProvider(), overflowing, false)).resolves.toBeUndefined();- expect(queuedTasks(overflowing)).toEqual(FEED_TASKS);-- const failing = createWorkerService();- failing.addJob.mockRejectedValue(new Error('jetstream unavailable'));- await expect(queueBlocklistFeedStartupJobs(new MockKVProvider(), failing, false)).rejects.toThrow(- 'jetstream unavailable',- );- });-});diff --git a/fluxer_api/src/api/worker/tests/BlocklistFeedsDisabled.test.ts b/fluxer_api/src/api/worker/tests/BlocklistFeedsDisabled.test.tsdeleted file mode 100644index 55b3d0926..000000000--- a/fluxer_api/src/api/worker/tests/BlocklistFeedsDisabled.test.ts+++ /dev/null@@ -1,180 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {Config} from '@app/api/Config';-import {- BANNED_FILE_SHAS_REFRESH_CHANNEL,- BANNED_URLS_REFRESH_CHANNEL,- ContentBlocklistCategory,-} from '@app/api/constants/ContentModeration';-import type {BannedFileShaRow} from '@app/api/database/types/AdminArchiveTypes';-import {fileShaCache} from '@app/api/middleware/FileShaCache';-import {getAdminRepository} from '@app/api/middleware/ServiceSingletons';-import {urlBlocklistCache} from '@app/api/middleware/UrlBlocklistCache';-import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';-import {NoopLogger} from '@app/api/test/mocks/NoopLogger';-import {createTestWorkerHelpers} from '@app/api/test/SyncTaskWorkerService';-import {canonicalizeUrl} from '@app/api/utils/UrlNormalizer';-import syncFileShaBlocklists from '@app/api/worker/tasks/SyncFileShaBlocklists';-import syncUrlBlocklists from '@app/api/worker/tasks/SyncUrlBlocklists';-import {clearWorkerDependencies, setWorkerDependenciesForTest} from '@app/api/worker/WorkerContext';-import type {MockKVProvider} from '@pkgs/kv_client/src/testing/MockKVProvider';-import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, type MockInstance, vi} from 'vitest';--const FEED_BUCKET = 'fluxer-geoip';-const FEED_KEY = 'blocklists/feed-urls.txt';-const FEED_SHA = 'a1'.repeat(32);-const ADMIN_BAZAAR_SHA = 'b2'.repeat(32);-const ADMIN_MANUAL_SHA = 'c3'.repeat(32);-const UNOWNED_NCMEC_SHA = 'd4'.repeat(32);-const ADMIN_USER_ID = 42n;--function fileShaRow(sha256Hex: string, category: string, addedBy: bigint | null): BannedFileShaRow {- return {- sha256_hex: sha256Hex,- category,- severity: 2,- content_type: null,- source_url: null,- added_at: new Date(),- added_by: addedBy,- notes: null,- };-}--async function seedFileShas(): Promise<void> {- const adminRepository = getAdminRepository();- await adminRepository.banFileSha(fileShaRow(FEED_SHA, ContentBlocklistCategory.MALWARE_BAZAAR, null));- await adminRepository.banFileSha(- fileShaRow(ADMIN_BAZAAR_SHA, ContentBlocklistCategory.MALWARE_BAZAAR, ADMIN_USER_ID),- );- await adminRepository.banFileSha(fileShaRow(ADMIN_MANUAL_SHA, ContentBlocklistCategory.MANUAL, ADMIN_USER_ID));- await adminRepository.banFileSha(fileShaRow(UNOWNED_NCMEC_SHA, ContentBlocklistCategory.NCMEC, null));-}--describe('blocklist feeds turned off', () => {- let harness: ApiTestHarness;- let previousFeedsEnabled: boolean;- let fetchSpy: MockInstance<typeof fetch>;-- beforeAll(async () => {- harness = await createApiTestHarness();- });-- beforeEach(async () => {- previousFeedsEnabled = Config.blocklistFeeds.enabled;- await harness.reset();- harness.storageService.reset();- setWorkerDependenciesForTest({- adminRepository: getAdminRepository(),- kvClient: harness.kvProvider,- storageService: harness.storageService,- });- fetchSpy = vi.spyOn(globalThis, 'fetch');- });-- afterEach(() => {- Config.blocklistFeeds.enabled = previousFeedsEnabled;- fetchSpy.mockRestore();- });-- afterAll(async () => {- clearWorkerDependencies();- await harness?.shutdown();- });-- function publishCalls(): Array<Array<string>> {- return (harness.kvProvider as MockKVProvider).publishSpy.mock.calls;- }-- it('removes MalwareBazaar feed rows and keeps every other file-SHA ban', async () => {- await seedFileShas();- Config.blocklistFeeds.enabled = false;-- await syncFileShaBlocklists({}, createTestWorkerHelpers({jobId: 4242n, ...{}}));-- const remaining = (await getAdminRepository().loadAllBannedFileShas()).map((row) => row.sha256_hex).sort();- expect(remaining).toEqual([ADMIN_BAZAAR_SHA, ADMIN_MANUAL_SHA, UNOWNED_NCMEC_SHA]);- expect(publishCalls()).toEqual([[BANNED_FILE_SHAS_REFRESH_CHANNEL, 'refresh']]);- expect(fetchSpy).not.toHaveBeenCalled();- });-- it('file-SHA cache skips feed rows only while feeds are off', async () => {- await seedFileShas();-- Config.blocklistFeeds.enabled = false;- await fileShaCache.refresh();- expect(fileShaCache.isBanned(FEED_SHA)).toBe(false);- expect(fileShaCache.isBanned(ADMIN_BAZAAR_SHA)).toBe(true);- expect(fileShaCache.isBanned(ADMIN_MANUAL_SHA)).toBe(true);- expect(fileShaCache.isBanned(UNOWNED_NCMEC_SHA)).toBe(true);-- Config.blocklistFeeds.enabled = true;- await fileShaCache.refresh();- expect(fileShaCache.isBanned(FEED_SHA)).toBe(true);- });-- it('deletes the URL feed file and never fetches while feeds are off', async () => {- await harness.storageService.uploadObject({- bucket: FEED_BUCKET,- key: FEED_KEY,- body: Buffer.from('https://feed.example/x\n'),- });- Config.blocklistFeeds.enabled = false;-- await syncUrlBlocklists({}, createTestWorkerHelpers({jobId: 4242n, ...{}}));-- expect(harness.storageService.deleteObjectSpy).toHaveBeenCalledWith(FEED_BUCKET, FEED_KEY);- expect(harness.storageService.hasObject(FEED_BUCKET, FEED_KEY)).toBe(false);- expect(publishCalls()).toEqual([[BANNED_URLS_REFRESH_CHANNEL, 'refresh']]);- expect(fetchSpy).not.toHaveBeenCalled();-- const quietLogger = new NoopLogger();- const quietWarn = vi.spyOn(quietLogger, 'warn');- vi.spyOn(harness.storageService, 'deleteObject').mockRejectedValueOnce(- Object.assign(new Error('The specified bucket does not exist'), {name: 'NoSuchBucket'}),- );- await expect(- syncUrlBlocklists({}, createTestWorkerHelpers({jobId: 4242n, ...{logger: quietLogger}})),- ).resolves.toBeUndefined();- expect(quietWarn).not.toHaveBeenCalled();-- const loudLogger = new NoopLogger();- const loudWarn = vi.spyOn(loudLogger, 'warn');- harness.storageService.configure({shouldFailDelete: true});- await expect(- syncUrlBlocklists({}, createTestWorkerHelpers({jobId: 4242n, ...{logger: loudLogger}})),- ).resolves.toBeUndefined();- expect(loudWarn).toHaveBeenCalledTimes(1);- });-- it('URL cache ignores the feed file only while feeds are off', async () => {- const feedUrl = canonicalizeUrl('https://feed.example/x');- const adminUrl = canonicalizeUrl('https://admin.example/y');- expect(feedUrl).not.toBeNull();- expect(adminUrl).not.toBeNull();- await harness.storageService.uploadObject({- bucket: FEED_BUCKET,- key: FEED_KEY,- body: Buffer.from(`${feedUrl}\n`),- });- await getAdminRepository().banUrl({- url_canonical: adminUrl!,- category: ContentBlocklistCategory.MANUAL,- severity: 2,- source_url: null,- added_at: new Date(),- added_by: ADMIN_USER_ID,- notes: null,- });- urlBlocklistCache.setStorageService(harness.storageService);-- Config.blocklistFeeds.enabled = false;- await urlBlocklistCache.refresh();- expect(urlBlocklistCache.isUrlBanned('https://feed.example/x')).toBe(false);- expect(urlBlocklistCache.isUrlBanned('https://admin.example/y')).toBe(true);-- Config.blocklistFeeds.enabled = true;- await urlBlocklistCache.refresh();- expect(urlBlocklistCache.isUrlBanned('https://feed.example/x')).toBe(true);- });-});diff --git a/fluxer_api/src/api/worker/tests/ClearAuthenticatedReporterEmails.test.ts b/fluxer_api/src/api/worker/tests/ClearAuthenticatedReporterEmails.test.tsdeleted file mode 100644index c843cca60..000000000--- a/fluxer_api/src/api/worker/tests/ClearAuthenticatedReporterEmails.test.ts+++ /dev/null@@ -1,114 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {createReportID, type ReportID, type UserID} from '@app/api/BrandedTypes';-import {IAR_SUBMISSION_COLUMNS, type IARSubmissionRow} from '@app/api/database/types/ReportTypes';-import {ReportRepository} from '@app/api/report/ReportRepository';-import {clearAuthenticatedReporterEmails} from '@app/api/worker/tasks/ClearAuthenticatedReporterEmails';-import {beforeEach, describe, expect, it} from 'vitest';--let sequence = 1_490_000_000_000_000_000n;--function nextId(): bigint {- sequence += 1n;- return sequence;-}--describe('clearAuthenticatedReporterEmails', () => {- let repository: ReportRepository;-- beforeEach(() => {- repository = new ReportRepository();- });-- async function seed(reporterId: bigint | null, reporterEmail: string | null): Promise<ReportID> {- const id = nextId();- await repository.createReport({- ...Object.fromEntries(IAR_SUBMISSION_COLUMNS.map((column) => [column, null])),- report_id: id,- reporter_id: reporterId,- reporter_email: reporterEmail,- reporter_full_legal_name: reporterId === null ? 'Notifier Name' : null,- reported_at: new Date(),- status: 0,- report_type: 1,- category: 'harassment',- } as IARSubmissionRow);- return createReportID(id);- }-- async function storedEmail(reportId: ReportID): Promise<string | null | undefined> {- return (await repository.getReport(reportId))?.reporterEmail;- }-- it('clears the stored address on account reports and keeps it on notices filed without an account', async () => {- const reporterId = nextId();- const accountReports = [];- for (let index = 0; index < 5; index++) {- accountReports.push(await seed(reporterId, `reporter${index}@example.com`));- }- const withoutEmail = await seed(nextId(), null);- const notices = [await seed(null, '[email protected]'), await seed(null, '[email protected]')];-- const summary = await clearAuthenticatedReporterEmails(repository, 2);-- expect(summary).toEqual({scanned: 8, cleared: 5, skipped: 0, failed: 0});- for (const reportId of accountReports) {- expect(await storedEmail(reportId)).toBeNull();- }- expect(await storedEmail(withoutEmail)).toBeNull();- expect(await storedEmail(notices[0]!)).toBe('[email protected]');- expect(await storedEmail(notices[1]!)).toBe('[email protected]');- const notice = await repository.getReport(notices[0]!);- expect(notice?.reporterFullLegalName).toBe('Notifier Name');- });-- it('changes nothing on a second run', async () => {- await seed(nextId(), '[email protected]');- await seed(null, '[email protected]');- await clearAuthenticatedReporterEmails(repository);-- const summary = await clearAuthenticatedReporterEmails(repository);-- expect(summary).toEqual({scanned: 2, cleared: 0, skipped: 0, failed: 0});- });-- it('keeps the other fields of the report', async () => {- const reporterId = nextId();- const reportId = await seed(reporterId, '[email protected]');- const before = await repository.getReport(reportId);-- await clearAuthenticatedReporterEmails(repository);-- expect(await repository.getReport(reportId)).toEqual({...before, reporterEmail: null});- });-- it('counts a report that could not be updated and moves on to the next', async () => {- const failing = await seed(nextId(), '[email protected]');- const other = await seed(nextId(), '[email protected]');- const failingRepository = Object.create(repository) as ReportRepository;- failingRepository.clearReporterEmail = async (reportId: ReportID, reporterId: UserID) => {- if (reportId === failing) throw new Error('write timeout');- return repository.clearReporterEmail(reportId, reporterId);- };-- const summary = await clearAuthenticatedReporterEmails(failingRepository);-- expect(summary).toEqual({scanned: 2, cleared: 1, skipped: 0, failed: 1});- expect(await storedEmail(failing)).toBe('[email protected]');- expect(await storedEmail(other)).toBeNull();- });-- it('counts a report deleted while the backfill ran as skipped', async () => {- const deleted = await seed(nextId(), '[email protected]');- const racingRepository = Object.create(repository) as ReportRepository;- racingRepository.clearReporterEmail = async (reportId: ReportID, reporterId: UserID) => {- await repository.deleteReport(reportId);- return repository.clearReporterEmail(reportId, reporterId);- };-- const summary = await clearAuthenticatedReporterEmails(racingRepository);-- expect(summary).toEqual({scanned: 1, cleared: 0, skipped: 1, failed: 0});- expect(await repository.getReport(deleted)).toBeNull();- });-});diff --git a/fluxer_api/src/api/worker/tests/HandleMentionChunk.test.ts b/fluxer_api/src/api/worker/tests/HandleMentionChunk.test.tsdeleted file mode 100644index 7bf58ed16..000000000--- a/fluxer_api/src/api/worker/tests/HandleMentionChunk.test.ts+++ /dev/null@@ -1,171 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {- type ChannelID,- createChannelID,- createGuildID,- createMessageID,- createUserID,- type GuildID,- type MessageID,- type UserID,-} from '@app/api/BrandedTypes';-import type {RecentMentionRow} from '@app/api/database/types/UserTypes';-import {UserGuildSettings} from '@app/api/models/UserGuildSettings';-import type {ReadStateService} from '@app/api/read_state/ReadStateService';-import {createTestWorkerHelpers} from '@app/api/test/SyncTaskWorkerService';-import type {UserRepository} from '@app/api/user/repositories/UserRepository';-import handleMentionChunk from '@app/api/worker/tasks/HandleMentionChunk';-import {clearWorkerDependencies, setWorkerDependenciesForTest} from '@app/api/worker/WorkerContext';-import {afterEach, describe, expect, test} from 'vitest';--const CHANNEL_ID = '2000';-const MESSAGE_ID = '3000';-const GUILD_ID = '4000';--interface SuppressionFlags {- suppressEveryone?: boolean;- suppressRoles?: boolean;-}--function createGuildSettings(userId: UserID, guildId: GuildID, flags: SuppressionFlags): UserGuildSettings {- return new UserGuildSettings({- user_id: userId,- guild_id: guildId,- message_notifications: null,- muted: false,- mute_config: null,- mobile_push: false,- suppress_everyone: flags.suppressEveryone ?? false,- suppress_roles: flags.suppressRoles ?? false,- hide_muted_channels: false,- channel_overrides: null,- unread_badges: null,- version: 1,- });-}--function createHarness(settingsByUserId: Record<string, SuppressionFlags>) {- const settingsReads: Array<string> = [];- const incrementedUserIds: Array<string> = [];- const recentMentions: Array<RecentMentionRow> = [];- const userRepository = {- async findGuildSettings(userId: UserID, guildId: GuildID | null): Promise<UserGuildSettings | null> {- settingsReads.push(userId.toString());- const flags = settingsByUserId[userId.toString()];- if (!flags || guildId == null) {- return null;- }- return createGuildSettings(userId, guildId, flags);- },- async createRecentMentions(mentions: Array<RecentMentionRow>): Promise<void> {- recentMentions.push(...mentions);- },- } as unknown as UserRepository;- const readStateService = {- async bulkIncrementMentionCounts(- updates: Array<{userId: UserID; channelId: ChannelID; messageId: MessageID}>,- ): Promise<void> {- for (const update of updates) {- incrementedUserIds.push(update.userId.toString());- }- },- } as unknown as ReadStateService;- setWorkerDependenciesForTest({userRepository, readStateService});- return {settingsReads, incrementedUserIds, recentMentions};-}--async function runChunk(mentions: Array<{userId: string; direct?: boolean; role?: boolean; everyone?: boolean}>) {- await handleMentionChunk(- {channelId: CHANNEL_ID, messageId: MESSAGE_ID, guildId: GUILD_ID, mentions},- createTestWorkerHelpers(),- );-}--describe('handleMentionChunk', () => {- afterEach(() => {- clearWorkerDependencies();- });-- test('reads no guild settings for a direct-only mention chunk', async () => {- const harness = createHarness({});-- await runChunk([- {userId: '10', direct: true},- {userId: '11', direct: true},- {userId: '12', direct: true},- ]);-- expect(harness.settingsReads).toEqual([]);- expect(harness.incrementedUserIds).toEqual(['10', '11', '12']);- expect(- harness.recentMentions.map((mention) => [mention.user_id.toString(), mention.is_everyone, mention.is_role]),- ).toEqual([- ['10', false, false],- ['11', false, false],- ['12', false, false],- ]);- });-- test('honours suppressEveryone for everyone mentions', async () => {- const harness = createHarness({'11': {suppressEveryone: true}});-- await runChunk([- {userId: '10', everyone: true},- {userId: '11', everyone: true},- ]);-- expect(harness.settingsReads).toEqual(['10', '11']);- expect(harness.incrementedUserIds).toEqual(['10']);- expect(harness.recentMentions.map((mention) => [mention.user_id.toString(), mention.is_everyone])).toEqual([- ['10', true],- ]);- });-- test('honours suppressRoles for role mentions', async () => {- const harness = createHarness({'11': {suppressRoles: true}});-- await runChunk([- {userId: '10', role: true},- {userId: '11', role: true},- ]);-- expect(harness.settingsReads).toEqual(['10', '11']);- expect(harness.incrementedUserIds).toEqual(['10']);- expect(harness.recentMentions.map((mention) => [mention.user_id.toString(), mention.is_role])).toEqual([- ['10', true],- ]);- });-- test('still applies suppression flags to recent mentions when a user is also directly mentioned', async () => {- const harness = createHarness({'10': {suppressEveryone: true, suppressRoles: true}});-- await runChunk([{userId: '10', direct: true, everyone: true, role: true}]);-- expect(harness.settingsReads).toEqual(['10']);- expect(harness.incrementedUserIds).toEqual(['10']);- expect(harness.recentMentions).toEqual([- {- user_id: createUserID(10n),- channel_id: createChannelID(BigInt(CHANNEL_ID)),- message_id: createMessageID(BigInt(MESSAGE_ID)),- guild_id: createGuildID(BigInt(GUILD_ID)),- is_everyone: false,- is_role: false,- },- ]);- });-- test('reads no guild settings outside a guild', async () => {- const harness = createHarness({});-- await handleMentionChunk(- {channelId: CHANNEL_ID, messageId: MESSAGE_ID, mentions: [{userId: '10', direct: true}]},- createTestWorkerHelpers(),- );-- expect(harness.settingsReads).toEqual([]);- expect(harness.incrementedUserIds).toEqual(['10']);- expect(harness.recentMentions).toEqual([]);- });-});diff --git a/fluxer_api/src/api/worker/tests/WorkerLaneConfig.test.ts b/fluxer_api/src/api/worker/tests/WorkerLaneConfig.test.tsdeleted file mode 100644index cb2274eb9..000000000--- a/fluxer_api/src/api/worker/tests/WorkerLaneConfig.test.ts+++ /dev/null@@ -1,39 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {resolveWorkerLanes, validateLaneCompleteness, WORKER_LANES} from '@app/api/worker/WorkerLaneConfig';-import {describe, expect, it} from 'vitest';--describe('WorkerLaneConfig', () => {- it('keeps each retired subject on the lane that used to run it', () => {- const lanes = resolveWorkerLanes({- mode: 'all_lanes',- laneConcurrencyOverrides: {},- });- const retired = Object.fromEntries(lanes.map((lane) => [lane.name, lane.retiredTaskTypes]));- expect(retired).toEqual({- realtime: [],- unfurl: [],- lifecycle: ['sendScheduledMessage', 'finalizeNcmecAttachmentReport'],- batch: [],- crosspost: [],- });- for (const lane of lanes) {- for (const task of lane.retiredTaskTypes) expect(lane.taskTypes).not.toContain(task);- }- });- it('never claims a retired subject from a single_task lane', () => {- const lanes = resolveWorkerLanes({- mode: 'single_task',- taskName: 'processStripeWebhook',- laneConcurrencyOverrides: {},- });- expect(lanes[0]!.retiredTaskTypes).toEqual([]);- });- it('rejects a registry that brings a retired task name back', () => {- const registry = Object.fromEntries(WORKER_LANES.flatMap((lane) => lane.taskTypes).map((task) => [task, () => {}]));- expect(() => validateLaneCompleteness(registry)).not.toThrow();- expect(() => validateLaneCompleteness({...registry, sendScheduledMessage: () => {}})).toThrow(- /Retired tasks registered again: sendScheduledMessage/,- );- });-});diff --git a/fluxer_api/src/api/worker/tests/WorkerServiceLedger.test.ts b/fluxer_api/src/api/worker/tests/WorkerServiceLedger.test.tsdeleted file mode 100644index 675eb6ce1..000000000--- a/fluxer_api/src/api/worker/tests/WorkerServiceLedger.test.ts+++ /dev/null@@ -1,148 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import type {ISnowflakeService} from '@app/api/infrastructure/ISnowflakeService';-import type {CreateJobInput, JobLedgerRepository} from '@app/api/jobs/JobLedgerRepository';-import type {JetStreamWorkerQueue} from '@app/api/worker/JetStreamWorkerQueue';-import {WorkerService} from '@app/api/worker/WorkerService';-import {describe, expect, test} from 'vitest';--const JOB_ID = 4242n;-const CREATED_AT = new Date('2026-09-21T12:00:00.000Z');--function createSnowflake(): ISnowflakeService {- return {- generate: async () => JOB_ID,- } as unknown as ISnowflakeService;-}--function createHarness(options?: {- createJobError?: Error;- enqueueError?: Error;- duplicate?: boolean;- discardError?: Error;-}) {- const calls: Array<string> = [];- const createdJobs: Array<CreateJobInput> = [];- const enqueued: Array<{taskType: string; payload: Record<string, unknown>}> = [];- const seqUpdates: Array<{jobId: bigint; seq: string}> = [];- const deadletters: Array<{jobId: bigint; errorMessage: string}> = [];- const discarded: Array<{jobId: bigint; createdAt: Date}> = [];- const ledger = {- createJob: async (input: CreateJobInput) => {- calls.push('createJob');- if (options?.createJobError) throw options.createJobError;- createdJobs.push(input);- return CREATED_AT;- },- setJetStreamSeq: async (jobId: bigint, seq: string) => {- calls.push('setJetStreamSeq');- seqUpdates.push({jobId, seq});- },- markDeadletter: async (jobId: bigint, errorMessage: string) => {- calls.push('markDeadletter');- deadletters.push({jobId, errorMessage});- },- discardJob: async (jobId: bigint, createdAt: Date) => {- calls.push('discardJob');- if (options?.discardError) throw options.discardError;- discarded.push({jobId, createdAt});- },- } as unknown as JobLedgerRepository;- const queue = {- enqueue: async (taskType: string, payload: Record<string, unknown>) => {- calls.push('enqueue');- if (options?.enqueueError) throw options.enqueueError;- enqueued.push({taskType, payload});- return {seq: 'seq-9', duplicate: options?.duplicate === true};- },- } as unknown as JetStreamWorkerQueue;- const service = new WorkerService(queue, createSnowflake(), ledger);- return {service, calls, createdJobs, enqueued, seqUpdates, deadletters, discarded};-}--describe('WorkerService ledger ordering', () => {- test('writes the ledger row before enqueueing and patches the sequence afterwards', async () => {- const harness = createHarness();-- const jobId = await harness.service.addJob('bulkUpdateUserFlags', {user_ids: []});-- expect(jobId).toBe(JOB_ID);- expect(harness.calls).toEqual(['createJob', 'enqueue', 'setJetStreamSeq']);- expect(harness.createdJobs[0]!.jetStreamSeq).toBeNull();- expect(harness.seqUpdates).toEqual([{jobId: JOB_ID, seq: 'seq-9'}]);- expect(harness.enqueued[0]!.payload.__jobId).toBe(JOB_ID.toString());- });-- test('rejects without enqueueing when the ledger write fails and the caller requires it', async () => {- const harness = createHarness({createJobError: new Error('cassandra unavailable')});-- await expect(harness.service.addJob('bulkUpdateUserFlags', {user_ids: []}, {requireLedger: true})).rejects.toThrow(- 'cassandra unavailable',- );- expect(harness.calls).toEqual(['createJob']);- expect(harness.enqueued).toEqual([]);- });-- test('still enqueues a row-less job when the ledger write fails and the caller tolerates it', async () => {- const harness = createHarness({createJobError: new Error('cassandra unavailable')});-- const jobId = await harness.service.addJob('bulkUpdateUserFlags', {user_ids: []});-- expect(jobId).toBe(JOB_ID);- expect(harness.calls).toEqual(['createJob', 'enqueue']);- expect(harness.enqueued[0]!.payload).not.toHaveProperty('__jobId');- });-- test('marks the ledger row terminal when the enqueue fails', async () => {- const harness = createHarness({enqueueError: new Error('stream unreachable')});-- await expect(harness.service.addJob('bulkUpdateUserFlags', {user_ids: []})).rejects.toThrow('stream unreachable');- expect(harness.calls).toEqual(['createJob', 'enqueue', 'markDeadletter']);- expect(harness.deadletters).toEqual([{jobId: JOB_ID, errorMessage: 'stream unreachable'}]);- });-- test('discards the ledger row when the stream already holds a job under the same key', async () => {- const harness = createHarness({duplicate: true});-- const jobId = await harness.service.addJob(- 'batchGuildAuditLogMessageDeletes',- {guildId: '1'},- {jobKey: 'batch-audit-log-message-deletes:1'},- );-- expect(jobId).toBe(JOB_ID);- expect(harness.calls).toEqual(['createJob', 'enqueue', 'discardJob']);- expect(harness.discarded).toEqual([{jobId: JOB_ID, createdAt: CREATED_AT}]);- expect(harness.seqUpdates).toEqual([]);- });-- test('still returns the job id when discarding the duplicate ledger row fails', async () => {- const harness = createHarness({duplicate: true, discardError: new Error('write timeout')});-- const jobId = await harness.service.addJob(- 'batchGuildAuditLogMessageDeletes',- {guildId: '1'},- {jobKey: 'batch-audit-log-message-deletes:1'},- );-- expect(jobId).toBe(JOB_ID);- expect(harness.calls).toEqual(['createJob', 'enqueue', 'discardJob']);- });-- test('does not touch the ledger for a duplicate the caller never ledgered', async () => {- const harness = createHarness({duplicate: true});-- await harness.service.addJob('handleMentions', {}, {skipLedger: true, jobKey: 'mentions:1'});-- expect(harness.calls).toEqual(['enqueue']);- });-- test('never touches the ledger when the caller skips it', async () => {- const harness = createHarness();-- await harness.service.addJob('handleMentions', {}, {skipLedger: true});-- expect(harness.calls).toEqual(['enqueue']);- expect(harness.enqueued[0]!.payload).not.toHaveProperty('__jobId');- });-});