Add Optional 2FA Support (#61)
* Add TOTP MFA Support * Add Passkey MFA Support It's not impossible I missed some minor cleanup, but most things make sense and there isn't a lot of obvious duplication anymore. --------- Co-authored-by: Bruno Bernardino <me@brunobernardino.com>
This commit is contained in:
119
routes/api/auth/multi-factor/disable.ts
Normal file
119
routes/api/auth/multi-factor/disable.ts
Normal file
@@ -0,0 +1,119 @@
|
||||
import { Handlers } from 'fresh/server.ts';
|
||||
|
||||
import { FreshContextState } from '/lib/types.ts';
|
||||
import { PASSWORD_SALT } from '/lib/auth.ts';
|
||||
import { generateHash } from '/lib/utils/misc.ts';
|
||||
import { UserModel } from '/lib/models/user.ts';
|
||||
import {
|
||||
getMultiFactorAuthMethodByIdFromUser,
|
||||
getMultiFactorAuthMethodsFromUser,
|
||||
} from '/lib/utils/multi-factor-auth.ts';
|
||||
import { AppConfig } from '/lib/config.ts';
|
||||
import { MultiFactorAuthModel } from '/lib/models/multi-factor-auth.ts';
|
||||
|
||||
export interface RequestBody {
|
||||
methodId?: string;
|
||||
password: string;
|
||||
disableAll?: boolean;
|
||||
}
|
||||
|
||||
export interface ResponseBody {
|
||||
success: boolean;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export const handler: Handlers<unknown, FreshContextState> = {
|
||||
async POST(request, context) {
|
||||
if (!context.state.user) {
|
||||
return new Response('Unauthorized', { status: 401 });
|
||||
}
|
||||
|
||||
const isMultiFactorAuthEnabled = await AppConfig.isMultiFactorAuthEnabled();
|
||||
|
||||
if (!isMultiFactorAuthEnabled) {
|
||||
const responseBody: ResponseBody = {
|
||||
success: false,
|
||||
error: 'Multi-factor authentication is not enabled on this server',
|
||||
};
|
||||
|
||||
return new Response(JSON.stringify(responseBody), { status: 403 });
|
||||
}
|
||||
|
||||
const { user } = context.state;
|
||||
|
||||
const body = await request.clone().json() as RequestBody;
|
||||
const { methodId, password, disableAll } = body;
|
||||
|
||||
if (!password) {
|
||||
const responseBody: ResponseBody = {
|
||||
success: false,
|
||||
error: 'Password is required',
|
||||
};
|
||||
|
||||
return new Response(JSON.stringify(responseBody), { status: 400 });
|
||||
}
|
||||
|
||||
const hashedPassword = await generateHash(`${password}:${PASSWORD_SALT}`, 'SHA-256');
|
||||
|
||||
if (user.hashed_password !== hashedPassword) {
|
||||
const responseBody: ResponseBody = {
|
||||
success: false,
|
||||
error: 'Invalid password',
|
||||
};
|
||||
|
||||
return new Response(JSON.stringify(responseBody), { status: 400 });
|
||||
}
|
||||
|
||||
if (disableAll) {
|
||||
user.extra.multi_factor_auth_methods = [];
|
||||
|
||||
await UserModel.update(user);
|
||||
|
||||
const responseBody: ResponseBody = {
|
||||
success: true,
|
||||
};
|
||||
|
||||
return new Response(JSON.stringify(responseBody));
|
||||
}
|
||||
|
||||
if (!methodId) {
|
||||
const responseBody: ResponseBody = {
|
||||
success: false,
|
||||
error: 'Method ID is required when not disabling all methods',
|
||||
};
|
||||
|
||||
return new Response(JSON.stringify(responseBody), { status: 400 });
|
||||
}
|
||||
|
||||
const methods = getMultiFactorAuthMethodsFromUser(user);
|
||||
const method = getMultiFactorAuthMethodByIdFromUser(user, methodId);
|
||||
|
||||
if (!method) {
|
||||
const responseBody: ResponseBody = {
|
||||
success: false,
|
||||
error: 'Multi-factor authentication method not found',
|
||||
};
|
||||
|
||||
return new Response(JSON.stringify(responseBody), { status: 404 });
|
||||
}
|
||||
|
||||
if (!method.enabled) {
|
||||
const responseBody: ResponseBody = {
|
||||
success: false,
|
||||
error: 'Multi-factor authentication method is not enabled',
|
||||
};
|
||||
|
||||
return new Response(JSON.stringify(responseBody), { status: 400 });
|
||||
}
|
||||
|
||||
MultiFactorAuthModel.disableMethodFromUser(user, methodId);
|
||||
|
||||
await UserModel.update(user);
|
||||
|
||||
const responseBody: ResponseBody = {
|
||||
success: true,
|
||||
};
|
||||
|
||||
return new Response(JSON.stringify(responseBody));
|
||||
},
|
||||
};
|
||||
130
routes/api/auth/multi-factor/enable.ts
Normal file
130
routes/api/auth/multi-factor/enable.ts
Normal file
@@ -0,0 +1,130 @@
|
||||
import { Handlers } from 'fresh/server.ts';
|
||||
|
||||
import { FreshContextState } from '/lib/types.ts';
|
||||
import { MultiFactorAuthModel } from '/lib/models/multi-factor-auth.ts';
|
||||
import { TOTPModel } from '/lib/models/multi-factor-auth/totp.ts';
|
||||
import { getMultiFactorAuthMethodByIdFromUser } from '/lib/utils/multi-factor-auth.ts';
|
||||
import { UserModel } from '/lib/models/user.ts';
|
||||
import { AppConfig } from '/lib/config.ts';
|
||||
|
||||
export interface RequestBody {
|
||||
methodId: string;
|
||||
code: string | 'passkey-verified';
|
||||
}
|
||||
|
||||
export interface ResponseBody {
|
||||
success: boolean;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export const handler: Handlers<unknown, FreshContextState> = {
|
||||
async POST(request, context) {
|
||||
if (!context.state.user) {
|
||||
return new Response('Unauthorized', { status: 401 });
|
||||
}
|
||||
|
||||
const isMultiFactorAuthEnabled = await AppConfig.isMultiFactorAuthEnabled();
|
||||
|
||||
if (!isMultiFactorAuthEnabled) {
|
||||
const responseBody: ResponseBody = {
|
||||
success: false,
|
||||
error: 'Multi-factor authentication is not enabled on this server',
|
||||
};
|
||||
|
||||
return new Response(JSON.stringify(responseBody), { status: 403 });
|
||||
}
|
||||
|
||||
const { user } = context.state;
|
||||
|
||||
const body = await request.clone().json() as RequestBody;
|
||||
const { methodId, code } = body;
|
||||
|
||||
if (!methodId || !code) {
|
||||
const responseBody: ResponseBody = {
|
||||
success: false,
|
||||
error: 'Method ID and verification code are required',
|
||||
};
|
||||
|
||||
return new Response(JSON.stringify(responseBody), { status: 400 });
|
||||
}
|
||||
|
||||
const method = getMultiFactorAuthMethodByIdFromUser(user, methodId);
|
||||
if (!method) {
|
||||
const responseBody: ResponseBody = {
|
||||
success: false,
|
||||
error: 'Multi-factor authentication method not found',
|
||||
};
|
||||
|
||||
return new Response(JSON.stringify(responseBody), { status: 404 });
|
||||
}
|
||||
|
||||
if (method.enabled) {
|
||||
const responseBody: ResponseBody = {
|
||||
success: false,
|
||||
error: 'Multi-factor authentication method is already enabled',
|
||||
};
|
||||
|
||||
return new Response(JSON.stringify(responseBody), { status: 400 });
|
||||
}
|
||||
|
||||
if (method.type === 'totp') {
|
||||
const hashedSecret = method.metadata.totp?.hashed_secret;
|
||||
if (!hashedSecret) {
|
||||
const responseBody: ResponseBody = {
|
||||
success: false,
|
||||
error: 'TOTP secret not found',
|
||||
};
|
||||
|
||||
return new Response(JSON.stringify(responseBody), { status: 400 });
|
||||
}
|
||||
|
||||
try {
|
||||
const secret = await TOTPModel.decryptTOTPSecret(hashedSecret);
|
||||
const isValid = TOTPModel.verifyTOTP(secret, code);
|
||||
if (!isValid) {
|
||||
const responseBody: ResponseBody = {
|
||||
success: false,
|
||||
error: 'Invalid verification code',
|
||||
};
|
||||
|
||||
return new Response(JSON.stringify(responseBody), { status: 400 });
|
||||
}
|
||||
} catch {
|
||||
const responseBody: ResponseBody = {
|
||||
success: false,
|
||||
error: 'Failed to decrypt TOTP secret',
|
||||
};
|
||||
|
||||
return new Response(JSON.stringify(responseBody), { status: 500 });
|
||||
}
|
||||
} else if (method.type === 'passkey') {
|
||||
if (code !== 'passkey-verified') {
|
||||
const responseBody: ResponseBody = {
|
||||
success: false,
|
||||
error: 'Passkey not properly verified',
|
||||
};
|
||||
|
||||
return new Response(JSON.stringify(responseBody), { status: 400 });
|
||||
}
|
||||
|
||||
if (!method.metadata.passkey?.credential_id || !method.metadata.passkey?.public_key) {
|
||||
const responseBody: ResponseBody = {
|
||||
success: false,
|
||||
error: 'Passkey credentials not found',
|
||||
};
|
||||
|
||||
return new Response(JSON.stringify(responseBody), { status: 400 });
|
||||
}
|
||||
}
|
||||
|
||||
MultiFactorAuthModel.enableMethodForUser(user, methodId);
|
||||
|
||||
await UserModel.update(user);
|
||||
|
||||
const responseBody: ResponseBody = {
|
||||
success: true,
|
||||
};
|
||||
|
||||
return new Response(JSON.stringify(responseBody));
|
||||
},
|
||||
};
|
||||
87
routes/api/auth/multi-factor/passkey/begin.ts
Normal file
87
routes/api/auth/multi-factor/passkey/begin.ts
Normal file
@@ -0,0 +1,87 @@
|
||||
import { Handlers } from 'fresh/server.ts';
|
||||
import { PublicKeyCredentialCreationOptionsJSON } from '@simplewebauthn/server';
|
||||
|
||||
import { FreshContextState } from '/lib/types.ts';
|
||||
import { PasskeyModel } from '/lib/models/multi-factor-auth/passkey.ts';
|
||||
import { UserModel } from '/lib/models/user.ts';
|
||||
import { AppConfig } from '/lib/config.ts';
|
||||
|
||||
export interface RequestBody {
|
||||
email: string;
|
||||
}
|
||||
|
||||
export interface ResponseBody {
|
||||
success: boolean;
|
||||
error?: string;
|
||||
options?: PublicKeyCredentialCreationOptionsJSON;
|
||||
sessionData?: {
|
||||
challenge: string;
|
||||
methodId: string;
|
||||
};
|
||||
}
|
||||
|
||||
export const handler: Handlers<unknown, FreshContextState> = {
|
||||
async POST(request) {
|
||||
const isMultiFactorAuthEnabled = await AppConfig.isMultiFactorAuthEnabled();
|
||||
|
||||
if (!isMultiFactorAuthEnabled) {
|
||||
const responseBody: ResponseBody = {
|
||||
success: false,
|
||||
error: 'Passwordless passkey login requires multi-factor authentication to be enabled.',
|
||||
};
|
||||
|
||||
return new Response(JSON.stringify(responseBody), { status: 403 });
|
||||
}
|
||||
|
||||
const body = await request.clone().json() as RequestBody;
|
||||
const { email } = body;
|
||||
|
||||
if (!email) {
|
||||
const responseBody: ResponseBody = {
|
||||
success: false,
|
||||
error: 'Email is required',
|
||||
};
|
||||
|
||||
return new Response(JSON.stringify(responseBody), { status: 400 });
|
||||
}
|
||||
|
||||
const user = await UserModel.getByEmail(email);
|
||||
|
||||
if (!user) {
|
||||
const responseBody: ResponseBody = {
|
||||
success: false,
|
||||
error: 'User not found',
|
||||
};
|
||||
|
||||
return new Response(JSON.stringify(responseBody), { status: 404 });
|
||||
}
|
||||
|
||||
const config = await AppConfig.getConfig();
|
||||
const allowedCredentials = PasskeyModel.getCredentialsFromUser(user);
|
||||
|
||||
if (allowedCredentials.length === 0) {
|
||||
const responseBody: ResponseBody = {
|
||||
success: false,
|
||||
error: 'No passkeys registered for this user',
|
||||
};
|
||||
|
||||
return new Response(JSON.stringify(responseBody), { status: 400 });
|
||||
}
|
||||
|
||||
const options = await PasskeyModel.generateAuthenticationOptions(
|
||||
config.auth.baseUrl,
|
||||
allowedCredentials,
|
||||
);
|
||||
|
||||
const responseBody: ResponseBody = {
|
||||
success: true,
|
||||
options,
|
||||
sessionData: {
|
||||
challenge: options.challenge,
|
||||
methodId: options.challenge,
|
||||
},
|
||||
};
|
||||
|
||||
return new Response(JSON.stringify(responseBody));
|
||||
},
|
||||
};
|
||||
67
routes/api/auth/multi-factor/passkey/setup-begin.ts
Normal file
67
routes/api/auth/multi-factor/passkey/setup-begin.ts
Normal file
@@ -0,0 +1,67 @@
|
||||
import { Handlers } from 'fresh/server.ts';
|
||||
import { PublicKeyCredentialCreationOptionsJSON } from '@simplewebauthn/server';
|
||||
|
||||
import { FreshContextState } from '/lib/types.ts';
|
||||
import { AppConfig } from '/lib/config.ts';
|
||||
import { PasskeyModel } from '/lib/models/multi-factor-auth/passkey.ts';
|
||||
import { MultiFactorAuthModel } from '/lib/models/multi-factor-auth.ts';
|
||||
|
||||
export interface RequestBody {}
|
||||
|
||||
export interface ResponseBody {
|
||||
success: boolean;
|
||||
error?: string;
|
||||
options?: PublicKeyCredentialCreationOptionsJSON;
|
||||
sessionData?: {
|
||||
challenge: string;
|
||||
methodId: string;
|
||||
userId: string;
|
||||
};
|
||||
}
|
||||
|
||||
export const handler: Handlers<unknown, FreshContextState> = {
|
||||
async POST(request, context) {
|
||||
if (!context.state.user) {
|
||||
return new Response('Unauthorized', { status: 401 });
|
||||
}
|
||||
|
||||
const isMultiFactorAuthEnabled = await AppConfig.isMultiFactorAuthEnabled();
|
||||
|
||||
if (!isMultiFactorAuthEnabled) {
|
||||
const responseBody: ResponseBody = {
|
||||
success: false,
|
||||
error: 'Passwordless passkey login requires multi-factor authentication to be enabled.',
|
||||
};
|
||||
|
||||
return new Response(JSON.stringify(responseBody), { status: 403 });
|
||||
}
|
||||
|
||||
const { user } = context.state;
|
||||
|
||||
const methodId = MultiFactorAuthModel.generateMethodId();
|
||||
|
||||
const config = await AppConfig.getConfig();
|
||||
const existingCredentials = PasskeyModel.getCredentialsFromUser(user);
|
||||
|
||||
const options = await PasskeyModel.generateRegistrationOptions(
|
||||
user.id,
|
||||
user.email,
|
||||
config.auth.baseUrl,
|
||||
existingCredentials,
|
||||
);
|
||||
|
||||
const sessionData: ResponseBody['sessionData'] = {
|
||||
challenge: options.challenge,
|
||||
methodId,
|
||||
userId: user.id,
|
||||
};
|
||||
|
||||
const responseBody: ResponseBody = {
|
||||
success: true,
|
||||
options,
|
||||
sessionData,
|
||||
};
|
||||
|
||||
return new Response(JSON.stringify(responseBody));
|
||||
},
|
||||
};
|
||||
102
routes/api/auth/multi-factor/passkey/setup-complete.ts
Normal file
102
routes/api/auth/multi-factor/passkey/setup-complete.ts
Normal file
@@ -0,0 +1,102 @@
|
||||
import { Handlers } from 'fresh/server.ts';
|
||||
import { isoBase64URL } from '@simplewebauthn/server/helpers';
|
||||
import { RegistrationResponseJSON } from '@simplewebauthn/server';
|
||||
|
||||
import { FreshContextState } from '/lib/types.ts';
|
||||
import { PasskeyModel } from '/lib/models/multi-factor-auth/passkey.ts';
|
||||
import { UserModel } from '/lib/models/user.ts';
|
||||
import { AppConfig } from '/lib/config.ts';
|
||||
|
||||
export interface RequestBody {
|
||||
methodId: string;
|
||||
challenge: string;
|
||||
registrationResponse: RegistrationResponseJSON;
|
||||
}
|
||||
|
||||
export interface ResponseBody {
|
||||
success: boolean;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export const handler: Handlers<unknown, FreshContextState> = {
|
||||
async POST(request, context) {
|
||||
if (!context.state.user) {
|
||||
return new Response('Unauthorized', { status: 401 });
|
||||
}
|
||||
|
||||
const isMultiFactorAuthEnabled = await AppConfig.isMultiFactorAuthEnabled();
|
||||
|
||||
if (!isMultiFactorAuthEnabled) {
|
||||
const responseBody: ResponseBody = {
|
||||
success: false,
|
||||
error: 'Passwordless passkey login requires multi-factor authentication to be enabled.',
|
||||
};
|
||||
|
||||
return new Response(JSON.stringify(responseBody), { status: 403 });
|
||||
}
|
||||
|
||||
const { user } = context.state;
|
||||
|
||||
const body = await request.clone().json() as RequestBody;
|
||||
const { methodId, challenge, registrationResponse } = body;
|
||||
|
||||
if (!methodId || !challenge || !registrationResponse) {
|
||||
const responseBody: ResponseBody = {
|
||||
success: false,
|
||||
error: 'Method ID, challenge, and registration response are required',
|
||||
};
|
||||
|
||||
return new Response(JSON.stringify(responseBody), { status: 400 });
|
||||
}
|
||||
|
||||
const config = await AppConfig.getConfig();
|
||||
const expectedOrigin = config.auth.baseUrl;
|
||||
const expectedRPID = new URL(config.auth.baseUrl).hostname;
|
||||
|
||||
const verification = await PasskeyModel.verifyRegistration(
|
||||
registrationResponse,
|
||||
challenge,
|
||||
expectedOrigin,
|
||||
expectedRPID,
|
||||
);
|
||||
|
||||
if (!verification.verified || !verification.registrationInfo) {
|
||||
const responseBody: ResponseBody = {
|
||||
success: false,
|
||||
error: 'Passkey registration verification failed',
|
||||
};
|
||||
|
||||
return new Response(JSON.stringify(responseBody), { status: 400 });
|
||||
}
|
||||
|
||||
const { registrationInfo } = verification;
|
||||
const credentialID = registrationInfo.credential.id;
|
||||
const credentialPublicKey = isoBase64URL.fromBuffer(registrationInfo.credential.publicKey);
|
||||
|
||||
const method = PasskeyModel.createMethod(
|
||||
methodId,
|
||||
'Passkey',
|
||||
credentialID,
|
||||
credentialPublicKey,
|
||||
registrationInfo.credential.counter,
|
||||
registrationInfo.credentialDeviceType,
|
||||
registrationInfo.credentialBackedUp,
|
||||
// @ts-expect-error SimpleWebAuthn supports a few more transports, and that's OK
|
||||
registrationResponse.response?.transports || [],
|
||||
);
|
||||
|
||||
if (!user.extra.multi_factor_auth_methods) {
|
||||
user.extra.multi_factor_auth_methods = [];
|
||||
}
|
||||
|
||||
user.extra.multi_factor_auth_methods.push(method);
|
||||
|
||||
await UserModel.update(user);
|
||||
|
||||
const responseBody: ResponseBody = {
|
||||
success: true,
|
||||
};
|
||||
|
||||
return new Response(JSON.stringify(responseBody));
|
||||
},
|
||||
};
|
||||
99
routes/api/auth/multi-factor/passkey/verify.ts
Normal file
99
routes/api/auth/multi-factor/passkey/verify.ts
Normal file
@@ -0,0 +1,99 @@
|
||||
import { Handlers } from 'fresh/server.ts';
|
||||
import { AuthenticationResponseJSON } from '@simplewebauthn/server';
|
||||
|
||||
import { FreshContextState } from '/lib/types.ts';
|
||||
import { PasskeyModel } from '/lib/models/multi-factor-auth/passkey.ts';
|
||||
import { UserModel } from '/lib/models/user.ts';
|
||||
import { AppConfig } from '/lib/config.ts';
|
||||
import { createSessionResponse } from '/lib/auth.ts';
|
||||
|
||||
export interface RequestBody {
|
||||
email: string;
|
||||
challenge: string;
|
||||
authenticationResponse: AuthenticationResponseJSON;
|
||||
redirectUrl?: string;
|
||||
}
|
||||
|
||||
export interface ResponseBody {
|
||||
success: boolean;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export const handler: Handlers<unknown, FreshContextState> = {
|
||||
async POST(request) {
|
||||
const isMultiFactorAuthEnabled = await AppConfig.isMultiFactorAuthEnabled();
|
||||
|
||||
if (!isMultiFactorAuthEnabled) {
|
||||
const responseBody: ResponseBody = {
|
||||
success: false,
|
||||
error: 'Multi-factor authentication is not enabled on this server',
|
||||
};
|
||||
|
||||
return new Response(JSON.stringify(responseBody), { status: 403 });
|
||||
}
|
||||
|
||||
const body = await request.clone().json() as RequestBody;
|
||||
const { email, challenge, authenticationResponse, redirectUrl } = body;
|
||||
|
||||
if (!email || !challenge || !authenticationResponse) {
|
||||
const responseBody: ResponseBody = {
|
||||
success: false,
|
||||
error: 'Email, challenge, and authentication response are required',
|
||||
};
|
||||
|
||||
return new Response(JSON.stringify(responseBody), { status: 400 });
|
||||
}
|
||||
|
||||
const user = await UserModel.getByEmail(email);
|
||||
if (!user) {
|
||||
const responseBody: ResponseBody = {
|
||||
success: false,
|
||||
error: 'User not found',
|
||||
};
|
||||
|
||||
return new Response(JSON.stringify(responseBody), { status: 404 });
|
||||
}
|
||||
|
||||
const config = await AppConfig.getConfig();
|
||||
const expectedOrigin = config.auth.baseUrl;
|
||||
const expectedRPID = new URL(config.auth.baseUrl).hostname;
|
||||
|
||||
const userCredentials = PasskeyModel.getCredentialsFromUser(user);
|
||||
const credentialID = authenticationResponse.id;
|
||||
|
||||
const credential = userCredentials.find((credential) => credential.credentialID === credentialID);
|
||||
if (!credential) {
|
||||
const responseBody: ResponseBody = {
|
||||
success: false,
|
||||
error: 'Credential not found for this user',
|
||||
};
|
||||
|
||||
return new Response(JSON.stringify(responseBody), { status: 400 });
|
||||
}
|
||||
|
||||
const verification = await PasskeyModel.verifyAuthentication(
|
||||
authenticationResponse,
|
||||
challenge,
|
||||
expectedOrigin,
|
||||
expectedRPID,
|
||||
credential,
|
||||
);
|
||||
|
||||
if (!verification.verified) {
|
||||
const responseBody: ResponseBody = {
|
||||
success: false,
|
||||
error: 'Passkey authentication verification failed',
|
||||
};
|
||||
|
||||
return new Response(JSON.stringify(responseBody), { status: 400 });
|
||||
}
|
||||
|
||||
// Update the counter to protect against replay attacks
|
||||
PasskeyModel.updateCounterForUser(user, credentialID, verification.authenticationInfo.newCounter);
|
||||
await UserModel.update(user);
|
||||
|
||||
return await createSessionResponse(request, user, {
|
||||
urlToRedirectTo: redirectUrl || '/',
|
||||
});
|
||||
},
|
||||
};
|
||||
66
routes/api/auth/multi-factor/totp/setup.ts
Normal file
66
routes/api/auth/multi-factor/totp/setup.ts
Normal file
@@ -0,0 +1,66 @@
|
||||
import { Handlers } from 'fresh/server.ts';
|
||||
|
||||
import { FreshContextState } from '/lib/types.ts';
|
||||
import { UserModel } from '/lib/models/user.ts';
|
||||
import { AppConfig } from '/lib/config.ts';
|
||||
import { MultiFactorAuthModel } from '/lib/models/multi-factor-auth.ts';
|
||||
import { TOTPModel } from '/lib/models/multi-factor-auth/totp.ts';
|
||||
|
||||
export interface RequestBody {}
|
||||
|
||||
export interface ResponseBody {
|
||||
success: boolean;
|
||||
error?: string;
|
||||
data?: {
|
||||
methodId: string;
|
||||
secret?: string;
|
||||
qrCodeUrl?: string;
|
||||
backupCodes?: string[];
|
||||
};
|
||||
}
|
||||
|
||||
export const handler: Handlers<unknown, FreshContextState> = {
|
||||
async POST(request, context) {
|
||||
if (!context.state.user) {
|
||||
return new Response('Unauthorized', { status: 401 });
|
||||
}
|
||||
|
||||
const isMultiFactorAuthEnabled = await AppConfig.isMultiFactorAuthEnabled();
|
||||
|
||||
if (!isMultiFactorAuthEnabled) {
|
||||
const responseBody: ResponseBody = {
|
||||
success: false,
|
||||
error: 'Multi-factor authentication is not enabled on this server',
|
||||
};
|
||||
|
||||
return new Response(JSON.stringify(responseBody), { status: 403 });
|
||||
}
|
||||
|
||||
const { user } = context.state;
|
||||
|
||||
const config = await AppConfig.getConfig();
|
||||
const issuer = new URL(config.auth.baseUrl).hostname;
|
||||
const methodId = MultiFactorAuthModel.generateMethodId();
|
||||
const setup = await TOTPModel.createMethod(methodId, 'Authenticator App', issuer, user.email);
|
||||
|
||||
if (!user.extra.multi_factor_auth_methods) {
|
||||
user.extra.multi_factor_auth_methods = [];
|
||||
}
|
||||
|
||||
user.extra.multi_factor_auth_methods.push(setup.method);
|
||||
|
||||
await UserModel.update(user);
|
||||
|
||||
const responseData: ResponseBody = {
|
||||
success: true,
|
||||
data: {
|
||||
methodId: setup.method.id,
|
||||
secret: setup.plainTextSecret,
|
||||
qrCodeUrl: setup.qrCodeUrl,
|
||||
backupCodes: setup.plainTextBackupCodes,
|
||||
},
|
||||
};
|
||||
|
||||
return new Response(JSON.stringify(responseData));
|
||||
},
|
||||
};
|
||||
@@ -7,6 +7,9 @@ import { UserModel, VerificationCodeModel } from '/lib/models/user.ts';
|
||||
import { sendVerifyEmailEmail } from '/lib/providers/brevo.ts';
|
||||
import { FreshContextState } from '/lib/types.ts';
|
||||
import { AppConfig } from '/lib/config.ts';
|
||||
import { isMultiFactorAuthEnabledForUser } from '/lib/utils/multi-factor-auth.ts';
|
||||
import { MultiFactorAuthModel } from '/lib/models/multi-factor-auth.ts';
|
||||
import PasswordlessPasskeyLogin from '/islands/auth/PasswordlessPasskeyLogin.tsx';
|
||||
|
||||
interface Data {
|
||||
error?: string;
|
||||
@@ -14,6 +17,7 @@ interface Data {
|
||||
email?: string;
|
||||
formData?: FormData;
|
||||
isEmailVerificationEnabled: boolean;
|
||||
isMultiFactorAuthEnabled: boolean;
|
||||
helpEmail: string;
|
||||
}
|
||||
|
||||
@@ -24,6 +28,7 @@ export const handler: Handlers<Data, FreshContextState> = {
|
||||
}
|
||||
|
||||
const isEmailVerificationEnabled = await AppConfig.isEmailVerificationEnabled();
|
||||
const isMultiFactorAuthEnabled = await AppConfig.isMultiFactorAuthEnabled() && await UserModel.isThereAnAdmin();
|
||||
const helpEmail = (await AppConfig.getConfig()).visuals.helpEmail;
|
||||
|
||||
const searchParams = new URL(request.url).searchParams;
|
||||
@@ -43,7 +48,14 @@ export const handler: Handlers<Data, FreshContextState> = {
|
||||
}
|
||||
}
|
||||
|
||||
return await context.render({ notice, email, formData, isEmailVerificationEnabled, helpEmail });
|
||||
return await context.render({
|
||||
notice,
|
||||
email,
|
||||
formData,
|
||||
isEmailVerificationEnabled,
|
||||
isMultiFactorAuthEnabled,
|
||||
helpEmail,
|
||||
});
|
||||
},
|
||||
async POST(request, context) {
|
||||
if (context.state.user) {
|
||||
@@ -51,11 +63,16 @@ export const handler: Handlers<Data, FreshContextState> = {
|
||||
}
|
||||
|
||||
const isEmailVerificationEnabled = await AppConfig.isEmailVerificationEnabled();
|
||||
const isMultiFactorAuthEnabled = await AppConfig.isMultiFactorAuthEnabled() && await UserModel.isThereAnAdmin();
|
||||
const helpEmail = (await AppConfig.getConfig()).visuals.helpEmail;
|
||||
|
||||
const searchParams = new URL(request.url).searchParams;
|
||||
|
||||
const formData = await request.clone().formData();
|
||||
const email = getFormDataField(formData, 'email');
|
||||
|
||||
const redirectUrl = searchParams.get('redirect') || '/';
|
||||
|
||||
try {
|
||||
if (!validateEmail(email)) {
|
||||
throw new Error(`Invalid email.`);
|
||||
@@ -75,7 +92,9 @@ export const handler: Handlers<Data, FreshContextState> = {
|
||||
throw new Error('Email not found or invalid password.');
|
||||
}
|
||||
|
||||
if (!(await AppConfig.isEmailVerificationEnabled()) && !user.extra.is_email_verified) {
|
||||
const isEmailVerificationEnabled = await AppConfig.isEmailVerificationEnabled();
|
||||
|
||||
if (!isEmailVerificationEnabled && !user.extra.is_email_verified) {
|
||||
user.extra.is_email_verified = true;
|
||||
|
||||
await UserModel.update(user);
|
||||
@@ -99,14 +118,20 @@ export const handler: Handlers<Data, FreshContextState> = {
|
||||
}
|
||||
}
|
||||
|
||||
return createSessionResponse(request, user, { urlToRedirectTo: `/` });
|
||||
if (user.extra.is_email_verified && isMultiFactorAuthEnabled && isMultiFactorAuthEnabledForUser(user)) {
|
||||
return MultiFactorAuthModel.createSessionResponse(request, user, { urlToRedirectTo: redirectUrl });
|
||||
}
|
||||
|
||||
return createSessionResponse(request, user, { urlToRedirectTo: redirectUrl });
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
|
||||
return await context.render({
|
||||
error: (error as Error).toString(),
|
||||
email,
|
||||
formData,
|
||||
isEmailVerificationEnabled,
|
||||
isMultiFactorAuthEnabled,
|
||||
helpEmail,
|
||||
});
|
||||
}
|
||||
@@ -170,7 +195,7 @@ export default function Login({ data }: PageProps<Data, FreshContextState>) {
|
||||
)
|
||||
: null}
|
||||
|
||||
<form method='POST' class='mb-12'>
|
||||
<form method='POST' class='mb-4'>
|
||||
{formFields(
|
||||
data?.email,
|
||||
data?.notice?.includes('verify your email') && data?.isEmailVerificationEnabled,
|
||||
@@ -178,6 +203,18 @@ export default function Login({ data }: PageProps<Data, FreshContextState>) {
|
||||
<section class='flex justify-center mt-8 mb-4'>
|
||||
<button class='button' type='submit'>Login</button>
|
||||
</section>
|
||||
|
||||
{data?.isMultiFactorAuthEnabled
|
||||
? (
|
||||
<section class='mb-12 max-w-sm mx-auto'>
|
||||
<section class='text-center'>
|
||||
<p class='text-gray-400 text-sm mb-3'>or</p>
|
||||
</section>
|
||||
|
||||
<PasswordlessPasskeyLogin />
|
||||
</section>
|
||||
)
|
||||
: null}
|
||||
</form>
|
||||
|
||||
<h2 class='text-2xl mb-4 text-center'>Need an account?</h2>
|
||||
|
||||
151
routes/mfa-verify.tsx
Normal file
151
routes/mfa-verify.tsx
Normal file
@@ -0,0 +1,151 @@
|
||||
import { Handlers, PageProps } from 'fresh/server.ts';
|
||||
|
||||
import { FreshContextState, MultiFactorAuthMethodType } from '/lib/types.ts';
|
||||
import { UserModel } from '/lib/models/user.ts';
|
||||
import { createSessionResponse } from '/lib/auth.ts';
|
||||
import { getFormDataField } from '/lib/form-utils.tsx';
|
||||
import { AppConfig } from '/lib/config.ts';
|
||||
import { MultiFactorAuthModel } from '/lib/models/multi-factor-auth.ts';
|
||||
import {
|
||||
getEnabledMultiFactorAuthMethodsFromUser,
|
||||
isMultiFactorAuthEnabledForUser,
|
||||
} from '/lib/utils/multi-factor-auth.ts';
|
||||
import { TOTPModel } from '/lib/models/multi-factor-auth/totp.ts';
|
||||
import MultiFactorAuthVerifyForm from '/components/auth/MultiFactorAuthVerifyForm.tsx';
|
||||
|
||||
interface Data {
|
||||
error?: {
|
||||
title: string;
|
||||
message: string;
|
||||
};
|
||||
email?: string;
|
||||
redirectUrl?: string;
|
||||
availableMethods?: MultiFactorAuthMethodType[];
|
||||
hasPasskey?: boolean;
|
||||
}
|
||||
|
||||
export const handler: Handlers<Data, FreshContextState> = {
|
||||
async GET(request, context) {
|
||||
const isMultiFactorAuthEnabled = await AppConfig.isMultiFactorAuthEnabled();
|
||||
|
||||
if (!isMultiFactorAuthEnabled) {
|
||||
return new Response('Redirect', { status: 303, headers: { 'Location': '/login' } });
|
||||
}
|
||||
|
||||
const searchParams = new URL(request.url).searchParams;
|
||||
const redirectUrl = searchParams.get('redirect') || '/';
|
||||
|
||||
const { user } = (await MultiFactorAuthModel.getDataFromRequest(request)) || {};
|
||||
|
||||
if (!user) {
|
||||
return new Response('Redirect', { status: 303, headers: { 'Location': '/login' } });
|
||||
}
|
||||
|
||||
const hasMultiFactorAuthEnabled = isMultiFactorAuthEnabledForUser(user);
|
||||
|
||||
if (!hasMultiFactorAuthEnabled) {
|
||||
return new Response('Redirect', { status: 303, headers: { 'Location': '/login' } });
|
||||
}
|
||||
|
||||
const enabledMethods = getEnabledMultiFactorAuthMethodsFromUser(user);
|
||||
const availableMethods = enabledMethods.map((method) => method.type);
|
||||
const hasPasskey = availableMethods.includes('passkey');
|
||||
|
||||
return await context.render({
|
||||
email: user.email,
|
||||
redirectUrl,
|
||||
availableMethods,
|
||||
hasPasskey,
|
||||
});
|
||||
},
|
||||
async POST(request, context) {
|
||||
const isMultiFactorAuthEnabled = await AppConfig.isMultiFactorAuthEnabled();
|
||||
|
||||
if (!isMultiFactorAuthEnabled) {
|
||||
return new Response('Redirect', { status: 303, headers: { 'Location': '/login' } });
|
||||
}
|
||||
|
||||
const searchParams = new URL(request.url).searchParams;
|
||||
const redirectUrl = searchParams.get('redirect') || '/';
|
||||
|
||||
const { user } = (await MultiFactorAuthModel.getDataFromRequest(request)) || {};
|
||||
|
||||
if (!user) {
|
||||
return new Response('Redirect', { status: 303, headers: { 'Location': '/login' } });
|
||||
}
|
||||
|
||||
const hasMultiFactorAuthEnabled = isMultiFactorAuthEnabledForUser(user);
|
||||
|
||||
if (!hasMultiFactorAuthEnabled) {
|
||||
return new Response('Redirect', { status: 303, headers: { 'Location': '/login' } });
|
||||
}
|
||||
|
||||
const enabledMethods = getEnabledMultiFactorAuthMethodsFromUser(user);
|
||||
const availableMethods = enabledMethods.map((method) => method.type);
|
||||
const hasPasskey = availableMethods.includes('passkey');
|
||||
|
||||
try {
|
||||
const formData = await request.formData();
|
||||
const token = getFormDataField(formData, 'token');
|
||||
|
||||
if (!token) {
|
||||
throw new Error('Authentication token is required');
|
||||
}
|
||||
|
||||
let isValid = false;
|
||||
let updateUser = false;
|
||||
|
||||
// Passkey verification is handled in a separate process
|
||||
for (const method of enabledMethods) {
|
||||
const verification = await TOTPModel.verifyMethodToken(method.metadata, token);
|
||||
if (verification.isValid) {
|
||||
isValid = true;
|
||||
|
||||
if (verification.remainingCodes && method.type === 'totp' && method.metadata.totp) {
|
||||
method.metadata.totp.hashed_backup_codes = verification.remainingCodes;
|
||||
updateUser = true;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!isValid) {
|
||||
throw new Error('Invalid authentication token or backup code');
|
||||
}
|
||||
|
||||
if (updateUser) {
|
||||
await UserModel.update(user);
|
||||
}
|
||||
|
||||
return await createSessionResponse(request, user, { urlToRedirectTo: redirectUrl });
|
||||
} catch (error) {
|
||||
console.error('Multi-factor authentication verification error:', error);
|
||||
|
||||
return await context.render({
|
||||
error: {
|
||||
title: 'Verification Failed',
|
||||
message: (error as Error).message,
|
||||
},
|
||||
email: user.email,
|
||||
redirectUrl,
|
||||
availableMethods,
|
||||
hasPasskey,
|
||||
});
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
export default function MultiFactorAuthVerifyPage({ data }: PageProps<Data, FreshContextState>) {
|
||||
return (
|
||||
<main>
|
||||
<section class='max-w-screen-md mx-auto flex flex-col items-center justify-center'>
|
||||
<MultiFactorAuthVerifyForm
|
||||
email={data.email || ''}
|
||||
redirectUrl={data.redirectUrl || '/'}
|
||||
availableMethods={data.availableMethods || []}
|
||||
error={data.error}
|
||||
/>
|
||||
</section>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Handlers, PageProps } from 'fresh/server.ts';
|
||||
|
||||
import { currencyMap, FreshContextState, SupportedCurrencySymbol } from '/lib/types.ts';
|
||||
import { currencyMap, FreshContextState, SupportedCurrencySymbol, User } from '/lib/types.ts';
|
||||
import { PASSWORD_SALT } from '/lib/auth.ts';
|
||||
import { UserModel, VerificationCodeModel } from '/lib/models/user.ts';
|
||||
import { convertFormDataToObject, generateHash, validateEmail } from '/lib/utils/misc.ts';
|
||||
@@ -21,7 +21,11 @@ interface Data {
|
||||
formData: Record<string, any>;
|
||||
currency?: SupportedCurrencySymbol;
|
||||
isExpensesAppEnabled: boolean;
|
||||
isMultiFactorAuthEnabled: boolean;
|
||||
helpEmail: string;
|
||||
user: {
|
||||
extra: Pick<User['extra'], 'multi_factor_auth_methods'>;
|
||||
};
|
||||
}
|
||||
|
||||
export const handler: Handlers<Data, FreshContextState> = {
|
||||
@@ -32,12 +36,15 @@ export const handler: Handlers<Data, FreshContextState> = {
|
||||
|
||||
const isExpensesAppEnabled = await AppConfig.isAppEnabled('expenses');
|
||||
const helpEmail = (await AppConfig.getConfig()).visuals.helpEmail;
|
||||
const isMultiFactorAuthEnabled = await AppConfig.isMultiFactorAuthEnabled();
|
||||
|
||||
return await context.render({
|
||||
formData: {},
|
||||
currency: context.state.user.extra.expenses_currency,
|
||||
isExpensesAppEnabled,
|
||||
helpEmail,
|
||||
isMultiFactorAuthEnabled,
|
||||
user: context.state.user,
|
||||
});
|
||||
},
|
||||
async POST(request, context) {
|
||||
@@ -47,6 +54,7 @@ export const handler: Handlers<Data, FreshContextState> = {
|
||||
|
||||
const isExpensesAppEnabled = await AppConfig.isAppEnabled('expenses');
|
||||
const helpEmail = (await AppConfig.getConfig()).visuals.helpEmail;
|
||||
const isMultiFactorAuthEnabled = await AppConfig.isMultiFactorAuthEnabled();
|
||||
|
||||
let action: Action = 'change-email';
|
||||
let errorTitle = '';
|
||||
@@ -190,6 +198,8 @@ export const handler: Handlers<Data, FreshContextState> = {
|
||||
currency: user.extra.expenses_currency,
|
||||
isExpensesAppEnabled,
|
||||
helpEmail,
|
||||
isMultiFactorAuthEnabled,
|
||||
user: user,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
@@ -202,6 +212,8 @@ export const handler: Handlers<Data, FreshContextState> = {
|
||||
currency: user.extra.expenses_currency,
|
||||
isExpensesAppEnabled,
|
||||
helpEmail,
|
||||
isMultiFactorAuthEnabled,
|
||||
user: user,
|
||||
});
|
||||
}
|
||||
},
|
||||
@@ -216,7 +228,9 @@ export default function SettingsPage({ data }: PageProps<Data, FreshContextState
|
||||
notice={data?.notice}
|
||||
currency={data?.currency}
|
||||
isExpensesAppEnabled={data?.isExpensesAppEnabled}
|
||||
isMultiFactorAuthEnabled={data?.isMultiFactorAuthEnabled}
|
||||
helpEmail={data?.helpEmail}
|
||||
user={data?.user}
|
||||
/>
|
||||
</main>
|
||||
);
|
||||
|
||||
@@ -69,7 +69,9 @@ export const handler: Handlers<Data, FreshContextState> = {
|
||||
|
||||
const user = await UserModel.create(email, hashedPassword);
|
||||
|
||||
if (await AppConfig.isEmailVerificationEnabled()) {
|
||||
const isEmailVerificationEnabled = await AppConfig.isEmailVerificationEnabled();
|
||||
|
||||
if (isEmailVerificationEnabled) {
|
||||
const verificationCode = await VerificationCodeModel.create(user, user.email, 'email');
|
||||
|
||||
await sendVerifyEmailEmail(user.email, verificationCode);
|
||||
|
||||
Reference in New Issue
Block a user