Skip to content

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

TypeScript fluxerfluxerapp
12.1 KB
Raw Blame
// SPDX-License-Identifier: AGPL-3.0-or-later

import crypto from 'node:crypto';
import type {ApiContext} from '@app/api/ApiContext';
import {createMfaTicketResponse, type LoginMfaResult} from '@app/api/auth/AuthLogin';
import * as AuthSession from '@app/api/auth/AuthSession';
import {revokeAllAuthSessions} from '@app/api/auth/AuthSessionRevocation';
import * as AuthUtility from '@app/api/auth/AuthUtility';
import {RecoveryKitRepository} from '@app/api/auth/services/RecoveryKitRepository';
import {resolveWebAuthnSecondFactor} from '@app/api/auth/services/WebAuthnSecondFactor';
import {createPasswordResetToken} from '@app/api/BrandedTypes';
import {Config} from '@app/api/Config';
import {getContentMessage} from '@app/api/content_i18n/ContentI18n';
import type {UserRow} from '@app/api/database/types/UserTypes';
import {Logger} from '@app/api/Logger';
import {getKVClient} from '@app/api/middleware/ServiceRegistry';
import type {User} from '@app/api/models/User';
import {PASSWORD_RESET_TOKEN_TTL_SECONDS} from '@app/api/user/repositories/auth/TokenRepository';
import {EXTERNAL_RESPONSE_LIMITS} from '@app/api/utils/ExternalResponseLimits';
import * as FetchUtils from '@app/api/utils/FetchUtils';
import {lookupGeoip} from '@app/api/utils/IpUtils';
import {hashPassword} from '@app/api/utils/PasswordUtils';
import * as RandomUtils from '@app/api/utils/RandomUtils';
import {createRateLimitError} from '@app/api/utils/RateLimitUtils';
import {requireConfiguredClientIp} from '@app/api/utils/RequestClientIp';
import {FLUXER_USER_AGENT} from '@fluxer/constants/src/Core';
import {UserAuthenticatorTypes, UserFlags} from '@fluxer/constants/src/UserConstants';
import {ValidationErrorCodes} from '@fluxer/constants/src/ValidationErrorCodes';
import {InputValidationError} from '@fluxer/errors/src/domains/core/InputValidationError';
import {getSameIpDecisionKey} from '@fluxer/ip_utils/src/IpAddress';
import type {ForgotPasswordRequest, ResetPasswordRequest} from '@fluxer/schema/src/domains/auth/AuthSchemas';
import {formatGeoipLocation} from '@pkgs/geoip/src/GeoipLookup';
import {ms} from 'itty-time';

const PWNED_PASSWORDS_TIMEOUT_MS = ms('5 seconds');
const PWNED_PASSWORD_CACHE_MAX_PREFIXES = 128;
const PASSWORD_RESET_CLAIM_KEY_PREFIX = 'auth:password-reset:claimed:';

interface CacheEntry {
	pwnedSuffixes: ReadonlySet<string>;
	expiresAt: number;
}

class PwnedPasswordCache {
	private cache = new Map<string, CacheEntry>();
	private readonly maxSize: number;
	private readonly ttlMs: number;

	constructor(maxSize: number, ttlMs: number) {
		this.maxSize = maxSize;
		this.ttlMs = ttlMs;
	}

	get(hashPrefix: string): ReadonlySet<string> | undefined {
		const entry = this.cache.get(hashPrefix);
		if (!entry) {
			return undefined;
		}
		if (Date.now() > entry.expiresAt) {
			this.cache.delete(hashPrefix);
			return undefined;
		}
		this.cache.delete(hashPrefix);
		this.cache.set(hashPrefix, entry);
		return entry.pwnedSuffixes;
	}

	set(hashPrefix: string, pwnedSuffixes: ReadonlySet<string>): void {
		if (this.cache.size >= this.maxSize && !this.cache.has(hashPrefix)) {
			const firstKey = this.cache.keys().next().value;
			if (firstKey !== undefined) {
				this.cache.delete(firstKey);
			}
		}
		this.cache.set(hashPrefix, {
			pwnedSuffixes,
			expiresAt: Date.now() + this.ttlMs,
		});
	}

	clear(): void {
		this.cache.clear();
	}
}

interface ForgotPasswordParams {
	data: ForgotPasswordRequest;
	request: Request;
}

interface ResetPasswordParams {
	data: ResetPasswordRequest;
	request: Request;
}

interface ApplyPasswordResetParams {
	user: User;
	password: string;
	request: Request;
	afterPasswordSet?: () => Promise<void>;
	onPasswordWritten?: () => void;
}

interface CommitPasswordResetParams {
	user: User;
	passwordHash: string;
	webauthnIsSecondFactor: boolean;
	onPasswordWritten?: () => void;
}

type ResetPasswordResult =
	| {
			user_id: string;
			token: string;
	  }
	| LoginMfaResult;

const pwnedPasswordCache = new PwnedPasswordCache(PWNED_PASSWORD_CACHE_MAX_PREFIXES, ms('1 hour'));

export function resetPwnedPasswordCacheForTesting(): void {
	pwnedPasswordCache.clear();
}

export async function isPasswordPwned(_ctx: ApiContext, password: string): Promise<boolean> {
	if (!Config.breachedPasswordCheck.enabled) {
		return false;
	}
	const hashed = crypto.createHash('sha1').update(password).digest('hex').toUpperCase();
	const hashPrefix = hashed.slice(0, 5);
	const hashSuffix = hashed.slice(5);
	const cachedSuffixes = pwnedPasswordCache.get(hashPrefix);
	if (cachedSuffixes !== undefined) {
		return cachedSuffixes.has(hashSuffix);
	}
	try {
		const response = await fetch(`https://api.pwnedpasswords.com/range/${hashPrefix}`, {
			headers: {
				'User-Agent': FLUXER_USER_AGENT,
				'Add-Padding': 'true',
			},
			signal: AbortSignal.timeout(PWNED_PASSWORDS_TIMEOUT_MS),
		});
		if (!response.ok) {
			FetchUtils.discardResponseBody(response.body, response.status);
			Logger.warn(
				{
					status: response.status,
					statusText: response.statusText,
					hashPrefix,
				},
				'Pwned Passwords API returned non-OK status',
			);
			return false;
		}
		const body = await FetchUtils.streamToStringWithLimit(response.body, {
			maxBytes: EXTERNAL_RESPONSE_LIMITS.pwnedPasswordsBytes,
			headers: response.headers,
			url: response.url,
			description: 'Pwned Passwords API response',
		});
		const MAX_PWNED_LINES = 10000;
		const lines = body.split('\n');
		if (lines.length > MAX_PWNED_LINES) {
			Logger.warn(
				{
					lineCount: lines.length,
					maxAllowed: MAX_PWNED_LINES,
					hashPrefix,
				},
				'Pwned Passwords API response exceeded safe line limit, truncating',
			);
		}
		const limit = Math.min(lines.length, MAX_PWNED_LINES);
		const pwnedSuffixes = new Set<string>();
		for (let i = 0; i < limit; i++) {
			const line = lines[i];
			const [hashSuffixLine, count] = line.split(':', 2);
			if (hashSuffixLine.length === hashSuffix.length && Number.parseInt(count, 10) > 0) {
				pwnedSuffixes.add(hashSuffixLine);
			}
		}
		pwnedPasswordCache.set(hashPrefix, pwnedSuffixes);
		return pwnedSuffixes.has(hashSuffix);
	} catch (error) {
		Logger.error({error}, 'Failed to check password against Pwned Passwords API');
		return false;
	}
}

export async function forgotPassword(ctx: ApiContext, {data, request}: ForgotPasswordParams): Promise<void> {
	const {users, email, rateLimit, emailDnsValidation, config} = ctx.services;
	const clientIp = requireConfiguredClientIp(request, config.proxy);
	const ipRateLimit = await rateLimit.checkLimit({
		identifier: `password_reset:ip:${getSameIpDecisionKey(clientIp) ?? clientIp}`,
		maxAttempts: 20,
		windowMs: ms('30 minutes'),
	});
	const emailRateLimit = await rateLimit.checkLimit({
		identifier: `password_reset:email:${data.email.toLowerCase()}`,
		maxAttempts: 5,
		windowMs: ms('30 minutes'),
	});
	if (!ipRateLimit.allowed) {
		throw createRateLimitError(ipRateLimit);
	}
	if (!emailRateLimit.allowed) {
		throw createRateLimitError(emailRateLimit);
	}
	const hasValidDns = await emailDnsValidation.hasValidDnsRecords(data.email);
	if (!hasValidDns) {
		throw InputValidationError.fromCode('email', ValidationErrorCodes.EMAIL_DOMAIN_CANNOT_RECEIVE_MAIL);
	}
	const user = await users.findByEmail(data.email);
	if (!user) {
		return;
	}
	AuthUtility.assertNonBotUser(ctx, user);
	const token = createPasswordResetToken(await RandomUtils.randomString(64));
	await users.createPasswordResetToken({
		token_: token,
		user_id: user.id,
		email: user.email!,
	});
	const location =
		formatGeoipLocation(await lookupGeoip(clientIp), user.locale) ??
		getContentMessage('auth.unknown_location', user.locale);
	await email.send('password_reset', user.email!, {resetToken: token, ipAddress: clientIp, location}, user.locale);
}

function resetTokenMatchesUser(user: User, tokenEmail: string | null): boolean {
	if (tokenEmail === null) return !user.email;
	return !!user.email && user.email.trim().toLowerCase() === tokenEmail.trim().toLowerCase();
}

export async function validateResetToken(ctx: ApiContext, token: string): Promise<boolean> {
	const {users} = ctx.services;
	const tokenData = await users.getPasswordResetToken(token);
	if (!tokenData) {
		return false;
	}
	const user = await users.findUnique(tokenData.userId);
	if (!user) {
		return false;
	}
	if (user.flags & UserFlags.DELETED || !resetTokenMatchesUser(user, tokenData.email)) {
		return false;
	}
	return true;
}

function passwordResetClaimKey(token: string): string {
	return `${PASSWORD_RESET_CLAIM_KEY_PREFIX}${crypto.createHash('sha256').update(token).digest('hex')}`;
}

function claimPasswordResetToken(token: string): Promise<boolean> {
	return getKVClient().setnx(passwordResetClaimKey(token), '1', PASSWORD_RESET_TOKEN_TTL_SECONDS);
}

async function releasePasswordResetTokenClaim(token: string): Promise<void> {
	try {
		await getKVClient().del(passwordResetClaimKey(token));
	} catch (error) {
		Logger.error({error}, 'Could not release the claim of a password reset token whose reset failed');
	}
}

export async function resetPassword(
	ctx: ApiContext,
	{data, request}: ResetPasswordParams,
): Promise<ResetPasswordResult> {
	const {users} = ctx.services;
	const tokenData = await users.getPasswordResetToken(data.token);
	if (!tokenData) {
		throw InputValidationError.fromCode('token', ValidationErrorCodes.INVALID_OR_EXPIRED_RESET_TOKEN);
	}
	const user = await users.findUnique(tokenData.userId);
	if (!user) {
		throw InputValidationError.fromCode('token', ValidationErrorCodes.INVALID_OR_EXPIRED_RESET_TOKEN);
	}
	AuthUtility.assertNonBotUser(ctx, user);
	if (user.flags & UserFlags.DELETED || !resetTokenMatchesUser(user, tokenData.email)) {
		throw InputValidationError.fromCode('token', ValidationErrorCodes.INVALID_OR_EXPIRED_RESET_TOKEN);
	}
	const currentUser = await AuthUtility.assertSignInAllowed(ctx, user);
	if (await isPasswordPwned(ctx, data.password)) {
		throw InputValidationError.fromCode('password', ValidationErrorCodes.PASSWORD_IS_TOO_COMMON);
	}
	if (!(await claimPasswordResetToken(data.token))) {
		throw InputValidationError.fromCode('token', ValidationErrorCodes.INVALID_OR_EXPIRED_RESET_TOKEN);
	}
	let passwordWritten = false;
	const onPasswordWritten = () => {
		passwordWritten = true;
	};
	try {
		return await applyPasswordReset(ctx, {
			user: currentUser,
			password: data.password,
			request,
			afterPasswordSet: async () => {
				await users.deleteAllPasswordResetTokens(currentUser.id);
				await new RecoveryKitRepository().delete(currentUser.id);
			},
			onPasswordWritten,
		});
	} catch (error) {
		if (!passwordWritten) await releasePasswordResetTokenClaim(data.token);
		throw error;
	}
}

export async function commitPasswordReset(
	ctx: ApiContext,
	{user, passwordHash, webauthnIsSecondFactor, onPasswordWritten}: CommitPasswordResetParams,
): Promise<User> {
	const {users} = ctx.services;
	const updates: Partial<UserRow> = {
		password_hash: passwordHash,
		password_last_changed_at: new Date(),
	};
	if (webauthnIsSecondFactor && !user.authenticatorTypes.has(UserAuthenticatorTypes.WEBAUTHN)) {
		const authenticatorTypes = new Set<number>(user.authenticatorTypes);
		authenticatorTypes.add(UserAuthenticatorTypes.WEBAUTHN);
		updates.authenticator_types = authenticatorTypes;
	}
	const updatedUser = await users.patchUpsert(user.id, updates, user.toRow());
	onPasswordWritten?.();
	if (updates.authenticator_types) {
		await ctx.services.botMfaMirror.syncAuthenticatorTypesForOwner(updatedUser);
	}
	await revokeAllAuthSessions(ctx.services, user.id);
	return updatedUser;
}

export async function applyPasswordReset(
	ctx: ApiContext,
	{user, password, request, afterPasswordSet, onPasswordWritten}: ApplyPasswordResetParams,
): Promise<ResetPasswordResult> {
	const webauthnIsSecondFactor = await resolveWebAuthnSecondFactor(ctx, user);
	const hasMfa = user.authenticatorTypes.has(UserAuthenticatorTypes.TOTP) || webauthnIsSecondFactor;
	const passwordHash = await hashPassword(password);
	const updatedUser = await commitPasswordReset(ctx, {user, passwordHash, webauthnIsSecondFactor, onPasswordWritten});
	await afterPasswordSet?.();
	if (hasMfa) {
		return await createMfaTicketResponse(ctx, updatedUser, webauthnIsSecondFactor);
	}
	const [token] = await AuthSession.createAuthSession(ctx, {
		user: updatedUser,
		origin: AuthSession.resolveSessionOrigin(ctx, request),
	});
	return {user_id: updatedUser.id.toString(), token};
}