refactor progress
This commit is contained in:
126
packages/api/src/middleware/AdminMiddleware.tsx
Normal file
126
packages/api/src/middleware/AdminMiddleware.tsx
Normal file
@@ -0,0 +1,126 @@
|
||||
/*
|
||||
* Copyright (C) 2026 Fluxer Contributors
|
||||
*
|
||||
* This file is part of Fluxer.
|
||||
*
|
||||
* Fluxer is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Fluxer is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with Fluxer. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import {Logger} from '@fluxer/api/src/Logger';
|
||||
import type {HonoEnv} from '@fluxer/api/src/types/HonoEnv';
|
||||
import {AdminACLs} from '@fluxer/constants/src/AdminACLs';
|
||||
import {MissingACLError} from '@fluxer/errors/src/domains/core/MissingACLError';
|
||||
import {MissingOAuthAdminScopeError} from '@fluxer/errors/src/domains/core/MissingOAuthAdminScopeError';
|
||||
import {MissingPermissionsError} from '@fluxer/errors/src/domains/core/MissingPermissionsError';
|
||||
import {UnauthorizedError} from '@fluxer/errors/src/domains/core/UnauthorizedError';
|
||||
import {createMiddleware} from 'hono/factory';
|
||||
|
||||
const REQUIRED_OAUTH_ADMIN_SCOPE = 'admin';
|
||||
|
||||
export function requireAdminACL(requiredACL: string) {
|
||||
return createMiddleware<HonoEnv>(async (ctx, next) => {
|
||||
const adminUser = ctx.get('user');
|
||||
if (!adminUser) throw new UnauthorizedError();
|
||||
|
||||
const tokenType = ctx.get('authTokenType');
|
||||
if (tokenType !== 'bearer' && tokenType !== 'session' && tokenType !== 'admin_api_key')
|
||||
throw new UnauthorizedError();
|
||||
|
||||
if (tokenType === 'bearer') {
|
||||
const oauthScopes = ctx.get('oauthBearerScopes');
|
||||
if (!oauthScopes || !oauthScopes.has(REQUIRED_OAUTH_ADMIN_SCOPE)) {
|
||||
throw new MissingOAuthAdminScopeError();
|
||||
}
|
||||
}
|
||||
|
||||
const userAcls: Set<string> =
|
||||
tokenType === 'admin_api_key' ? (ctx.get('adminApiKeyAcls') ?? new Set()) : adminUser.acls;
|
||||
|
||||
Logger.debug(
|
||||
{
|
||||
adminUserId: adminUser.id.toString(),
|
||||
acls: Array.from(userAcls),
|
||||
requiredACL,
|
||||
tokenType,
|
||||
},
|
||||
'Checking admin ACL requirements',
|
||||
);
|
||||
if (!adminUser.acls.has(AdminACLs.AUTHENTICATE) && !adminUser.acls.has(AdminACLs.WILDCARD)) {
|
||||
throw new MissingPermissionsError();
|
||||
}
|
||||
|
||||
if (tokenType === 'admin_api_key' && !adminUser.acls.has(requiredACL) && !adminUser.acls.has(AdminACLs.WILDCARD)) {
|
||||
throw new MissingACLError(requiredACL);
|
||||
}
|
||||
|
||||
if (!userAcls.has(requiredACL) && !userAcls.has(AdminACLs.WILDCARD)) {
|
||||
throw new MissingACLError(requiredACL);
|
||||
}
|
||||
|
||||
ctx.set('adminUserId', adminUser.id);
|
||||
ctx.set('adminUserAcls', userAcls);
|
||||
await next();
|
||||
});
|
||||
}
|
||||
|
||||
export function requireAnyAdminACL(requiredACLs: Array<string>) {
|
||||
return createMiddleware<HonoEnv>(async (ctx, next) => {
|
||||
const adminUser = ctx.get('user');
|
||||
if (!adminUser) throw new UnauthorizedError();
|
||||
|
||||
const tokenType = ctx.get('authTokenType');
|
||||
if (tokenType !== 'bearer' && tokenType !== 'session' && tokenType !== 'admin_api_key')
|
||||
throw new UnauthorizedError();
|
||||
|
||||
if (tokenType === 'bearer') {
|
||||
const oauthScopes = ctx.get('oauthBearerScopes');
|
||||
if (!oauthScopes || !oauthScopes.has(REQUIRED_OAUTH_ADMIN_SCOPE)) {
|
||||
throw new MissingOAuthAdminScopeError();
|
||||
}
|
||||
}
|
||||
|
||||
const userAcls: Set<string> =
|
||||
tokenType === 'admin_api_key' ? (ctx.get('adminApiKeyAcls') ?? new Set()) : adminUser.acls;
|
||||
|
||||
Logger.debug(
|
||||
{
|
||||
adminUserId: adminUser.id.toString(),
|
||||
acls: Array.from(userAcls),
|
||||
requiredACLs,
|
||||
tokenType,
|
||||
},
|
||||
'Checking admin ACL requirements (any)',
|
||||
);
|
||||
if (!adminUser.acls.has(AdminACLs.AUTHENTICATE) && !adminUser.acls.has(AdminACLs.WILDCARD)) {
|
||||
throw new MissingPermissionsError();
|
||||
}
|
||||
|
||||
if (tokenType === 'admin_api_key' && !adminUser.acls.has(AdminACLs.WILDCARD)) {
|
||||
const ownerHasAny = requiredACLs.some((acl) => adminUser.acls.has(acl));
|
||||
if (!ownerHasAny) {
|
||||
throw new MissingACLError(requiredACLs[0] ?? AdminACLs.AUTHENTICATE);
|
||||
}
|
||||
}
|
||||
|
||||
const hasAny = userAcls.has(AdminACLs.WILDCARD) || requiredACLs.some((acl) => userAcls.has(acl));
|
||||
|
||||
if (!hasAny) {
|
||||
throw new MissingACLError(requiredACLs[0] ?? AdminACLs.AUTHENTICATE);
|
||||
}
|
||||
|
||||
ctx.set('adminUserId', adminUser.id);
|
||||
ctx.set('adminUserAcls', userAcls);
|
||||
await next();
|
||||
});
|
||||
}
|
||||
40
packages/api/src/middleware/AuditLogMiddleware.tsx
Normal file
40
packages/api/src/middleware/AuditLogMiddleware.tsx
Normal file
@@ -0,0 +1,40 @@
|
||||
/*
|
||||
* Copyright (C) 2026 Fluxer Contributors
|
||||
*
|
||||
* This file is part of Fluxer.
|
||||
*
|
||||
* Fluxer is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Fluxer is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with Fluxer. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import type {HonoEnv} from '@fluxer/api/src/types/HonoEnv';
|
||||
import {ValidationErrorCodes} from '@fluxer/constants/src/ValidationErrorCodes';
|
||||
import {InputValidationError} from '@fluxer/errors/src/domains/core/InputValidationError';
|
||||
import {AuditLogReasonType} from '@fluxer/schema/src/primitives/ChannelValidators';
|
||||
import {createMiddleware} from 'hono/factory';
|
||||
|
||||
export const AuditLogMiddleware = createMiddleware<HonoEnv>(async (ctx, next) => {
|
||||
const auditLogReasonHeader = ctx.req.header('X-Audit-Log-Reason');
|
||||
|
||||
if (auditLogReasonHeader) {
|
||||
const result = AuditLogReasonType.safeParse(auditLogReasonHeader);
|
||||
if (!result.success) {
|
||||
throw InputValidationError.fromCode('X-Audit-Log-Reason', ValidationErrorCodes.INVALID_AUDIT_LOG_REASON);
|
||||
}
|
||||
ctx.set('auditLogReason', result.data);
|
||||
} else {
|
||||
ctx.set('auditLogReason', null);
|
||||
}
|
||||
|
||||
await next();
|
||||
});
|
||||
66
packages/api/src/middleware/AuthMiddleware.tsx
Normal file
66
packages/api/src/middleware/AuthMiddleware.tsx
Normal file
@@ -0,0 +1,66 @@
|
||||
/*
|
||||
* Copyright (C) 2026 Fluxer Contributors
|
||||
*
|
||||
* This file is part of Fluxer.
|
||||
*
|
||||
* Fluxer is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Fluxer is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with Fluxer. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import type {HonoEnv} from '@fluxer/api/src/types/HonoEnv';
|
||||
import {AccessDeniedError} from '@fluxer/errors/src/domains/core/AccessDeniedError';
|
||||
import {UnauthorizedError} from '@fluxer/errors/src/domains/core/UnauthorizedError';
|
||||
import {AccountSuspiciousActivityError} from '@fluxer/errors/src/domains/user/AccountSuspiciousActivityError';
|
||||
import {createMiddleware} from 'hono/factory';
|
||||
|
||||
function ensureOAuth2BearerRouteSupport(
|
||||
authTokenType: 'session' | 'bearer' | 'bot' | 'admin_api_key' | undefined,
|
||||
oauthBearerAllowed: boolean | undefined,
|
||||
): void {
|
||||
if (authTokenType === 'bearer' && !oauthBearerAllowed) {
|
||||
throw new AccessDeniedError();
|
||||
}
|
||||
}
|
||||
|
||||
export const LoginRequired = createMiddleware<HonoEnv>(async (ctx, next) => {
|
||||
const user = ctx.get('user');
|
||||
if (!user) {
|
||||
throw new UnauthorizedError();
|
||||
}
|
||||
ensureOAuth2BearerRouteSupport(ctx.get('authTokenType'), ctx.get('oauthBearerAllowed'));
|
||||
if (user.suspiciousActivityFlags !== null && user.suspiciousActivityFlags !== 0) {
|
||||
throw new AccountSuspiciousActivityError(user.suspiciousActivityFlags);
|
||||
}
|
||||
|
||||
await next();
|
||||
});
|
||||
|
||||
export const LoginRequiredAllowSuspicious = createMiddleware<HonoEnv>(async (ctx, next) => {
|
||||
const user = ctx.get('user');
|
||||
if (!user) {
|
||||
throw new UnauthorizedError();
|
||||
}
|
||||
ensureOAuth2BearerRouteSupport(ctx.get('authTokenType'), ctx.get('oauthBearerAllowed'));
|
||||
await next();
|
||||
});
|
||||
|
||||
export const DefaultUserOnly = createMiddleware<HonoEnv>(async (ctx, next) => {
|
||||
const user = ctx.get('user');
|
||||
if (!user) {
|
||||
throw new UnauthorizedError();
|
||||
}
|
||||
if (user.isBot) {
|
||||
throw new AccessDeniedError();
|
||||
}
|
||||
await next();
|
||||
});
|
||||
29
packages/api/src/middleware/BlockAppOriginMiddleware.tsx
Normal file
29
packages/api/src/middleware/BlockAppOriginMiddleware.tsx
Normal file
@@ -0,0 +1,29 @@
|
||||
/*
|
||||
* Copyright (C) 2026 Fluxer Contributors
|
||||
*
|
||||
* This file is part of Fluxer.
|
||||
*
|
||||
* Fluxer is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Fluxer is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with Fluxer. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import {InvalidApiOriginError} from '@fluxer/errors/src/domains/core/InvalidApiOriginError';
|
||||
import type {Context, Next} from 'hono';
|
||||
|
||||
export async function BlockAppOriginMiddleware(ctx: Context, next: Next) {
|
||||
const origin = ctx.req.header('origin');
|
||||
if (origin === 'https://web.fluxer.app' || origin === 'https://web.canary.fluxer.app') {
|
||||
throw new InvalidApiOriginError();
|
||||
}
|
||||
await next();
|
||||
}
|
||||
105
packages/api/src/middleware/CaptchaMiddleware.tsx
Normal file
105
packages/api/src/middleware/CaptchaMiddleware.tsx
Normal file
@@ -0,0 +1,105 @@
|
||||
/*
|
||||
* Copyright (C) 2026 Fluxer Contributors
|
||||
*
|
||||
* This file is part of Fluxer.
|
||||
*
|
||||
* Fluxer is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Fluxer is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with Fluxer. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import {Config} from '@fluxer/api/src/Config';
|
||||
import type {HonoEnv} from '@fluxer/api/src/types/HonoEnv';
|
||||
import {createCaptchaProvider} from '@fluxer/captcha/src/CaptchaProviderFactory';
|
||||
import type {ICaptchaProvider} from '@fluxer/captcha/src/ICaptchaProvider';
|
||||
import {CaptchaRequiredError, InvalidCaptchaError} from '@fluxer/errors/src/CaptchaErrors';
|
||||
import {extractClientIp} from '@fluxer/ip_utils/src/ClientIp';
|
||||
import {createMiddleware} from 'hono/factory';
|
||||
|
||||
let providers: Map<string, ICaptchaProvider> | null = null;
|
||||
let defaultProvider: ICaptchaProvider | null = null;
|
||||
|
||||
function initializeProviders(): void {
|
||||
if (providers) return;
|
||||
providers = new Map();
|
||||
|
||||
if (Config.dev.testModeEnabled) {
|
||||
const testProvider = createCaptchaProvider({mode: 'test'});
|
||||
defaultProvider = testProvider;
|
||||
return;
|
||||
}
|
||||
|
||||
if (Config.captcha.hcaptcha?.secretKey) {
|
||||
const provider = createCaptchaProvider({mode: 'hcaptcha', secretKey: Config.captcha.hcaptcha.secretKey});
|
||||
providers.set('hcaptcha', provider);
|
||||
}
|
||||
|
||||
if (Config.captcha.turnstile?.secretKey) {
|
||||
const provider = createCaptchaProvider({mode: 'turnstile', secretKey: Config.captcha.turnstile.secretKey});
|
||||
providers.set('turnstile', provider);
|
||||
}
|
||||
|
||||
if (providers.size === 0) {
|
||||
throw new Error(
|
||||
'CAPTCHA_ENABLED=true but no captcha service has been configured. ' +
|
||||
'Please supply HCAPTCHA_SECRET_KEY or TURNSTILE_SECRET_KEY (or disable captcha).',
|
||||
);
|
||||
}
|
||||
|
||||
defaultProvider = providers.get(Config.captcha.provider) ?? providers.values().next().value ?? null;
|
||||
}
|
||||
|
||||
function resolveProvider(requestedType: string | undefined): ICaptchaProvider {
|
||||
if (defaultProvider && !providers?.size) {
|
||||
return defaultProvider;
|
||||
}
|
||||
|
||||
if (requestedType && providers?.has(requestedType)) {
|
||||
return providers.get(requestedType)!;
|
||||
}
|
||||
|
||||
if (defaultProvider) {
|
||||
return defaultProvider;
|
||||
}
|
||||
|
||||
throw new Error('No captcha provider available');
|
||||
}
|
||||
|
||||
export const CaptchaMiddleware = createMiddleware<HonoEnv>(async (ctx, next) => {
|
||||
if (!Config.captcha.enabled) {
|
||||
await next();
|
||||
return;
|
||||
}
|
||||
|
||||
initializeProviders();
|
||||
|
||||
const token = ctx.req.header('x-captcha-token');
|
||||
if (!token) {
|
||||
throw new CaptchaRequiredError();
|
||||
}
|
||||
|
||||
const provider = resolveProvider(ctx.req.header('x-captcha-type'));
|
||||
|
||||
const isValid = await provider.verify({
|
||||
token,
|
||||
remoteIp:
|
||||
extractClientIp(ctx.req.raw, {
|
||||
trustCfConnectingIp: Config.proxy.trust_cf_connecting_ip,
|
||||
}) ?? undefined,
|
||||
});
|
||||
|
||||
if (!isValid) {
|
||||
throw new InvalidCaptchaError();
|
||||
}
|
||||
|
||||
await next();
|
||||
});
|
||||
53
packages/api/src/middleware/ConcurrencyLimitMiddleware.tsx
Normal file
53
packages/api/src/middleware/ConcurrencyLimitMiddleware.tsx
Normal file
@@ -0,0 +1,53 @@
|
||||
/*
|
||||
* Copyright (C) 2026 Fluxer Contributors
|
||||
*
|
||||
* This file is part of Fluxer.
|
||||
*
|
||||
* Fluxer is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Fluxer is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with Fluxer. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import {Logger} from '@fluxer/api/src/Logger';
|
||||
import {recordCounter} from '@fluxer/telemetry/src/Metrics';
|
||||
import type {MiddlewareHandler} from 'hono';
|
||||
|
||||
const MAX_CONCURRENT_REQUESTS = 500;
|
||||
const SKIP_PATHS = new Set(['/_health', '/internal/telemetry']);
|
||||
|
||||
let inFlightRequests = 0;
|
||||
|
||||
export const ConcurrencyLimitMiddleware: MiddlewareHandler = async (ctx, next) => {
|
||||
if (SKIP_PATHS.has(ctx.req.path)) {
|
||||
await next();
|
||||
return;
|
||||
}
|
||||
|
||||
if (inFlightRequests >= MAX_CONCURRENT_REQUESTS) {
|
||||
recordCounter({name: 'api.concurrency_limit.rejected'});
|
||||
Logger.warn(
|
||||
{inFlightRequests, max: MAX_CONCURRENT_REQUESTS},
|
||||
'[concurrency-limit] Rejecting request, server at capacity',
|
||||
);
|
||||
ctx.header('Retry-After', '5');
|
||||
ctx.status(503);
|
||||
ctx.res = ctx.json({message: 'Server is at capacity, please retry shortly'}, 503);
|
||||
return;
|
||||
}
|
||||
|
||||
inFlightRequests += 1;
|
||||
try {
|
||||
await next();
|
||||
} finally {
|
||||
inFlightRequests -= 1;
|
||||
}
|
||||
};
|
||||
124
packages/api/src/middleware/GuildAvailabilityMiddleware.tsx
Normal file
124
packages/api/src/middleware/GuildAvailabilityMiddleware.tsx
Normal file
@@ -0,0 +1,124 @@
|
||||
/*
|
||||
* Copyright (C) 2026 Fluxer Contributors
|
||||
*
|
||||
* This file is part of Fluxer.
|
||||
*
|
||||
* Fluxer is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Fluxer is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with Fluxer. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import {type ChannelID, createChannelID, createGuildID, type GuildID} from '@fluxer/api/src/BrandedTypes';
|
||||
import type {Guild} from '@fluxer/api/src/models/Guild';
|
||||
import type {User} from '@fluxer/api/src/models/User';
|
||||
import type {HonoEnv} from '@fluxer/api/src/types/HonoEnv';
|
||||
import {normalizeRequestPath} from '@fluxer/api/src/utils/RequestPathUtils';
|
||||
import {GuildFeatures} from '@fluxer/constants/src/GuildConstants';
|
||||
import {UserFlags} from '@fluxer/constants/src/UserConstants';
|
||||
import {MissingAccessError} from '@fluxer/errors/src/domains/core/MissingAccessError';
|
||||
import {UnknownGuildError} from '@fluxer/errors/src/domains/guild/UnknownGuildError';
|
||||
import type {Context} from 'hono';
|
||||
import {createMiddleware} from 'hono/factory';
|
||||
|
||||
function parseResourceId(path: string, resourceName: 'guilds' | 'channels'): string | null {
|
||||
const segments = path.split('/').filter(Boolean);
|
||||
if (segments.length < 2 || segments[0] !== resourceName) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const id = segments[1];
|
||||
if (!/^\d+$/.test(id)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return id;
|
||||
}
|
||||
|
||||
function extractGuildId(path: string): GuildID | null {
|
||||
const guildId = parseResourceId(path, 'guilds');
|
||||
if (!guildId) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return createGuildID(BigInt(guildId));
|
||||
}
|
||||
|
||||
function extractChannelId(path: string): ChannelID | null {
|
||||
const channelId = parseResourceId(path, 'channels');
|
||||
if (!channelId) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return createChannelID(BigInt(channelId));
|
||||
}
|
||||
|
||||
function isStaffUser(user: User): boolean {
|
||||
return (user.flags & UserFlags.STAFF) === UserFlags.STAFF;
|
||||
}
|
||||
|
||||
function isGuildUnavailableForUser(guild: Guild, user: User): boolean {
|
||||
if (guild.features.has(GuildFeatures.UNAVAILABLE_FOR_EVERYONE)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (guild.features.has(GuildFeatures.UNAVAILABLE_FOR_EVERYONE_BUT_STAFF)) {
|
||||
return !isStaffUser(user);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
async function resolveGuildIdForRequest(ctx: Context<HonoEnv>, path: string): Promise<GuildID | null> {
|
||||
const guildId = extractGuildId(path);
|
||||
if (guildId !== null) {
|
||||
return guildId;
|
||||
}
|
||||
|
||||
const channelId = extractChannelId(path);
|
||||
if (channelId === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const channel = await ctx.get('channelRepository').findUnique(channelId);
|
||||
return channel?.guildId ?? null;
|
||||
}
|
||||
|
||||
export const GuildAvailabilityMiddleware = createMiddleware<HonoEnv>(async (ctx, next) => {
|
||||
const user = ctx.get('user');
|
||||
if (!user) {
|
||||
await next();
|
||||
return;
|
||||
}
|
||||
|
||||
const normalizedPath = normalizeRequestPath(ctx.req.path);
|
||||
const guildId = await resolveGuildIdForRequest(ctx, normalizedPath);
|
||||
if (guildId === null) {
|
||||
await next();
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const guild = await ctx.get('guildService').data.getGuildSystem(guildId);
|
||||
if (isGuildUnavailableForUser(guild, user)) {
|
||||
throw new MissingAccessError();
|
||||
}
|
||||
} catch (error) {
|
||||
if (error instanceof UnknownGuildError) {
|
||||
await next();
|
||||
return;
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
|
||||
await next();
|
||||
});
|
||||
223
packages/api/src/middleware/IpBanMiddleware.tsx
Normal file
223
packages/api/src/middleware/IpBanMiddleware.tsx
Normal file
@@ -0,0 +1,223 @@
|
||||
/*
|
||||
* Copyright (C) 2026 Fluxer Contributors
|
||||
*
|
||||
* This file is part of Fluxer.
|
||||
*
|
||||
* Fluxer is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Fluxer is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with Fluxer. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import {AdminRepository} from '@fluxer/api/src/admin/AdminRepository';
|
||||
import {Config} from '@fluxer/api/src/Config';
|
||||
import {IP_BAN_REFRESH_CHANNEL} from '@fluxer/api/src/constants/IpBan';
|
||||
import {Logger} from '@fluxer/api/src/Logger';
|
||||
import type {HonoEnv} from '@fluxer/api/src/types/HonoEnv';
|
||||
import {parseIpBanEntry, tryParseSingleIp} from '@fluxer/api/src/utils/IpRangeUtils';
|
||||
import {IpBannedError} from '@fluxer/errors/src/domains/moderation/IpBannedError';
|
||||
import {extractClientIp} from '@fluxer/ip_utils/src/ClientIp';
|
||||
import type {IpAddressFamily} from '@fluxer/ip_utils/src/IpAddress';
|
||||
import type {IKVProvider, IKVSubscription} from '@fluxer/kv_client/src/IKVProvider';
|
||||
import {createMiddleware} from 'hono/factory';
|
||||
|
||||
type FamilyMap<T> = Record<IpAddressFamily, Map<string, T>>;
|
||||
|
||||
interface SingleCacheEntry {
|
||||
value: bigint;
|
||||
count: number;
|
||||
}
|
||||
|
||||
interface RangeCacheEntry {
|
||||
start: bigint;
|
||||
end: bigint;
|
||||
count: number;
|
||||
}
|
||||
|
||||
class IpBanCache {
|
||||
private singleIpBans: FamilyMap<SingleCacheEntry>;
|
||||
private rangeIpBans: FamilyMap<RangeCacheEntry>;
|
||||
private isInitialized = false;
|
||||
private adminRepository = new AdminRepository();
|
||||
private consecutiveFailures = 0;
|
||||
private maxConsecutiveFailures = 5;
|
||||
private kvClient: IKVProvider | null = null;
|
||||
private kvSubscription: IKVSubscription | null = null;
|
||||
private subscriberInitialized = false;
|
||||
|
||||
constructor() {
|
||||
this.singleIpBans = this.createFamilyMaps();
|
||||
this.rangeIpBans = this.createFamilyMaps();
|
||||
}
|
||||
|
||||
setRefreshSubscriber(kvClient: IKVProvider | null): void {
|
||||
this.kvClient = kvClient;
|
||||
}
|
||||
|
||||
async initialize(): Promise<void> {
|
||||
if (this.isInitialized) return;
|
||||
|
||||
await this.refresh();
|
||||
this.isInitialized = true;
|
||||
this.setupSubscriber();
|
||||
}
|
||||
|
||||
private setupSubscriber(): void {
|
||||
if (this.subscriberInitialized || !this.kvClient) {
|
||||
return;
|
||||
}
|
||||
|
||||
const subscription = this.kvClient.duplicate();
|
||||
this.kvSubscription = subscription;
|
||||
|
||||
subscription
|
||||
.connect()
|
||||
.then(() => subscription.subscribe(IP_BAN_REFRESH_CHANNEL))
|
||||
.then(() => {
|
||||
subscription.on('message', (channel) => {
|
||||
if (channel === IP_BAN_REFRESH_CHANNEL) {
|
||||
this.refresh().catch((err) => {
|
||||
this.consecutiveFailures++;
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
if (this.consecutiveFailures >= this.maxConsecutiveFailures) {
|
||||
Logger.error({error: message}, 'Failed to refresh IP ban cache after notification');
|
||||
} else {
|
||||
Logger.warn({error: message}, 'Failed to refresh IP ban cache after notification');
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
})
|
||||
.catch((error) => {
|
||||
Logger.error({error}, 'Failed to subscribe to IP ban refresh channel');
|
||||
});
|
||||
|
||||
this.subscriberInitialized = true;
|
||||
}
|
||||
|
||||
async refresh(): Promise<void> {
|
||||
const ips = await this.adminRepository.listBannedIps();
|
||||
this.resetCaches();
|
||||
for (const ip of ips) {
|
||||
this.addEntry(ip);
|
||||
}
|
||||
this.consecutiveFailures = 0;
|
||||
}
|
||||
|
||||
isBanned(ip: string): boolean {
|
||||
const parsed = tryParseSingleIp(ip);
|
||||
if (!parsed) return false;
|
||||
|
||||
const singleMap = this.singleIpBans[parsed.family];
|
||||
if (singleMap.has(parsed.canonical)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const rangeMap = this.rangeIpBans[parsed.family];
|
||||
for (const range of rangeMap.values()) {
|
||||
if (parsed.value >= range.start && parsed.value <= range.end) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
ban(ip: string): void {
|
||||
this.addEntry(ip);
|
||||
}
|
||||
|
||||
unban(ip: string): void {
|
||||
this.removeEntry(ip);
|
||||
}
|
||||
|
||||
resetCaches(): void {
|
||||
this.singleIpBans = this.createFamilyMaps();
|
||||
this.rangeIpBans = this.createFamilyMaps();
|
||||
}
|
||||
|
||||
private createFamilyMaps<T>(): FamilyMap<T> {
|
||||
return {
|
||||
ipv4: new Map(),
|
||||
ipv6: new Map(),
|
||||
};
|
||||
}
|
||||
|
||||
private addEntry(value: string): void {
|
||||
const parsed = parseIpBanEntry(value);
|
||||
if (!parsed) {
|
||||
Logger.warn({value}, 'Skipping invalid IP ban entry');
|
||||
return;
|
||||
}
|
||||
|
||||
if (parsed.type === 'single') {
|
||||
const map = this.singleIpBans[parsed.family];
|
||||
const existing = map.get(parsed.canonical);
|
||||
if (existing) {
|
||||
existing.count += 1;
|
||||
} else {
|
||||
map.set(parsed.canonical, {value: parsed.value, count: 1});
|
||||
}
|
||||
} else {
|
||||
const map = this.rangeIpBans[parsed.family];
|
||||
const existing = map.get(parsed.canonical);
|
||||
if (existing) {
|
||||
existing.count += 1;
|
||||
} else {
|
||||
map.set(parsed.canonical, {start: parsed.start, end: parsed.end, count: 1});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private removeEntry(value: string): void {
|
||||
const parsed = parseIpBanEntry(value);
|
||||
if (!parsed) return;
|
||||
|
||||
if (parsed.type === 'single') {
|
||||
const map = this.singleIpBans[parsed.family];
|
||||
const existing = map.get(parsed.canonical);
|
||||
if (!existing) return;
|
||||
if (existing.count <= 1) {
|
||||
map.delete(parsed.canonical);
|
||||
} else {
|
||||
existing.count -= 1;
|
||||
}
|
||||
} else {
|
||||
const map = this.rangeIpBans[parsed.family];
|
||||
const existing = map.get(parsed.canonical);
|
||||
if (!existing) return;
|
||||
if (existing.count <= 1) {
|
||||
map.delete(parsed.canonical);
|
||||
} else {
|
||||
existing.count -= 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
shutdown(): void {
|
||||
if (this.kvSubscription) {
|
||||
this.kvSubscription.disconnect();
|
||||
this.kvSubscription = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const ipBanCache = new IpBanCache();
|
||||
|
||||
export const IpBanMiddleware = createMiddleware<HonoEnv>(async (ctx, next) => {
|
||||
const clientIp = extractClientIp(ctx.req.raw, {trustCfConnectingIp: Config.proxy.trust_cf_connecting_ip});
|
||||
|
||||
if (clientIp && ipBanCache.isBanned(clientIp)) {
|
||||
throw new IpBannedError();
|
||||
}
|
||||
|
||||
await next();
|
||||
});
|
||||
30
packages/api/src/middleware/LocalAuthMiddleware.tsx
Normal file
30
packages/api/src/middleware/LocalAuthMiddleware.tsx
Normal file
@@ -0,0 +1,30 @@
|
||||
/*
|
||||
* Copyright (C) 2026 Fluxer Contributors
|
||||
*
|
||||
* This file is part of Fluxer.
|
||||
*
|
||||
* Fluxer is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Fluxer is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with Fluxer. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import type {HonoEnv} from '@fluxer/api/src/types/HonoEnv';
|
||||
import {SsoRequiredError} from '@fluxer/errors/src/domains/auth/SsoRequiredError';
|
||||
import {createMiddleware} from 'hono/factory';
|
||||
|
||||
export const LocalAuthMiddleware = createMiddleware<HonoEnv>(async (ctx, next) => {
|
||||
const ssoService = ctx.get('ssoService');
|
||||
if (await ssoService.isEnforced()) {
|
||||
throw new SsoRequiredError();
|
||||
}
|
||||
await next();
|
||||
});
|
||||
32
packages/api/src/middleware/LocaleMiddleware.tsx
Normal file
32
packages/api/src/middleware/LocaleMiddleware.tsx
Normal file
@@ -0,0 +1,32 @@
|
||||
/*
|
||||
* Copyright (C) 2026 Fluxer Contributors
|
||||
*
|
||||
* This file is part of Fluxer.
|
||||
*
|
||||
* Fluxer is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Fluxer is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with Fluxer. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import type {HonoEnv} from '@fluxer/api/src/types/HonoEnv';
|
||||
import {Locales} from '@fluxer/constants/src/Locales';
|
||||
import {parseAcceptLanguage} from '@fluxer/locale/src/LocaleService';
|
||||
import {createMiddleware} from 'hono/factory';
|
||||
|
||||
export const LocaleMiddleware = createMiddleware<HonoEnv>(async (ctx, next) => {
|
||||
const acceptLanguage = ctx.req.header('accept-language');
|
||||
const headerLocale = parseAcceptLanguage(acceptLanguage);
|
||||
const user = ctx.get('user');
|
||||
const locale = user?.locale ?? headerLocale ?? Locales.EN_US;
|
||||
ctx.set('requestLocale', locale);
|
||||
return next();
|
||||
});
|
||||
87
packages/api/src/middleware/MetricsMiddleware.tsx
Normal file
87
packages/api/src/middleware/MetricsMiddleware.tsx
Normal file
@@ -0,0 +1,87 @@
|
||||
/*
|
||||
* Copyright (C) 2026 Fluxer Contributors
|
||||
*
|
||||
* This file is part of Fluxer.
|
||||
*
|
||||
* Fluxer is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Fluxer is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with Fluxer. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import type {HonoEnv} from '@fluxer/api/src/types/HonoEnv';
|
||||
import {recordCounter, recordHistogram} from '@fluxer/telemetry/src/Metrics';
|
||||
import {createMiddleware} from 'hono/factory';
|
||||
|
||||
function normalizePath(path: string): string {
|
||||
return path
|
||||
.replace(/\/\d{17,20}/g, '/:id')
|
||||
.replace(/\/[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}/gi, '/:uuid')
|
||||
.replace(/\/[A-Za-z0-9_-]{6,}/g, (match) => {
|
||||
if (match.match(/^\/[0-9]+$/)) {
|
||||
return '/:id';
|
||||
}
|
||||
return match;
|
||||
});
|
||||
}
|
||||
|
||||
export const MetricsMiddleware = createMiddleware<HonoEnv>(async (ctx, next) => {
|
||||
const start = performance.now();
|
||||
const method = ctx.req.method;
|
||||
const path = new URL(ctx.req.url).pathname;
|
||||
|
||||
try {
|
||||
await next();
|
||||
} finally {
|
||||
const durationMs = performance.now() - start;
|
||||
const normalizedPath = normalizePath(path);
|
||||
const status = ctx.res.status;
|
||||
|
||||
const baseDimensions = {
|
||||
'http.request.method': method,
|
||||
'url.path': normalizedPath,
|
||||
'http.response.status_code': String(status),
|
||||
};
|
||||
|
||||
recordHistogram({
|
||||
name: 'http.server.request.duration',
|
||||
dimensions: baseDimensions,
|
||||
valueMs: durationMs,
|
||||
});
|
||||
|
||||
recordCounter({
|
||||
name: 'http.server.request.count',
|
||||
dimensions: baseDimensions,
|
||||
value: 1,
|
||||
});
|
||||
|
||||
recordHistogram({
|
||||
name: 'api.latency',
|
||||
dimensions: {
|
||||
method,
|
||||
path: normalizedPath,
|
||||
status: String(status),
|
||||
},
|
||||
valueMs: durationMs,
|
||||
});
|
||||
|
||||
const counterName = status >= 500 ? 'api.request.5xx' : status >= 400 ? 'api.request.4xx' : 'api.request.2xx';
|
||||
recordCounter({
|
||||
name: counterName,
|
||||
dimensions: {
|
||||
method,
|
||||
path: normalizedPath,
|
||||
status: String(status),
|
||||
},
|
||||
value: 1,
|
||||
});
|
||||
}
|
||||
});
|
||||
105
packages/api/src/middleware/OAuth2ScopeMiddleware.tsx
Normal file
105
packages/api/src/middleware/OAuth2ScopeMiddleware.tsx
Normal file
@@ -0,0 +1,105 @@
|
||||
/*
|
||||
* Copyright (C) 2026 Fluxer Contributors
|
||||
*
|
||||
* This file is part of Fluxer.
|
||||
*
|
||||
* Fluxer is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Fluxer is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with Fluxer. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import type {HonoEnv} from '@fluxer/api/src/types/HonoEnv';
|
||||
import type {OAuth2Scope} from '@fluxer/constants/src/OAuth2Constants';
|
||||
import {UnauthorizedError} from '@fluxer/errors/src/domains/core/UnauthorizedError';
|
||||
import {MissingOAuthScopeError} from '@fluxer/errors/src/domains/oauth/MissingOAuthScopeError';
|
||||
import type {Context} from 'hono';
|
||||
import {createMiddleware} from 'hono/factory';
|
||||
|
||||
type OAuth2ScopeCheckMode = 'strict' | 'bearer_only';
|
||||
|
||||
function ensureBearerScope(ctx: Context<HonoEnv>, scope: OAuth2Scope, mode: OAuth2ScopeCheckMode): boolean {
|
||||
const tokenType = ctx.get('authTokenType');
|
||||
if (tokenType !== 'bearer') {
|
||||
if (mode === 'strict') {
|
||||
throw new UnauthorizedError();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
const oauthScopes = ctx.get('oauthBearerScopes');
|
||||
if (!oauthScopes || !oauthScopes.has(scope)) {
|
||||
throw new MissingOAuthScopeError(scope);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
function ensureAnyBearerScope(ctx: Context<HonoEnv>, scopes: Array<OAuth2Scope>, mode: OAuth2ScopeCheckMode): boolean {
|
||||
const tokenType = ctx.get('authTokenType');
|
||||
if (tokenType !== 'bearer') {
|
||||
if (mode === 'strict') {
|
||||
throw new UnauthorizedError();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
const oauthScopes = ctx.get('oauthBearerScopes');
|
||||
const hasAnyScope = oauthScopes && scopes.some((scope) => oauthScopes.has(scope));
|
||||
if (!hasAnyScope) {
|
||||
throw new MissingOAuthScopeError(scopes[0]);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
export function requireOAuth2Scope(scope: OAuth2Scope) {
|
||||
return createMiddleware<HonoEnv>(async (ctx, next) => {
|
||||
ctx.set('oauthBearerAllowed', true);
|
||||
ensureBearerScope(ctx, scope, 'strict');
|
||||
await next();
|
||||
});
|
||||
}
|
||||
|
||||
export function requireAnyOAuth2Scope(...scopes: Array<OAuth2Scope>) {
|
||||
return createMiddleware<HonoEnv>(async (ctx, next) => {
|
||||
ctx.set('oauthBearerAllowed', true);
|
||||
ensureAnyBearerScope(ctx, scopes, 'strict');
|
||||
await next();
|
||||
});
|
||||
}
|
||||
|
||||
export function requireOAuth2ScopeForBearer(scope: OAuth2Scope) {
|
||||
return createMiddleware<HonoEnv>(async (ctx, next) => {
|
||||
ctx.set('oauthBearerAllowed', true);
|
||||
ensureBearerScope(ctx, scope, 'bearer_only');
|
||||
await next();
|
||||
});
|
||||
}
|
||||
|
||||
export function requireAnyOAuth2ScopeForBearer(...scopes: Array<OAuth2Scope>) {
|
||||
return createMiddleware<HonoEnv>(async (ctx, next) => {
|
||||
ctx.set('oauthBearerAllowed', true);
|
||||
ensureAnyBearerScope(ctx, scopes, 'bearer_only');
|
||||
await next();
|
||||
});
|
||||
}
|
||||
|
||||
export function requireOAuth2BearerToken() {
|
||||
return createMiddleware<HonoEnv>(async (ctx, next) => {
|
||||
ctx.set('oauthBearerAllowed', true);
|
||||
const tokenType = ctx.get('authTokenType');
|
||||
if (tokenType !== 'bearer') {
|
||||
throw new UnauthorizedError();
|
||||
}
|
||||
await next();
|
||||
});
|
||||
}
|
||||
213
packages/api/src/middleware/RateLimitMiddleware.tsx
Normal file
213
packages/api/src/middleware/RateLimitMiddleware.tsx
Normal file
@@ -0,0 +1,213 @@
|
||||
/*
|
||||
* Copyright (C) 2026 Fluxer Contributors
|
||||
*
|
||||
* This file is part of Fluxer.
|
||||
*
|
||||
* Fluxer is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Fluxer is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with Fluxer. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import {Config} from '@fluxer/api/src/Config';
|
||||
import type {HonoEnv} from '@fluxer/api/src/types/HonoEnv';
|
||||
import {UserFlags} from '@fluxer/constants/src/UserConstants';
|
||||
import {RateLimitError} from '@fluxer/errors/src/domains/core/RateLimitError';
|
||||
import {extractClientIp} from '@fluxer/ip_utils/src/ClientIp';
|
||||
import type {BucketConfig} from '@fluxer/rate_limit/src/IRateLimitService';
|
||||
import {recordCounter, recordHistogram} from '@fluxer/telemetry/src/Metrics';
|
||||
import type {Context, MiddlewareHandler} from 'hono';
|
||||
import {createMiddleware} from 'hono/factory';
|
||||
|
||||
export interface RouteRateLimitConfig {
|
||||
bucket: string;
|
||||
config: BucketConfig;
|
||||
}
|
||||
|
||||
const TEST_ENABLE_RATE_LIMITS_HEADER = 'x-fluxer-test-enable-rate-limits';
|
||||
const TEST_GLOBAL_RATE_LIMIT_OVERRIDE_HEADER = 'x-fluxer-test-global-rate-limit';
|
||||
|
||||
function shouldEnforceRateLimits(ctx: Context<HonoEnv>): boolean {
|
||||
if (!Config.dev.testModeEnabled) {
|
||||
return !Config.dev.disableRateLimits;
|
||||
}
|
||||
|
||||
// Test mode disables rate limits by default; tests can opt in per-request.
|
||||
return ctx.req.header(TEST_ENABLE_RATE_LIMITS_HEADER) === 'true';
|
||||
}
|
||||
|
||||
function getClientIdentifier(ctx: Context<HonoEnv>): string {
|
||||
const user = ctx.get('user');
|
||||
if (user?.id) {
|
||||
return `user:${user.id}`;
|
||||
}
|
||||
const ip = extractClientIp(ctx.req.raw, {trustCfConnectingIp: Config.proxy.trust_cf_connecting_ip});
|
||||
if (!ip) return 'internal';
|
||||
return `ip:${ip}`;
|
||||
}
|
||||
|
||||
function getGlobalRateLimit(ctx: Context<HonoEnv>): number {
|
||||
if (Config.dev.testModeEnabled) {
|
||||
const override = ctx.req.header(TEST_GLOBAL_RATE_LIMIT_OVERRIDE_HEADER);
|
||||
if (override) {
|
||||
const parsed = Number.parseInt(override, 10);
|
||||
if (Number.isFinite(parsed) && parsed > 0) {
|
||||
return parsed;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const user = ctx.get('user');
|
||||
if (user?.flags && (user.flags & UserFlags.HIGH_GLOBAL_RATE_LIMIT) !== 0n) {
|
||||
return 1200;
|
||||
}
|
||||
return 50;
|
||||
}
|
||||
|
||||
function resolveBucket(bucket: string, ctx: Context<HonoEnv>): string {
|
||||
let resolved = bucket;
|
||||
|
||||
const params = ctx.req.param();
|
||||
for (const [key, value] of Object.entries(params)) {
|
||||
resolved = resolved.replace(`:${key}`, String(value));
|
||||
}
|
||||
|
||||
const clientId = getClientIdentifier(ctx);
|
||||
return `${clientId}:${resolved}`;
|
||||
}
|
||||
|
||||
function setRateLimitHeaders(ctx: Context<HonoEnv>, limit: number, remaining: number, resetTime: Date): void {
|
||||
ctx.header('X-RateLimit-Limit', limit.toString());
|
||||
ctx.header('X-RateLimit-Remaining', remaining.toString());
|
||||
ctx.header('X-RateLimit-Reset', Math.floor(resetTime.getTime() / 1000).toString());
|
||||
}
|
||||
|
||||
function getRetryAfterSeconds(retryAfter: number | undefined, resetTime: Date): number {
|
||||
return retryAfter ?? Math.max(0, Math.ceil((resetTime.getTime() - Date.now()) / 1000));
|
||||
}
|
||||
|
||||
async function revokeAuthenticatedSessionOnGlobalRateLimit(ctx: Context<HonoEnv>): Promise<void> {
|
||||
const authTokenType = ctx.get('authTokenType');
|
||||
if (authTokenType !== 'session') return;
|
||||
|
||||
const user = ctx.get('user');
|
||||
if (!user || user.isBot) return;
|
||||
|
||||
const token = ctx.get('authToken');
|
||||
if (!token) return;
|
||||
|
||||
try {
|
||||
await ctx.get('authService').revokeToken(token);
|
||||
} catch (_error) {
|
||||
recordCounter({
|
||||
name: 'api.ratelimit.global_session_revocation_failed',
|
||||
dimensions: {},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export function RateLimitMiddleware(routeConfig: RouteRateLimitConfig): MiddlewareHandler<HonoEnv> {
|
||||
return createMiddleware<HonoEnv>(async (ctx, next) => {
|
||||
if (!shouldEnforceRateLimits(ctx)) {
|
||||
await next();
|
||||
return;
|
||||
}
|
||||
|
||||
const user = ctx.get('user');
|
||||
|
||||
if (user?.flags && (user.flags & UserFlags.RATE_LIMIT_BYPASS) !== 0n) {
|
||||
await next();
|
||||
return;
|
||||
}
|
||||
|
||||
const rateLimitService = ctx.get('rateLimitService');
|
||||
if (!rateLimitService) {
|
||||
await next();
|
||||
return;
|
||||
}
|
||||
|
||||
const clientId = getClientIdentifier(ctx);
|
||||
|
||||
if (!routeConfig.config.exemptFromGlobal) {
|
||||
const checkStart = Date.now();
|
||||
const globalLimit = getGlobalRateLimit(ctx);
|
||||
const globalResult = await rateLimitService.checkGlobalLimit(clientId, globalLimit);
|
||||
const checkDuration = Date.now() - checkStart;
|
||||
|
||||
recordHistogram({
|
||||
name: 'api.ratelimit.check_latency',
|
||||
valueMs: checkDuration,
|
||||
dimensions: {bucket: 'global'},
|
||||
});
|
||||
|
||||
recordCounter({
|
||||
name: 'api.ratelimit.check',
|
||||
dimensions: {bucket: 'global'},
|
||||
});
|
||||
|
||||
if (!globalResult.allowed) {
|
||||
recordCounter({
|
||||
name: 'api.ratelimit.blocked',
|
||||
dimensions: {bucket: 'global'},
|
||||
});
|
||||
await revokeAuthenticatedSessionOnGlobalRateLimit(ctx);
|
||||
throw new RateLimitError({
|
||||
global: true,
|
||||
retryAfter: getRetryAfterSeconds(globalResult.retryAfter, globalResult.resetTime),
|
||||
limit: globalResult.limit,
|
||||
resetTime: globalResult.resetTime,
|
||||
});
|
||||
}
|
||||
|
||||
recordCounter({
|
||||
name: 'api.ratelimit.allowed',
|
||||
dimensions: {bucket: 'global'},
|
||||
});
|
||||
}
|
||||
|
||||
const bucket = resolveBucket(routeConfig.bucket, ctx);
|
||||
const bucketCheckStart = Date.now();
|
||||
const bucketResult = await rateLimitService.checkBucketLimit(bucket, routeConfig.config);
|
||||
const bucketCheckDuration = Date.now() - bucketCheckStart;
|
||||
|
||||
recordHistogram({
|
||||
name: 'api.ratelimit.check_latency',
|
||||
valueMs: bucketCheckDuration,
|
||||
dimensions: {bucket: routeConfig.bucket},
|
||||
});
|
||||
|
||||
recordCounter({
|
||||
name: 'api.ratelimit.check',
|
||||
dimensions: {bucket: routeConfig.bucket},
|
||||
});
|
||||
|
||||
if (!bucketResult.allowed) {
|
||||
recordCounter({
|
||||
name: 'api.ratelimit.blocked',
|
||||
dimensions: {bucket: routeConfig.bucket},
|
||||
});
|
||||
throw new RateLimitError({
|
||||
retryAfter: getRetryAfterSeconds(bucketResult.retryAfter, bucketResult.resetTime),
|
||||
limit: bucketResult.limit,
|
||||
resetTime: bucketResult.resetTime,
|
||||
});
|
||||
}
|
||||
|
||||
recordCounter({
|
||||
name: 'api.ratelimit.allowed',
|
||||
dimensions: {bucket: routeConfig.bucket},
|
||||
});
|
||||
|
||||
setRateLimitHeaders(ctx, bucketResult.limit, bucketResult.remaining, bucketResult.resetTime);
|
||||
|
||||
await next();
|
||||
});
|
||||
}
|
||||
49
packages/api/src/middleware/RequestCacheMiddleware.tsx
Normal file
49
packages/api/src/middleware/RequestCacheMiddleware.tsx
Normal file
@@ -0,0 +1,49 @@
|
||||
/*
|
||||
* Copyright (C) 2026 Fluxer Contributors
|
||||
*
|
||||
* This file is part of Fluxer.
|
||||
*
|
||||
* Fluxer is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Fluxer is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with Fluxer. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import type {HonoEnv} from '@fluxer/api/src/types/HonoEnv';
|
||||
import type {UserPartialResponse} from '@fluxer/schema/src/domains/user/UserResponseSchemas';
|
||||
import {createMiddleware} from 'hono/factory';
|
||||
|
||||
export interface RequestCache {
|
||||
userPartials: Map<bigint, UserPartialResponse>;
|
||||
clear(): void;
|
||||
}
|
||||
|
||||
class RequestCacheImpl implements RequestCache {
|
||||
userPartials = new Map<bigint, UserPartialResponse>();
|
||||
|
||||
clear(): void {
|
||||
this.userPartials.clear();
|
||||
}
|
||||
}
|
||||
|
||||
export const RequestCacheMiddleware = createMiddleware<HonoEnv>(async (ctx, next) => {
|
||||
const requestCache: RequestCache = new RequestCacheImpl();
|
||||
ctx.set('requestCache', requestCache);
|
||||
try {
|
||||
await next();
|
||||
} finally {
|
||||
requestCache.clear();
|
||||
}
|
||||
});
|
||||
|
||||
export function createRequestCache(): RequestCache {
|
||||
return new RequestCacheImpl();
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
/*
|
||||
* Copyright (C) 2026 Fluxer Contributors
|
||||
*
|
||||
* This file is part of Fluxer.
|
||||
*
|
||||
* Fluxer is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Fluxer is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with Fluxer. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import {Config} from '@fluxer/api/src/Config';
|
||||
import {Logger} from '@fluxer/api/src/Logger';
|
||||
import type {HonoEnv} from '@fluxer/api/src/types/HonoEnv';
|
||||
import {stripApiPrefix} from '@fluxer/api/src/utils/RequestPathUtils';
|
||||
import {createMiddleware} from 'hono/factory';
|
||||
import {HTTPException} from 'hono/http-exception';
|
||||
|
||||
interface RequireXForwardedForOptions {
|
||||
exemptPaths?: Array<string>;
|
||||
}
|
||||
|
||||
const defaultExemptPaths: Array<string> = [
|
||||
'/_health',
|
||||
'/_rpc',
|
||||
'/webhooks/livekit',
|
||||
'/test',
|
||||
'/connections/bluesky/client-metadata.json',
|
||||
'/connections/bluesky/jwks.json',
|
||||
];
|
||||
|
||||
export function RequireXForwardedForMiddleware({exemptPaths = defaultExemptPaths}: RequireXForwardedForOptions = {}) {
|
||||
return createMiddleware<HonoEnv>(async (ctx, next) => {
|
||||
if (Config.dev.testModeEnabled) {
|
||||
await next();
|
||||
return;
|
||||
}
|
||||
|
||||
const path = stripApiPrefix(ctx.req.path);
|
||||
if (exemptPaths.some((prefix) => path === prefix || path.startsWith(prefix))) {
|
||||
await next();
|
||||
return;
|
||||
}
|
||||
|
||||
const headerValue = ctx.req.header('x-forwarded-for');
|
||||
if (!headerValue || headerValue.trim() === '') {
|
||||
Logger.warn({path}, 'Rejected request without X-Forwarded-For header');
|
||||
throw new HTTPException(403, {message: 'Forbidden'});
|
||||
}
|
||||
|
||||
await next();
|
||||
});
|
||||
}
|
||||
299
packages/api/src/middleware/ResponseTypeMiddleware.tsx
Normal file
299
packages/api/src/middleware/ResponseTypeMiddleware.tsx
Normal file
@@ -0,0 +1,299 @@
|
||||
/*
|
||||
* Copyright (C) 2026 Fluxer Contributors
|
||||
*
|
||||
* This file is part of Fluxer.
|
||||
*
|
||||
* Fluxer is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Fluxer is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with Fluxer. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import type {HonoEnv} from '@fluxer/api/src/types/HonoEnv';
|
||||
import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
|
||||
import {InternalServerError} from '@fluxer/errors/src/domains/core/InternalServerError';
|
||||
import {createLogger} from '@fluxer/logger/src/Logger';
|
||||
import {captureException} from '@fluxer/sentry/src/Sentry';
|
||||
import type {MiddlewareHandler} from 'hono';
|
||||
import type {ZodType} from 'zod';
|
||||
|
||||
export const RESPONSE_SCHEMA_KEY = Symbol('responseSchema');
|
||||
|
||||
export class MissingResponseTypeError extends Error {
|
||||
constructor(method: string, path: string) {
|
||||
super(
|
||||
`Missing ResponseType middleware for ${method.toUpperCase()} ${path}. All endpoints must define a response schema.`,
|
||||
);
|
||||
this.name = 'MissingResponseTypeError';
|
||||
}
|
||||
}
|
||||
|
||||
const responseValidationLogger = createLogger('response_validation');
|
||||
|
||||
export class ResponseValidationError extends InternalServerError {
|
||||
constructor(public readonly validationErrors: Array<{path: string; message: string}>) {
|
||||
const errorsDescription = validationErrors.map((e) => `${e.path}: ${e.message}`).join(', ');
|
||||
super({
|
||||
code: APIErrorCodes.RESPONSE_VALIDATION_ERROR,
|
||||
messageVariables: {errors: errorsDescription},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export function ResponseType<T extends ZodType>(
|
||||
schema: T,
|
||||
options?: {
|
||||
skipValidation?: boolean;
|
||||
allowNoContent?: boolean;
|
||||
},
|
||||
): MiddlewareHandler<HonoEnv> {
|
||||
const {skipValidation = false, allowNoContent = false} = options ?? {};
|
||||
|
||||
return async (ctx, next) => {
|
||||
ctx.set('responseSchema' as keyof HonoEnv['Variables'], schema);
|
||||
|
||||
await next();
|
||||
|
||||
if (skipValidation) {
|
||||
return;
|
||||
}
|
||||
|
||||
const response = ctx.res;
|
||||
|
||||
if (allowNoContent && response.status === 204) {
|
||||
return;
|
||||
}
|
||||
|
||||
const contentType = response.headers.get('content-type');
|
||||
if (!contentType?.includes('application/json')) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (response.status >= 400) {
|
||||
return;
|
||||
}
|
||||
|
||||
const clonedResponse = response.clone();
|
||||
let body: unknown;
|
||||
try {
|
||||
body = await clonedResponse.json();
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
|
||||
const result = schema.safeParse(body);
|
||||
|
||||
if (!result.success) {
|
||||
const validationErrors = result.error.issues.map((issue) => ({
|
||||
path: issue.path.join('.') || 'root',
|
||||
message: issue.message,
|
||||
}));
|
||||
|
||||
const errorContext = {
|
||||
method: ctx.req.method,
|
||||
path: ctx.req.path,
|
||||
status: response.status,
|
||||
validationErrors,
|
||||
body,
|
||||
};
|
||||
const responseValidationError = new ResponseValidationError(validationErrors);
|
||||
|
||||
responseValidationLogger.error(errorContext, 'Response validation failed');
|
||||
captureException(responseValidationError, errorContext);
|
||||
|
||||
throw responseValidationError;
|
||||
}
|
||||
|
||||
ctx.res = new Response(JSON.stringify(result.data), {
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
headers: response.headers,
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
export function NoContent(): MiddlewareHandler<HonoEnv> {
|
||||
return async (ctx, next) => {
|
||||
ctx.set('responseSchema' as keyof HonoEnv['Variables'], null);
|
||||
await next();
|
||||
};
|
||||
}
|
||||
|
||||
export type ResponseTypeOf<T extends ZodType> = T['_output'];
|
||||
|
||||
export const OPENAPI_METADATA_KEY = Symbol('openapiMetadata');
|
||||
|
||||
export interface OpenAPIMetadata {
|
||||
operationId: string;
|
||||
summary: string;
|
||||
description: string;
|
||||
responseSchema: ZodType | null;
|
||||
statusCode?: number | Array<number>;
|
||||
security?: SecurityScheme | Array<SecurityScheme>;
|
||||
tags: string | Array<string>;
|
||||
deprecated?: boolean;
|
||||
externalDocs?: {url: string; description?: string};
|
||||
}
|
||||
|
||||
export type SecurityScheme = 'botToken' | 'oauth2Token' | 'bearerToken' | 'sessionToken' | 'adminApiKey';
|
||||
|
||||
export interface OpenAPIRouteMetadata {
|
||||
operationId: string;
|
||||
summary: string;
|
||||
description: string;
|
||||
responseSchema: ZodType | null;
|
||||
statusCode?: number | Array<number>;
|
||||
security?: SecurityScheme | Array<SecurityScheme>;
|
||||
tags: string | Array<string>;
|
||||
deprecated?: boolean;
|
||||
externalDocs?: {url: string; description?: string};
|
||||
}
|
||||
|
||||
export interface OpenAPIOptions {
|
||||
description: string;
|
||||
}
|
||||
|
||||
function validateOperationId(operationId: string): void {
|
||||
if (!/^[a-z][a-z0-9_]*$/.test(operationId)) {
|
||||
throw new Error(
|
||||
`Invalid operationId "${operationId}". Must be snake_case (lowercase letters, numbers, and underscores only, starting with a letter).`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeSecurityToArray(
|
||||
security?: SecurityScheme | Array<SecurityScheme>,
|
||||
): Array<SecurityScheme> | undefined {
|
||||
if (!security) return undefined;
|
||||
return Array.isArray(security) ? security : [security];
|
||||
}
|
||||
|
||||
function normalizeTagsToArray(tags: string | Array<string>): Array<string> {
|
||||
return Array.isArray(tags) ? tags : [tags];
|
||||
}
|
||||
|
||||
function normalizeStatusCodeToArray(statusCode?: number | Array<number>): Array<number> | undefined {
|
||||
if (!statusCode) return undefined;
|
||||
return Array.isArray(statusCode) ? statusCode : [statusCode];
|
||||
}
|
||||
|
||||
export function OpenAPI(metadata: OpenAPIRouteMetadata): MiddlewareHandler<HonoEnv>;
|
||||
export function OpenAPI(
|
||||
operationId: string,
|
||||
summary: string,
|
||||
responseSchema: ZodType | null,
|
||||
options: OpenAPIOptions,
|
||||
): MiddlewareHandler<HonoEnv>;
|
||||
export function OpenAPI(
|
||||
operationIdOrMetadata: string | OpenAPIRouteMetadata,
|
||||
summary?: string,
|
||||
responseSchema?: ZodType | null,
|
||||
options?: OpenAPIOptions,
|
||||
): MiddlewareHandler<HonoEnv> {
|
||||
let metadata: OpenAPIRouteMetadata;
|
||||
|
||||
if (typeof operationIdOrMetadata === 'string') {
|
||||
if (!options?.description) {
|
||||
throw new Error(
|
||||
`Missing description for OpenAPI route ${operationIdOrMetadata}. The description field is required.`,
|
||||
);
|
||||
}
|
||||
if (responseSchema === undefined) {
|
||||
throw new Error(
|
||||
`Missing responseSchema for OpenAPI route ${operationIdOrMetadata}. The responseSchema field is required (use null for no-content responses).`,
|
||||
);
|
||||
}
|
||||
metadata = {
|
||||
operationId: operationIdOrMetadata,
|
||||
summary: summary!,
|
||||
description: options.description,
|
||||
responseSchema,
|
||||
tags: [],
|
||||
};
|
||||
} else {
|
||||
metadata = operationIdOrMetadata;
|
||||
}
|
||||
|
||||
validateOperationId(metadata.operationId);
|
||||
const {statusCode, security, tags, deprecated, externalDocs} = metadata;
|
||||
const schema = metadata.responseSchema;
|
||||
|
||||
return async (ctx, next) => {
|
||||
const fullMetadata: OpenAPIMetadata = {
|
||||
operationId: metadata.operationId,
|
||||
summary: metadata.summary,
|
||||
description: metadata.description,
|
||||
responseSchema: schema,
|
||||
statusCode: statusCode ? normalizeStatusCodeToArray(statusCode) : undefined,
|
||||
security: security ? normalizeSecurityToArray(security) : undefined,
|
||||
tags: normalizeTagsToArray(tags),
|
||||
deprecated,
|
||||
externalDocs,
|
||||
};
|
||||
|
||||
ctx.set('openapiMetadata' as keyof HonoEnv['Variables'], fullMetadata);
|
||||
ctx.set('responseSchema' as keyof HonoEnv['Variables'], schema);
|
||||
|
||||
await next();
|
||||
|
||||
if (!schema) {
|
||||
return;
|
||||
}
|
||||
|
||||
const response = ctx.res;
|
||||
|
||||
const contentType = response.headers.get('content-type');
|
||||
if (!contentType?.includes('application/json')) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (response.status >= 400) {
|
||||
return;
|
||||
}
|
||||
|
||||
const clonedResponse = response.clone();
|
||||
let body: unknown;
|
||||
try {
|
||||
body = await clonedResponse.json();
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
|
||||
const result = schema.safeParse(body);
|
||||
|
||||
if (!result.success) {
|
||||
const validationErrors = result.error.issues.map((issue) => ({
|
||||
path: issue.path.join('.') || 'root',
|
||||
message: issue.message,
|
||||
}));
|
||||
|
||||
const errorContext = {
|
||||
method: ctx.req.method,
|
||||
path: ctx.req.path,
|
||||
status: response.status,
|
||||
validationErrors,
|
||||
body,
|
||||
};
|
||||
const responseValidationError = new ResponseValidationError(validationErrors);
|
||||
|
||||
responseValidationLogger.error(errorContext, 'Response validation failed');
|
||||
captureException(responseValidationError, errorContext);
|
||||
|
||||
throw responseValidationError;
|
||||
}
|
||||
|
||||
ctx.res = new Response(JSON.stringify(result.data), {
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
headers: response.headers,
|
||||
});
|
||||
};
|
||||
}
|
||||
957
packages/api/src/middleware/ServiceMiddleware.tsx
Normal file
957
packages/api/src/middleware/ServiceMiddleware.tsx
Normal file
@@ -0,0 +1,957 @@
|
||||
/*
|
||||
* Copyright (C) 2026 Fluxer Contributors
|
||||
*
|
||||
* This file is part of Fluxer.
|
||||
*
|
||||
* Fluxer is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Fluxer is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with Fluxer. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import {AdminRepository} from '@fluxer/api/src/admin/AdminRepository';
|
||||
import {AdminService} from '@fluxer/api/src/admin/AdminService';
|
||||
import {AdminApiKeyRepository} from '@fluxer/api/src/admin/repositories/AdminApiKeyRepository';
|
||||
import {AdminArchiveRepository} from '@fluxer/api/src/admin/repositories/AdminArchiveRepository';
|
||||
import {AdminApiKeyService} from '@fluxer/api/src/admin/services/AdminApiKeyService';
|
||||
import {AdminArchiveService} from '@fluxer/api/src/admin/services/AdminArchiveService';
|
||||
import {AlertService} from '@fluxer/api/src/alert/AlertService';
|
||||
import {AuthRequestService} from '@fluxer/api/src/auth/AuthRequestService';
|
||||
import {AuthService} from '@fluxer/api/src/auth/AuthService';
|
||||
import {AuthMfaService} from '@fluxer/api/src/auth/services/AuthMfaService';
|
||||
import {DesktopHandoffService} from '@fluxer/api/src/auth/services/DesktopHandoffService';
|
||||
import {SsoService} from '@fluxer/api/src/auth/services/SsoService';
|
||||
import {BlueskyOAuthService} from '@fluxer/api/src/bluesky/BlueskyOAuthService';
|
||||
import type {IBlueskyOAuthService} from '@fluxer/api/src/bluesky/IBlueskyOAuthService';
|
||||
import {Config} from '@fluxer/api/src/Config';
|
||||
import {ChannelRepository} from '@fluxer/api/src/channel/ChannelRepository';
|
||||
import {ChannelRequestService} from '@fluxer/api/src/channel/services/ChannelRequestService';
|
||||
import {ChannelService} from '@fluxer/api/src/channel/services/ChannelService';
|
||||
import {MessageRequestService} from '@fluxer/api/src/channel/services/message/MessageRequestService';
|
||||
import {ScheduledMessageService} from '@fluxer/api/src/channel/services/ScheduledMessageService';
|
||||
import {StreamPreviewService} from '@fluxer/api/src/channel/services/StreamPreviewService';
|
||||
import {StreamService} from '@fluxer/api/src/channel/services/StreamService';
|
||||
import {ConnectionRepository} from '@fluxer/api/src/connection/ConnectionRepository';
|
||||
import {ConnectionRequestService} from '@fluxer/api/src/connection/ConnectionRequestService';
|
||||
import {ConnectionService} from '@fluxer/api/src/connection/ConnectionService';
|
||||
import {CsamEvidenceRetentionService} from '@fluxer/api/src/csam/CsamEvidenceRetentionService';
|
||||
import {CsamLegalHoldService} from '@fluxer/api/src/csam/CsamLegalHoldService';
|
||||
import {createNcmecApiConfig, NcmecReporter} from '@fluxer/api/src/csam/NcmecReporter';
|
||||
import {NcmecSubmissionService} from '@fluxer/api/src/csam/NcmecSubmissionService';
|
||||
import {DonationRepository} from '@fluxer/api/src/donation/DonationRepository';
|
||||
import {DonationService} from '@fluxer/api/src/donation/DonationService';
|
||||
import {DonationCheckoutService} from '@fluxer/api/src/donation/services/DonationCheckoutService';
|
||||
import {DonationMagicLinkService} from '@fluxer/api/src/donation/services/DonationMagicLinkService';
|
||||
import {DownloadService} from '@fluxer/api/src/download/DownloadService';
|
||||
import {createEmailProvider} from '@fluxer/api/src/email/EmailProviderFactory';
|
||||
import {FavoriteMemeRepository} from '@fluxer/api/src/favorite_meme/FavoriteMemeRepository';
|
||||
import {FavoriteMemeRequestService} from '@fluxer/api/src/favorite_meme/FavoriteMemeRequestService';
|
||||
import {FavoriteMemeService} from '@fluxer/api/src/favorite_meme/FavoriteMemeService';
|
||||
import {GatewayRequestService} from '@fluxer/api/src/gateway/GatewayRequestService';
|
||||
import {GuildAuditLogService} from '@fluxer/api/src/guild/GuildAuditLogService';
|
||||
import {GuildDiscoveryRepository} from '@fluxer/api/src/guild/repositories/GuildDiscoveryRepository';
|
||||
import {GuildRepository} from '@fluxer/api/src/guild/repositories/GuildRepository';
|
||||
import {ExpressionAssetPurger} from '@fluxer/api/src/guild/services/content/ExpressionAssetPurger';
|
||||
import {GuildDiscoveryService} from '@fluxer/api/src/guild/services/GuildDiscoveryService';
|
||||
import {GuildService} from '@fluxer/api/src/guild/services/GuildService';
|
||||
import {AssetDeletionQueue} from '@fluxer/api/src/infrastructure/AssetDeletionQueue';
|
||||
import {AvatarService} from '@fluxer/api/src/infrastructure/AvatarService';
|
||||
import {
|
||||
CloudflarePurgeQueue,
|
||||
type IPurgeQueue,
|
||||
NoopPurgeQueue,
|
||||
} from '@fluxer/api/src/infrastructure/CloudflarePurgeQueue';
|
||||
import {DisabledLiveKitService} from '@fluxer/api/src/infrastructure/DisabledLiveKitService';
|
||||
import {DisabledVirusScanService} from '@fluxer/api/src/infrastructure/DisabledVirusScanService';
|
||||
import {DiscriminatorService} from '@fluxer/api/src/infrastructure/DiscriminatorService';
|
||||
import {EmbedService} from '@fluxer/api/src/infrastructure/EmbedService';
|
||||
import {EntityAssetService} from '@fluxer/api/src/infrastructure/EntityAssetService';
|
||||
import {ErrorI18nService} from '@fluxer/api/src/infrastructure/ErrorI18nService';
|
||||
import type {IAssetDeletionQueue} from '@fluxer/api/src/infrastructure/IAssetDeletionQueue';
|
||||
import type {ILiveKitService} from '@fluxer/api/src/infrastructure/ILiveKitService';
|
||||
import {InMemoryVoiceRoomStore} from '@fluxer/api/src/infrastructure/InMemoryVoiceRoomStore';
|
||||
import type {IVoiceRoomStore} from '@fluxer/api/src/infrastructure/IVoiceRoomStore';
|
||||
import {KVAccountDeletionQueueService} from '@fluxer/api/src/infrastructure/KVAccountDeletionQueueService';
|
||||
import {KVActivityTracker} from '@fluxer/api/src/infrastructure/KVActivityTracker';
|
||||
import {KVBulkMessageDeletionQueueService} from '@fluxer/api/src/infrastructure/KVBulkMessageDeletionQueueService';
|
||||
import {LiveKitService} from '@fluxer/api/src/infrastructure/LiveKitService';
|
||||
import {LiveKitWebhookService} from '@fluxer/api/src/infrastructure/LiveKitWebhookService';
|
||||
import {createStorageService} from '@fluxer/api/src/infrastructure/StorageServiceFactory';
|
||||
import {UnfurlerService} from '@fluxer/api/src/infrastructure/UnfurlerService';
|
||||
import {UserCacheService} from '@fluxer/api/src/infrastructure/UserCacheService';
|
||||
import {VirusScanService} from '@fluxer/api/src/infrastructure/VirusScanService';
|
||||
import {VoiceRoomStore} from '@fluxer/api/src/infrastructure/VoiceRoomStore';
|
||||
import {InstanceConfigRepository} from '@fluxer/api/src/instance/InstanceConfigRepository';
|
||||
import {SnowflakeReservationRepository} from '@fluxer/api/src/instance/SnowflakeReservationRepository';
|
||||
import {SnowflakeReservationService} from '@fluxer/api/src/instance/SnowflakeReservationService';
|
||||
import {InviteRepository} from '@fluxer/api/src/invite/InviteRepository';
|
||||
import {InviteRequestService} from '@fluxer/api/src/invite/InviteRequestService';
|
||||
import {InviteService} from '@fluxer/api/src/invite/InviteService';
|
||||
import {KlipyService} from '@fluxer/api/src/klipy/KlipyService';
|
||||
import {LimitConfigService} from '@fluxer/api/src/limits/LimitConfigService';
|
||||
import {
|
||||
ensureVoiceResourcesInitialized,
|
||||
getGatewayService,
|
||||
getInjectedBlueskyOAuthService,
|
||||
getInjectedS3Service,
|
||||
getKVClient,
|
||||
getLiveKitServiceInstance,
|
||||
getMediaService,
|
||||
getSnowflakeService,
|
||||
getVoiceAvailabilityService,
|
||||
getVoiceRoomStoreInstance,
|
||||
getVoiceTopology,
|
||||
getWorkerService,
|
||||
} from '@fluxer/api/src/middleware/ServiceRegistry';
|
||||
import {ApplicationService} from '@fluxer/api/src/oauth/ApplicationService';
|
||||
import {BotAuthService} from '@fluxer/api/src/oauth/BotAuthService';
|
||||
import {BotMfaMirrorService} from '@fluxer/api/src/oauth/BotMfaMirrorService';
|
||||
import {OAuth2ApplicationsRequestService} from '@fluxer/api/src/oauth/OAuth2ApplicationsRequestService';
|
||||
import {OAuth2RequestService} from '@fluxer/api/src/oauth/OAuth2RequestService';
|
||||
import {OAuth2Service} from '@fluxer/api/src/oauth/OAuth2Service';
|
||||
import {ApplicationRepository} from '@fluxer/api/src/oauth/repositories/ApplicationRepository';
|
||||
import {OAuth2TokenRepository} from '@fluxer/api/src/oauth/repositories/OAuth2TokenRepository';
|
||||
import {PackRepository} from '@fluxer/api/src/pack/PackRepository';
|
||||
import {PackRequestService} from '@fluxer/api/src/pack/PackRequestService';
|
||||
import {PackService} from '@fluxer/api/src/pack/PackService';
|
||||
import {ReadStateRepository} from '@fluxer/api/src/read_state/ReadStateRepository';
|
||||
import {ReadStateRequestService} from '@fluxer/api/src/read_state/ReadStateRequestService';
|
||||
import {ReadStateService} from '@fluxer/api/src/read_state/ReadStateService';
|
||||
import {ReportRepository} from '@fluxer/api/src/report/ReportRepository';
|
||||
import {ReportRequestService} from '@fluxer/api/src/report/ReportRequestService';
|
||||
import {ReportService} from '@fluxer/api/src/report/ReportService';
|
||||
import {RpcService} from '@fluxer/api/src/rpc/RpcService';
|
||||
import {getGuildSearchService, getReportSearchService} from '@fluxer/api/src/SearchFactory';
|
||||
import {SearchService} from '@fluxer/api/src/search/SearchService';
|
||||
import {StripeService} from '@fluxer/api/src/stripe/StripeService';
|
||||
import {TenorService} from '@fluxer/api/src/tenor/TenorService';
|
||||
import {ThemeService} from '@fluxer/api/src/theme/ThemeService';
|
||||
import {GuildManagedTraitService} from '@fluxer/api/src/traits/GuildManagedTraitService';
|
||||
import type {HonoEnv} from '@fluxer/api/src/types/HonoEnv';
|
||||
import {EmailChangeRepository} from '@fluxer/api/src/user/repositories/auth/EmailChangeRepository';
|
||||
import {PasswordChangeRepository} from '@fluxer/api/src/user/repositories/auth/PasswordChangeRepository';
|
||||
import {ScheduledMessageRepository} from '@fluxer/api/src/user/repositories/ScheduledMessageRepository';
|
||||
import {UserContactChangeLogRepository} from '@fluxer/api/src/user/repositories/UserContactChangeLogRepository';
|
||||
import {UserRepository} from '@fluxer/api/src/user/repositories/UserRepository';
|
||||
import {EmailChangeService} from '@fluxer/api/src/user/services/EmailChangeService';
|
||||
import {PasswordChangeService} from '@fluxer/api/src/user/services/PasswordChangeService';
|
||||
import {UserAccountRequestService} from '@fluxer/api/src/user/services/UserAccountRequestService';
|
||||
import {UserAuthRequestService} from '@fluxer/api/src/user/services/UserAuthRequestService';
|
||||
import {UserChannelRequestService} from '@fluxer/api/src/user/services/UserChannelRequestService';
|
||||
import {UserContactChangeLogService} from '@fluxer/api/src/user/services/UserContactChangeLogService';
|
||||
import {UserContentRequestService} from '@fluxer/api/src/user/services/UserContentRequestService';
|
||||
import {UserRelationshipRequestService} from '@fluxer/api/src/user/services/UserRelationshipRequestService';
|
||||
import {UserService} from '@fluxer/api/src/user/services/UserService';
|
||||
import {UserPermissionUtils} from '@fluxer/api/src/utils/UserPermissionUtils';
|
||||
import {VoiceRepository} from '@fluxer/api/src/voice/VoiceRepository';
|
||||
import {VoiceService} from '@fluxer/api/src/voice/VoiceService';
|
||||
import {SendGridWebhookService} from '@fluxer/api/src/webhook/SendGridWebhookService';
|
||||
import {WebhookRepository} from '@fluxer/api/src/webhook/WebhookRepository';
|
||||
import {WebhookRequestService} from '@fluxer/api/src/webhook/WebhookRequestService';
|
||||
import {WebhookService} from '@fluxer/api/src/webhook/WebhookService';
|
||||
import type {ICacheService} from '@fluxer/cache/src/ICacheService';
|
||||
import {KVCacheProvider} from '@fluxer/cache/src/providers/KVCacheProvider';
|
||||
import {EmailI18nService} from '@fluxer/email/src/EmailI18nService';
|
||||
import type {EmailConfig, UserBouncedEmailChecker} from '@fluxer/email/src/EmailProviderTypes';
|
||||
import {EmailService} from '@fluxer/email/src/EmailService';
|
||||
import type {IEmailService} from '@fluxer/email/src/IEmailService';
|
||||
import {TestEmailService} from '@fluxer/email/src/TestEmailService';
|
||||
import {createMockLogger} from '@fluxer/logger/src/mock';
|
||||
import {RateLimitService} from '@fluxer/rate_limit/src/RateLimitService';
|
||||
import type {ISmsProvider} from '@fluxer/sms/src/providers/ISmsProvider';
|
||||
import {createSmsProvider} from '@fluxer/sms/src/providers/SmsProviderFactory';
|
||||
import {SmsService} from '@fluxer/sms/src/SmsService';
|
||||
import {createMiddleware} from 'hono/factory';
|
||||
|
||||
const errorI18nService = new ErrorI18nService();
|
||||
|
||||
let _testEmailService: TestEmailService | null = null;
|
||||
function getTestEmailService(): TestEmailService {
|
||||
if (!_testEmailService) {
|
||||
_testEmailService = new TestEmailService();
|
||||
}
|
||||
return _testEmailService;
|
||||
}
|
||||
|
||||
function getVirusScanService() {
|
||||
return Config.clamav.enabled ? VirusScanService : DisabledVirusScanService;
|
||||
}
|
||||
|
||||
let _cacheService: ICacheService | null = null;
|
||||
function getCacheService(): ICacheService {
|
||||
if (!_cacheService) {
|
||||
_cacheService = new KVCacheProvider({client: getKVClient()});
|
||||
}
|
||||
return _cacheService;
|
||||
}
|
||||
|
||||
let _rateLimitService: RateLimitService | null = null;
|
||||
function getRateLimitService(): RateLimitService {
|
||||
if (!_rateLimitService) {
|
||||
_rateLimitService = new RateLimitService(getCacheService());
|
||||
}
|
||||
return _rateLimitService;
|
||||
}
|
||||
|
||||
function createRuntimeSmsProvider(): ISmsProvider {
|
||||
if (Config.dev.testModeEnabled) {
|
||||
return createSmsProvider({
|
||||
mode: 'test',
|
||||
logger: createMockLogger(),
|
||||
});
|
||||
}
|
||||
|
||||
if (Config.sms.enabled && Config.sms.accountSid && Config.sms.authToken && Config.sms.verifyServiceSid) {
|
||||
return createSmsProvider({
|
||||
mode: 'twilio',
|
||||
config: {
|
||||
accountSid: Config.sms.accountSid,
|
||||
authToken: Config.sms.authToken,
|
||||
verifyServiceSid: Config.sms.verifyServiceSid,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return createSmsProvider({
|
||||
mode: 'unavailable',
|
||||
});
|
||||
}
|
||||
|
||||
let _purgeQueue: IPurgeQueue | null = null;
|
||||
function getPurgeQueue(): IPurgeQueue {
|
||||
if (!_purgeQueue) {
|
||||
_purgeQueue = Config.cloudflare.purgeEnabled ? new CloudflarePurgeQueue(getKVClient()) : new NoopPurgeQueue();
|
||||
}
|
||||
return _purgeQueue;
|
||||
}
|
||||
|
||||
let _assetDeletionQueue: IAssetDeletionQueue | null = null;
|
||||
function getAssetDeletionQueue(): IAssetDeletionQueue {
|
||||
if (!_assetDeletionQueue) {
|
||||
_assetDeletionQueue = new AssetDeletionQueue(getKVClient());
|
||||
}
|
||||
return _assetDeletionQueue;
|
||||
}
|
||||
|
||||
let _csamLegalHoldService: CsamLegalHoldService | null = null;
|
||||
function getCsamLegalHoldService(): CsamLegalHoldService {
|
||||
if (!_csamLegalHoldService) {
|
||||
_csamLegalHoldService = new CsamLegalHoldService();
|
||||
}
|
||||
return _csamLegalHoldService;
|
||||
}
|
||||
|
||||
const instanceConfigRepository = new InstanceConfigRepository();
|
||||
let _limitConfigService: LimitConfigService | null = null;
|
||||
function getLimitConfigService(): LimitConfigService {
|
||||
if (!_limitConfigService) {
|
||||
_limitConfigService = new LimitConfigService(instanceConfigRepository, getCacheService(), getKVClient());
|
||||
}
|
||||
return _limitConfigService;
|
||||
}
|
||||
|
||||
const snowflakeReservationRepository = new SnowflakeReservationRepository();
|
||||
let _snowflakeReservationService: SnowflakeReservationService | null = null;
|
||||
function getSnowflakeReservationService(): SnowflakeReservationService {
|
||||
if (!_snowflakeReservationService) {
|
||||
_snowflakeReservationService = new SnowflakeReservationService(snowflakeReservationRepository, getKVClient());
|
||||
}
|
||||
return _snowflakeReservationService;
|
||||
}
|
||||
|
||||
let serviceSingletonInitializationPromise: Promise<void> | null = null;
|
||||
|
||||
export async function initializeServiceSingletons(): Promise<void> {
|
||||
if (!serviceSingletonInitializationPromise) {
|
||||
serviceSingletonInitializationPromise = (async () => {
|
||||
const snowflakeService = getSnowflakeService();
|
||||
await snowflakeService.initialize();
|
||||
|
||||
const limitConfigService = getLimitConfigService();
|
||||
await limitConfigService.initialize();
|
||||
limitConfigService.setAsGlobalInstance();
|
||||
|
||||
const snowflakeReservationService = getSnowflakeReservationService();
|
||||
await snowflakeReservationService.initialize();
|
||||
})();
|
||||
}
|
||||
|
||||
await serviceSingletonInitializationPromise;
|
||||
}
|
||||
|
||||
let _alertService: AlertService | null = null;
|
||||
function getAlertService(): AlertService {
|
||||
if (!_alertService) {
|
||||
_alertService = new AlertService(Config.alerts.webhookUrl);
|
||||
}
|
||||
return _alertService;
|
||||
}
|
||||
|
||||
let _liveKitWebhookService: LiveKitWebhookService | null = null;
|
||||
function getLiveKitWebhookService(): LiveKitWebhookService | null {
|
||||
if (!_liveKitWebhookService) {
|
||||
const voiceTopology = getVoiceTopology();
|
||||
if (!voiceTopology) return null;
|
||||
|
||||
const gatewayService = getGatewayService();
|
||||
const userRepository = new UserRepository();
|
||||
const liveKitService: ILiveKitService = getLiveKitServiceInstance() ?? new DisabledLiveKitService();
|
||||
const voiceRoomStore: IVoiceRoomStore = getVoiceRoomStoreInstance() ?? new InMemoryVoiceRoomStore();
|
||||
const limitConfigService = getLimitConfigService();
|
||||
|
||||
const hasVoiceInfrastructure =
|
||||
Config.voice.enabled &&
|
||||
voiceTopology !== null &&
|
||||
liveKitService instanceof LiveKitService &&
|
||||
voiceRoomStore instanceof VoiceRoomStore;
|
||||
|
||||
if (hasVoiceInfrastructure && voiceTopology) {
|
||||
_liveKitWebhookService = new LiveKitWebhookService(
|
||||
voiceRoomStore,
|
||||
gatewayService,
|
||||
userRepository,
|
||||
liveKitService,
|
||||
voiceTopology,
|
||||
limitConfigService,
|
||||
);
|
||||
}
|
||||
}
|
||||
return _liveKitWebhookService;
|
||||
}
|
||||
|
||||
export const ServiceMiddleware = createMiddleware<HonoEnv>(async (ctx, next) => {
|
||||
const snowflakeService = getSnowflakeService();
|
||||
const limitConfigService = getLimitConfigService();
|
||||
|
||||
const snowflakeReservationService = getSnowflakeReservationService();
|
||||
|
||||
const userRepository = new UserRepository();
|
||||
const guildRepository = new GuildRepository();
|
||||
const channelRepository = new ChannelRepository();
|
||||
const inviteRepository = new InviteRepository();
|
||||
const webhookRepository = new WebhookRepository();
|
||||
const readStateRepository = new ReadStateRepository();
|
||||
const favoriteMemeRepository = new FavoriteMemeRepository();
|
||||
const connectionRepository = new ConnectionRepository();
|
||||
const reportRepository = new ReportRepository();
|
||||
const adminRepository = new AdminRepository();
|
||||
const adminArchiveRepository = new AdminArchiveRepository();
|
||||
const voiceRepository = new VoiceRepository();
|
||||
const applicationRepository = new ApplicationRepository();
|
||||
const oauth2TokenRepository = new OAuth2TokenRepository();
|
||||
|
||||
const cacheService = getCacheService();
|
||||
const kvClient = getKVClient();
|
||||
const rateLimitService = getRateLimitService();
|
||||
const purgeQueue = getPurgeQueue();
|
||||
const assetDeletionQueue = getAssetDeletionQueue();
|
||||
const csamLegalHoldService = getCsamLegalHoldService();
|
||||
|
||||
const userCacheService = new UserCacheService(cacheService, userRepository);
|
||||
const kvAccountDeletionQueue = new KVAccountDeletionQueueService(kvClient, userRepository);
|
||||
const kvBulkMessageDeletionQueue = new KVBulkMessageDeletionQueueService(kvClient);
|
||||
const kvActivityTracker = new KVActivityTracker(kvClient);
|
||||
const mediaService = getMediaService();
|
||||
const storageService = createStorageService({s3Service: getInjectedS3Service()});
|
||||
const downloadService = new DownloadService(storageService);
|
||||
const themeService = new ThemeService(storageService);
|
||||
const csamEvidenceRetentionService = new CsamEvidenceRetentionService(storageService);
|
||||
const gatewayService = getGatewayService();
|
||||
const guildManagedTraitService = new GuildManagedTraitService({
|
||||
userRepository,
|
||||
guildRepository,
|
||||
gatewayService,
|
||||
userCacheService,
|
||||
});
|
||||
const alertService = getAlertService();
|
||||
const workerService = getWorkerService();
|
||||
const botMfaMirrorService = new BotMfaMirrorService(applicationRepository, userRepository, gatewayService);
|
||||
|
||||
const unfurlerService = new UnfurlerService(cacheService, mediaService);
|
||||
const embedService = new EmbedService(channelRepository, cacheService, unfurlerService, mediaService, workerService);
|
||||
const readStateService = new ReadStateService(readStateRepository, gatewayService);
|
||||
const avatarService = new AvatarService(storageService, mediaService, limitConfigService);
|
||||
const entityAssetService = new EntityAssetService(
|
||||
storageService,
|
||||
mediaService,
|
||||
assetDeletionQueue,
|
||||
limitConfigService,
|
||||
);
|
||||
|
||||
const emailConfig: EmailConfig = {
|
||||
enabled: Config.email.enabled,
|
||||
fromEmail: Config.email.fromEmail,
|
||||
fromName: Config.email.fromName,
|
||||
appBaseUrl: Config.endpoints.webApp,
|
||||
marketingBaseUrl: Config.endpoints.marketing,
|
||||
};
|
||||
|
||||
const bouncedEmailChecker: UserBouncedEmailChecker = {
|
||||
isEmailBounced: async (email: string) => {
|
||||
const user = await userRepository.findByEmail(email);
|
||||
return user?.emailBounced ?? false;
|
||||
},
|
||||
};
|
||||
|
||||
let emailService: IEmailService;
|
||||
if (Config.dev.testModeEnabled) {
|
||||
emailService = getTestEmailService();
|
||||
} else {
|
||||
const emailI18n = new EmailI18nService();
|
||||
const emailProvider = createEmailProvider(Config.email);
|
||||
emailService = new EmailService(emailConfig, emailI18n, emailProvider, bouncedEmailChecker);
|
||||
}
|
||||
|
||||
const smsProvider = createRuntimeSmsProvider();
|
||||
const smsService = new SmsService(smsProvider);
|
||||
const VirusScanServiceClass = getVirusScanService();
|
||||
const virusScanService = new VirusScanServiceClass(cacheService);
|
||||
await virusScanService.initialize();
|
||||
|
||||
await ensureVoiceResourcesInitialized();
|
||||
const liveKitService: ILiveKitService = getLiveKitServiceInstance() ?? new DisabledLiveKitService();
|
||||
const voiceRoomStore: IVoiceRoomStore = getVoiceRoomStoreInstance() ?? new InMemoryVoiceRoomStore();
|
||||
|
||||
const userPermissionUtils = new UserPermissionUtils(userRepository, guildRepository);
|
||||
const guildAuditLogService = new GuildAuditLogService(guildRepository, snowflakeService, workerService);
|
||||
|
||||
const packRepository = new PackRepository();
|
||||
const packAssetPurger = new ExpressionAssetPurger(assetDeletionQueue);
|
||||
const packService = new PackService(
|
||||
packRepository,
|
||||
guildRepository,
|
||||
avatarService,
|
||||
snowflakeService,
|
||||
packAssetPurger,
|
||||
userRepository,
|
||||
userCacheService,
|
||||
limitConfigService,
|
||||
);
|
||||
|
||||
const channelService = new ChannelService(
|
||||
channelRepository,
|
||||
userRepository,
|
||||
guildRepository,
|
||||
packService,
|
||||
userCacheService,
|
||||
embedService,
|
||||
readStateService,
|
||||
cacheService,
|
||||
storageService,
|
||||
gatewayService,
|
||||
mediaService,
|
||||
avatarService,
|
||||
workerService,
|
||||
virusScanService,
|
||||
snowflakeService,
|
||||
rateLimitService,
|
||||
purgeQueue,
|
||||
favoriteMemeRepository,
|
||||
guildAuditLogService,
|
||||
voiceRoomStore,
|
||||
liveKitService,
|
||||
inviteRepository,
|
||||
webhookRepository,
|
||||
limitConfigService,
|
||||
getVoiceAvailabilityService() ?? undefined,
|
||||
);
|
||||
const channelRequestService = new ChannelRequestService(channelService, userCacheService);
|
||||
const messageRequestService = new MessageRequestService(
|
||||
channelService,
|
||||
channelRepository,
|
||||
userCacheService,
|
||||
mediaService,
|
||||
);
|
||||
|
||||
const scheduledMessageRepository = new ScheduledMessageRepository();
|
||||
const scheduledMessageService = new ScheduledMessageService(
|
||||
channelService,
|
||||
scheduledMessageRepository,
|
||||
workerService,
|
||||
snowflakeService,
|
||||
);
|
||||
|
||||
const streamPreviewService = new StreamPreviewService(storageService, cacheService);
|
||||
const streamService = new StreamService(cacheService, channelService, gatewayService, streamPreviewService);
|
||||
|
||||
const guildService = new GuildService(
|
||||
guildRepository,
|
||||
channelRepository,
|
||||
inviteRepository,
|
||||
channelService,
|
||||
userCacheService,
|
||||
gatewayService,
|
||||
entityAssetService,
|
||||
avatarService,
|
||||
assetDeletionQueue,
|
||||
userRepository,
|
||||
mediaService,
|
||||
cacheService,
|
||||
snowflakeService,
|
||||
rateLimitService,
|
||||
workerService,
|
||||
webhookRepository,
|
||||
guildAuditLogService,
|
||||
limitConfigService,
|
||||
guildManagedTraitService,
|
||||
);
|
||||
|
||||
const discoveryRepository = new GuildDiscoveryRepository();
|
||||
const discoveryService = new GuildDiscoveryService(
|
||||
discoveryRepository,
|
||||
guildRepository,
|
||||
gatewayService,
|
||||
getGuildSearchService(),
|
||||
);
|
||||
|
||||
const inviteService = new InviteService(
|
||||
inviteRepository,
|
||||
guildService,
|
||||
channelService,
|
||||
gatewayService,
|
||||
guildAuditLogService,
|
||||
userRepository,
|
||||
packRepository,
|
||||
packService,
|
||||
limitConfigService,
|
||||
);
|
||||
const inviteRequestService = new InviteRequestService(
|
||||
inviteService,
|
||||
channelService,
|
||||
guildService,
|
||||
gatewayService,
|
||||
packRepository,
|
||||
userCacheService,
|
||||
);
|
||||
|
||||
const injectedBlueskyOAuth = getInjectedBlueskyOAuthService();
|
||||
let blueskyOAuthService: IBlueskyOAuthService | null = injectedBlueskyOAuth ?? null;
|
||||
if (!blueskyOAuthService && Config.auth.bluesky.enabled) {
|
||||
blueskyOAuthService = await BlueskyOAuthService.create(Config.auth.bluesky, kvClient, Config.endpoints.apiPublic);
|
||||
}
|
||||
|
||||
const connectionService = new ConnectionService(connectionRepository, gatewayService, blueskyOAuthService);
|
||||
|
||||
const favoriteMemeService = new FavoriteMemeService(
|
||||
favoriteMemeRepository,
|
||||
channelService,
|
||||
storageService,
|
||||
mediaService,
|
||||
snowflakeService,
|
||||
gatewayService,
|
||||
unfurlerService,
|
||||
limitConfigService,
|
||||
);
|
||||
|
||||
const discriminatorService = new DiscriminatorService(userRepository, cacheService, limitConfigService);
|
||||
|
||||
const voiceTopology = getVoiceTopology();
|
||||
const voiceAvailabilityService = getVoiceAvailabilityService();
|
||||
const hasVoiceInfrastructure =
|
||||
Config.voice.enabled &&
|
||||
voiceTopology !== null &&
|
||||
liveKitService instanceof LiveKitService &&
|
||||
voiceRoomStore instanceof VoiceRoomStore;
|
||||
|
||||
const liveKitWebhookService = hasVoiceInfrastructure ? getLiveKitWebhookService() : undefined;
|
||||
|
||||
const voiceService =
|
||||
hasVoiceInfrastructure && voiceAvailabilityService
|
||||
? new VoiceService(
|
||||
liveKitService,
|
||||
guildRepository,
|
||||
userRepository,
|
||||
channelRepository,
|
||||
voiceRoomStore,
|
||||
voiceAvailabilityService,
|
||||
)
|
||||
: undefined;
|
||||
|
||||
const contactChangeLogRepository = new UserContactChangeLogRepository();
|
||||
const contactChangeLogService = new UserContactChangeLogService(contactChangeLogRepository);
|
||||
|
||||
const authMfaService = new AuthMfaService(
|
||||
userRepository,
|
||||
cacheService,
|
||||
smsService,
|
||||
gatewayService,
|
||||
botMfaMirrorService,
|
||||
);
|
||||
const authService = new AuthService(
|
||||
userRepository,
|
||||
inviteService,
|
||||
cacheService,
|
||||
gatewayService,
|
||||
rateLimitService,
|
||||
emailService,
|
||||
smsService,
|
||||
snowflakeService,
|
||||
snowflakeReservationService,
|
||||
discriminatorService,
|
||||
kvAccountDeletionQueue,
|
||||
kvActivityTracker,
|
||||
contactChangeLogService,
|
||||
botMfaMirrorService,
|
||||
authMfaService,
|
||||
);
|
||||
const ssoService = new SsoService(
|
||||
instanceConfigRepository,
|
||||
cacheService,
|
||||
userRepository,
|
||||
discriminatorService,
|
||||
snowflakeService,
|
||||
authService,
|
||||
kvActivityTracker,
|
||||
);
|
||||
const desktopHandoffService = new DesktopHandoffService(cacheService);
|
||||
const authRequestService = new AuthRequestService(authService, ssoService, cacheService, desktopHandoffService);
|
||||
|
||||
const reportSearchService = getReportSearchService();
|
||||
const reportService = new ReportService(
|
||||
reportRepository,
|
||||
channelRepository,
|
||||
guildRepository,
|
||||
userRepository,
|
||||
inviteRepository,
|
||||
emailService,
|
||||
snowflakeService,
|
||||
storageService,
|
||||
reportSearchService,
|
||||
);
|
||||
const reportRequestService = new ReportRequestService(reportService);
|
||||
|
||||
const adminService = new AdminService(
|
||||
userRepository,
|
||||
guildRepository,
|
||||
channelRepository,
|
||||
adminRepository,
|
||||
inviteRepository,
|
||||
discriminatorService,
|
||||
snowflakeService,
|
||||
guildService,
|
||||
authService,
|
||||
gatewayService,
|
||||
userCacheService,
|
||||
entityAssetService,
|
||||
assetDeletionQueue,
|
||||
emailService,
|
||||
mediaService,
|
||||
storageService,
|
||||
reportService,
|
||||
workerService,
|
||||
cacheService,
|
||||
voiceRepository,
|
||||
botMfaMirrorService,
|
||||
contactChangeLogService,
|
||||
kvBulkMessageDeletionQueue,
|
||||
);
|
||||
|
||||
const adminArchiveService = new AdminArchiveService(
|
||||
adminArchiveRepository,
|
||||
userRepository,
|
||||
guildRepository,
|
||||
storageService,
|
||||
snowflakeService,
|
||||
workerService,
|
||||
);
|
||||
|
||||
const adminApiKeyRepository = new AdminApiKeyRepository();
|
||||
const adminApiKeyService = new AdminApiKeyService(adminApiKeyRepository, snowflakeService);
|
||||
|
||||
const botAuthService = new BotAuthService(applicationRepository);
|
||||
const gatewayRequestService = new GatewayRequestService(botAuthService);
|
||||
|
||||
const rpcService = new RpcService(
|
||||
userRepository,
|
||||
applicationRepository,
|
||||
guildRepository,
|
||||
channelRepository,
|
||||
userCacheService,
|
||||
readStateService,
|
||||
authService,
|
||||
gatewayService,
|
||||
alertService,
|
||||
discriminatorService,
|
||||
favoriteMemeRepository,
|
||||
packService,
|
||||
botAuthService,
|
||||
inviteRepository,
|
||||
webhookRepository,
|
||||
storageService,
|
||||
avatarService,
|
||||
rateLimitService,
|
||||
mediaService,
|
||||
limitConfigService,
|
||||
voiceService,
|
||||
voiceAvailabilityService ?? undefined,
|
||||
);
|
||||
|
||||
const webhookService = new WebhookService(
|
||||
webhookRepository,
|
||||
guildService,
|
||||
channelService,
|
||||
channelRepository,
|
||||
cacheService,
|
||||
gatewayService,
|
||||
avatarService,
|
||||
mediaService,
|
||||
snowflakeService,
|
||||
guildAuditLogService,
|
||||
limitConfigService,
|
||||
);
|
||||
|
||||
const klipyService = new KlipyService(cacheService, mediaService);
|
||||
const tenorService = new TenorService(cacheService, mediaService);
|
||||
|
||||
const emailChangeRepository = new EmailChangeRepository();
|
||||
const emailChangeService = new EmailChangeService(
|
||||
emailChangeRepository,
|
||||
emailService,
|
||||
userRepository,
|
||||
rateLimitService,
|
||||
);
|
||||
|
||||
const passwordChangeRepository = new PasswordChangeRepository();
|
||||
const passwordChangeService = new PasswordChangeService(
|
||||
passwordChangeRepository,
|
||||
emailService,
|
||||
authService,
|
||||
userRepository,
|
||||
rateLimitService,
|
||||
);
|
||||
|
||||
const userService = new UserService(
|
||||
userRepository,
|
||||
userRepository,
|
||||
userRepository,
|
||||
userRepository,
|
||||
userRepository,
|
||||
userRepository,
|
||||
authService,
|
||||
userCacheService,
|
||||
channelService,
|
||||
channelRepository,
|
||||
guildService,
|
||||
gatewayService,
|
||||
entityAssetService,
|
||||
mediaService,
|
||||
packService,
|
||||
emailService,
|
||||
snowflakeService,
|
||||
discriminatorService,
|
||||
rateLimitService,
|
||||
guildRepository,
|
||||
workerService,
|
||||
userPermissionUtils,
|
||||
kvAccountDeletionQueue,
|
||||
kvBulkMessageDeletionQueue,
|
||||
botMfaMirrorService,
|
||||
contactChangeLogService,
|
||||
connectionRepository,
|
||||
limitConfigService,
|
||||
);
|
||||
const userAccountRequestService = new UserAccountRequestService(
|
||||
authService,
|
||||
authMfaService,
|
||||
emailChangeService,
|
||||
userService,
|
||||
userRepository,
|
||||
userCacheService,
|
||||
mediaService,
|
||||
);
|
||||
const userAuthRequestService = new UserAuthRequestService(authService, authMfaService, userService, userRepository);
|
||||
const userChannelRequestService = new UserChannelRequestService(userService, userCacheService);
|
||||
const userContentRequestService = new UserContentRequestService(userService, userCacheService, mediaService);
|
||||
const userRelationshipRequestService = new UserRelationshipRequestService(userService, userCacheService);
|
||||
|
||||
const donationRepository = new DonationRepository();
|
||||
let stripeService: StripeService | null = null;
|
||||
let donationService: DonationService | null = null;
|
||||
if (!Config.instance.selfHosted) {
|
||||
stripeService = new StripeService(
|
||||
userRepository,
|
||||
userCacheService,
|
||||
authService,
|
||||
gatewayService,
|
||||
emailService,
|
||||
guildRepository,
|
||||
guildService,
|
||||
cacheService,
|
||||
donationRepository,
|
||||
);
|
||||
|
||||
const donationMagicLinkService = new DonationMagicLinkService(donationRepository, emailService);
|
||||
const donationCheckoutService = new DonationCheckoutService(stripeService.getStripe(), donationRepository);
|
||||
donationService = new DonationService(donationMagicLinkService, donationCheckoutService);
|
||||
}
|
||||
|
||||
const sendGridWebhookService = new SendGridWebhookService(userRepository, gatewayService);
|
||||
|
||||
const applicationService = new ApplicationService({
|
||||
applicationRepository,
|
||||
channelRepository,
|
||||
userRepository,
|
||||
userCacheService,
|
||||
entityAssetService,
|
||||
discriminatorService,
|
||||
snowflakeService,
|
||||
botAuthService,
|
||||
gatewayService,
|
||||
});
|
||||
|
||||
const oauth2Service = new OAuth2Service({
|
||||
userRepository,
|
||||
applicationRepository,
|
||||
oauth2TokenRepository,
|
||||
cacheService,
|
||||
});
|
||||
const oauth2RequestService = new OAuth2RequestService(
|
||||
oauth2Service,
|
||||
applicationRepository,
|
||||
oauth2TokenRepository,
|
||||
userRepository,
|
||||
botAuthService,
|
||||
applicationService,
|
||||
gatewayService,
|
||||
guildService,
|
||||
authService,
|
||||
authMfaService,
|
||||
);
|
||||
const oauth2ApplicationsRequestService = new OAuth2ApplicationsRequestService(
|
||||
applicationService,
|
||||
applicationRepository,
|
||||
userRepository,
|
||||
authService,
|
||||
authMfaService,
|
||||
);
|
||||
|
||||
const searchService = new SearchService({
|
||||
channelRepository,
|
||||
channelService,
|
||||
guildService,
|
||||
userRepository,
|
||||
userCacheService,
|
||||
mediaService,
|
||||
workerService,
|
||||
});
|
||||
const connectionRequestService = new ConnectionRequestService(
|
||||
connectionService,
|
||||
Config.auth.connectionInitiationSecret,
|
||||
);
|
||||
const favoriteMemeRequestService = new FavoriteMemeRequestService(favoriteMemeService);
|
||||
const webhookRequestService = new WebhookRequestService(
|
||||
webhookService,
|
||||
channelRepository,
|
||||
userCacheService,
|
||||
mediaService,
|
||||
liveKitWebhookService ?? null,
|
||||
sendGridWebhookService,
|
||||
);
|
||||
const packRequestService = new PackRequestService(packService);
|
||||
|
||||
ctx.set('adminService', adminService);
|
||||
ctx.set('adminArchiveService', adminArchiveService);
|
||||
ctx.set('adminApiKeyService', adminApiKeyService);
|
||||
ctx.set('applicationRepository', applicationRepository);
|
||||
ctx.set('applicationService', applicationService);
|
||||
ctx.set('authMfaService', authMfaService);
|
||||
ctx.set('authService', authService);
|
||||
ctx.set('authRequestService', authRequestService);
|
||||
ctx.set('ssoService', ssoService);
|
||||
ctx.set('botAuthService', botAuthService);
|
||||
ctx.set('cacheService', cacheService);
|
||||
ctx.set('channelService', channelService);
|
||||
ctx.set('channelRequestService', channelRequestService);
|
||||
ctx.set('messageRequestService', messageRequestService);
|
||||
ctx.set('channelRepository', channelRepository);
|
||||
ctx.set('connectionService', connectionService);
|
||||
ctx.set('connectionRequestService', connectionRequestService);
|
||||
ctx.set('blueskyOAuthService', blueskyOAuthService);
|
||||
ctx.set('streamPreviewService', streamPreviewService);
|
||||
ctx.set('streamService', streamService);
|
||||
ctx.set('downloadService', downloadService);
|
||||
ctx.set('desktopHandoffService', desktopHandoffService);
|
||||
ctx.set('emailService', emailService);
|
||||
ctx.set('embedService', embedService);
|
||||
ctx.set('entityAssetService', entityAssetService);
|
||||
ctx.set('favoriteMemeService', favoriteMemeService);
|
||||
ctx.set('favoriteMemeRequestService', favoriteMemeRequestService);
|
||||
ctx.set('gatewayService', gatewayService);
|
||||
ctx.set('gatewayRequestService', gatewayRequestService);
|
||||
ctx.set('alertService', alertService);
|
||||
ctx.set('guildService', guildService);
|
||||
ctx.set('discoveryService', discoveryService);
|
||||
ctx.set('emailChangeService', emailChangeService);
|
||||
ctx.set('passwordChangeService', passwordChangeService);
|
||||
ctx.set('inviteService', inviteService);
|
||||
ctx.set('inviteRequestService', inviteRequestService);
|
||||
ctx.set('packService', packService);
|
||||
ctx.set('packRequestService', packRequestService);
|
||||
ctx.set('packRepository', packRepository);
|
||||
if (liveKitWebhookService) {
|
||||
ctx.set('liveKitWebhookService', liveKitWebhookService);
|
||||
}
|
||||
ctx.set('mediaService', mediaService);
|
||||
ctx.set('oauth2Service', oauth2Service);
|
||||
ctx.set('oauth2RequestService', oauth2RequestService);
|
||||
ctx.set('oauth2ApplicationsRequestService', oauth2ApplicationsRequestService);
|
||||
ctx.set('oauth2TokenRepository', oauth2TokenRepository);
|
||||
ctx.set('rateLimitService', rateLimitService);
|
||||
ctx.set('readStateService', readStateService);
|
||||
ctx.set('readStateRequestService', new ReadStateRequestService(readStateService));
|
||||
ctx.set('kvActivityTracker', kvActivityTracker);
|
||||
ctx.set('reportService', reportService);
|
||||
ctx.set('reportRequestService', reportRequestService);
|
||||
ctx.set('rpcService', rpcService);
|
||||
ctx.set('searchService', searchService);
|
||||
ctx.set('sendGridWebhookService', sendGridWebhookService);
|
||||
ctx.set('snowflakeService', snowflakeService);
|
||||
ctx.set('storageService', storageService);
|
||||
ctx.set('themeService', themeService);
|
||||
if (stripeService) {
|
||||
ctx.set('stripeService', stripeService);
|
||||
}
|
||||
if (donationService) {
|
||||
ctx.set('donationService', donationService);
|
||||
}
|
||||
ctx.set('sudoModeValid', false);
|
||||
ctx.set('klipyService', klipyService);
|
||||
ctx.set('tenorService', tenorService);
|
||||
ctx.set('userCacheService', userCacheService);
|
||||
ctx.set('userRepository', userRepository);
|
||||
ctx.set('userService', userService);
|
||||
ctx.set('userAccountRequestService', userAccountRequestService);
|
||||
ctx.set('userAuthRequestService', userAuthRequestService);
|
||||
ctx.set('userChannelRequestService', userChannelRequestService);
|
||||
ctx.set('userContentRequestService', userContentRequestService);
|
||||
ctx.set('userRelationshipRequestService', userRelationshipRequestService);
|
||||
ctx.set('scheduledMessageService', scheduledMessageService);
|
||||
ctx.set('webhookService', webhookService);
|
||||
ctx.set('webhookRequestService', webhookRequestService);
|
||||
ctx.set('workerService', workerService);
|
||||
ctx.set('contactChangeLogService', contactChangeLogService);
|
||||
ctx.set('csamLegalHoldService', csamLegalHoldService);
|
||||
ctx.set('csamEvidenceRetentionService', csamEvidenceRetentionService);
|
||||
ctx.set('instanceConfigRepository', instanceConfigRepository);
|
||||
ctx.set('limitConfigService', limitConfigService);
|
||||
ctx.set('guildManagedTraitService', guildManagedTraitService);
|
||||
ctx.set('errorI18nService', errorI18nService);
|
||||
|
||||
const ncmecReporter = new NcmecReporter({config: createNcmecApiConfig(), fetch});
|
||||
const ncmecSubmissionService = new NcmecSubmissionService({
|
||||
reportRepository,
|
||||
ncmecApi: ncmecReporter,
|
||||
storageService,
|
||||
});
|
||||
ctx.set('ncmecSubmissionService', ncmecSubmissionService);
|
||||
|
||||
await next();
|
||||
});
|
||||
199
packages/api/src/middleware/ServiceRegistry.tsx
Normal file
199
packages/api/src/middleware/ServiceRegistry.tsx
Normal file
@@ -0,0 +1,199 @@
|
||||
/*
|
||||
* Copyright (C) 2026 Fluxer Contributors
|
||||
*
|
||||
* This file is part of Fluxer.
|
||||
*
|
||||
* Fluxer is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Fluxer is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with Fluxer. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import type {IBlueskyOAuthService} from '@fluxer/api/src/bluesky/IBlueskyOAuthService';
|
||||
import {Config} from '@fluxer/api/src/Config';
|
||||
import {DisabledLiveKitService} from '@fluxer/api/src/infrastructure/DisabledLiveKitService';
|
||||
import {GatewayService as ProdGatewayService} from '@fluxer/api/src/infrastructure/GatewayService';
|
||||
import type {IGatewayService} from '@fluxer/api/src/infrastructure/IGatewayService';
|
||||
import type {ILiveKitService} from '@fluxer/api/src/infrastructure/ILiveKitService';
|
||||
import type {IMediaService} from '@fluxer/api/src/infrastructure/IMediaService';
|
||||
import {InMemoryVoiceRoomStore} from '@fluxer/api/src/infrastructure/InMemoryVoiceRoomStore';
|
||||
import type {IVoiceRoomStore} from '@fluxer/api/src/infrastructure/IVoiceRoomStore';
|
||||
import {LiveKitService} from '@fluxer/api/src/infrastructure/LiveKitService';
|
||||
import {MediaService as ProdMediaService} from '@fluxer/api/src/infrastructure/MediaService';
|
||||
import {SnowflakeService} from '@fluxer/api/src/infrastructure/SnowflakeService';
|
||||
import {VoiceRoomStore} from '@fluxer/api/src/infrastructure/VoiceRoomStore';
|
||||
import {setInjectedSearchProvider} from '@fluxer/api/src/SearchFactory';
|
||||
import type {ISearchProvider} from '@fluxer/api/src/search/ISearchProvider';
|
||||
import {VoiceAvailabilityService} from '@fluxer/api/src/voice/VoiceAvailabilityService';
|
||||
import {VoiceRepository} from '@fluxer/api/src/voice/VoiceRepository';
|
||||
import {VoiceTopology} from '@fluxer/api/src/voice/VoiceTopology';
|
||||
import {WorkerService as ProdWorkerService} from '@fluxer/api/src/worker/WorkerService';
|
||||
import type {IKVProvider} from '@fluxer/kv_client/src/IKVProvider';
|
||||
import {KVClient} from '@fluxer/kv_client/src/KVClient';
|
||||
import type {S3Service} from '@fluxer/s3/src/s3/S3Service';
|
||||
import type {IWorkerService} from '@fluxer/worker/src/contracts/IWorkerService';
|
||||
|
||||
let _kvClient: IKVProvider | null = null;
|
||||
let _injectedKVProvider: IKVProvider | undefined;
|
||||
|
||||
export function setInjectedKVProvider(provider: IKVProvider | undefined): void {
|
||||
_injectedKVProvider = provider;
|
||||
}
|
||||
|
||||
export function getKVClient(): IKVProvider {
|
||||
if (_injectedKVProvider) {
|
||||
return _injectedKVProvider;
|
||||
}
|
||||
if (!_kvClient) {
|
||||
_kvClient = new KVClient({
|
||||
url: Config.kv.url,
|
||||
});
|
||||
}
|
||||
return _kvClient;
|
||||
}
|
||||
|
||||
let _injectedWorkerService: IWorkerService | undefined;
|
||||
|
||||
export function setInjectedWorkerService(service: IWorkerService | undefined): void {
|
||||
_injectedWorkerService = service;
|
||||
}
|
||||
|
||||
export function getWorkerService(): IWorkerService {
|
||||
if (_injectedWorkerService) {
|
||||
return _injectedWorkerService;
|
||||
}
|
||||
return new ProdWorkerService();
|
||||
}
|
||||
|
||||
let _injectedGatewayService: IGatewayService | undefined;
|
||||
|
||||
export function setInjectedGatewayService(service: IGatewayService | undefined): void {
|
||||
_injectedGatewayService = service;
|
||||
}
|
||||
|
||||
export function getGatewayService(): IGatewayService {
|
||||
if (_injectedGatewayService) {
|
||||
return _injectedGatewayService;
|
||||
}
|
||||
return new ProdGatewayService();
|
||||
}
|
||||
|
||||
let _snowflakeService: SnowflakeService | null = null;
|
||||
export function getSnowflakeService(): SnowflakeService {
|
||||
if (!_snowflakeService) {
|
||||
_snowflakeService = Config.dev.testModeEnabled ? new SnowflakeService() : new SnowflakeService(getKVClient());
|
||||
}
|
||||
return _snowflakeService;
|
||||
}
|
||||
|
||||
let _injectedMediaService: IMediaService | undefined;
|
||||
|
||||
export function setInjectedMediaService(mediaService: IMediaService | undefined): void {
|
||||
_injectedMediaService = mediaService;
|
||||
}
|
||||
|
||||
export function getMediaService(): IMediaService {
|
||||
if (_injectedMediaService) {
|
||||
return _injectedMediaService;
|
||||
}
|
||||
return new ProdMediaService();
|
||||
}
|
||||
|
||||
let _injectedS3Service: S3Service | undefined;
|
||||
|
||||
export function setInjectedS3Service(s3Service: S3Service | undefined): void {
|
||||
_injectedS3Service = s3Service;
|
||||
}
|
||||
|
||||
export function getInjectedS3Service(): S3Service | undefined {
|
||||
return _injectedS3Service;
|
||||
}
|
||||
|
||||
let _injectedSearchProvider: ISearchProvider | undefined;
|
||||
|
||||
export function setInjectedSearchProviderService(provider: ISearchProvider | undefined): void {
|
||||
_injectedSearchProvider = provider;
|
||||
setInjectedSearchProvider(provider);
|
||||
}
|
||||
|
||||
export function getInjectedSearchProvider(): ISearchProvider | undefined {
|
||||
return _injectedSearchProvider;
|
||||
}
|
||||
|
||||
let _injectedBlueskyOAuthService: IBlueskyOAuthService | undefined;
|
||||
|
||||
export function setInjectedBlueskyOAuthService(service: IBlueskyOAuthService | undefined): void {
|
||||
_injectedBlueskyOAuthService = service;
|
||||
}
|
||||
|
||||
export function getInjectedBlueskyOAuthService(): IBlueskyOAuthService | undefined {
|
||||
return _injectedBlueskyOAuthService;
|
||||
}
|
||||
|
||||
let voiceTopology: VoiceTopology | null = null;
|
||||
let voiceAvailabilityService: VoiceAvailabilityService | null = null;
|
||||
let liveKitServiceInstance: ILiveKitService | null = null;
|
||||
let voiceRoomStoreInstance: IVoiceRoomStore | null = null;
|
||||
let voiceConfigSubscriber: IKVProvider | null = null;
|
||||
let voiceInitializationPromise: Promise<void> | null = null;
|
||||
|
||||
export async function ensureVoiceResourcesInitialized(): Promise<void> {
|
||||
if (!Config.voice.enabled) {
|
||||
if (!liveKitServiceInstance) {
|
||||
liveKitServiceInstance = new DisabledLiveKitService();
|
||||
}
|
||||
if (!voiceRoomStoreInstance) {
|
||||
voiceRoomStoreInstance = new InMemoryVoiceRoomStore();
|
||||
}
|
||||
voiceTopology = null;
|
||||
voiceAvailabilityService = null;
|
||||
return;
|
||||
}
|
||||
|
||||
if (voiceTopology && voiceAvailabilityService && liveKitServiceInstance && voiceRoomStoreInstance) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!voiceInitializationPromise) {
|
||||
voiceInitializationPromise = (async () => {
|
||||
const voiceRepository = new VoiceRepository();
|
||||
if (!voiceConfigSubscriber) {
|
||||
voiceConfigSubscriber = getKVClient();
|
||||
}
|
||||
const topology = new VoiceTopology(voiceRepository, voiceConfigSubscriber);
|
||||
await topology.initialize();
|
||||
voiceTopology = topology;
|
||||
voiceAvailabilityService = new VoiceAvailabilityService(topology);
|
||||
liveKitServiceInstance = new LiveKitService(topology);
|
||||
voiceRoomStoreInstance = new VoiceRoomStore(getKVClient());
|
||||
})().finally(() => {
|
||||
voiceInitializationPromise = null;
|
||||
});
|
||||
}
|
||||
|
||||
await voiceInitializationPromise;
|
||||
}
|
||||
|
||||
export function getVoiceTopology(): VoiceTopology | null {
|
||||
return voiceTopology;
|
||||
}
|
||||
|
||||
export function getVoiceAvailabilityService(): VoiceAvailabilityService | null {
|
||||
return voiceAvailabilityService;
|
||||
}
|
||||
|
||||
export function getLiveKitServiceInstance(): ILiveKitService | null {
|
||||
return liveKitServiceInstance;
|
||||
}
|
||||
|
||||
export function getVoiceRoomStoreInstance(): IVoiceRoomStore | null {
|
||||
return voiceRoomStoreInstance;
|
||||
}
|
||||
65
packages/api/src/middleware/SudoModeMiddleware.tsx
Normal file
65
packages/api/src/middleware/SudoModeMiddleware.tsx
Normal file
@@ -0,0 +1,65 @@
|
||||
/*
|
||||
* Copyright (C) 2026 Fluxer Contributors
|
||||
*
|
||||
* This file is part of Fluxer.
|
||||
*
|
||||
* Fluxer is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Fluxer is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with Fluxer. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import {getSudoModeService} from '@fluxer/api/src/auth/services/SudoModeService';
|
||||
import type {HonoEnv} from '@fluxer/api/src/types/HonoEnv';
|
||||
import {getSudoCookie} from '@fluxer/api/src/utils/SudoCookieUtils';
|
||||
import {createMiddleware} from 'hono/factory';
|
||||
|
||||
export const SUDO_MODE_HEADER = 'X-Fluxer-Sudo-Mode-JWT';
|
||||
export const SudoModeMiddleware = createMiddleware<HonoEnv>(async (ctx, next) => {
|
||||
const user = ctx.get('user');
|
||||
|
||||
ctx.set('sudoModeValid', false);
|
||||
ctx.set('sudoModeToken', null);
|
||||
|
||||
if (!user) {
|
||||
await next();
|
||||
return;
|
||||
}
|
||||
|
||||
if (user.isBot) {
|
||||
ctx.set('sudoModeValid', true);
|
||||
await next();
|
||||
return;
|
||||
}
|
||||
|
||||
const sudoToken = ctx.req.header(SUDO_MODE_HEADER);
|
||||
|
||||
let tokenToVerify: string | undefined = sudoToken;
|
||||
|
||||
if (!tokenToVerify) {
|
||||
tokenToVerify = getSudoCookie(ctx, user.id.toString());
|
||||
}
|
||||
|
||||
if (!tokenToVerify) {
|
||||
await next();
|
||||
return;
|
||||
}
|
||||
|
||||
const sudoModeService = getSudoModeService();
|
||||
const isValid = await sudoModeService.verifySudoToken(tokenToVerify, user.id);
|
||||
|
||||
if (isValid) {
|
||||
ctx.set('sudoModeValid', true);
|
||||
ctx.set('sudoModeToken', tokenToVerify);
|
||||
}
|
||||
|
||||
await next();
|
||||
});
|
||||
283
packages/api/src/middleware/UserMiddleware.tsx
Normal file
283
packages/api/src/middleware/UserMiddleware.tsx
Normal file
@@ -0,0 +1,283 @@
|
||||
/*
|
||||
* Copyright (C) 2026 Fluxer Contributors
|
||||
*
|
||||
* This file is part of Fluxer.
|
||||
*
|
||||
* Fluxer is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Fluxer is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with Fluxer. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import {Config} from '@fluxer/api/src/Config';
|
||||
import {getMetricsService} from '@fluxer/api/src/infrastructure/MetricsService';
|
||||
import {Logger} from '@fluxer/api/src/Logger';
|
||||
import type {User} from '@fluxer/api/src/models/User';
|
||||
import type {HonoEnv} from '@fluxer/api/src/types/HonoEnv';
|
||||
import {stripApiPrefix} from '@fluxer/api/src/utils/RequestPathUtils';
|
||||
import {requireClientIp} from '@fluxer/ip_utils/src/ClientIp';
|
||||
import {recordCounter} from '@fluxer/telemetry/src/Metrics';
|
||||
import type {Context} from 'hono';
|
||||
import {createMiddleware} from 'hono/factory';
|
||||
|
||||
type TokenType = 'session' | 'bearer' | 'bot' | 'admin_api_key';
|
||||
|
||||
interface ParsedAuthHeader {
|
||||
token: string;
|
||||
type: TokenType;
|
||||
}
|
||||
|
||||
function parseAuthHeader(authHeader?: string | null): ParsedAuthHeader | null {
|
||||
if (!authHeader) return null;
|
||||
|
||||
if (authHeader !== authHeader.trim()) return null;
|
||||
const normalized = authHeader;
|
||||
if (!normalized) return null;
|
||||
|
||||
if (normalized.startsWith('Bearer ')) {
|
||||
const token = normalized.slice('Bearer '.length);
|
||||
if (token.length === 0 || token !== token.trim()) return null;
|
||||
return {
|
||||
token,
|
||||
type: 'bearer',
|
||||
};
|
||||
}
|
||||
|
||||
if (normalized.startsWith('Bot ')) {
|
||||
const token = normalized.slice('Bot '.length);
|
||||
if (token.length === 0 || token !== token.trim()) return null;
|
||||
return {
|
||||
token,
|
||||
type: 'bot',
|
||||
};
|
||||
}
|
||||
|
||||
if (normalized.startsWith('Admin ')) {
|
||||
const token = normalized.slice('Admin '.length);
|
||||
if (token.length === 0 || token !== token.trim()) return null;
|
||||
return {
|
||||
token,
|
||||
type: 'admin_api_key',
|
||||
};
|
||||
}
|
||||
|
||||
if (normalized.includes(' ')) return null;
|
||||
return {
|
||||
token: normalized,
|
||||
type: 'session',
|
||||
};
|
||||
}
|
||||
|
||||
function setUserInContext(ctx: Context<HonoEnv>, user: User, trackActivity: boolean): void {
|
||||
ctx.set('user', user);
|
||||
if (trackActivity) {
|
||||
const now = new Date();
|
||||
const userRepository = ctx.get('userRepository');
|
||||
const kvActivityTracker = ctx.get('kvActivityTracker');
|
||||
void Promise.all([
|
||||
userRepository.updateLastActiveAt({
|
||||
userId: user.id,
|
||||
lastActiveAt: now,
|
||||
lastActiveIp: requireClientIp(ctx.req.raw, {
|
||||
trustCfConnectingIp: Config.proxy.trust_cf_connecting_ip,
|
||||
}),
|
||||
}),
|
||||
kvActivityTracker.updateActivity(user.id, now),
|
||||
]).catch((error: unknown) => {
|
||||
Logger.warn({error, userId: user.id}, 'Failed to update background user activity');
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export const UserMiddleware = createMiddleware<HonoEnv>(async (ctx, next) => {
|
||||
const rawAuthHeader = ctx.req.header('Authorization');
|
||||
const parsed = parseAuthHeader(rawAuthHeader);
|
||||
|
||||
ctx.set('oauthBearerToken', undefined);
|
||||
ctx.set('oauthBearerAllowed', false);
|
||||
ctx.set('oauthBearerScopes', undefined);
|
||||
ctx.set('oauthBearerUserId', undefined);
|
||||
ctx.set('authToken', undefined);
|
||||
|
||||
if (!parsed) {
|
||||
return next();
|
||||
}
|
||||
|
||||
const {token, type} = parsed;
|
||||
ctx.set('authToken', token);
|
||||
|
||||
if (type === 'session') {
|
||||
const authService = ctx.get('authService');
|
||||
const authSession = await authService.getAuthSessionByToken(token);
|
||||
if (authSession) {
|
||||
recordCounter({
|
||||
name: 'auth.token_validation',
|
||||
dimensions: {token_type: 'session', valid: 'true'},
|
||||
});
|
||||
|
||||
void authService.updateAuthSessionLastUsed(authSession.sessionIdHash);
|
||||
void authService.updateUserActivity({
|
||||
userId: authSession.userId,
|
||||
clientIp: requireClientIp(ctx.req.raw, {
|
||||
trustCfConnectingIp: Config.proxy.trust_cf_connecting_ip,
|
||||
}),
|
||||
});
|
||||
|
||||
const user = await ctx.get('userService').findUniqueAssert(authSession.userId);
|
||||
|
||||
ctx.set('authSession', authSession);
|
||||
ctx.set('authTokenType', 'session');
|
||||
setUserInContext(ctx, user, true);
|
||||
} else {
|
||||
recordCounter({
|
||||
name: 'auth.token_validation',
|
||||
dimensions: {token_type: 'session', valid: 'false'},
|
||||
});
|
||||
|
||||
getMetricsService().counter({
|
||||
name: 'auth.token.invalid',
|
||||
dimensions: {type: 'session'},
|
||||
});
|
||||
}
|
||||
await next();
|
||||
return;
|
||||
}
|
||||
|
||||
if (type === 'bearer') {
|
||||
const oauth2TokenRepository = ctx.get('oauth2TokenRepository');
|
||||
const accessToken = await oauth2TokenRepository.getAccessToken(token);
|
||||
|
||||
if (accessToken) {
|
||||
recordCounter({
|
||||
name: 'auth.token_validation',
|
||||
dimensions: {token_type: 'bearer', valid: 'true'},
|
||||
});
|
||||
|
||||
ctx.set('oauthBearerToken', token);
|
||||
ctx.set('oauthBearerScopes', accessToken.scope);
|
||||
ctx.set('oauthBearerUserId', accessToken.userId ?? undefined);
|
||||
ctx.set('authTokenType', 'bearer');
|
||||
|
||||
const userId = accessToken.userId ?? null;
|
||||
if (userId) {
|
||||
const user = await ctx.get('userService').findUnique(userId);
|
||||
if (user) {
|
||||
setUserInContext(ctx, user, false);
|
||||
}
|
||||
}
|
||||
await next();
|
||||
return;
|
||||
}
|
||||
|
||||
const authService = ctx.get('authService');
|
||||
const authSession = await authService.getAuthSessionByToken(token);
|
||||
if (authSession) {
|
||||
recordCounter({
|
||||
name: 'auth.token_validation',
|
||||
dimensions: {token_type: 'session', valid: 'true'},
|
||||
});
|
||||
|
||||
void authService.updateAuthSessionLastUsed(authSession.sessionIdHash);
|
||||
void authService.updateUserActivity({
|
||||
userId: authSession.userId,
|
||||
clientIp: requireClientIp(ctx.req.raw, {
|
||||
trustCfConnectingIp: Config.proxy.trust_cf_connecting_ip,
|
||||
}),
|
||||
});
|
||||
|
||||
const user = await ctx.get('userService').findUniqueAssert(authSession.userId);
|
||||
ctx.set('authSession', authSession);
|
||||
ctx.set('authTokenType', 'session');
|
||||
setUserInContext(ctx, user, true);
|
||||
} else {
|
||||
recordCounter({
|
||||
name: 'auth.token_validation',
|
||||
dimensions: {token_type: 'bearer', valid: 'false'},
|
||||
});
|
||||
|
||||
getMetricsService().counter({
|
||||
name: 'auth.token.invalid',
|
||||
dimensions: {type: 'bearer'},
|
||||
});
|
||||
}
|
||||
await next();
|
||||
return;
|
||||
}
|
||||
|
||||
if (type === 'bot') {
|
||||
const botAuthService = ctx.get('botAuthService');
|
||||
const botUserId = await botAuthService.validateBotToken(token);
|
||||
if (botUserId) {
|
||||
recordCounter({
|
||||
name: 'auth.token_validation',
|
||||
dimensions: {token_type: 'bot', valid: 'true'},
|
||||
});
|
||||
|
||||
const botUser = await ctx.get('userService').findUnique(botUserId);
|
||||
if (botUser) {
|
||||
ctx.set('authTokenType', 'bot');
|
||||
setUserInContext(ctx, botUser, false);
|
||||
}
|
||||
} else {
|
||||
recordCounter({
|
||||
name: 'auth.token_validation',
|
||||
dimensions: {token_type: 'bot', valid: 'false'},
|
||||
});
|
||||
|
||||
getMetricsService().counter({
|
||||
name: 'auth.token.invalid',
|
||||
dimensions: {type: 'bot'},
|
||||
});
|
||||
}
|
||||
await next();
|
||||
return;
|
||||
}
|
||||
|
||||
if (type === 'admin_api_key') {
|
||||
const path = stripApiPrefix(ctx.req.path);
|
||||
if (!(path === '/admin' || path.startsWith('/admin/'))) {
|
||||
await next();
|
||||
return;
|
||||
}
|
||||
|
||||
const adminApiKeyService = ctx.get('adminApiKeyService');
|
||||
const apiKey = await adminApiKeyService.validateApiKey(token);
|
||||
if (apiKey) {
|
||||
recordCounter({
|
||||
name: 'auth.token_validation',
|
||||
dimensions: {token_type: 'admin_api_key', valid: 'true'},
|
||||
});
|
||||
|
||||
const userService = ctx.get('userService');
|
||||
const user = await userService.findUnique(apiKey.createdById);
|
||||
if (user) {
|
||||
ctx.set('authTokenType', 'admin_api_key');
|
||||
ctx.set('adminApiKey', apiKey);
|
||||
ctx.set('adminApiKeyAcls', apiKey.acls);
|
||||
setUserInContext(ctx, user, false);
|
||||
}
|
||||
} else {
|
||||
recordCounter({
|
||||
name: 'auth.token_validation',
|
||||
dimensions: {token_type: 'admin_api_key', valid: 'false'},
|
||||
});
|
||||
|
||||
getMetricsService().counter({
|
||||
name: 'auth.token.invalid',
|
||||
dimensions: {type: 'admin_api_key'},
|
||||
});
|
||||
}
|
||||
await next();
|
||||
return;
|
||||
}
|
||||
|
||||
await next();
|
||||
});
|
||||
@@ -0,0 +1,83 @@
|
||||
/*
|
||||
* Copyright (C) 2026 Fluxer Contributors
|
||||
*
|
||||
* This file is part of Fluxer.
|
||||
*
|
||||
* Fluxer is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Fluxer is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with Fluxer. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import {createAuthHarness, createTestAccount} from '@fluxer/api/src/auth/tests/AuthTestUtils';
|
||||
import type {ApiTestHarness} from '@fluxer/api/src/test/ApiTestHarness';
|
||||
import {HTTP_STATUS} from '@fluxer/api/src/test/TestConstants';
|
||||
import {createBuilder} from '@fluxer/api/src/test/TestRequestBuilder';
|
||||
import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
|
||||
import {afterAll, beforeAll, beforeEach, describe, expect, it} from 'vitest';
|
||||
|
||||
const HTTP_TOO_MANY_REQUESTS = 429;
|
||||
|
||||
interface RateLimitErrorResponse {
|
||||
code?: string;
|
||||
message?: string;
|
||||
global?: boolean;
|
||||
retry_after?: number;
|
||||
}
|
||||
|
||||
interface UnauthorizedErrorResponse {
|
||||
code?: string;
|
||||
message?: string;
|
||||
}
|
||||
|
||||
describe('Global API rate limit', () => {
|
||||
let harness: ApiTestHarness;
|
||||
|
||||
beforeAll(async () => {
|
||||
harness = await createAuthHarness();
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
await harness.reset();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await harness?.shutdown();
|
||||
});
|
||||
|
||||
it('revokes the auth session when an authenticated user hits the global rate limit', async () => {
|
||||
const account = await createTestAccount(harness);
|
||||
|
||||
await createBuilder(harness, account.token)
|
||||
.get('/users/@me')
|
||||
.header('x-fluxer-test-enable-rate-limits', 'true')
|
||||
.header('x-fluxer-test-global-rate-limit', '1')
|
||||
.expect(HTTP_STATUS.OK)
|
||||
.execute();
|
||||
|
||||
const rateLimitError = await createBuilder<RateLimitErrorResponse>(harness, account.token)
|
||||
.get('/users/@me')
|
||||
.header('x-fluxer-test-enable-rate-limits', 'true')
|
||||
.header('x-fluxer-test-global-rate-limit', '1')
|
||||
.expect(HTTP_TOO_MANY_REQUESTS, APIErrorCodes.RATE_LIMITED)
|
||||
.execute();
|
||||
|
||||
expect(rateLimitError.global).toBe(true);
|
||||
expect(typeof rateLimitError.retry_after).toBe('number');
|
||||
|
||||
const unauth = await createBuilder<UnauthorizedErrorResponse>(harness, account.token)
|
||||
.get('/users/@me')
|
||||
.expect(HTTP_STATUS.UNAUTHORIZED, APIErrorCodes.UNAUTHORIZED)
|
||||
.execute();
|
||||
|
||||
expect(unauth.code).toBe(APIErrorCodes.UNAUTHORIZED);
|
||||
});
|
||||
});
|
||||
48
packages/api/src/middleware/tests/IpBanMiddleware.test.tsx
Normal file
48
packages/api/src/middleware/tests/IpBanMiddleware.test.tsx
Normal file
@@ -0,0 +1,48 @@
|
||||
/*
|
||||
* Copyright (C) 2026 Fluxer Contributors
|
||||
*
|
||||
* This file is part of Fluxer.
|
||||
*
|
||||
* Fluxer is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Fluxer is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with Fluxer. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import {ipBanCache} from '@fluxer/api/src/middleware/IpBanMiddleware';
|
||||
import {beforeEach, describe, expect, it} from 'vitest';
|
||||
|
||||
beforeEach(() => {
|
||||
ipBanCache.resetCaches();
|
||||
});
|
||||
|
||||
describe('IpBanCache', () => {
|
||||
it('blocks IPv4-mapped IPv6 when a single IPv4 address is banned', () => {
|
||||
ipBanCache.ban('127.0.0.1');
|
||||
|
||||
expect(ipBanCache.isBanned('127.0.0.1')).toBe(true);
|
||||
expect(ipBanCache.isBanned('::ffff:7f00:1')).toBe(true);
|
||||
});
|
||||
|
||||
it('blocks IPv4-mapped IPv6 when an IPv4 range is banned', () => {
|
||||
ipBanCache.ban('127.0.0.0/24');
|
||||
|
||||
expect(ipBanCache.isBanned('127.0.0.5')).toBe(true);
|
||||
expect(ipBanCache.isBanned('::ffff:7f00:5')).toBe(true);
|
||||
});
|
||||
|
||||
it('blocks IPv4 clients when the IPv4-mapped IPv6 range is banned', () => {
|
||||
ipBanCache.ban('::ffff:0:0/96');
|
||||
|
||||
expect(ipBanCache.isBanned('::ffff:127.0.0.1')).toBe(true);
|
||||
expect(ipBanCache.isBanned('127.0.0.1')).toBe(true);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user