Skip to content

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

TypeScript fluxerfluxerapp

test(packages): trim error handler, server limit, thread suites

Hampus8d25c3a8c21d
diff --git a/packages/constants/src/ThreadConstants.test.ts b/packages/constants/src/ThreadConstants.test.ts
index 6af8d216f..72ea07198 100644
--- a/packages/constants/src/ThreadConstants.test.ts
+++ b/packages/constants/src/ThreadConstants.test.ts
@@ -1,25 +1,14 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import * as ChannelConstants from '@fluxer/constants/src/ChannelConstants';
-import {
- ChannelTypes,
- GUILD_TEXT_BASED_CHANNEL_TYPES,
- isMessageTypeDeletable,
- MessageTypes,
- TEXT_BASED_CHANNEL_TYPES,
-} from '@fluxer/constants/src/ChannelConstants';
+import {ChannelTypes, isMessageTypeDeletable, MessageTypes} from '@fluxer/constants/src/ChannelConstants';
import * as ThreadConstants from '@fluxer/constants/src/ThreadConstants';
import {
ChannelFlags,
isValidThreadMemberSettingsFlags,
- publicThreadTypeFor,
resolveTextThreadType,
settableChannelFlags,
- THREAD_CHANNEL_TYPES,
- THREAD_FEATURE_CHANNEL_TYPES,
THREAD_MESSAGE_FLAG_MASK,
- THREAD_ONLY_CHANNEL_TYPES,
- THREAD_PARENT_CHANNEL_TYPES,
ThreadMemberFlags,
} from '@fluxer/constants/src/ThreadConstants';
import {describe, expect, it} from 'vitest';
@@ -33,37 +22,6 @@ function numericValues(value: unknown): Array<number> {
}
describe('thread channel and message types', () => {
- it('uses the expected channel type numbers', () => {
- expect(ChannelTypes.ANNOUNCEMENT_THREAD).toBe(10);
- expect(ChannelTypes.PUBLIC_THREAD).toBe(11);
- expect(ChannelTypes.PRIVATE_THREAD).toBe(12);
- expect(ChannelTypes.GUILD_FORUM).toBe(15);
- expect(ChannelTypes.GUILD_MEDIA).toBe(16);
- expect(MessageTypes.THREAD_CREATED).toBe(18);
- expect(MessageTypes.THREAD_STARTER_MESSAGE).toBe(21);
- });
-
- it('keeps the text type sets unchanged', () => {
- expect([...GUILD_TEXT_BASED_CHANNEL_TYPES].sort((a, b) => a - b)).toEqual([
- ChannelTypes.GUILD_TEXT,
- ChannelTypes.GUILD_VOICE,
- ChannelTypes.GUILD_ANNOUNCEMENT,
- ]);
- expect([...TEXT_BASED_CHANNEL_TYPES].sort((a, b) => a - b)).toEqual([0, 1, 2, 3, 5, 999]);
- for (const type of THREAD_FEATURE_CHANNEL_TYPES) {
- expect(TEXT_BASED_CHANNEL_TYPES.has(type)).toBe(false);
- }
- });
-
- it('makes announcement channels thread parents of announcement threads', () => {
- expect(THREAD_CHANNEL_TYPES.has(ChannelTypes.ANNOUNCEMENT_THREAD)).toBe(true);
- expect(THREAD_PARENT_CHANNEL_TYPES.has(ChannelTypes.GUILD_ANNOUNCEMENT)).toBe(true);
- expect(THREAD_ONLY_CHANNEL_TYPES.has(ChannelTypes.GUILD_ANNOUNCEMENT)).toBe(false);
- expect(publicThreadTypeFor(ChannelTypes.GUILD_ANNOUNCEMENT)).toBe(ChannelTypes.ANNOUNCEMENT_THREAD);
- expect(publicThreadTypeFor(ChannelTypes.GUILD_TEXT)).toBe(ChannelTypes.PUBLIC_THREAD);
- expect(publicThreadTypeFor(ChannelTypes.GUILD_FORUM)).toBe(ChannelTypes.PUBLIC_THREAD);
- });
-
it('resolves the thread type a text or announcement parent creates', () => {
const {GUILD_TEXT, GUILD_ANNOUNCEMENT, GUILD_FORUM, ANNOUNCEMENT_THREAD, PUBLIC_THREAD, PRIVATE_THREAD} =
ChannelTypes;
@@ -82,7 +40,6 @@ describe('thread channel and message types', () => {
});
it('masks both server-only message flags', () => {
- expect(THREAD_MESSAGE_FLAG_MASK).toBe(0x120);
expect(THREAD_MESSAGE_FLAG_MASK & ChannelConstants.SENDABLE_MESSAGE_FLAGS).toBe(0);
});
});
diff --git a/packages/constants/src/ThreadPermissionUtils.test.ts b/packages/constants/src/ThreadPermissionUtils.test.ts
index 8b48ca7c2..d70bcbf73 100644
--- a/packages/constants/src/ThreadPermissionUtils.test.ts
+++ b/packages/constants/src/ThreadPermissionUtils.test.ts
@@ -125,13 +125,6 @@ describe('thread permission case table', () => {
});
describe('thread permission bits', () => {
- it('uses the expected bit positions', () => {
- expect(ThreadPermissionFlags.MANAGE_THREADS).toBe(1n << 34n);
- expect(ThreadPermissionFlags.CREATE_PUBLIC_THREADS).toBe(1n << 35n);
- expect(ThreadPermissionFlags.CREATE_PRIVATE_THREADS).toBe(1n << 36n);
- expect(ThreadPermissionFlags.SEND_MESSAGES_IN_THREADS).toBe(1n << 38n);
- });
-
it('stays outside the control permission set', () => {
expect(ALL_PERMISSIONS & THREAD_PERMISSIONS).toBe(0n);
expect(THREAD_AWARE_ALL_PERMISSIONS).toBe(ALL_PERMISSIONS | THREAD_PERMISSIONS);
diff --git a/packages/errors/src/__tests__/AppErrorHandlerLogging.test.ts b/packages/errors/src/__tests__/AppErrorHandlerLogging.test.ts
index bfef604d2..80d7285af 100644
--- a/packages/errors/src/__tests__/AppErrorHandlerLogging.test.ts
+++ b/packages/errors/src/__tests__/AppErrorHandlerLogging.test.ts
@@ -1,6 +1,5 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
-import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
import {AppErrorHandler, type BaseHonoEnv} from '@fluxer/errors/src/domains/core/ErrorHandlers';
import {ServiceUnavailableError} from '@fluxer/errors/src/domains/core/ServiceUnavailableError';
import {Hono} from 'hono';
@@ -40,34 +39,6 @@ describe('AppErrorHandler logging', () => {
logCalls.error.length = 0;
});
- it('logs 5xx FluxerErrors with the underlying cause', async () => {
- const cause = new Error('connect ECONNREFUSED 127.0.0.1:9000');
- const app = createApp();
- app.use('*', async (ctx, next) => {
- ctx.set('requestId', 'req-1');
- await next();
- });
- app.post('/messages', () => {
- throw new ServiceUnavailableError({
- message: 'Attachment storage is temporarily unavailable',
- cause,
- });
- });
- const response = await app.request('/messages', {method: 'POST'});
- expect(response.status).toBe(503);
- expect(logCalls.error).toHaveLength(1);
- const [details, message] = logCalls.error[0]!;
- expect(message).toBe('Request failed');
- expect(details.status).toBe(503);
- expect(details.method).toBe('POST');
- expect(details.path).toBe('/messages');
- expect(details.requestId).toBe('req-1');
- const loggedError = details.err as ServiceUnavailableError;
- expect(loggedError.message).toBe('Attachment storage is temporarily unavailable');
- expect(loggedError.code).toBe(APIErrorCodes.SERVICE_UNAVAILABLE);
- expect(loggedError.cause).toBe(cause);
- });
-
it('logs the matched route pattern instead of the request path', async () => {
const app = createApp();
app.get('/reset/:token', () => {
diff --git a/packages/errors/src/__tests__/AppErrorHandlers.test.ts b/packages/errors/src/__tests__/AppErrorHandlers.test.ts
index 28939bfc1..8bcbfa168 100644
--- a/packages/errors/src/__tests__/AppErrorHandlers.test.ts
+++ b/packages/errors/src/__tests__/AppErrorHandlers.test.ts
@@ -2,16 +2,9 @@
import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
import {Locales} from '@fluxer/constants/src/Locales';
-import {BadRequestError} from '@fluxer/errors/src/domains/core/BadRequestError';
import {AppErrorHandler, type BaseHonoEnv} from '@fluxer/errors/src/domains/core/ErrorHandlers';
-import {getErrorMessageUnsafe} from '@fluxer/errors/src/i18n/ErrorI18n';
-import {Logger} from '@fluxer/logger/src/Logger';
import {Hono} from 'hono';
-import {afterEach, describe, expect, it, vi} from 'vitest';
-
-afterEach(() => {
- vi.restoreAllMocks();
-});
+import {describe, expect, it} from 'vitest';
function createApp(error: Error, requestLocale?: string, requestId?: string): Hono<BaseHonoEnv> {
const app = new Hono<BaseHonoEnv>();
@@ -50,39 +43,14 @@ describe('AppErrorHandler i18n fallbacks', () => {
requestId: undefined,
message: 'Internal server error.',
},
- ])(
- '$name and logs unexpected errors with request metadata',
- async ({acceptLanguage, requestLocale, requestId, message}) => {
- const errorLogger = vi.spyOn(Logger.prototype, 'error').mockImplementation(() => {});
- const error = new Error('Private internal failure');
- const headers = new Headers();
- if (acceptLanguage !== undefined) {
- headers.set('accept-language', acceptLanguage);
- }
- const response = await createApp(error, requestLocale, requestId).request('/test', {headers});
- expect(response.status).toBe(500);
- expect(await response.json()).toEqual({code: APIErrorCodes.INTERNAL_SERVER_ERROR, message});
- expect(errorLogger).toHaveBeenCalledExactlyOnceWith(
- {err: error, status: 500, method: 'GET', path: '/test', requestId},
- 'Unhandled error occurred',
- );
- },
- );
-
- it('localizes FluxerError responses without an i18n service and logs them as expected rejections', async () => {
- const errorLogger = vi.spyOn(Logger.prototype, 'error').mockImplementation(() => {});
- const debugLogger = vi.spyOn(Logger.prototype, 'debug').mockImplementation(() => {});
- const error = new BadRequestError({code: APIErrorCodes.BAD_REQUEST});
- const response = await createApp(error).request('/test', {headers: {'accept-language': 'fr'}});
- expect(response.status).toBe(400);
- expect(await response.json()).toEqual({
- code: APIErrorCodes.BAD_REQUEST,
- message: getErrorMessageUnsafe('http.bad_request', 'fr'),
- });
- expect(errorLogger).not.toHaveBeenCalled();
- expect(debugLogger).toHaveBeenCalledExactlyOnceWith(
- {err: error, status: 400, method: 'GET', path: '/test', requestId: undefined},
- 'Request rejected',
- );
+ ])('$name without leaking the internal message', async ({acceptLanguage, requestLocale, requestId, message}) => {
+ const error = new Error('Private internal failure');
+ const headers = new Headers();
+ if (acceptLanguage !== undefined) {
+ headers.set('accept-language', acceptLanguage);
+ }
+ const response = await createApp(error, requestLocale, requestId).request('/test', {headers});
+ expect(response.status).toBe(500);
+ expect(await response.json()).toEqual({code: APIErrorCodes.INTERNAL_SERVER_ERROR, message});
});
});
diff --git a/packages/errors/src/__tests__/SlowmodeRateLimitError.test.ts b/packages/errors/src/__tests__/SlowmodeRateLimitError.test.ts
deleted file mode 100644
index 690e8019e..000000000
--- a/packages/errors/src/__tests__/SlowmodeRateLimitError.test.ts
+++ /dev/null
@@ -1,46 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {SlowmodeRateLimitError} from '@fluxer/errors/src/domains/core/SlowmodeRateLimitError';
-import {describe, expect, it} from 'vitest';
-
-interface SlowmodeResponseBody {
- code: string;
- retry_after: number;
-}
-
-async function readSlowmodeResponse(error: SlowmodeRateLimitError): Promise<{
- status: number;
- header: string | null;
- body: SlowmodeResponseBody;
-}> {
- const response = error.getResponse();
- const body = (await response.json()) as SlowmodeResponseBody;
- return {status: response.status, header: response.headers.get('Retry-After'), body};
-}
-
-describe('SlowmodeRateLimitError', () => {
- it('reports Retry-After in whole seconds and the body in decimal seconds', async () => {
- const {status, header, body} = await readSlowmodeResponse(
- new SlowmodeRateLimitError({retryAfter: 5, retryAfterDecimal: 4.7}),
- );
- expect(status).toBe(400);
- expect(body.code).toBe('SLOWMODE_RATE_LIMITED');
- expect(body.retry_after).toBe(4.7);
- expect(header).toBe('5');
- });
-
- it('keeps the header and the body within one second of each other', async () => {
- const {header, body} = await readSlowmodeResponse(
- new SlowmodeRateLimitError({retryAfter: 5, retryAfterDecimal: 4.997}),
- );
- const headerSeconds = Number(header);
- expect(headerSeconds - body.retry_after).toBeLessThan(1);
- expect(headerSeconds).toBeGreaterThanOrEqual(body.retry_after);
- });
-
- it('falls back to one second when the caller has no retry window', async () => {
- const {header, body} = await readSlowmodeResponse(new SlowmodeRateLimitError({retryAfter: undefined}));
- expect(header).toBe('1');
- expect(body.retry_after).toBe(1);
- });
-});
diff --git a/packages/errors/src/__tests__/ThrottledError.test.ts b/packages/errors/src/__tests__/ThrottledError.test.ts
deleted file mode 100644
index 786061949..000000000
--- a/packages/errors/src/__tests__/ThrottledError.test.ts
+++ /dev/null
@@ -1,78 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
-import {IpAuthorizationResendCooldownError} from '@fluxer/errors/src/domains/auth/IpAuthorizationResendCooldownError';
-import {IpAuthorizationResendLimitExceededError} from '@fluxer/errors/src/domains/auth/IpAuthorizationResendLimitExceededError';
-import {ThrottledError} from '@fluxer/errors/src/domains/core/ThrottledError';
-import type {FluxerError} from '@fluxer/errors/src/FluxerError';
-import {describe, expect, it} from 'vitest';
-
-interface ThrottledResponseBody {
- code: string;
- [key: string]: unknown;
-}
-
-async function readResponse(error: FluxerError): Promise<{
- status: number;
- retryAfter: string | null;
- body: ThrottledResponseBody;
-}> {
- const response = error.getResponse();
- const body = (await response.json()) as ThrottledResponseBody;
- return {status: response.status, retryAfter: response.headers.get('Retry-After'), body};
-}
-
-describe('ThrottledError', () => {
- it('answers 429 with a Retry-After header taken from the caller', async () => {
- const {status, retryAfter} = await readResponse(
- new ThrottledError({code: APIErrorCodes.RESOURCE_LOCKED, retryAfterSeconds: 1}),
- );
- expect(status).toBe(429);
- expect(retryAfter).toBe('1');
- });
-
- it('rounds a fractional delay up to whole seconds', async () => {
- const {retryAfter} = await readResponse(
- new ThrottledError({code: APIErrorCodes.RESOURCE_LOCKED, retryAfterSeconds: 2.1}),
- );
- expect(retryAfter).toBe('3');
- });
-
- it('falls back to one second when the delay is not a usable number', async () => {
- const {retryAfter} = await readResponse(
- new ThrottledError({code: APIErrorCodes.RESOURCE_LOCKED, retryAfterSeconds: Number.NaN}),
- );
- expect(retryAfter).toBe('1');
- });
-
- it('keeps the computed Retry-After when the caller passes other headers', async () => {
- const error = new ThrottledError({
- code: APIErrorCodes.RESOURCE_LOCKED,
- retryAfterSeconds: 4,
- headers: {'X-RateLimit-Scope': 'user'},
- });
- const response = error.getResponse();
- expect(response.headers.get('Retry-After')).toBe('4');
- expect(response.headers.get('X-RateLimit-Scope')).toBe('user');
- });
-});
-
-describe('IpAuthorizationResendCooldownError', () => {
- it('reports the cooldown as a header and in the body', async () => {
- const {status, retryAfter, body} = await readResponse(new IpAuthorizationResendCooldownError(17));
- expect(status).toBe(429);
- expect(body.code).toBe(APIErrorCodes.IP_AUTHORIZATION_RESEND_COOLDOWN);
- expect(body.resend_available_in).toBe(17);
- expect(body.retry_after).toBe(17);
- expect(retryAfter).toBe('17');
- });
-});
-
-describe('IpAuthorizationResendLimitExceededError', () => {
- it('answers 400 with no retry guidance because the allowance never refills', async () => {
- const {status, retryAfter, body} = await readResponse(new IpAuthorizationResendLimitExceededError());
- expect(status).toBe(400);
- expect(body.code).toBe(APIErrorCodes.IP_AUTHORIZATION_RESEND_LIMIT_EXCEEDED);
- expect(retryAfter).toBeNull();
- });
-});
diff --git a/packages/hono/src/tests/ServerLimits.test.ts b/packages/hono/src/tests/ServerLimits.test.ts
deleted file mode 100644
index 95a20b194..000000000
--- a/packages/hono/src/tests/ServerLimits.test.ts
+++ /dev/null
@@ -1,73 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import type {Server} from 'node:http';
-import {createServer} from '@fluxer/hono/src/Server';
-import type {ServerType} from '@hono/node-server';
-import {Hono} from 'hono';
-import {afterEach, describe, expect, test} from 'vitest';
-
-function closeServer(server: ServerType): Promise<void> {
- return new Promise((resolve, reject) => {
- server.close((error?: Error) => {
- if (error) {
- reject(error);
- return;
- }
- resolve();
- });
- });
-}
-
-function listen(options: Parameters<typeof createServer>[1]): Promise<{server: ServerType; port: number}> {
- return new Promise((resolve) => {
- const app = new Hono();
- app.get('/', (ctx) => ctx.text('OK'));
- const server = createServer(app, {
- ...options,
- onListen: ({port}) => resolve({server, port}),
- });
- });
-}
-
-describe('Server limits', () => {
- let server: ServerType | null = null;
- afterEach(async () => {
- if (server) {
- await closeServer(server);
- server = null;
- }
- });
-
- test('applies bounded defaults instead of stock node timeouts', async () => {
- const listening = await listen({port: 0});
- server = listening.server;
- const httpServer = server as Server;
- expect(httpServer.requestTimeout).toBe(120_000);
- expect(httpServer.keepAliveTimeout).toBe(125_000);
- expect(httpServer.maxRequestsPerSocket).toBe(1_000);
- expect(httpServer.headersTimeout).toBe(30_000);
- });
-
- test('honours explicit limit overrides', async () => {
- const listening = await listen({
- port: 0,
- requestTimeoutMs: 15_000,
- headersTimeoutMs: 10_000,
- keepAliveTimeoutMs: 61_000,
- maxRequestsPerSocket: 250,
- });
- server = listening.server;
- const httpServer = server as Server;
- expect(httpServer.requestTimeout).toBe(15_000);
- expect(httpServer.headersTimeout).toBe(10_000);
- expect(httpServer.keepAliveTimeout).toBe(61_000);
- expect(httpServer.maxRequestsPerSocket).toBe(250);
- });
-
- test('clamps the header timeout to the request timeout', async () => {
- const listening = await listen({port: 0, requestTimeoutMs: 5_000});
- server = listening.server;
- const httpServer = server as Server;
- expect(httpServer.headersTimeout).toBe(5_000);
- });
-});