mirror of
https://github.com/documenso/documenso.git
synced 2025-11-13 00:03:33 +10:00
feat: add passkeys (#989)
## Description Add support to login with passkeys. Passkeys can be added via the user security settings page. Note: Currently left out adding the type of authentication method for the 'user security audit logs' because we're using the `signIn` next-auth event which doesn't appear to provide the context. Will look into it at another time. ## Changes Made - Add passkeys to login - Add passkeys feature flag - Add page to manage passkeys - Add audit logs relating to passkeys - Updated prisma schema to support passkeys & anonymous verification tokens ## Testing Performed To be done. MacOS: - Safari ✅ - Chrome ✅ - Firefox ✅ Windows: - Chrome [Untested] - Firefox [Untested] Linux: - Chrome [Untested] - Firefox [Untested] iOS: - Safari ✅ ## Checklist <!--- Please check the boxes that apply to this pull request. --> <!--- You can add or remove items as needed. --> - [X] I have tested these changes locally and they work as expected. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit - **New Features** - Introduced Passkey authentication, including creation, sign-in, and management of passkeys. - Added a Passkeys section in Security Settings for managing user passkeys. - Implemented UI updates for Passkey authentication, including a new dialog for creating passkeys and a data table for managing them. - Enhanced security settings with server-side feature flags to conditionally display new security features. - **Bug Fixes** - Improved UI consistency in the Settings Security Activity Page. - Updated button styling in the 2FA Recovery Codes component for better visibility. - **Refactor** - Streamlined authentication options to include WebAuthn credentials provider. - **Chores** - Updated database schema to support passkeys and related functionality. - Added new audit log types for passkey-related activities. - Enhanced server-only authentication utilities for passkey registration and management. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
This commit is contained in:
106
packages/lib/server-only/auth/create-passkey.ts
Normal file
106
packages/lib/server-only/auth/create-passkey.ts
Normal file
@ -0,0 +1,106 @@
|
||||
import { verifyRegistrationResponse } from '@simplewebauthn/server';
|
||||
import type { RegistrationResponseJSON } from '@simplewebauthn/types';
|
||||
|
||||
import { prisma } from '@documenso/prisma';
|
||||
import { UserSecurityAuditLogType } from '@documenso/prisma/client';
|
||||
|
||||
import { MAXIMUM_PASSKEYS } from '../../constants/auth';
|
||||
import { AppError, AppErrorCode } from '../../errors/app-error';
|
||||
import type { RequestMetadata } from '../../universal/extract-request-metadata';
|
||||
import { getAuthenticatorRegistrationOptions } from '../../utils/authenticator';
|
||||
|
||||
type CreatePasskeyOptions = {
|
||||
userId: number;
|
||||
passkeyName: string;
|
||||
verificationResponse: RegistrationResponseJSON;
|
||||
requestMetadata?: RequestMetadata;
|
||||
};
|
||||
|
||||
export const createPasskey = async ({
|
||||
userId,
|
||||
passkeyName,
|
||||
verificationResponse,
|
||||
requestMetadata,
|
||||
}: CreatePasskeyOptions) => {
|
||||
const { _count } = await prisma.user.findFirstOrThrow({
|
||||
where: {
|
||||
id: userId,
|
||||
},
|
||||
include: {
|
||||
_count: {
|
||||
select: {
|
||||
passkeys: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (_count.passkeys >= MAXIMUM_PASSKEYS) {
|
||||
throw new AppError('TOO_MANY_PASSKEYS');
|
||||
}
|
||||
|
||||
const verificationToken = await prisma.verificationToken.findFirst({
|
||||
where: {
|
||||
userId,
|
||||
identifier: 'PASSKEY_CHALLENGE',
|
||||
},
|
||||
orderBy: {
|
||||
createdAt: 'desc',
|
||||
},
|
||||
});
|
||||
|
||||
if (!verificationToken) {
|
||||
throw new AppError(AppErrorCode.NOT_FOUND, 'Challenge token not found');
|
||||
}
|
||||
|
||||
await prisma.verificationToken.deleteMany({
|
||||
where: {
|
||||
userId,
|
||||
identifier: 'PASSKEY_CHALLENGE',
|
||||
},
|
||||
});
|
||||
|
||||
if (verificationToken.expires < new Date()) {
|
||||
throw new AppError(AppErrorCode.EXPIRED_CODE, 'Challenge token expired');
|
||||
}
|
||||
|
||||
const { rpId: expectedRPID, origin: expectedOrigin } = getAuthenticatorRegistrationOptions();
|
||||
|
||||
const verification = await verifyRegistrationResponse({
|
||||
response: verificationResponse,
|
||||
expectedChallenge: verificationToken.token,
|
||||
expectedOrigin,
|
||||
expectedRPID,
|
||||
});
|
||||
|
||||
if (!verification.verified || !verification.registrationInfo) {
|
||||
throw new AppError(AppErrorCode.UNAUTHORIZED, 'Verification failed');
|
||||
}
|
||||
|
||||
const { credentialPublicKey, credentialID, counter, credentialDeviceType, credentialBackedUp } =
|
||||
verification.registrationInfo;
|
||||
|
||||
await prisma.$transaction(async (tx) => {
|
||||
await tx.passkey.create({
|
||||
data: {
|
||||
userId,
|
||||
name: passkeyName,
|
||||
credentialId: Buffer.from(credentialID),
|
||||
credentialPublicKey: Buffer.from(credentialPublicKey),
|
||||
counter,
|
||||
credentialDeviceType,
|
||||
credentialBackedUp,
|
||||
transports: verificationResponse.response.transports,
|
||||
},
|
||||
});
|
||||
|
||||
await tx.userSecurityAuditLog.create({
|
||||
data: {
|
||||
userId,
|
||||
type: UserSecurityAuditLogType.PASSKEY_CREATED,
|
||||
userAgent: requestMetadata?.userAgent,
|
||||
ipAddress: requestMetadata?.ipAddress,
|
||||
},
|
||||
});
|
||||
});
|
||||
};
|
||||
Reference in New Issue
Block a user