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 1 commit
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,31 @@ 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
# Hanko Passkeys Config
Copy link
Member

Choose a reason for hiding this comment

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

lets mention this lower in the file

Copy link
Author

Choose a reason for hiding this comment

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

yeah was unsure about that. wanted to place it below google auth stuff since i did that everywhere else, but agreed, for the env file its a little too high up

#
# 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

# 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
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;
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 @@ -41,6 +41,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 @@ -62,6 +63,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(503).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(503).json({ message: "Passkey API not configured" });
Copy link
Contributor

Choose a reason for hiding this comment

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

Is 503 the best status code to use here?

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.

Other routes use 403: https://github.com/calcom/cal.com/blob/main/apps/web/pages/api/auth/signup.ts#L23

However, MDN says

[...] 503 Service Unavailable server error response code indicates that the server is not ready to handle the request.

Common causes are a server that is down for maintenance or that is overloaded. This response should be used for temporary conditions [...]

While in my mind 403 has always been more for insufficient permissions etc

What do you think? Maybe 403 for consistency's sake?

Copy link
Contributor

Choose a reason for hiding this comment

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

I'd prefer 403 Forbidden, 503 implies a server issue but most of the time this'll be a client issue (don't access the route)

Copy link
Contributor

Choose a reason for hiding this comment

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

Don't think a 403 is correct here though because that leads the client to believe they are lacking permissions when in reality the functionality isn't supported at all due to a lack of server configuration. Would consider 501 Not Implemented or 405 Method Not Allowed instead.

Copy link
Contributor

Choose a reason for hiding this comment

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

Copy link
Author

Choose a reason for hiding this comment

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

If everyone is fine with it, will go with 501 - seems like the most appropriate IMO

}

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(503).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(503).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({});
}
24 changes: 23 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 Down Expand Up @@ -44,6 +45,7 @@
export default function Login({
csrfToken,
isGoogleLoginEnabled,
isPasskeyLoginEnabled,
isSAMLLoginEnabled,
samlTenantID,
samlProductID,
Expand Down Expand Up @@ -238,7 +240,9 @@
</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 +258,24 @@
{t("signin_with_google")}
</Button>
)}
{isPasskeyLoginEnabled && (
<Button
color="secondary"
className="w-full justify-center"
disabled={formState.isSubmitting}
StartIcon="key-round"
onClick={async (e) => {
e.preventDefault();
await signInWithPasskey({
tenantId: process.env.NEXT_PUBLIC_HANKO_PASSKEYS_TENANT_ID!,

Check warning on line 270 in apps/web/pages/auth/login.tsx

View workflow job for this annotation

GitHub Actions / ESLint Report Analysis

apps/web/pages/auth/login.tsx#L270

[@typescript-eslint/no-non-null-assertion] Forbidden non-null assertion.
PeerRich marked this conversation as resolved.
Show resolved Hide resolved
}).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