Skip to content

feat: Passkeys section to show/add/delete passkeys #459

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions apps/platform/trpc/routers/userRouter/securityRouter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -763,7 +763,10 @@ export const securityRouter = router({
.input(
z.object({
verificationToken: zodSchemas.nanoIdToken(),
authenticatorType: z.enum(['platform', 'cross-platform'])
/**
* @deprecated Let the browser decide
*/
authenticatorType: z.enum(['platform', 'cross-platform']).optional()
})
)
.query(async ({ ctx, input }) => {
Expand Down Expand Up @@ -806,8 +809,7 @@ export const securityRouter = router({
const passkeyOptions = await usePasskeys.generateRegistrationOptions({
userDisplayName: accountData.username,
username: accountData.username,
accountPublicId: accountData.publicId,
authenticatorAttachment: input.authenticatorType
accountPublicId: accountData.publicId
});
return { options: passkeyOptions };
}),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { type ModalComponent } from '@/src/hooks/use-awaitable-modal';
import { Button, Dialog } from '@radix-ui/themes';
import { type TypeId } from '@u22n/utils';
import { api } from '@/src/lib/trpc';

export function DeletePasskeyModal({
open,
publicId,
name,
verificationToken,
onClose,
onResolve
}: ModalComponent<{
publicId: TypeId<'accountPasskey'>;
name: string;
verificationToken: string;
}>) {
const {
mutateAsync: deletePasskey,
isLoading: deletePasskeyLoading,
error
} = api.account.security.deletePasskey.useMutation();

return (
<Dialog.Root open={open}>
<Dialog.Content className="w-full max-w-96 p-4">
<Dialog.Title className="mx-auto w-fit">Delete Passkey</Dialog.Title>
<Dialog.Description className="mx-auto my-6 flex w-fit text-balance p-2 text-center text-sm font-bold">
This action is irreversible. You will not be able to recover this
passkey. Are you sure you want to delete {name}?
</Dialog.Description>
<div className="text-red-10 w-full">{error?.message}</div>
<div className="flex flex-col gap-3">
<Button
color="red"
className="w-full"
loading={deletePasskeyLoading}
onClick={async () => {
await deletePasskey({
passkeyPublicId: publicId,
verificationToken
});
onResolve(null);
}}>
Delete
</Button>
<Button
disabled={deletePasskeyLoading}
onClick={() => onClose()}
className="w-full"
variant="soft"
color="gray">
Cancel
</Button>
</div>
</Dialog.Content>
</Dialog.Root>
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { type ModalComponent } from '@/src/hooks/use-awaitable-modal';
import { Dialog, TextField, Button } from '@radix-ui/themes';
import { useState } from 'react';

export function PasskeyNameModal({
open,
onClose,
onResolve
}: ModalComponent<NonNullable<unknown>, string>) {
const [name, setName] = useState('Passkey');
return (
<Dialog.Root open={open}>
<Dialog.Content className="w-full max-w-96 p-4">
<Dialog.Title className="mx-auto w-fit">
Name your new passkey
</Dialog.Title>
<Dialog.Description className="mx-auto flex w-fit text-balance p-2 text-center text-sm font-bold">
This will help you identify your passkey in the future. Keep it simple
like Android Phone, Apple ID, Windows Hello, YubiKey etc.
</Dialog.Description>
<div className="my-6 flex flex-col gap-2">
<TextField.Root
defaultValue={'Passkey'}
onChange={(e) => {
setName(e.target.value);
}}
/>
</div>
<div className="flex flex-col gap-3">
<Button
className="w-full"
onClick={async () => {
onResolve(name);
}}>
Save
</Button>
<Button
onClick={() => onClose()}
className="w-full"
variant="soft"
color="gray">
Cancel
</Button>
</div>
</Dialog.Content>
</Dialog.Root>
);
}
116 changes: 114 additions & 2 deletions apps/web/src/app/[orgShortCode]/settings/user/security/page.tsx
Original file line number Diff line number Diff line change
@@ -1,16 +1,30 @@
'use client';

import { Flex, Heading, Spinner, Text, Switch, Button } from '@radix-ui/themes';
import {
Flex,
Heading,
Spinner,
Text,
Switch,
Button,
IconButton
} from '@radix-ui/themes';
import { useEffect, useState } from 'react';
import { api } from '@/src/lib/trpc';
import { VerificationModal } from './_components/verification-modal';
import { DeletePasskeyModal } from './_components/delete-modals';
import {
PasswordModal,
TOTPModal,
RecoveryCodeModal
} from './_components/reset-modals';
import useAwaitableModal from '@/src/hooks/use-awaitable-modal';
import { toast } from 'sonner';
import { Trash } from 'lucide-react';
import { format } from 'date-fns';
import useLoading from '@/src/hooks/use-loading';
import { startRegistration } from '@simplewebauthn/browser';
// import { PasskeyNameModal } from './_components/passkey-modals';

export default function Page() {
const {
Expand Down Expand Up @@ -59,6 +73,55 @@ export default function Page() {
}
);

const [DeletePasskeyModalRoot, openDeletePasskeyModal] = useAwaitableModal(
DeletePasskeyModal,
{
publicId: 'ap_',
name: '',
verificationToken: ''
}
);

// const [PasskeyNameModalRoot, openPasskeyNameModal] = useAwaitableModal(
// PasskeyNameModal,
// {}
// );

const fetchPasskeyChallengeApi =
api.useUtils().account.security.generateNewPasskeyChallenge;
const { mutateAsync: addNewPasskey } =
api.account.security.addNewPasskey.useMutation({
onSuccess: () => {
void refreshSecurityData();
},
onError: (err) => {
toast.error('Something went wrong while adding new passkey', {
description: err.message
});
}
});

const { loading: passkeyAddLoading, run: addPasskey } = useLoading(
async () => {
const token = await waitForVerification();
if (!token) return;
const challenge = await fetchPasskeyChallengeApi.fetch({
verificationToken: token
});
const response = await startRegistration(challenge.options);

// Need to have a separate endpoint for rename
// const passkeyName = await openPasskeyNameModal().catch(() => null);
// if (!passkeyName) return;

await addNewPasskey({
verificationToken: token,
// nickname: passkeyName,
registrationResponseRaw: response
});
}
);

async function waitForVerification() {
if (!initData) throw new Error('No init data');
if (verificationToken) return verificationToken;
Expand All @@ -83,6 +146,8 @@ export default function Page() {
});

const canDisableLegacySecurity = (initData?.passkeys.length ?? 0) > 0;
const canDeletePasskey =
(initData?.passkeys.length ?? 0) > 1 || isPassword2FaEnabled;

return (
<Flex
Expand Down Expand Up @@ -121,7 +186,7 @@ export default function Page() {
checked={isPassword2FaEnabled}
disabled={
isDisablingLegacySecurity ||
!(isPassword2FaEnabled && canDisableLegacySecurity)
(isPassword2FaEnabled && !canDisableLegacySecurity)
}
onCheckedChange={async () => {
const token = await waitForVerification();
Expand Down Expand Up @@ -200,13 +265,60 @@ export default function Page() {
</Button>
</div>
)}
<div className="flex flex-col gap-3">
<span className="text-lg font-bold">Passkeys</span>
<div className="flex flex-wrap gap-2">
{initData?.passkeys.map((passkey) => (
<div
key={passkey.publicId}
className="bg-muted flex items-center justify-center gap-2 rounded border px-2 py-1">
<div className="flex flex-col">
<span>{passkey.nickname}</span>
<span className="text-muted-foreground text-xs">
{format(passkey.createdAt, ' HH:mm, do MMM yyyy')}
</span>
</div>
<div>
<IconButton
size="2"
variant="soft"
disabled={!canDeletePasskey}
onClick={async () => {
const token = await waitForVerification();
if (!token) return;
await openDeletePasskeyModal({
publicId: passkey.publicId,
name: passkey.nickname,
verificationToken: verificationToken ?? token
})
.then(() => refreshSecurityData())
.catch(() => null);
}}>
<Trash size={16} />
</IconButton>
</div>
</div>
))}
{initData?.passkeys.length === 0 && (
<div className="text-muted-foreground">No passkeys found</div>
)}
</div>
<Button
className="w-fit"
loading={passkeyAddLoading}
onClick={() => addPasskey({ clearError: true, clearData: true })}>
Add New Passkey
</Button>
</div>
</div>
)}

<VerificationModalRoot />
<PasswordModalRoot />
<TOTPModalRoot />
<RecoveryModalRoot />
<DeletePasskeyModalRoot />
{/* <PasskeyNameModalRoot /> */}
</Flex>
);
}