Skip to content
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

feat: Hanko passkeys support #14741

Open
wants to merge 9 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
20 changes: 18 additions & 2 deletions .env.example
Expand Up @@ -116,15 +116,15 @@ NEXT_PUBLIC_FRESHCHAT_HOST=
# @see https://support.google.com/cloud/answer/6158849#public-and-internal&zippy=%2Cpublic-and-internal-applications
GOOGLE_LOGIN_ENABLED=false

# - GOOGLE CALENDAR/MEET/LOGIN
# GOOGLE CALENDAR/MEET/LOGIN
# Needed to enable Google Calendar integration and Login with Google
# @see https://github.com/calcom/cal.com#obtaining-the-google-api-credentials
GOOGLE_API_CREDENTIALS=

# Inbox to send user feedback
SEND_FEEDBACK_EMAIL=

# Sengrid
# SendGrid
# Used for email reminders in workflows and internal sync services
SENDGRID_API_KEY=
SENDGRID_EMAIL=
Expand Down Expand Up @@ -359,3 +359,19 @@ UNKEY_ROOT_KEY=
# Used for Cal.ai Enterprise Voice AI Agents
# https://retellai.com
RETELL_AI_KEY=

# Hanko Passkeys Config
#
# To quickly set these up:
# 1. Go to https://cloud.hanko.io/login
# 2. Create a "Passkey API" project.
# Enter a URL, e.g. http://localhost:3000
# You'll find the tenant ID on the resulting page. Paste it below.
# 3. Click on "Create API Key".
# Copy the API key "Secret" (you can safely ignore the "ID") and paste it below.
#
# Then set `PASSKEY_LOGIN_ENABLED` to `true`.
NEXT_PUBLIC_HANKO_PASSKEYS_TENANT_ID=
# Make sure this API key is surrounded by quotes:
HANKO_PASSKEYS_API_KEY=""
PASSKEY_LOGIN_ENABLED=false
5 changes: 5 additions & 0 deletions apps/web/app/future/settings/security/passkeys/layout.tsx
@@ -0,0 +1,5 @@
import { WithLayout } from "app/layoutHOC";

import { getLayout } from "@calcom/features/settings/layouts/SettingsLayoutAppDir";

export default WithLayout({ getLayout });
10 changes: 10 additions & 0 deletions apps/web/app/future/settings/security/passkeys/page.tsx
@@ -0,0 +1,10 @@
import Page from "@pages/settings/security/passkeys";
import { _generateMetadata } from "app/_utils";

export const generateMetadata = async () =>
await _generateMetadata(
(t) => t("passkeys"),
(t) => t("passkeys_description")
);

export default Page;
26 changes: 26 additions & 0 deletions apps/web/components/auth/PasskeyIcon.tsx
@@ -0,0 +1,26 @@
import type { ComponentProps } from "react";

export default function PasskeyIcon(props: ComponentProps<"svg">) {
return (
<svg
id="icon-passkey"
xmlns="http://www.w3.org/2000/svg"
viewBox="3 1.5 19.5 19"
width="16"
height="16"
fill="currentColor"
{...props}>
<g id="icon-passkey-all">
<circle id="icon-passkey-head" cx="10.5" cy="6" r="4.5" />
<path
id="icon-passkey-key"
d="M22.5,10.5a3.5,3.5,0,1,0-5,3.15V19L19,20.5,21.5,18,20,16.5,21.5,15l-1.24-1.24A3.5,3.5,0,0,0,22.5,10.5Zm-3.5,0a1,1,0,1,1,1-1A1,1,0,0,1,19,10.5Z"
/>
<path
id="icon-passkey-body"
d="M14.44,12.52A6,6,0,0,0,12,12H9a6,6,0,0,0-6,6v2H16V14.49A5.16,5.16,0,0,1,14.44,12.52Z"
/>
</g>
</svg>
);
}
1 change: 1 addition & 0 deletions apps/web/next.config.js
Expand Up @@ -189,6 +189,7 @@ const nextConfig = {
"@calcom/prisma",
"@calcom/trpc",
"@calcom/ui",
"@teamhanko/passkeys-next-auth-provider",
"lucide-react",
],
modularizeImports: {
Expand Down
2 changes: 2 additions & 0 deletions apps/web/package.json
Expand Up @@ -42,6 +42,7 @@
"@daily-co/daily-js": "^0.59.0",
"@daily-co/daily-react": "^0.17.2",
"@formkit/auto-animate": "1.0.0-beta.5",
"@github/webauthn-json": "^2.1.1",
"@glidejs/glide": "^3.5.2",
"@hookform/error-message": "^2.0.0",
"@hookform/resolvers": "^2.9.7",
Expand All @@ -63,6 +64,7 @@
"@stripe/react-stripe-js": "^1.10.0",
"@stripe/stripe-js": "^1.35.0",
"@tanstack/react-query": "^5.17.15",
"@teamhanko/passkeys-next-auth-provider": "^0.2.7",
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wish Node had a better way to make optional dependencies 🤷‍♂️

Copy link
Author

@merlindru merlindru Apr 25, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure since when npm has this, but there is optionalDependencies

https://docs.npmjs.com/cli/v10/configuring-npm/package-json#optionaldependencies

Was supported in yarn v1 so I assume v2+ has it too

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Opted not to do this for now because optionalDependencies isn't in use for any other packages atm. Also I'm unsure if a build without installing optional deps would be successful, especially because of import behavior, haven't tested it

Do you want me to test this? What other not-strictly-needed dependencies are there that could be moved to optionalDependencies (at least in theory)?

"@tremor/react": "^2.0.0",
"@types/turndown": "^5.0.1",
"@unkey/ratelimit": "^0.1.1",
Expand Down
48 changes: 48 additions & 0 deletions apps/web/pages/api/auth/passkeys/list.ts
@@ -0,0 +1,48 @@
import { tenant } from "@teamhanko/passkeys-next-auth-provider";
import type { NextApiRequest, NextApiResponse } from "next";

import { ErrorCode } from "@calcom/features/auth/lib/ErrorCode";
import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
import prisma from "@calcom/prisma";

const tenantId = process.env.NEXT_PUBLIC_HANKO_PASSKEYS_TENANT_ID ?? "";
const apiKey = process.env.HANKO_PASSKEYS_API_KEY ?? "";

const passkeyApi = tenant({ tenantId, apiKey });

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
if (!tenantId || !apiKey) {
return res.status(501).json({ message: "Passkey API not configured" });
}

if (req.method !== "GET") {
return res.status(405).json({ message: "Method not allowed" });
}

const session = await getServerSession({ req, res });
if (!session) {
return res.status(401).json({ message: "Not authenticated" });
}

if (!session.user?.id) {
console.error("Session is missing a user id.");
return res.status(500).json({ error: ErrorCode.InternalServerError });
}

const user = await prisma.user.findUnique({ where: { id: session.user.id } });
if (!user) {
console.error(`Session references user that no longer exists.`);
return res.status(401).json({ message: "Not authenticated" });
}

const credentials = await passkeyApi.user(user.id.toString()).credentials();

return res.status(200).json({
credentials: credentials.map((c) => ({
id: c.id,
name: c.name,
createdAt: c.created_at,
lastUsedAt: c.last_used_at,
})),
});
}
41 changes: 41 additions & 0 deletions apps/web/pages/api/auth/passkeys/register/finalize.ts
@@ -0,0 +1,41 @@
import { tenant } from "@teamhanko/passkeys-next-auth-provider";
import type { NextApiRequest, NextApiResponse } from "next";

import { ErrorCode } from "@calcom/features/auth/lib/ErrorCode";
import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
import prisma from "@calcom/prisma";

const tenantId = process.env.NEXT_PUBLIC_HANKO_PASSKEYS_TENANT_ID ?? "";
const apiKey = process.env.HANKO_PASSKEYS_API_KEY ?? "";

const passkeyApi = tenant({ tenantId, apiKey });

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
if (!tenantId || !apiKey) {
return res.status(501).json({ message: "Passkey API not configured" });
}

if (req.method !== "POST") {
return res.status(405).json({ message: "Method not allowed" });
}

const session = await getServerSession({ req, res });
if (!session) {
return res.status(401).json({ message: "Not authenticated" });
}

if (!session.user?.id) {
console.error("Session is missing a user id.");
return res.status(500).json({ error: ErrorCode.InternalServerError });
}

const user = await prisma.user.findUnique({ where: { id: session.user.id } });
if (!user) {
console.error(`Session references user that no longer exists.`);
return res.status(401).json({ message: "Not authenticated" });
}

await passkeyApi.registration.finalize(req.body);

return res.status(200).json({ message: "Passkey registered" });
}
44 changes: 44 additions & 0 deletions apps/web/pages/api/auth/passkeys/register/initialize.ts
@@ -0,0 +1,44 @@
import { tenant } from "@teamhanko/passkeys-next-auth-provider";
import type { NextApiRequest, NextApiResponse } from "next";

import { ErrorCode } from "@calcom/features/auth/lib/ErrorCode";
import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
import prisma from "@calcom/prisma";

const tenantId = process.env.NEXT_PUBLIC_HANKO_PASSKEYS_TENANT_ID ?? "";
const apiKey = process.env.HANKO_PASSKEYS_API_KEY ?? "";

const passkeyApi = tenant({ tenantId, apiKey });

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
if (!tenantId || !apiKey) {
return res.status(501).json({ message: "Passkey API not configured" });
}

if (req.method !== "POST") {
return res.status(405).json({ message: "Method not allowed" });
}

const session = await getServerSession({ req, res });
if (!session) {
return res.status(401).json({ message: "Not authenticated" });
}

if (!session.user?.id) {
console.error("Session is missing a user id.");
return res.status(500).json({ error: ErrorCode.InternalServerError });
}

const user = await prisma.user.findUnique({ where: { id: session.user.id } });
if (!user) {
console.error(`Session references user that no longer exists.`);
return res.status(401).json({ message: "Not authenticated" });
}

const createOptions = await passkeyApi.registration.initialize({
userId: session.user.id.toString(),
username: session.user.username ?? "",
});

return res.status(200).json(createOptions);
}
46 changes: 46 additions & 0 deletions apps/web/pages/api/auth/passkeys/remove.ts
@@ -0,0 +1,46 @@
import { tenant } from "@teamhanko/passkeys-next-auth-provider";
import type { NextApiRequest, NextApiResponse } from "next";

import { ErrorCode } from "@calcom/features/auth/lib/ErrorCode";
import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
import prisma from "@calcom/prisma";

const tenantId = process.env.NEXT_PUBLIC_HANKO_PASSKEYS_TENANT_ID ?? "";
const apiKey = process.env.HANKO_PASSKEYS_API_KEY ?? "";

const passkeyApi = tenant({ tenantId, apiKey });

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
if (!tenantId || !apiKey) {
return res.status(501).json({ message: "Passkey API not configured" });
}

if (req.method !== "DELETE") {
return res.status(405).json({ message: "Method not allowed" });
}

const credentialId = req.body?.credentialId;
if (!credentialId) {
return res.status(400).json({ message: "Missing credential id" });
}

const session = await getServerSession({ req, res });
if (!session) {
return res.status(401).json({ message: "Not authenticated" });
}

if (!session.user?.id) {
console.error("Session is missing a user id.");
return res.status(500).json({ error: ErrorCode.InternalServerError });
}

const user = await prisma.user.findUnique({ where: { id: session.user.id } });
if (!user) {
console.error(`Session references user that no longer exists.`);
return res.status(401).json({ message: "Not authenticated" });
}

await passkeyApi.credential(credentialId).remove();

return res.status(200).json({});
}
33 changes: 32 additions & 1 deletion apps/web/pages/auth/login.tsx
@@ -1,6 +1,7 @@
"use client";

import { zodResolver } from "@hookform/resolvers/zod";
import { signInWithPasskey } from "@teamhanko/passkeys-next-auth-provider/client";
import classNames from "classnames";
import { signIn } from "next-auth/react";
import Link from "next/link";
Expand All @@ -25,6 +26,7 @@ import type { WithNonceProps } from "@lib/withNonce";
import AddToHomescreen from "@components/AddToHomescreen";
import PageWrapper from "@components/PageWrapper";
import BackupCode from "@components/auth/BackupCode";
import PasskeyIcon from "@components/auth/PasskeyIcon";
import TwoFactor from "@components/auth/TwoFactor";
import AuthContainer from "@components/ui/AuthContainer";

Expand All @@ -44,6 +46,7 @@ const GoogleIcon = () => (
export default function Login({
csrfToken,
isGoogleLoginEnabled,
isPasskeyLoginEnabled,
isSAMLLoginEnabled,
samlTenantID,
samlProductID,
Expand Down Expand Up @@ -238,7 +241,9 @@ inferSSRProps<typeof getServerSideProps> & WithNonceProps<{}>) {
</form>
{!twoFactorRequired && (
<>
{(isGoogleLoginEnabled || displaySSOLogin) && <hr className="border-subtle my-8" />}
{(isGoogleLoginEnabled || displaySSOLogin || isPasskeyLoginEnabled) && (
<hr className="border-subtle my-8" />
)}
<div className="space-y-3">
{isGoogleLoginEnabled && (
<Button
Expand All @@ -254,6 +259,32 @@ inferSSRProps<typeof getServerSideProps> & WithNonceProps<{}>) {
{t("signin_with_google")}
</Button>
)}
{isPasskeyLoginEnabled && (
<Button
color="secondary"
className="w-full justify-center"
disabled={formState.isSubmitting}
CustomStartIcon={<PasskeyIcon className="ltr:-ml-1 ltr:mr-2 rtl:-mr-1 rtl:ml-2" />}
onClick={async (e) => {
e.preventDefault();

const tenantId = process.env.NEXT_PUBLIC_HANKO_PASSKEYS_TENANT_ID;
if (!tenantId) {
// This should never happen, as HANKO_PASSKEYS_TENANT_ID should always be set when passkey login is enabled
// see /apps/web/server/lib/constants.ts
console.error("Hanko Passkeys tenant ID not configured");
setErrorMessage(t("passkey_login_failed"));
return;
}

await signInWithPasskey({ tenantId }).catch((err) => {
console.error("Error signing in with passkey", err);
setErrorMessage(t("passkey_login_failed"));
});
}}>
{t("signin_with_passkey")}
</Button>
)}
{displaySSOLogin && (
<SAMLLogin
samlTenantID={samlTenantID}
Expand Down