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:
0xGingi
2025-05-29 12:30:28 -04:00
committed by GitHub
parent 2a77915630
commit 455a7201e9
28 changed files with 2361 additions and 40 deletions

View 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));
},
};