initial commit
This commit is contained in:
84
fluxer_api/src/middleware/AdminMiddleware.ts
Normal file
84
fluxer_api/src/middleware/AdminMiddleware.ts
Normal file
@@ -0,0 +1,84 @@
|
||||
/*
|
||||
* 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 {createMiddleware} from 'hono/factory';
|
||||
import type {HonoEnv} from '~/App';
|
||||
import {AdminACLs} from '~/Constants';
|
||||
import {MissingACLError, MissingPermissionsError, UnauthorizedError} from '~/Errors';
|
||||
import {Logger} from '~/Logger';
|
||||
|
||||
export const requireAdminACL = (requiredACL: string) =>
|
||||
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') throw new UnauthorizedError();
|
||||
|
||||
Logger.debug(
|
||||
{
|
||||
adminUserId: adminUser.id.toString(),
|
||||
acls: Array.from(adminUser.acls),
|
||||
requiredACL,
|
||||
},
|
||||
'Checking admin ACL requirements',
|
||||
);
|
||||
if (!adminUser.acls.has(AdminACLs.AUTHENTICATE) && !adminUser.acls.has(AdminACLs.WILDCARD)) {
|
||||
throw new MissingPermissionsError();
|
||||
}
|
||||
|
||||
if (!adminUser.acls.has(requiredACL) && !adminUser.acls.has(AdminACLs.WILDCARD)) {
|
||||
throw new MissingACLError(requiredACL);
|
||||
}
|
||||
|
||||
ctx.set('adminUserId', adminUser.id);
|
||||
ctx.set('adminUserAcls', adminUser.acls);
|
||||
await next();
|
||||
});
|
||||
|
||||
export const requireAnyAdminACL = (requiredACLs: Array<string>) =>
|
||||
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') throw new UnauthorizedError();
|
||||
|
||||
Logger.debug(
|
||||
{
|
||||
adminUserId: adminUser.id.toString(),
|
||||
acls: Array.from(adminUser.acls),
|
||||
requiredACLs,
|
||||
},
|
||||
'Checking admin ACL requirements (any)',
|
||||
);
|
||||
if (!adminUser.acls.has(AdminACLs.AUTHENTICATE) && !adminUser.acls.has(AdminACLs.WILDCARD)) {
|
||||
throw new MissingPermissionsError();
|
||||
}
|
||||
|
||||
const hasAny = adminUser.acls.has(AdminACLs.WILDCARD) || requiredACLs.some((acl) => adminUser.acls.has(acl));
|
||||
|
||||
if (!hasAny) {
|
||||
throw new MissingACLError(requiredACLs[0] ?? AdminACLs.AUTHENTICATE);
|
||||
}
|
||||
|
||||
ctx.set('adminUserId', adminUser.id);
|
||||
ctx.set('adminUserAcls', adminUser.acls);
|
||||
await next();
|
||||
});
|
||||
40
fluxer_api/src/middleware/AuditLogMiddleware.ts
Normal file
40
fluxer_api/src/middleware/AuditLogMiddleware.ts
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 {createMiddleware} from 'hono/factory';
|
||||
import type {HonoEnv} from '~/App';
|
||||
import {InputValidationError} from '~/Errors';
|
||||
import {AuditLogReasonType} from '~/Schema';
|
||||
|
||||
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.create(
|
||||
'X-Audit-Log-Reason',
|
||||
result.error.issues[0]?.message ?? 'Invalid audit log reason',
|
||||
);
|
||||
}
|
||||
ctx.set('auditLogReason', result.data);
|
||||
}
|
||||
|
||||
await next();
|
||||
});
|
||||
57
fluxer_api/src/middleware/AuthMiddleware.ts
Normal file
57
fluxer_api/src/middleware/AuthMiddleware.ts
Normal file
@@ -0,0 +1,57 @@
|
||||
/*
|
||||
* 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 {createMiddleware} from 'hono/factory';
|
||||
import type {HonoEnv} from '~/App';
|
||||
import {UserFlags} from '~/Constants';
|
||||
import {AccessDeniedError, AccountSuspiciousActivityError, MissingAccessError, UnauthorizedError} from '~/Errors';
|
||||
|
||||
export const LoginRequired = createMiddleware<HonoEnv>(async (ctx, next) => {
|
||||
const user = ctx.get('user');
|
||||
if (!user) {
|
||||
throw new UnauthorizedError();
|
||||
}
|
||||
if (user.suspiciousActivityFlags !== null && user.suspiciousActivityFlags !== 0) {
|
||||
throw new AccountSuspiciousActivityError(user.suspiciousActivityFlags);
|
||||
}
|
||||
if ((user.flags & UserFlags.PENDING_MANUAL_VERIFICATION) !== 0n) {
|
||||
throw new MissingAccessError();
|
||||
}
|
||||
|
||||
await next();
|
||||
});
|
||||
|
||||
export const LoginRequiredAllowSuspicious = createMiddleware<HonoEnv>(async (ctx, next) => {
|
||||
const user = ctx.get('user');
|
||||
if (!user) {
|
||||
throw new UnauthorizedError();
|
||||
}
|
||||
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
fluxer_api/src/middleware/BlockAppOriginMiddleware.ts
Normal file
29
fluxer_api/src/middleware/BlockAppOriginMiddleware.ts
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 type {Context, Next} from 'hono';
|
||||
import {InvalidApiOriginError} from '~/errors/InvalidApiOriginError';
|
||||
|
||||
export const BlockAppOriginMiddleware = async (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();
|
||||
};
|
||||
97
fluxer_api/src/middleware/CaptchaMiddleware.ts
Normal file
97
fluxer_api/src/middleware/CaptchaMiddleware.ts
Normal file
@@ -0,0 +1,97 @@
|
||||
/*
|
||||
* 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 {createMiddleware} from 'hono/factory';
|
||||
import type {HonoEnv} from '~/App';
|
||||
import {Config} from '~/Config';
|
||||
import {CaptchaVerificationRequiredError, InvalidCaptchaError} from '~/Errors';
|
||||
import {CaptchaService} from '~/infrastructure/CaptchaService';
|
||||
import type {ICaptchaService} from '~/infrastructure/ICaptchaService';
|
||||
import {TestCaptchaService} from '~/infrastructure/TestCaptchaService';
|
||||
import {TurnstileService} from '~/infrastructure/TurnstileService';
|
||||
import {extractClientIp} from '~/utils/IpUtils';
|
||||
|
||||
const useTestCaptcha = Config.dev.testModeEnabled;
|
||||
const testCaptchaService = new TestCaptchaService();
|
||||
let hcaptchaService: ICaptchaService | null = null;
|
||||
let turnstileService: ICaptchaService | null = null;
|
||||
|
||||
if (!useTestCaptcha && Config.captcha.enabled) {
|
||||
if (Config.captcha.hcaptcha?.secretKey) {
|
||||
hcaptchaService = new CaptchaService();
|
||||
}
|
||||
if (Config.captcha.turnstile?.secretKey) {
|
||||
turnstileService = new TurnstileService();
|
||||
}
|
||||
if (!hcaptchaService && !turnstileService) {
|
||||
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).',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export const CaptchaMiddleware = createMiddleware<HonoEnv>(async (ctx, next) => {
|
||||
if (!Config.captcha.enabled) {
|
||||
await next();
|
||||
return;
|
||||
}
|
||||
|
||||
const token = ctx.req.header('x-captcha-token');
|
||||
const captchaType = ctx.req.header('x-captcha-type');
|
||||
|
||||
if (!token) {
|
||||
throw new CaptchaVerificationRequiredError();
|
||||
}
|
||||
|
||||
let captchaService: ICaptchaService;
|
||||
if (useTestCaptcha) {
|
||||
captchaService = testCaptchaService;
|
||||
} else if (captchaType === 'turnstile' && turnstileService) {
|
||||
captchaService = turnstileService;
|
||||
} else if (captchaType === 'hcaptcha' && hcaptchaService) {
|
||||
captchaService = hcaptchaService;
|
||||
} else {
|
||||
if (Config.captcha.provider === 'turnstile' && turnstileService) {
|
||||
captchaService = turnstileService;
|
||||
} else if (Config.captcha.provider === 'hcaptcha' && hcaptchaService) {
|
||||
captchaService = hcaptchaService;
|
||||
} else {
|
||||
const fallbackService = turnstileService || hcaptchaService;
|
||||
if (!fallbackService) {
|
||||
throw new Error(
|
||||
`Captcha service not available (provider=${Config.captcha.provider}, ` +
|
||||
`turnstile=${Boolean(turnstileService)}, hcaptcha=${Boolean(hcaptchaService)})`,
|
||||
);
|
||||
}
|
||||
captchaService = fallbackService;
|
||||
}
|
||||
}
|
||||
|
||||
const isValid = await captchaService.verify({
|
||||
token,
|
||||
remoteIp: extractClientIp(ctx.req.raw) ?? undefined,
|
||||
});
|
||||
|
||||
if (!isValid) {
|
||||
throw new InvalidCaptchaError();
|
||||
}
|
||||
|
||||
await next();
|
||||
});
|
||||
189
fluxer_api/src/middleware/IpBanMiddleware.ts
Normal file
189
fluxer_api/src/middleware/IpBanMiddleware.ts
Normal file
@@ -0,0 +1,189 @@
|
||||
/*
|
||||
* 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 {createMiddleware} from 'hono/factory';
|
||||
import type {HonoEnv} from '~/App';
|
||||
import {AdminRepository} from '~/admin/AdminRepository';
|
||||
import {IpBannedError} from '~/Errors';
|
||||
import {Logger} from '~/Logger';
|
||||
import {type IpFamily, parseIpBanEntry, tryParseSingleIp} from '~/utils/IpRangeUtils';
|
||||
import {extractClientIp} from '~/utils/IpUtils';
|
||||
|
||||
type FamilyMap<T> = Record<IpFamily, 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 refreshIntervalMs = 30 * 1000;
|
||||
private adminRepository = new AdminRepository();
|
||||
private consecutiveFailures = 0;
|
||||
private maxConsecutiveFailures = 5;
|
||||
|
||||
constructor() {
|
||||
this.singleIpBans = this.createFamilyMaps();
|
||||
this.rangeIpBans = this.createFamilyMaps();
|
||||
}
|
||||
|
||||
async initialize(): Promise<void> {
|
||||
if (this.isInitialized) return;
|
||||
|
||||
await this.refresh();
|
||||
this.isInitialized = true;
|
||||
|
||||
setInterval(() => {
|
||||
this.refresh().catch((err) => {
|
||||
this.consecutiveFailures++;
|
||||
|
||||
if (this.consecutiveFailures >= this.maxConsecutiveFailures) {
|
||||
console.error(
|
||||
`Failed to refresh IP ban cache ${this.consecutiveFailures} times in a row. ` +
|
||||
`Last error: ${err.message}. Cache may be stale.`,
|
||||
);
|
||||
} else {
|
||||
console.warn(
|
||||
`Failed to refresh IP ban cache (${this.consecutiveFailures}/${this.maxConsecutiveFailures}): ${err.message}`,
|
||||
);
|
||||
}
|
||||
});
|
||||
}, this.refreshIntervalMs);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
private 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const ipBanCache = new IpBanCache();
|
||||
|
||||
export const IpBanMiddleware = createMiddleware<HonoEnv>(async (ctx, next) => {
|
||||
const clientIp = extractClientIp(ctx.req.raw);
|
||||
|
||||
if (clientIp && ipBanCache.isBanned(clientIp)) {
|
||||
throw new IpBannedError();
|
||||
}
|
||||
|
||||
await next();
|
||||
});
|
||||
96
fluxer_api/src/middleware/MetricsMiddleware.ts
Normal file
96
fluxer_api/src/middleware/MetricsMiddleware.ts
Normal file
@@ -0,0 +1,96 @@
|
||||
/*
|
||||
* 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 {createMiddleware} from 'hono/factory';
|
||||
import type {HonoEnv} from '~/App';
|
||||
import {getMetricsService} from '~/infrastructure/MetricsService';
|
||||
|
||||
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 metrics = getMetricsService();
|
||||
if (!metrics.isEnabled()) {
|
||||
await next();
|
||||
return;
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
metrics.histogram({
|
||||
name: 'api.latency',
|
||||
dimensions: {
|
||||
method,
|
||||
path: normalizedPath,
|
||||
status: String(status),
|
||||
},
|
||||
valueMs: durationMs,
|
||||
});
|
||||
|
||||
if (status >= 200 && status < 300) {
|
||||
metrics.counter({
|
||||
name: 'api.request.2xx',
|
||||
dimensions: {
|
||||
method,
|
||||
path: normalizedPath,
|
||||
status: String(status),
|
||||
},
|
||||
value: 1,
|
||||
});
|
||||
} else if (status >= 400 && status < 500) {
|
||||
metrics.counter({
|
||||
name: 'api.request.4xx',
|
||||
dimensions: {
|
||||
method,
|
||||
path: normalizedPath,
|
||||
status: String(status),
|
||||
},
|
||||
value: 1,
|
||||
});
|
||||
} else if (status >= 500 && status < 600) {
|
||||
metrics.counter({
|
||||
name: 'api.request.5xx',
|
||||
dimensions: {
|
||||
method,
|
||||
path: normalizedPath,
|
||||
status: String(status),
|
||||
},
|
||||
value: 1,
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,60 @@
|
||||
/*
|
||||
* 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 {createMiddleware} from 'hono/factory';
|
||||
import type {HonoEnv} from '~/App';
|
||||
import {UserFlags} from '~/Constants';
|
||||
import {MissingAccessError} from '~/Errors';
|
||||
|
||||
const ALLOWED_EXACT_PATHS = new Set(['/instance', '/_health']);
|
||||
const ALLOWED_PREFIXES = ['/auth'];
|
||||
|
||||
function stripV1Prefix(path: string): string {
|
||||
if (path.startsWith('/v1/') || path === '/v1') {
|
||||
return path === '/v1' ? '/' : path.slice(3);
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
function normalizePath(path: string): string {
|
||||
if (path.length > 1 && path.endsWith('/')) {
|
||||
return path.slice(0, -1);
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
export const PendingManualVerificationMiddleware = createMiddleware<HonoEnv>(async (ctx, next) => {
|
||||
const user = ctx.get('user');
|
||||
if (!user || (user.flags & UserFlags.PENDING_MANUAL_VERIFICATION) === 0n) {
|
||||
return next();
|
||||
}
|
||||
|
||||
const rawPath = stripV1Prefix(ctx.req.path);
|
||||
const normalizedPath = normalizePath(rawPath);
|
||||
|
||||
if (ALLOWED_EXACT_PATHS.has(normalizedPath)) {
|
||||
return next();
|
||||
}
|
||||
|
||||
if (ALLOWED_PREFIXES.some((prefix) => normalizedPath === prefix || normalizedPath.startsWith(`${prefix}/`))) {
|
||||
return next();
|
||||
}
|
||||
|
||||
throw new MissingAccessError();
|
||||
});
|
||||
154
fluxer_api/src/middleware/RateLimitMiddleware.ts
Normal file
154
fluxer_api/src/middleware/RateLimitMiddleware.ts
Normal file
@@ -0,0 +1,154 @@
|
||||
/*
|
||||
* 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 {Context, MiddlewareHandler} from 'hono';
|
||||
import {createMiddleware} from 'hono/factory';
|
||||
import type {HonoEnv} from '~/App';
|
||||
import {Config} from '~/Config';
|
||||
import {UserFlags} from '~/Constants';
|
||||
import {RateLimitError} from '~/Errors';
|
||||
import type {BucketConfig} from '~/infrastructure/IRateLimitService';
|
||||
import {getMetricsService} from '~/infrastructure/MetricsService';
|
||||
import {extractClientIp} from '~/utils/IpUtils';
|
||||
|
||||
export interface RouteRateLimitConfig {
|
||||
bucket: string;
|
||||
config: BucketConfig;
|
||||
}
|
||||
|
||||
function getClientIdentifier(ctx: Context<HonoEnv>): string {
|
||||
const user = ctx.get('user');
|
||||
if (user?.id) {
|
||||
return `user:${user.id}`;
|
||||
}
|
||||
const ip = extractClientIp(ctx.req.raw);
|
||||
if (!ip) return 'internal';
|
||||
return `ip:${ip}`;
|
||||
}
|
||||
|
||||
function getGlobalRateLimit(ctx: Context<HonoEnv>): number {
|
||||
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());
|
||||
}
|
||||
|
||||
export function RateLimitMiddleware(routeConfig: RouteRateLimitConfig): MiddlewareHandler<HonoEnv> {
|
||||
return createMiddleware<HonoEnv>(async (ctx, next) => {
|
||||
if (Config.dev.disableRateLimits || Config.dev.testModeEnabled || process.env.CI === 'true') {
|
||||
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 metrics = getMetricsService();
|
||||
const clientId = getClientIdentifier(ctx);
|
||||
|
||||
if (!routeConfig.config.exemptFromGlobal) {
|
||||
const globalLimit = getGlobalRateLimit(ctx);
|
||||
const globalResult = await rateLimitService.checkGlobalLimit(clientId, globalLimit);
|
||||
|
||||
metrics.counter({
|
||||
name: 'api.ratelimit.check',
|
||||
dimensions: {bucket: 'global'},
|
||||
});
|
||||
|
||||
if (!globalResult.allowed) {
|
||||
metrics.counter({
|
||||
name: 'api.ratelimit.blocked',
|
||||
dimensions: {bucket: 'global'},
|
||||
});
|
||||
throw new RateLimitError({
|
||||
global: true,
|
||||
retryAfter: globalResult.retryAfter!,
|
||||
retryAfterDecimal: globalResult.retryAfterDecimal,
|
||||
limit: globalResult.limit,
|
||||
resetTime: globalResult.resetTime,
|
||||
});
|
||||
}
|
||||
|
||||
metrics.counter({
|
||||
name: 'api.ratelimit.allowed',
|
||||
dimensions: {bucket: 'global'},
|
||||
});
|
||||
}
|
||||
|
||||
const bucket = resolveBucket(routeConfig.bucket, ctx);
|
||||
const bucketResult = await rateLimitService.checkBucketLimit(bucket, routeConfig.config);
|
||||
|
||||
metrics.counter({
|
||||
name: 'api.ratelimit.check',
|
||||
dimensions: {bucket: routeConfig.bucket},
|
||||
});
|
||||
|
||||
if (!bucketResult.allowed) {
|
||||
metrics.counter({
|
||||
name: 'api.ratelimit.blocked',
|
||||
dimensions: {bucket: routeConfig.bucket},
|
||||
});
|
||||
throw new RateLimitError({
|
||||
global: false,
|
||||
retryAfter: bucketResult.retryAfter!,
|
||||
retryAfterDecimal: bucketResult.retryAfterDecimal,
|
||||
limit: bucketResult.limit,
|
||||
resetTime: bucketResult.resetTime,
|
||||
});
|
||||
}
|
||||
|
||||
metrics.counter({
|
||||
name: 'api.ratelimit.allowed',
|
||||
dimensions: {bucket: routeConfig.bucket},
|
||||
});
|
||||
|
||||
setRateLimitHeaders(ctx, bucketResult.limit, bucketResult.remaining, bucketResult.resetTime);
|
||||
|
||||
await next();
|
||||
});
|
||||
}
|
||||
49
fluxer_api/src/middleware/RequestCacheMiddleware.ts
Normal file
49
fluxer_api/src/middleware/RequestCacheMiddleware.ts
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 {createMiddleware} from 'hono/factory';
|
||||
import type {HonoEnv} from '~/App';
|
||||
import type {UserPartialResponse} from '~/user/UserModel';
|
||||
|
||||
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();
|
||||
}
|
||||
46
fluxer_api/src/middleware/RequireXForwardedForMiddleware.ts
Normal file
46
fluxer_api/src/middleware/RequireXForwardedForMiddleware.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
/*
|
||||
* 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 {createMiddleware} from 'hono/factory';
|
||||
import {HTTPException} from 'hono/http-exception';
|
||||
import type {HonoEnv} from '~/App';
|
||||
import {Logger} from '~/Logger';
|
||||
|
||||
interface RequireXForwardedForOptions {
|
||||
exemptPaths?: Array<string>;
|
||||
}
|
||||
|
||||
const defaultExemptPaths: Array<string> = ['/_health', '/_rpc', '/webhooks/livekit', '/test'];
|
||||
|
||||
export const RequireXForwardedForMiddleware = ({exemptPaths = defaultExemptPaths}: RequireXForwardedForOptions = {}) =>
|
||||
createMiddleware<HonoEnv>(async (ctx, next) => {
|
||||
const path = 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();
|
||||
});
|
||||
600
fluxer_api/src/middleware/ServiceMiddleware.ts
Normal file
600
fluxer_api/src/middleware/ServiceMiddleware.ts
Normal file
@@ -0,0 +1,600 @@
|
||||
/*
|
||||
* 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 {createMiddleware} from 'hono/factory';
|
||||
import {Redis} from 'ioredis';
|
||||
import type {HonoEnv} from '~/App';
|
||||
import {AdminRepository} from '~/admin/AdminRepository';
|
||||
import {AdminService} from '~/admin/AdminService';
|
||||
import {AdminArchiveRepository} from '~/admin/repositories/AdminArchiveRepository';
|
||||
import {AdminArchiveService} from '~/admin/services/AdminArchiveService';
|
||||
import {AuthService} from '~/auth/AuthService';
|
||||
import {AuthMfaService} from '~/auth/services/AuthMfaService';
|
||||
import {DesktopHandoffService} from '~/auth/services/DesktopHandoffService';
|
||||
import {Config} from '~/Config';
|
||||
import {ChannelRepository as ProdChannelRepository} from '~/channel/ChannelRepository';
|
||||
import {ChannelService} from '~/channel/services/ChannelService';
|
||||
import {ScheduledMessageService} from '~/channel/services/ScheduledMessageService';
|
||||
import {StreamPreviewService} from '~/channel/services/StreamPreviewService';
|
||||
import {FavoriteMemeRepository} from '~/favorite_meme/FavoriteMemeRepository';
|
||||
import {FavoriteMemeService} from '~/favorite_meme/FavoriteMemeService';
|
||||
import {FeatureFlagRepository} from '~/feature_flag/FeatureFlagRepository';
|
||||
import {FeatureFlagService} from '~/feature_flag/FeatureFlagService';
|
||||
import {GuildAuditLogService} from '~/guild/GuildAuditLogService';
|
||||
import {GuildRepository as ProdGuildRepository} from '~/guild/repositories/GuildRepository';
|
||||
import {ExpressionAssetPurger} from '~/guild/services/content/ExpressionAssetPurger';
|
||||
import {GuildService} from '~/guild/services/GuildService';
|
||||
import {AssetDeletionQueue} from '~/infrastructure/AssetDeletionQueue';
|
||||
import {AvatarService} from '~/infrastructure/AvatarService';
|
||||
import {
|
||||
CloudflarePurgeQueue,
|
||||
type ICloudflarePurgeQueue,
|
||||
NoopCloudflarePurgeQueue,
|
||||
} from '~/infrastructure/CloudflarePurgeQueue';
|
||||
import {DisabledLiveKitService} from '~/infrastructure/DisabledLiveKitService';
|
||||
import {DisabledVirusScanService} from '~/infrastructure/DisabledVirusScanService';
|
||||
import {DiscriminatorService as ProdDiscriminatorService} from '~/infrastructure/DiscriminatorService';
|
||||
import {EmailService as ProdEmailService} from '~/infrastructure/EmailService';
|
||||
import {EmbedService} from '~/infrastructure/EmbedService';
|
||||
import {EntityAssetService} from '~/infrastructure/EntityAssetService';
|
||||
import {GatewayService as ProdGatewayService} from '~/infrastructure/GatewayService';
|
||||
import type {IAssetDeletionQueue} from '~/infrastructure/IAssetDeletionQueue';
|
||||
import type {ICacheService} from '~/infrastructure/ICacheService';
|
||||
import type {IEmailService} from '~/infrastructure/IEmailService';
|
||||
import type {ILiveKitService} from '~/infrastructure/ILiveKitService';
|
||||
import {InMemoryVoiceRoomStore} from '~/infrastructure/InMemoryVoiceRoomStore';
|
||||
import type {IVoiceRoomStore} from '~/infrastructure/IVoiceRoomStore';
|
||||
import {LiveKitService} from '~/infrastructure/LiveKitService';
|
||||
import {LiveKitWebhookService} from '~/infrastructure/LiveKitWebhookService';
|
||||
import {MediaService as ProdMediaService} from '~/infrastructure/MediaService';
|
||||
import {PendingJoinInviteStore} from '~/infrastructure/PendingJoinInviteStore';
|
||||
import {RateLimitService} from '~/infrastructure/RateLimitService';
|
||||
import {RedisAccountDeletionQueueService} from '~/infrastructure/RedisAccountDeletionQueueService';
|
||||
import {RedisActivityTracker} from '~/infrastructure/RedisActivityTracker';
|
||||
import {RedisBulkMessageDeletionQueueService} from '~/infrastructure/RedisBulkMessageDeletionQueueService';
|
||||
import {RedisCacheService} from '~/infrastructure/RedisCacheService';
|
||||
import {SMSService} from '~/infrastructure/SMSService';
|
||||
import {SnowflakeService} from '~/infrastructure/SnowflakeService';
|
||||
import {StorageService as ProdStorageService} from '~/infrastructure/StorageService';
|
||||
import {TestEmailService} from '~/infrastructure/TestEmailService';
|
||||
import {UnfurlerService as ProdUnfurlerService} from '~/infrastructure/UnfurlerService';
|
||||
import {UserCacheService} from '~/infrastructure/UserCacheService';
|
||||
import {VirusScanService as ProdVirusScanService} from '~/infrastructure/VirusScanService';
|
||||
import {VoiceRoomStore} from '~/infrastructure/VoiceRoomStore';
|
||||
import {InviteRepository as ProdInviteRepository} from '~/invite/InviteRepository';
|
||||
import {InviteService} from '~/invite/InviteService';
|
||||
import {getReportSearchService} from '~/Meilisearch';
|
||||
import {ApplicationService} from '~/oauth/ApplicationService';
|
||||
import {BotAuthService} from '~/oauth/BotAuthService';
|
||||
import {BotMfaMirrorService} from '~/oauth/BotMfaMirrorService';
|
||||
import {OAuth2Service} from '~/oauth/OAuth2Service';
|
||||
import {ApplicationRepository} from '~/oauth/repositories/ApplicationRepository';
|
||||
import {OAuth2TokenRepository} from '~/oauth/repositories/OAuth2TokenRepository';
|
||||
import {PackRepository} from '~/pack/PackRepository';
|
||||
import {PackService} from '~/pack/PackService';
|
||||
import {ReadStateRepository as ProdReadStateRepository} from '~/read_state/ReadStateRepository';
|
||||
import {ReadStateService} from '~/read_state/ReadStateService';
|
||||
import {ReportRepository} from '~/report/ReportRepository';
|
||||
import {ReportService} from '~/report/ReportService';
|
||||
import {RpcService} from '~/rpc/RpcService';
|
||||
import {StripeService} from '~/stripe/StripeService';
|
||||
import {TenorService as ProdTenorService} from '~/tenor/TenorService';
|
||||
import {EmailChangeRepository} from '~/user/repositories/auth/EmailChangeRepository';
|
||||
import {ScheduledMessageRepository} from '~/user/repositories/ScheduledMessageRepository';
|
||||
import {UserContactChangeLogRepository} from '~/user/repositories/UserContactChangeLogRepository';
|
||||
import {EmailChangeService} from '~/user/services/EmailChangeService';
|
||||
import {UserContactChangeLogService} from '~/user/services/UserContactChangeLogService';
|
||||
import {UserRepository as ProdUserRepository} from '~/user/UserRepository';
|
||||
import {UserService} from '~/user/UserService';
|
||||
import {UserPermissionUtils} from '~/utils/UserPermissionUtils';
|
||||
import {VoiceAvailabilityService} from '~/voice/VoiceAvailabilityService';
|
||||
import {VoiceRepository} from '~/voice/VoiceRepository';
|
||||
import {VoiceService} from '~/voice/VoiceService';
|
||||
import {VoiceTopology} from '~/voice/VoiceTopology';
|
||||
import {SendGridWebhookService} from '~/webhook/SendGridWebhookService';
|
||||
import {WebhookRepository as ProdWebhookRepository} from '~/webhook/WebhookRepository';
|
||||
import {WebhookService} from '~/webhook/WebhookService';
|
||||
import {WorkerService as ProdWorkerService} from '~/worker/WorkerService';
|
||||
|
||||
const ChannelRepository = ProdChannelRepository;
|
||||
const UserRepository = ProdUserRepository;
|
||||
const GuildRepository = ProdGuildRepository;
|
||||
const InviteRepository = ProdInviteRepository;
|
||||
const WebhookRepository = ProdWebhookRepository;
|
||||
const ReadStateRepository = ProdReadStateRepository;
|
||||
|
||||
const MediaService = ProdMediaService;
|
||||
const UnfurlerService = ProdUnfurlerService;
|
||||
const GatewayService = ProdGatewayService;
|
||||
const StorageService = ProdStorageService;
|
||||
const TenorService = ProdTenorService;
|
||||
const EmailService = ProdEmailService;
|
||||
const WorkerService = ProdWorkerService;
|
||||
const DiscriminatorService = ProdDiscriminatorService;
|
||||
|
||||
const VirusScanService = Config.clamav.enabled ? ProdVirusScanService : DisabledVirusScanService;
|
||||
const testEmailServiceInstance = Config.dev.testModeEnabled ? new TestEmailService() : null;
|
||||
|
||||
const redis = new Redis(Config.redis.url);
|
||||
|
||||
const cacheService: ICacheService = new RedisCacheService(redis);
|
||||
const pendingJoinInviteStore = new PendingJoinInviteStore(cacheService);
|
||||
const rateLimitService = new RateLimitService(cacheService);
|
||||
const snowflakeService = new SnowflakeService(redis);
|
||||
const cloudflarePurgeQueue: ICloudflarePurgeQueue = Config.cloudflare.purgeEnabled
|
||||
? new CloudflarePurgeQueue(redis)
|
||||
: new NoopCloudflarePurgeQueue();
|
||||
const assetDeletionQueue: IAssetDeletionQueue = new AssetDeletionQueue(redis);
|
||||
|
||||
const featureFlagRepository = new FeatureFlagRepository();
|
||||
const featureFlagService = new FeatureFlagService(featureFlagRepository, cacheService);
|
||||
let featureFlagServiceInitialized = false;
|
||||
|
||||
let voiceTopology: VoiceTopology | null = null;
|
||||
let voiceAvailabilityService: VoiceAvailabilityService | null = null;
|
||||
let liveKitServiceInstance: ILiveKitService | null = null;
|
||||
let voiceRoomStoreInstance: IVoiceRoomStore | null = null;
|
||||
let voiceConfigSubscriber: Redis | 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 = new Redis(Config.redis.url);
|
||||
}
|
||||
const topology = new VoiceTopology(voiceRepository, voiceConfigSubscriber);
|
||||
await topology.initialize();
|
||||
voiceTopology = topology;
|
||||
voiceAvailabilityService = new VoiceAvailabilityService(topology);
|
||||
liveKitServiceInstance = new LiveKitService(topology);
|
||||
voiceRoomStoreInstance = new VoiceRoomStore(redis);
|
||||
})().finally(() => {
|
||||
voiceInitializationPromise = null;
|
||||
});
|
||||
}
|
||||
|
||||
await voiceInitializationPromise;
|
||||
}
|
||||
|
||||
export const ServiceMiddleware = createMiddleware<HonoEnv>(async (ctx, next) => {
|
||||
await snowflakeService.initialize();
|
||||
|
||||
if (!featureFlagServiceInitialized) {
|
||||
await featureFlagService.initialize();
|
||||
featureFlagServiceInitialized = true;
|
||||
}
|
||||
|
||||
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 reportRepository = new ReportRepository();
|
||||
const adminRepository = new AdminRepository();
|
||||
const adminArchiveRepository = new AdminArchiveRepository();
|
||||
const voiceRepository = new VoiceRepository();
|
||||
const applicationRepository = new ApplicationRepository();
|
||||
const oauth2TokenRepository = new OAuth2TokenRepository();
|
||||
|
||||
const userCacheService = new UserCacheService(cacheService, userRepository);
|
||||
const redisAccountDeletionQueue = new RedisAccountDeletionQueueService(redis, userRepository);
|
||||
const redisBulkMessageDeletionQueue = new RedisBulkMessageDeletionQueueService(redis);
|
||||
const redisActivityTracker = new RedisActivityTracker(redis);
|
||||
const mediaService = new MediaService();
|
||||
const storageService = new StorageService();
|
||||
const gatewayService = new GatewayService();
|
||||
const workerService = new WorkerService();
|
||||
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);
|
||||
const entityAssetService = new EntityAssetService(storageService, mediaService, assetDeletionQueue);
|
||||
|
||||
const emailService: IEmailService = testEmailServiceInstance ?? new EmailService(userRepository);
|
||||
const smsService = new SMSService();
|
||||
const virusScanService = new VirusScanService(cacheService);
|
||||
await virusScanService.initialize();
|
||||
|
||||
await ensureVoiceResourcesInitialized();
|
||||
const liveKitService: ILiveKitService = liveKitServiceInstance ?? new DisabledLiveKitService();
|
||||
const voiceRoomStore: IVoiceRoomStore = voiceRoomStoreInstance ?? 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,
|
||||
featureFlagService,
|
||||
);
|
||||
|
||||
const channelService = new ChannelService(
|
||||
channelRepository,
|
||||
userRepository,
|
||||
guildRepository,
|
||||
packService,
|
||||
userCacheService,
|
||||
embedService,
|
||||
readStateService,
|
||||
cacheService,
|
||||
storageService,
|
||||
gatewayService,
|
||||
mediaService,
|
||||
avatarService,
|
||||
workerService,
|
||||
virusScanService,
|
||||
snowflakeService,
|
||||
rateLimitService,
|
||||
cloudflarePurgeQueue,
|
||||
favoriteMemeRepository,
|
||||
guildAuditLogService,
|
||||
voiceRoomStore,
|
||||
liveKitService,
|
||||
inviteRepository,
|
||||
webhookRepository,
|
||||
voiceAvailabilityService ?? undefined,
|
||||
);
|
||||
|
||||
const scheduledMessageRepository = new ScheduledMessageRepository();
|
||||
const scheduledMessageService = new ScheduledMessageService(
|
||||
channelService,
|
||||
scheduledMessageRepository,
|
||||
workerService,
|
||||
snowflakeService,
|
||||
channelRepository,
|
||||
featureFlagService,
|
||||
);
|
||||
|
||||
const streamPreviewService = new StreamPreviewService(storageService, cacheService);
|
||||
|
||||
const guildService = new GuildService(
|
||||
guildRepository,
|
||||
channelRepository,
|
||||
inviteRepository,
|
||||
channelService,
|
||||
userCacheService,
|
||||
gatewayService,
|
||||
entityAssetService,
|
||||
avatarService,
|
||||
assetDeletionQueue,
|
||||
userRepository,
|
||||
mediaService,
|
||||
cacheService,
|
||||
snowflakeService,
|
||||
rateLimitService,
|
||||
workerService,
|
||||
webhookRepository,
|
||||
guildAuditLogService,
|
||||
);
|
||||
|
||||
const inviteService = new InviteService(
|
||||
inviteRepository,
|
||||
guildService,
|
||||
channelService,
|
||||
gatewayService,
|
||||
guildAuditLogService,
|
||||
userRepository,
|
||||
packRepository,
|
||||
packService,
|
||||
);
|
||||
|
||||
const favoriteMemeService = new FavoriteMemeService(
|
||||
favoriteMemeRepository,
|
||||
channelService,
|
||||
storageService,
|
||||
mediaService,
|
||||
snowflakeService,
|
||||
gatewayService,
|
||||
unfurlerService,
|
||||
);
|
||||
|
||||
const discriminatorService = new DiscriminatorService(userRepository, cacheService);
|
||||
|
||||
const hasVoiceInfrastructure =
|
||||
Config.voice.enabled &&
|
||||
voiceTopology !== null &&
|
||||
liveKitService instanceof LiveKitService &&
|
||||
voiceRoomStore instanceof VoiceRoomStore;
|
||||
|
||||
const liveKitWebhookService =
|
||||
hasVoiceInfrastructure && voiceTopology
|
||||
? new LiveKitWebhookService(voiceRoomStore, gatewayService, userRepository, liveKitService, voiceTopology)
|
||||
: 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,
|
||||
discriminatorService,
|
||||
redisAccountDeletionQueue,
|
||||
redisActivityTracker,
|
||||
pendingJoinInviteStore,
|
||||
contactChangeLogService,
|
||||
botMfaMirrorService,
|
||||
authMfaService,
|
||||
);
|
||||
const desktopHandoffService = new DesktopHandoffService(cacheService);
|
||||
|
||||
const reportSearchService = getReportSearchService();
|
||||
const reportService = new ReportService(
|
||||
reportRepository,
|
||||
channelRepository,
|
||||
guildRepository,
|
||||
userRepository,
|
||||
inviteRepository,
|
||||
emailService,
|
||||
snowflakeService,
|
||||
storageService,
|
||||
reportSearchService,
|
||||
);
|
||||
|
||||
const adminService = new AdminService(
|
||||
userRepository,
|
||||
guildRepository,
|
||||
channelRepository,
|
||||
adminRepository,
|
||||
inviteRepository,
|
||||
inviteService,
|
||||
pendingJoinInviteStore,
|
||||
discriminatorService,
|
||||
snowflakeService,
|
||||
guildService,
|
||||
authService,
|
||||
gatewayService,
|
||||
userCacheService,
|
||||
entityAssetService,
|
||||
assetDeletionQueue,
|
||||
emailService,
|
||||
mediaService,
|
||||
storageService,
|
||||
reportService,
|
||||
workerService,
|
||||
cacheService,
|
||||
voiceRepository,
|
||||
botMfaMirrorService,
|
||||
contactChangeLogService,
|
||||
redisBulkMessageDeletionQueue,
|
||||
);
|
||||
|
||||
const adminArchiveService = new AdminArchiveService(
|
||||
adminArchiveRepository,
|
||||
userRepository,
|
||||
guildRepository,
|
||||
storageService,
|
||||
snowflakeService,
|
||||
workerService,
|
||||
);
|
||||
|
||||
const botAuthService = new BotAuthService(applicationRepository);
|
||||
|
||||
const rpcService = new RpcService(
|
||||
userRepository,
|
||||
guildRepository,
|
||||
channelRepository,
|
||||
userCacheService,
|
||||
readStateService,
|
||||
authService,
|
||||
gatewayService,
|
||||
discriminatorService,
|
||||
favoriteMemeRepository,
|
||||
packService,
|
||||
botAuthService,
|
||||
inviteRepository,
|
||||
webhookRepository,
|
||||
storageService,
|
||||
voiceService,
|
||||
voiceAvailabilityService ?? undefined,
|
||||
rateLimitService,
|
||||
mediaService,
|
||||
featureFlagService,
|
||||
);
|
||||
|
||||
const webhookService = new WebhookService(
|
||||
webhookRepository,
|
||||
guildService,
|
||||
channelService,
|
||||
channelRepository,
|
||||
cacheService,
|
||||
gatewayService,
|
||||
avatarService,
|
||||
mediaService,
|
||||
snowflakeService,
|
||||
guildAuditLogService,
|
||||
);
|
||||
|
||||
const tenorService = new TenorService(cacheService, mediaService);
|
||||
|
||||
const emailChangeRepository = new EmailChangeRepository();
|
||||
const emailChangeService = new EmailChangeService(
|
||||
emailChangeRepository,
|
||||
emailService,
|
||||
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,
|
||||
redisAccountDeletionQueue,
|
||||
redisBulkMessageDeletionQueue,
|
||||
botMfaMirrorService,
|
||||
contactChangeLogService,
|
||||
);
|
||||
|
||||
let stripeService: StripeService | null = null;
|
||||
if (!Config.instance.selfHosted) {
|
||||
stripeService = new StripeService(
|
||||
userRepository,
|
||||
authService,
|
||||
gatewayService,
|
||||
emailService,
|
||||
guildRepository,
|
||||
guildService,
|
||||
cacheService,
|
||||
);
|
||||
}
|
||||
|
||||
const sendGridWebhookService = new SendGridWebhookService(userRepository, gatewayService);
|
||||
|
||||
const applicationService = new ApplicationService({
|
||||
applicationRepository,
|
||||
userRepository,
|
||||
userService,
|
||||
userCacheService,
|
||||
entityAssetService,
|
||||
discriminatorService,
|
||||
snowflakeService,
|
||||
botAuthService,
|
||||
gatewayService,
|
||||
});
|
||||
|
||||
const oauth2Service = new OAuth2Service({
|
||||
userRepository,
|
||||
applicationRepository,
|
||||
oauth2TokenRepository,
|
||||
cacheService,
|
||||
});
|
||||
|
||||
ctx.set('adminService', adminService);
|
||||
ctx.set('adminArchiveService', adminArchiveService);
|
||||
ctx.set('applicationRepository', applicationRepository);
|
||||
ctx.set('applicationService', applicationService);
|
||||
ctx.set('authMfaService', authMfaService);
|
||||
ctx.set('authService', authService);
|
||||
ctx.set('botAuthService', botAuthService);
|
||||
ctx.set('cacheService', cacheService);
|
||||
ctx.set('channelService', channelService);
|
||||
ctx.set('channelRepository', channelRepository);
|
||||
ctx.set('streamPreviewService', streamPreviewService);
|
||||
ctx.set('desktopHandoffService', desktopHandoffService);
|
||||
ctx.set('emailService', emailService);
|
||||
ctx.set('embedService', embedService);
|
||||
ctx.set('entityAssetService', entityAssetService);
|
||||
ctx.set('favoriteMemeService', favoriteMemeService);
|
||||
ctx.set('gatewayService', gatewayService);
|
||||
ctx.set('guildService', guildService);
|
||||
ctx.set('emailChangeService', emailChangeService);
|
||||
ctx.set('inviteService', inviteService);
|
||||
ctx.set('packService', packService);
|
||||
ctx.set('packRepository', packRepository);
|
||||
if (liveKitWebhookService) {
|
||||
ctx.set('liveKitWebhookService', liveKitWebhookService);
|
||||
}
|
||||
ctx.set('mediaService', mediaService);
|
||||
ctx.set('oauth2Service', oauth2Service);
|
||||
ctx.set('oauth2TokenRepository', oauth2TokenRepository);
|
||||
ctx.set('rateLimitService', rateLimitService);
|
||||
ctx.set('readStateService', readStateService);
|
||||
ctx.set('redisActivityTracker', redisActivityTracker);
|
||||
ctx.set('reportService', reportService);
|
||||
ctx.set('rpcService', rpcService);
|
||||
ctx.set('sendGridWebhookService', sendGridWebhookService);
|
||||
ctx.set('snowflakeService', snowflakeService);
|
||||
ctx.set('storageService', storageService);
|
||||
if (stripeService) {
|
||||
ctx.set('stripeService', stripeService);
|
||||
}
|
||||
ctx.set('sudoModeValid', false);
|
||||
ctx.set('tenorService', tenorService);
|
||||
ctx.set('userCacheService', userCacheService);
|
||||
ctx.set('userRepository', userRepository);
|
||||
ctx.set('userService', userService);
|
||||
ctx.set('scheduledMessageService', scheduledMessageService);
|
||||
ctx.set('webhookService', webhookService);
|
||||
ctx.set('workerService', workerService);
|
||||
ctx.set('featureFlagService', featureFlagService);
|
||||
|
||||
await next();
|
||||
});
|
||||
66
fluxer_api/src/middleware/SudoModeMiddleware.ts
Normal file
66
fluxer_api/src/middleware/SudoModeMiddleware.ts
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 {createMiddleware} from 'hono/factory';
|
||||
import type {HonoEnv} from '~/App';
|
||||
import {getSudoModeService} from '~/auth/services/SudoModeService';
|
||||
import {getSudoCookie} from '~/utils/SudoCookieUtils';
|
||||
|
||||
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();
|
||||
});
|
||||
167
fluxer_api/src/middleware/UserMiddleware.ts
Normal file
167
fluxer_api/src/middleware/UserMiddleware.ts
Normal file
@@ -0,0 +1,167 @@
|
||||
/*
|
||||
* 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 {Context} from 'hono';
|
||||
import {createMiddleware} from 'hono/factory';
|
||||
import type {HonoEnv} from '~/App';
|
||||
import {getMetricsService} from '~/infrastructure/MetricsService';
|
||||
import type {User} from '~/Models';
|
||||
import * as IpUtils from '~/utils/IpUtils';
|
||||
|
||||
type TokenType = 'session' | 'bearer' | 'bot';
|
||||
|
||||
interface ParsedAuthHeader {
|
||||
token: string;
|
||||
type: TokenType;
|
||||
}
|
||||
|
||||
function parseAuthHeader(authHeader?: string | null): ParsedAuthHeader | null {
|
||||
if (!authHeader) return null;
|
||||
|
||||
const normalized = authHeader.trim();
|
||||
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.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 redisActivityTracker = ctx.get('redisActivityTracker');
|
||||
void Promise.all([
|
||||
userRepository.updateLastActiveAt({
|
||||
userId: user.id,
|
||||
lastActiveAt: now,
|
||||
lastActiveIp: IpUtils.requireClientIp(ctx.req.raw),
|
||||
}),
|
||||
redisActivityTracker.updateActivity(user.id, now),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
export const UserMiddleware = createMiddleware<HonoEnv>(async (ctx, next) => {
|
||||
const rawAuthHeader = ctx.req.header('Authorization');
|
||||
const parsed = parseAuthHeader(rawAuthHeader);
|
||||
|
||||
ctx.set('oauthBearerToken', undefined);
|
||||
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) {
|
||||
void authService.updateAuthSessionLastUsed(authSession.sessionIdHash);
|
||||
void authService.updateUserActivity({
|
||||
userId: authSession.userId,
|
||||
clientIp: IpUtils.requireClientIp(ctx.req.raw),
|
||||
});
|
||||
|
||||
const user = await ctx.get('userService').findUniqueAssert(authSession.userId);
|
||||
|
||||
ctx.set('authSession', authSession);
|
||||
ctx.set('authTokenType', 'session');
|
||||
setUserInContext(ctx, user, true);
|
||||
} else {
|
||||
getMetricsService().counter({
|
||||
name: 'auth.token.invalid',
|
||||
dimensions: {type: 'session'},
|
||||
});
|
||||
}
|
||||
await next();
|
||||
return;
|
||||
}
|
||||
|
||||
if (type === 'bearer') {
|
||||
const accessToken = await ctx.get('oauth2TokenRepository').getAccessToken(token);
|
||||
const userId = accessToken?.userId ?? null;
|
||||
if (accessToken) {
|
||||
ctx.set('oauthBearerToken', token);
|
||||
ctx.set('oauthBearerScopes', accessToken.scope);
|
||||
ctx.set('oauthBearerUserId', accessToken.userId ?? undefined);
|
||||
} else {
|
||||
getMetricsService().counter({
|
||||
name: 'auth.token.invalid',
|
||||
dimensions: {type: 'bearer'},
|
||||
});
|
||||
}
|
||||
if (userId) {
|
||||
const user = await ctx.get('userService').findUnique(userId);
|
||||
if (user) {
|
||||
ctx.set('authTokenType', 'bearer');
|
||||
setUserInContext(ctx, user, false);
|
||||
}
|
||||
}
|
||||
await next();
|
||||
return;
|
||||
}
|
||||
|
||||
if (type === 'bot') {
|
||||
const botAuthService = ctx.get('botAuthService');
|
||||
const botUserId = await botAuthService.validateBotToken(token);
|
||||
if (botUserId) {
|
||||
const botUser = await ctx.get('userService').findUnique(botUserId);
|
||||
if (botUser) {
|
||||
ctx.set('authTokenType', 'bot');
|
||||
setUserInContext(ctx, botUser, false);
|
||||
}
|
||||
} else {
|
||||
getMetricsService().counter({
|
||||
name: 'auth.token.invalid',
|
||||
dimensions: {type: 'bot'},
|
||||
});
|
||||
}
|
||||
await next();
|
||||
return;
|
||||
}
|
||||
|
||||
await next();
|
||||
});
|
||||
Reference in New Issue
Block a user