A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
feat(api/auth): add instant accounts with escalating captcha
Hampusc766107df5fa
diff --git a/fluxer_api/src/api/auth/AuthInstantAccounts.ts b/fluxer_api/src/api/auth/AuthInstantAccounts.tsnew file mode 100644index 000000000..231d831e7--- /dev/null+++ b/fluxer_api/src/api/auth/AuthInstantAccounts.ts@@ -0,0 +1,173 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {timingSafeEqual} from 'node:crypto';+import type {ApiContext} from '@app/api/ApiContext';+import {budgetEnvFor, instantAccountCaptchaSteps} from '@app/api/auth/AccountBudgets';+import {generateOpaqueToken, sha256Hex} from '@app/api/auth/AccountCodes';+import {+ type AccountCreationResult,+ assertAccountCreationPastSetup,+ assertInstantAccountAvailable,+ assertRegistrationConsent,+ createAccount,+ type RegistrationDependencies,+ resolveInstantAccountAvailabilityFor,+} from '@app/api/auth/AuthRegistration';+import {profileSubstringBlocklistCache} from '@app/api/middleware/ProfileSubstringBlocklistCache';+import type {RequestCache} from '@app/api/middleware/RequestCacheMiddleware';+import {getInstanceConfigRepository} from '@app/api/middleware/ServiceSingletons';+import type {User} from '@app/api/models/User';+import type {TierContext} from '@app/api/user/AccountTier';+import {isJsonRecord, parseJsonWithGuard} from '@app/api/utils/JsonBoundaryUtils';+import {requireConfiguredClientIp} from '@app/api/utils/RequestClientIp';+import {InvalidAccountHandoffNonceError} from '@fluxer/errors/src/domains/auth/InvalidAccountHandoffNonceError';+import {RegistrationClosedError} from '@fluxer/errors/src/domains/auth/RegistrationClosedError';+import {UnknownAccountHandoffError} from '@fluxer/errors/src/domains/auth/UnknownAccountHandoffError';+import {ContentBlockedError} from '@fluxer/errors/src/domains/content/ContentBlockedError';+import {InputValidationError} from '@fluxer/errors/src/domains/core/InputValidationError';+import {FluxerError} from '@fluxer/errors/src/FluxerError';+import type {GuildEntryResult} from '@fluxer/schema/src/domains/user/AccountSchemas';+import {seconds} from 'itty-time';++const HANDOFF_TTL_SECONDS = seconds('15 minutes');++interface AccountHandoffRecord {+ global_name: string;+ nonce_hash: string;+ client_ip: string;+ locale: string | null;+ registration_url_code?: string | null;+ created_at: number;+}++function isHandoffRecord(value: unknown): value is AccountHandoffRecord {+ return (+ isJsonRecord(value) &&+ typeof value.global_name === 'string' &&+ typeof value.nonce_hash === 'string' &&+ typeof value.client_ip === 'string' &&+ (value.locale === null || typeof value.locale === 'string') &&+ (value.registration_url_code == null || typeof value.registration_url_code === 'string') &&+ typeof value.created_at === 'number'+ );+}++function assertDisplayNameAllowed(globalName: string): void {+ if (profileSubstringBlocklistCache.containsBannedSubstring('global_name', globalName)) {+ throw new ContentBlockedError();+ }+}++function handoffKey(code: string): string {+ return `auth:account_handoff:${sha256Hex(code)}`;+}++function isRetryableBeforeCreation(error: unknown): boolean {+ if (error instanceof InputValidationError || error instanceof ContentBlockedError) return true;+ return error instanceof FluxerError && error.status === 429;+}++async function restoreHandoff(ctx: ApiContext, handoffCode: string, record: AccountHandoffRecord): Promise<void> {+ const remainingSeconds = HANDOFF_TTL_SECONDS - Math.ceil((Date.now() - record.created_at) / 1000);+ if (remainingSeconds <= 0) return;+ await ctx.services.kv.setex(handoffKey(handoffCode), remainingSeconds, JSON.stringify(record));+}++export async function instantAccountChallengeSteps(+ ctx: ApiContext,+ request: Request,+ clientIp: string,+ registrationUrlCode: string | null = null,+) {+ const repository = getInstanceConfigRepository();+ assertInstantAccountAvailable(await resolveInstantAccountAvailabilityFor(repository, registrationUrlCode));+ const auth = await repository.getAuthConfig();+ return await instantAccountCaptchaSteps(budgetEnvFor(ctx.services, request), {+ clientIp,+ escalationPerHour: auth.instant_accounts.pow_escalation_per_hour,+ });+}++export async function createAccountHandoff(+ ctx: ApiContext,+ params: {+ globalName: string;+ nonceHash: string;+ locale: string | undefined;+ registrationUrlCode: string | null | undefined;+ clientIp: string;+ },+): Promise<{handoff_code: string}> {+ const repository = getInstanceConfigRepository();+ await assertAccountCreationPastSetup(ctx, repository, params.clientIp);+ assertInstantAccountAvailable(await resolveInstantAccountAvailabilityFor(repository, params.registrationUrlCode));+ assertDisplayNameAllowed(params.globalName);+ const handoffCode = generateOpaqueToken();+ const record: AccountHandoffRecord = {+ global_name: params.globalName,+ nonce_hash: params.nonceHash,+ client_ip: params.clientIp,+ locale: params.locale ?? null,+ registration_url_code: params.registrationUrlCode?.trim() || null,+ created_at: Date.now(),+ };+ await ctx.services.kv.setex(handoffKey(handoffCode), HANDOFF_TTL_SECONDS, JSON.stringify(record));+ return {handoff_code: handoffCode};+}++export async function redeemHandoff(+ ctx: ApiContext,+ deps: RegistrationDependencies,+ params: {+ handoffCode: string;+ nonce: string;+ consent: boolean | undefined;+ globalName: string | undefined;+ request: Request;+ requestCache: RequestCache;+ tierContext: TierContext;+ },+): Promise<{user: User; token: string; deviceProof: string; entry: GuildEntryResult | null}> {+ await assertAccountCreationPastSetup(+ ctx,+ deps.instanceConfigRepository,+ requireConfiguredClientIp(params.request, ctx.services.config.proxy),+ );+ assertRegistrationConsent(+ ctx.services.config,+ await deps.instanceConfigRepository.getAppPublicConfig(),+ params.consent,+ );+ if (params.globalName !== undefined) assertDisplayNameAllowed(params.globalName);+ const raw = await ctx.services.kv.getdel(handoffKey(params.handoffCode));+ const record = raw === null ? null : parseJsonWithGuard(raw, isHandoffRecord);+ if (!record) throw new UnknownAccountHandoffError();+ const expected = Buffer.from(record.nonce_hash, 'hex');+ const actual = Buffer.from(sha256Hex(params.nonce), 'hex');+ if (expected.length !== actual.length || !timingSafeEqual(expected, actual)) {+ throw new InvalidAccountHandoffNonceError();+ }+ let result: AccountCreationResult;+ try {+ result = await createAccount(ctx, deps, {+ input: {+ email: null,+ emailProven: false,+ globalName: params.globalName ?? record.global_name,+ consent: params.consent,+ locale: record.locale,+ registrationUrlCode: record.registration_url_code ?? null,+ },+ request: params.request,+ clientIp: record.client_ip,+ requestCache: params.requestCache,+ source: 'marketing',+ tierContext: params.tierContext,+ });+ } catch (error) {+ if (isRetryableBeforeCreation(error)) await restoreHandoff(ctx, params.handoffCode, record);+ throw error;+ }+ if (result.pendingApproval) throw new RegistrationClosedError();+ return {user: result.user, token: result.token, deviceProof: result.deviceProof, entry: result.entry};+}diff --git a/fluxer_api/src/api/auth/tests/CaptchaChallenge.test.ts b/fluxer_api/src/api/auth/tests/CaptchaChallenge.test.tsindex 7ee506d93..2c3afee26 100644--- a/fluxer_api/src/api/auth/tests/CaptchaChallenge.test.ts+++ b/fluxer_api/src/api/auth/tests/CaptchaChallenge.test.ts@@ -91,9 +91,9 @@ describe('Captcha challenge', () => {const updated = await createBuilder<{captcha: CaptchaConfigResponse}>(harness, admin.token).patch('/admin/instance/config')- .body({captcha: {enabled: false}})+ .body({captcha: {provider: 'none'}, auth: {instant_accounts: {enabled: false}}}).execute();- expect(updated.captcha).toEqual({enabled: false, cost: 1000, max_counter: 100});+ expect(updated.captcha).toEqual({provider: 'none', enabled: false, cost: 1000, max_counter: 100});await forgot(harness).expect(HTTP_STATUS.NO_CONTENT).execute();});diff --git a/fluxer_api/src/api/auth/tests/InstantAccounts.test.ts b/fluxer_api/src/api/auth/tests/InstantAccounts.test.tsnew file mode 100644index 000000000..652328e18--- /dev/null+++ b/fluxer_api/src/api/auth/tests/InstantAccounts.test.ts@@ -0,0 +1,333 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {createHash, randomBytes} from 'node:crypto';+import {enforceInstantAccountLimits} from '@app/api/auth/AccountBudgets';+import {createUserID} from '@app/api/BrandedTypes';+import {Config} from '@app/api/Config';+import {getKVClient} from '@app/api/middleware/ServiceRegistry';+import {+ getInstanceConfigRepository,+ getRateLimitService,+ getUserRepository,+} from '@app/api/middleware/ServiceSingletons';+import {RateLimitConfigs} from '@app/api/RateLimitConfig';+import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';+import {+ CAPTCHA_TEST_HEADER,+ type CaptchaErrorBody,+ solveCaptchaChallenge,+ useCheapCaptcha,+} from '@app/api/test/CaptchaTestUtils';+import {HTTP_STATUS} from '@app/api/test/TestConstants';+import {createBuilder, createBuilderWithoutAuth} from '@app/api/test/TestRequestBuilder';+import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';+import {SensitiveMediaFilterLevel} from '@fluxer/constants/src/UserConstants';+import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it} from 'vitest';++const MARKETING_KEY = 'marketing-test-key-0123456789abcdefghijkl';+const VISITOR_IP = '192.0.2.44';++interface RegisterBody {+ token: string;+ user_id: string;+}++function nonceWithHash(): {nonce: string; hash: string} {+ const nonce = randomBytes(32).toString('base64url');+ return {nonce, hash: createHash('sha256').update(nonce).digest('hex')};+}++describe('Username-only accounts', () => {+ let harness: ApiTestHarness;+ const originalTrustedCallers = Config.internal.trustedCallers;+ const originalRelax = Config.dev.relaxRegistrationRateLimits;+ beforeAll(async () => {+ harness = await createApiTestHarness();+ });+ beforeEach(async () => {+ await harness.reset();+ Config.internal.trustedCallers = [+ ...originalTrustedCallers,+ {+ name: 'marketing',+ key: MARKETING_KEY,+ buckets: [+ RateLimitConfigs.AUTH_REGISTER_HANDOFF.bucket,+ RateLimitConfigs.AUTH_REGISTER_HANDOFF_CHALLENGE.bucket,+ ],+ },+ ];+ });+ afterEach(() => {+ Config.internal.trustedCallers = originalTrustedCallers;+ Config.dev.relaxRegistrationRateLimits = originalRelax;+ });+ afterAll(async () => {+ await harness?.shutdown();+ });++ async function registerInstant(ip = VISITOR_IP): Promise<RegisterBody> {+ return await createBuilderWithoutAuth<RegisterBody>(harness)+ .post('/auth/register')+ .header('x-forwarded-for', ip)+ .body({global_name: 'Newcomer', consent: true})+ .execute();+ }++ function handoff(globalName: string, nonceHash: string, extra: Record<string, unknown> = {}) {+ return createBuilderWithoutAuth<{handoff_code: string}>(harness)+ .post('/auth/register/handoff')+ .header('x-fluxer-internal-key', MARKETING_KEY)+ .header('x-fluxer-client-ip', VISITOR_IP)+ .header('x-forwarded-for', '10.9.9.9')+ .body({global_name: globalName, nonce_hash: nonceHash, ...extra});+ }++ async function createRegistrationUrlCode(approvalRequired: boolean): Promise<string> {+ const {code} = await getInstanceConfigRepository().createRegistrationUrl({+ label: null,+ createdByUserId: '1',+ expiresAt: null,+ maxUses: null,+ approvalRequired,+ });+ return code;+ }++ async function fetchFeatures(): Promise<{instant_accounts: boolean; instant_account_availability?: string}> {+ const discovery = await createBuilderWithoutAuth<{+ features: {instant_accounts: boolean; instant_account_availability?: string};+ }>(harness)+ .get('/.well-known/fluxer')+ .execute();+ return discovery.features;+ }++ function redeem(handoffCode: string, nonce: string, extra: Record<string, unknown> = {consent: true}) {+ return createBuilderWithoutAuth<{token: string; user_id: string; device_proof: string}>(harness)+ .post('/auth/register/handoff/redeem')+ .body({handoff_code: handoffCode, nonce, ...extra});+ }++ async function expectConsentRefused(builder: ReturnType<typeof createBuilderWithoutAuth>) {+ const refused = await builder.expect(HTTP_STATUS.BAD_REQUEST, 'INVALID_FORM_BODY').executeWithResponse();+ expect(JSON.stringify(refused.json)).toContain('MUST_AGREE_TO_TOS_AND_PRIVACY_POLICY');+ }++ it('creates an unclaimed account that must enter a date of birth', async () => {+ const created = await registerInstant();+ const me = await createBuilder<{claimed: boolean; has_password: boolean; date_of_birth_required: boolean}>(+ harness,+ created.token,+ )+ .get('/users/@me')+ .execute();+ expect(me).toEqual(expect.objectContaining({claimed: false, has_password: false, date_of_birth_required: true}));+ const settings = await createBuilder<{sensitive_content_friend_dm_filter: number}>(harness, created.token)+ .get('/users/@me/settings')+ .execute();+ expect(settings.sensitive_content_friend_dm_filter).toBe(SensitiveMediaFilterLevel.BLUR);+ });++ it('refuses a username-only account without accepting the terms', async () => {+ for (const body of [{global_name: 'Newcomer'}, {global_name: 'Newcomer', consent: false}]) {+ await expectConsentRefused(createBuilderWithoutAuth(harness).post('/auth/register').body(body));+ }+ expect(await getUserRepository().findUsersByUsername('Newcomer')).toEqual([]);+ });++ it('refuses username-only accounts while the switch is off', async () => {+ await getInstanceConfigRepository().updateAuthConfig({instant_accounts: {enabled: false}});+ await createBuilderWithoutAuth(harness)+ .post('/auth/register')+ .body({global_name: 'Newcomer', consent: true})+ .expect(HTTP_STATUS.FORBIDDEN, APIErrorCodes.INSTANT_ACCOUNTS_DISABLED)+ .execute();+ });++ it('limits username-only accounts per network without the older three per hour rule', async () => {+ Config.dev.relaxRegistrationRateLimits = false;+ for (let index = 0; index < 5; index++) {+ await registerInstant();+ }+ await createBuilderWithoutAuth(harness)+ .post('/auth/register')+ .header('x-forwarded-for', VISITOR_IP)+ .body({global_name: 'Newcomer', consent: true})+ .expect(429)+ .execute();+ await registerInstant('192.0.2.99');+ });++ it('raises the captcha cost with every account from the same network', async () => {+ await useCheapCaptcha();+ const askChallenge = async () =>+ (+ await createBuilderWithoutAuth<CaptchaErrorBody>(harness)+ .post('/auth/register')+ .header('x-forwarded-for', VISITOR_IP)+ .header(CAPTCHA_TEST_HEADER, 'true')+ .body({global_name: 'Newcomer', consent: true})+ .expect(HTTP_STATUS.BAD_REQUEST, APIErrorCodes.CAPTCHA_REQUIRED)+ .executeWithResponse()+ ).json;+ const first = await askChallenge();+ const firstCost = (first.altcha_challenge!.parameters as {cost: number}).cost;+ const token = await solveCaptchaChallenge(first);+ await createBuilderWithoutAuth(harness)+ .post('/auth/register')+ .header('x-forwarded-for', VISITOR_IP)+ .header(CAPTCHA_TEST_HEADER, 'true')+ .header('x-captcha-token', token)+ .body({global_name: 'Newcomer', consent: true})+ .expect(HTTP_STATUS.OK)+ .execute();+ const second = await askChallenge();+ expect((second.altcha_challenge!.parameters as {cost: number}).cost).toBe(firstCost * 2);+ const cheapToken = await solveCaptchaChallenge(first);+ await createBuilderWithoutAuth(harness)+ .post('/auth/register')+ .header('x-forwarded-for', VISITOR_IP)+ .header(CAPTCHA_TEST_HEADER, 'true')+ .header('x-captcha-token', cheapToken)+ .body({global_name: 'Newcomer', consent: true})+ .expect(HTTP_STATUS.BAD_REQUEST, APIErrorCodes.INVALID_CAPTCHA)+ .execute();+ });++ it('creates the website account only when the browser redeems it with the terms accepted', async () => {+ const {nonce, hash} = nonceWithHash();+ const {handoff_code} = await handoff('Web Visitor', hash).execute();+ expect(handoff_code).toHaveLength(43);+ expect(await getUserRepository().findUsersByUsername('Web_Visitor')).toEqual([]);+ await expectConsentRefused(redeem(handoff_code, nonce, {}));+ await expectConsentRefused(redeem(handoff_code, nonce, {consent: false}));+ const redeemed = await redeem(handoff_code, nonce).execute();+ expect(redeemed.token).toBeTruthy();+ expect(redeemed.device_proof).toBeTruthy();+ const user = await getUserRepository().findUniqueAssert(createUserID(BigInt(redeemed.user_id)));+ expect(user.username).toBe('Web_Visitor');+ expect(user.globalName).toBe('Web Visitor');+ expect(user.lastActiveIp).toBe(VISITOR_IP);+ expect(user.termsAgreedAt).not.toBeNull();+ expect(user.privacyAgreedAt).not.toBeNull();+ await redeem(handoff_code, nonce).expect(HTTP_STATUS.BAD_REQUEST, APIErrorCodes.UNKNOWN_ACCOUNT_HANDOFF).execute();+ });++ it('starts every website account at the date of birth step', async () => {+ const {nonce, hash} = nonceWithHash();+ const {handoff_code} = await handoff('Web Visitor', hash).execute();+ const redeemed = await redeem(handoff_code, nonce, {consent: true}).execute();+ const me = await createBuilder<{date_of_birth_required: boolean}>(harness, redeemed.token)+ .get('/users/@me')+ .execute();+ expect(me.date_of_birth_required).toBe(true);+ });++ it('refuses a website handoff for a display name that is not allowed', async () => {+ const {hash} = nonceWithHash();+ for (const name of ['everyone', ' ']) {+ await handoff(name, hash).expect(HTTP_STATUS.BAD_REQUEST, 'INVALID_FORM_BODY').execute();+ }+ });++ it('keeps the code when the account cannot be made yet, and uses it up once it is', async () => {+ const {nonce, hash} = nonceWithHash();+ const {handoff_code} = await handoff('Web Visitor', hash).execute();+ Config.dev.relaxRegistrationRateLimits = false;+ const env = {kv: getKVClient(), rateLimit: getRateLimitService(), enforce: true};+ for (let attempt = 0; attempt < 5; attempt++) await enforceInstantAccountLimits(env, VISITOR_IP);+ await redeem(handoff_code, nonce).expect(429).execute();+ Config.dev.relaxRegistrationRateLimits = true;+ const redeemed = await redeem(handoff_code, nonce).execute();+ expect(redeemed.user_id).toBeDefined();+ await redeem(handoff_code, nonce).expect(HTTP_STATUS.BAD_REQUEST, APIErrorCodes.UNKNOWN_ACCOUNT_HANDOFF).execute();+ });++ it('uses up the code on a wrong nonce', async () => {+ const {nonce, hash} = nonceWithHash();+ const {handoff_code} = await handoff('Web Visitor', hash).execute();+ await redeem(handoff_code, nonceWithHash().nonce)+ .expect(HTTP_STATUS.BAD_REQUEST, APIErrorCodes.INVALID_ACCOUNT_HANDOFF_NONCE)+ .execute();+ await redeem(handoff_code, nonce).expect(HTTP_STATUS.BAD_REQUEST, APIErrorCodes.UNKNOWN_ACCOUNT_HANDOFF).execute();+ });++ it('refuses callers without the website key', async () => {+ const {hash} = nonceWithHash();+ await createBuilderWithoutAuth(harness)+ .post('/auth/register/handoff')+ .header('x-fluxer-client-ip', VISITOR_IP)+ .body({global_name: 'Web Visitor', nonce_hash: hash})+ .expect(HTTP_STATUS.FORBIDDEN, APIErrorCodes.MISSING_ACCESS)+ .execute();+ });++ it('lets a native app with no Origin header redeem the handoff on the hosted instance', async () => {+ expect(Config.instance.selfHosted).toBe(false);+ const {nonce, hash} = nonceWithHash();+ const {handoff_code} = await handoff('App Visitor', hash).execute();+ const redeemed = await createBuilderWithoutAuth<RegisterBody>(harness)+ .post('/auth/register/handoff/redeem')+ .body({handoff_code, nonce, consent: true})+ .execute();+ const user = await getUserRepository().findUniqueAssert(createUserID(BigInt(redeemed.user_id)));+ expect(user.globalName).toBe('App Visitor');+ await createBuilder(harness, redeemed.token).get('/users/@me').execute();+ });++ it('stops advertising instant accounts while sign-ups need approval', async () => {+ expect(await fetchFeatures()).toMatchObject({instant_accounts: true, instant_account_availability: 'available'});+ await getInstanceConfigRepository().setRegistrationConfig({mode: 'approval'});+ expect(await fetchFeatures()).toMatchObject({+ instant_accounts: false,+ instant_account_availability: 'approval_required',+ });+ await createBuilderWithoutAuth(harness)+ .post('/auth/register')+ .body({global_name: 'Newcomer', consent: true})+ .expect(HTTP_STATUS.BAD_REQUEST, APIErrorCodes.REGISTRATION_CREDENTIALS_REQUIRED)+ .execute();+ });++ it('reports the captcha being off as the reason instant accounts are unavailable', async () => {+ await getInstanceConfigRepository().updateCaptchaConfig({provider: 'none'});+ expect(await fetchFeatures()).toMatchObject({instant_accounts: false, instant_account_availability: 'captcha_off'});+ });++ it('lets a registration URL without approval admit instant accounts while sign-ups need approval', async () => {+ await getInstanceConfigRepository().setRegistrationConfig({mode: 'approval'});+ const code = await createRegistrationUrlCode(false);+ const created = await createBuilderWithoutAuth<RegisterBody>(harness)+ .post('/auth/register')+ .body({global_name: 'Invited', consent: true, registration_url_code: code})+ .execute();+ expect(created.token).toBeTruthy();+ });++ it('takes a registration URL without approval on the website handoff while sign-ups are closed', async () => {+ await getInstanceConfigRepository().setRegistrationConfig({mode: 'closed'});+ const {nonce, hash} = nonceWithHash();+ await handoff('Web Visitor', hash).expect(HTTP_STATUS.FORBIDDEN, APIErrorCodes.REGISTRATION_CLOSED).execute();+ const approvalCode = await createRegistrationUrlCode(true);+ await handoff('Web Visitor', hash, {registration_url_code: approvalCode})+ .expect(HTTP_STATUS.FORBIDDEN, APIErrorCodes.INSTANT_ACCOUNTS_DISABLED)+ .execute();+ const code = await createRegistrationUrlCode(false);+ const {handoff_code} = await handoff('Web Visitor', hash, {registration_url_code: code}).execute();+ const redeemed = await redeem(handoff_code, nonce).execute();+ const user = await getUserRepository().findUniqueAssert(createUserID(BigInt(redeemed.user_id)));+ expect(user.globalName).toBe('Web Visitor');+ });++ it('hands the website a challenge for the visitor', async () => {+ await useCheapCaptcha();+ const challenge = await createBuilderWithoutAuth<{captcha_provider: string}>(harness)+ .get('/auth/register/handoff/challenge')+ .header('x-fluxer-internal-key', MARKETING_KEY)+ .header('x-fluxer-client-ip', VISITOR_IP)+ .header(CAPTCHA_TEST_HEADER, 'true')+ .execute();+ expect(challenge.captcha_provider).toBe('altcha');+ });+});diff --git a/fluxer_api/src/api/middleware/CaptchaMiddleware.ts b/fluxer_api/src/api/middleware/CaptchaMiddleware.tsindex 7314fd29f..5662b6e91 100644--- a/fluxer_api/src/api/middleware/CaptchaMiddleware.ts+++ b/fluxer_api/src/api/middleware/CaptchaMiddleware.ts@@ -9,10 +9,11 @@ import {getKVClient} from '@app/api/middleware/ServiceRegistry';import type {User} from '@app/api/models/User';import type {HonoEnv} from '@app/api/types/HonoEnv';import {extractEmailDomain} from '@app/api/utils/EmailDomainUtils';+import {CaptchaProviders} from '@fluxer/constants/src/CaptchaConstants';import {Headers} from '@fluxer/constants/src/Headers';import {UserFlags} from '@fluxer/constants/src/UserConstants';import {CaptchaRequiredError, InvalidCaptchaError} from '@fluxer/errors/src/CaptchaErrors';-import type {CaptchaConfig} from '@fluxer/schema/src/domains/admin/CaptchaSchemas';+import {type CaptchaConfig, isCaptchaActive} from '@fluxer/schema/src/domains/admin/CaptchaSchemas';import {AltchaProvider} from '@pkgs/captcha/src/providers/AltchaProvider';import type {Context} from 'hono';import {createMiddleware} from 'hono/factory';@@ -36,25 +37,59 @@ function createAltchaProvider(config: CaptchaConfig): AltchaProvider {});}-async function altchaChallengeData(altcha: AltchaProvider): Promise<Record<string, unknown>> {- return {captcha_provider: 'altcha', altcha_challenge: await altcha.createChallenge()};+const MAX_CAPTCHA_ESCALATION_STEPS = 6;++async function altchaChallengeData(altcha: AltchaProvider, cost?: number): Promise<Record<string, unknown>> {+ return {captcha_provider: CaptchaProviders.ALTCHA, altcha_challenge: await altcha.createChallenge(cost)};+}++function isCaptchaBypassedForTest(ctx: Context<HonoEnv>): boolean {+ return Config.dev.testModeEnabled && ctx.req.header(TEST_ENABLE_CAPTCHA_HEADER) !== 'true';+}++function escalatedCaptchaCost(baseCost: number, steps: number): number {+ const boundedSteps = Math.min(Math.max(0, Math.floor(steps)), MAX_CAPTCHA_ESCALATION_STEPS);+ return baseCost * 2 ** boundedSteps;+}++export type CaptchaChallengeResponse =+ | {captcha_provider: typeof CaptchaProviders.NONE}+ | {+ captcha_provider: typeof CaptchaProviders.ALTCHA;+ altcha_challenge: Awaited<ReturnType<AltchaProvider['createChallenge']>>;+ };++export async function createCaptchaChallenge(+ ctx: Context<HonoEnv>,+ escalationSteps = 0,+): Promise<CaptchaChallengeResponse> {+ if (isCaptchaBypassedForTest(ctx)) return {captcha_provider: CaptchaProviders.NONE};+ const config = await ctx.get('instanceConfigRepository').getCaptchaConfig();+ if (!isCaptchaActive(config)) return {captcha_provider: CaptchaProviders.NONE};+ return {+ captcha_provider: CaptchaProviders.ALTCHA,+ altcha_challenge: await createAltchaProvider(config).createChallenge(+ escalatedCaptchaCost(config.cost, escalationSteps),+ ),+ };}-export async function verifyCaptchaToken(ctx: Context<HonoEnv>): Promise<boolean> {- if (Config.dev.testModeEnabled && ctx.req.header(TEST_ENABLE_CAPTCHA_HEADER) !== 'true') return false;+export async function verifyCaptchaToken(ctx: Context<HonoEnv>, escalationSteps = 0): Promise<boolean> {+ if (isCaptchaBypassedForTest(ctx)) return false;const config = await ctx.get('instanceConfigRepository').getCaptchaConfig();- if (!config.enabled) return false;+ if (!isCaptchaActive(config)) return false;const user = ctx.get('user') as User | undefined;if (sharedListHas('email_domain_exempt', extractEmailDomain(user?.email))) return false;if (userHasCaptchaExemptFlag(user)) return false;if (await requestUserHasCaptchaExemptFlag(ctx)) return false;const altcha = createAltchaProvider(config);+ const cost = escalatedCaptchaCost(config.cost, escalationSteps);const token = ctx.req.header(Headers.X_CAPTCHA_TOKEN);if (!token) {- throw new CaptchaRequiredError(await altchaChallengeData(altcha));+ throw new CaptchaRequiredError(await altchaChallengeData(altcha, cost));}- if (!(await altcha.verify({token}))) {- throw new InvalidCaptchaError(await altchaChallengeData(altcha));+ if (!(await altcha.verify({token, minCost: cost}))) {+ throw new InvalidCaptchaError(await altchaChallengeData(altcha, cost));}return true;}@@ -81,3 +116,10 @@ export const CaptchaMiddleware = createMiddleware<HonoEnv>(async (ctx, next) =>ctx.set('captchaVerified', await verifyCaptchaToken(ctx));await next();});++export function EscalatingCaptchaMiddleware(resolveSteps: (ctx: Context<HonoEnv>) => Promise<number>) {+ return createMiddleware<HonoEnv>(async (ctx, next) => {+ ctx.set('captchaVerified', await verifyCaptchaToken(ctx, await resolveSteps(ctx)));+ await next();+ });+}diff --git a/fluxer_api/src/api/middleware/tests/CaptchaMiddleware.test.ts b/fluxer_api/src/api/middleware/tests/CaptchaMiddleware.test.tsindex 66f06f9ea..6db2ae9ba 100644--- a/fluxer_api/src/api/middleware/tests/CaptchaMiddleware.test.ts+++ b/fluxer_api/src/api/middleware/tests/CaptchaMiddleware.test.ts@@ -1,10 +1,10 @@// SPDX-License-Identifier: AGPL-3.0-or-laterimport {Config} from '@app/api/Config';-import type {InstanceConfigRepository} from '@app/api/instance/InstanceConfigRepository';import {CaptchaMiddleware} from '@app/api/middleware/CaptchaMiddleware';import {CAPTCHA_TEST_HEADER} from '@app/api/test/CaptchaTestUtils';import type {HonoEnv} from '@app/api/types/HonoEnv';+import {CaptchaProviders} from '@fluxer/constants/src/CaptchaConstants';import {AppErrorHandler} from '@fluxer/errors/src/domains/core/ErrorHandlers';import {type CaptchaConfig, DEFAULT_CAPTCHA_CONFIG} from '@fluxer/schema/src/domains/admin/CaptchaSchemas';import {Hono} from 'hono';@@ -40,7 +40,7 @@ describe('CaptchaMiddleware', () => {});it('passes every request while the captcha is disabled', async () => {- const response = await createHarness({...CHEAP_CAPTCHA_CONFIG, enabled: false})({});+ const response = await createHarness({...CHEAP_CAPTCHA_CONFIG, provider: CaptchaProviders.NONE})({});expect(response.status).toBe(200);});