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

Add WebAuthn and Magic Links in auth-sveltekit #914

Draft
wants to merge 2 commits into
base: master
Choose a base branch
from
Draft
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
19 changes: 14 additions & 5 deletions packages/auth-sveltekit/src/client.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
import type { BuiltinOAuthProviderNames } from "@edgedb/auth-core";
import { WebAuthnClient } from "@edgedb/auth-core/webauthn";

export interface AuthOptions {
baseUrl: string;
authRoutesPath?: string;
authCookieName?: string;
pkceVerifierCookieName?: string;
passwordResetPath?: string;
magicLinkFailurePath?: string;
}

type OptionalOptions = "passwordResetPath";
type OptionalOptions = "passwordResetPath" | "magicLinkFailurePath";

export type AuthConfig = Required<Omit<AuthOptions, OptionalOptions>> &
Pick<AuthOptions, OptionalOptions> & { authRoute: string };
Expand All @@ -19,12 +21,11 @@ export function getConfig(options: AuthOptions) {
options.authRoutesPath?.replace(/^\/|\/$/g, "") ?? "auth";

return {
authCookieName: "edgedb-session",
pkceVerifierCookieName: "edgedb-pkce-verifier",
...options,
baseUrl,
authRoutesPath,
authCookieName: options.authCookieName ?? "edgedb-session",
pkceVerifierCookieName:
options.pkceVerifierCookieName ?? "edgedb-pkce-verifier",
passwordResetPath: options.passwordResetPath,
authRoute: `${baseUrl}/${authRoutesPath}`,
};
}
Expand All @@ -35,10 +36,18 @@ export default function createClientAuth(options: AuthOptions) {

export class ClientAuth {
protected readonly config: AuthConfig;
readonly webAuthnClient: WebAuthnClient;

/** @internal */
constructor(options: AuthOptions) {
this.config = getConfig(options);
this.webAuthnClient = new WebAuthnClient({
signupOptionsUrl: `${this.config.authRoute}/webauthn/signup/options`,
signupUrl: `${this.config.authRoute}/webauthn/signup`,
signinOptionsUrl: `${this.config.authRoute}/webauthn/signin/options`,
signinUrl: `${this.config.authRoute}/webauthn/signin`,
verifyUrl: `${this.config.authRoute}/webauthn/verify`,
});
}

getOAuthUrl(providerName: BuiltinOAuthProviderNames) {
Expand Down
257 changes: 231 additions & 26 deletions packages/auth-sveltekit/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ import {
InvalidDataError,
OAuthProviderFailureError,
EdgeDBAuthError,
type RegistrationResponseJSON,
type AuthenticationResponseJSON,
} from "@edgedb/auth-core";
import {
ClientAuth,
Expand Down Expand Up @@ -47,6 +49,9 @@ export interface AuthRouteHandlers {
isSignUp: boolean;
}>
) => Promise<never>;
onMagicLinkCallback?: (
params: ParamsOrError<{ tokenData: TokenData; isSignUp: boolean }>
) => Promise<never>;
onBuiltinUICallback?: (
params: ParamsOrError<
(
Expand Down Expand Up @@ -153,21 +158,12 @@ export class ServerRequestAuth extends ClientAuth {
`${this.config.authRoute}/emailpassword/verify`
);

this.cookies.set(this.config.pkceVerifierCookieName, result.verifier, {
httpOnly: true,
sameSite: "strict",
path: "/",
});
this.setVerifierCookie(result.verifier);

if (result.status === "complete") {
const tokenData = result.tokenData;

this.cookies.set(this.config.authCookieName, tokenData.auth_token, {
httpOnly: true,
sameSite: "strict",
path: "/",
});

this.setAuthTokenCookie(tokenData.auth_token);
return { tokenData };
}

Expand Down Expand Up @@ -199,11 +195,7 @@ export class ServerRequestAuth extends ClientAuth {
await this.core
).signinWithEmailPassword(email, password);

this.cookies.set(this.config.authCookieName, tokenData.auth_token, {
httpOnly: true,
sameSite: "strict",
path: "/",
});
this.setAuthTokenCookie(tokenData.auth_token);

return { tokenData };
}
Expand All @@ -224,11 +216,7 @@ export class ServerRequestAuth extends ClientAuth {
new URL(this.config.passwordResetPath, this.config.baseUrl).toString()
);

this.cookies.set(this.config.pkceVerifierCookieName, verifier, {
httpOnly: true,
sameSite: "strict",
path: "/",
});
this.setVerifierCookie(verifier);
}

async emailPasswordResetPassword(
Expand All @@ -250,20 +238,121 @@ export class ServerRequestAuth extends ClientAuth {
await this.core
).resetPasswordWithResetToken(resetToken, verifier, password);

this.cookies.set(this.config.authCookieName, tokenData.auth_token, {
this.setAuthTokenCookie(tokenData.auth_token);
this.deleteVerifierCookie();
return { tokenData };
}

async magicLinkSignUp(data: { email: string } | FormData): Promise<void> {
if (!this.config.magicLinkFailurePath) {
throw new ConfigurationError(
`'magicLinkFailurePath' option not configured`
);
}
const [email] = extractParams(data, ["email"], "email missing");

const callbackUrl = new URL("magiclink/callback", this.config.authRoute);
callbackUrl.searchParams.set("isSignUp", "true");
const errorUrl = new URL(
this.config.magicLinkFailurePath,
this.config.baseUrl
);
const { verifier } = await (
await this.core
).signupWithMagicLink(email, callbackUrl.href, errorUrl.href);

this.setVerifierCookie(verifier);
}

async magicLinkSend(data: { email: string } | FormData): Promise<void> {
if (!this.config.magicLinkFailurePath) {
throw new ConfigurationError(
`'magicLinkFailurePath' option not configured`
);
}
const [email] = extractParams(data, ["email"], "email missing");

const callbackUrl = new URL("magiclink/callback", this.config.authRoute);
const errorUrl = new URL(
this.config.magicLinkFailurePath,
this.config.baseUrl
);
const { verifier } = await (
await this.core
).signinWithMagicLink(email, callbackUrl.href, errorUrl.href);

this.setVerifierCookie(verifier);
}

async webAuthnSignUp(data: {
email: string;
credentials: RegistrationResponseJSON;
verify_url: string;
user_handle: string;
}): Promise<{ tokenData: TokenData | null }> {
const {
email,
credentials,
verify_url: verifyUrl,
user_handle: userHandle,
} = data;

const result = await (
await this.core
).signupWithWebAuthn(email, credentials, verifyUrl, userHandle);

this.setVerifierCookie(result.verifier);
if (result.status === "complete") {
this.setAuthTokenCookie(result.tokenData.auth_token);
return { tokenData: result.tokenData };
}

return { tokenData: null };
}

async webAuthnSignIn(data: {
email: string;
assertion: AuthenticationResponseJSON;
}): Promise<{ tokenData: TokenData | null }> {
const { email, assertion } = data;
const tokenData = await (
await this.core
).signinWithWebAuthn(email, assertion);

this.setAuthTokenCookie(tokenData.auth_token);
return { tokenData };
}

async signout(): Promise<void> {
this.deleteAuthTokenCookie();
}

private setVerifierCookie(verifier: string) {
this.cookies.set(this.config.pkceVerifierCookieName, verifier, {
httpOnly: true,
sameSite: "lax",
sameSite: "strict",
path: "/",
});
}

private deleteVerifierCookie() {
this.cookies.delete(this.config.pkceVerifierCookieName, {
path: "/",
});
return { tokenData };
}

async signout(): Promise<void> {
this.cookies.delete(this.config.authCookieName, { path: "/" });
private setAuthTokenCookie(authToken: string) {
this.cookies.set(this.config.authCookieName, authToken, {
httpOnly: true,
sameSite: "strict",
path: "/",
});
}

private deleteAuthTokenCookie() {
this.cookies.delete(this.config.authCookieName, {
path: "/",
});
}
}

Expand Down Expand Up @@ -328,6 +417,7 @@ async function handleAuthRoutes(
onBuiltinUICallback,
onEmailVerify,
onSignout,
onMagicLinkCallback,
}: AuthRouteHandlers,
{ url, cookies }: RequestEvent,
core: Promise<Auth>,
Expand Down Expand Up @@ -423,6 +513,61 @@ async function handleAuthRoutes(
});
}

case "magiclink/callback": {
if (!onMagicLinkCallback) {
throw new ConfigurationError(
`'onMagicLinkCallback' auth route handler not configured`
);
}

const error = searchParams.get("error");
if (error) {
const desc = searchParams.get("error_description");
return onMagicLinkCallback({
error: new EdgeDBAuthError(error + (desc ? `: ${desc}` : "")),
});
}

const code = searchParams.get("code");
if (!code) {
return onMagicLinkCallback({
error: new PKCEError("no pkce code in response"),
});
}
const isSignUp = searchParams.get("isSignUp") === "true";
const verifier = cookies.get(config.pkceVerifierCookieName);

if (!verifier) {
return onMagicLinkCallback({
error: new PKCEError("no pkce verifier cookie found"),
});
}
let tokenData: TokenData;
try {
tokenData = await (await core).getToken(code, verifier);
} catch (err) {
return onMagicLinkCallback({
error: err instanceof Error ? err : new Error(String(err)),
});
}
cookies.set(config.authCookieName, tokenData.auth_token, {
httpOnly: true,
sameSite: "strict",
path: "/",
});

cookies.set(config.pkceVerifierCookieName, "", {
maxAge: 0,
path: "/",
});

return onMagicLinkCallback({
error: null,
tokenData,
isSignUp,
});
}

case "builtin/callback": {
if (!onBuiltinUICallback) {
throw new ConfigurationError(
Expand Down Expand Up @@ -549,6 +694,66 @@ async function handleAuthRoutes(
});
}

case "webauthn/signup/options": {
const email = searchParams.get("email");
if (!email) {
throw new InvalidDataError("email missing");
}
return redirect(302, (await core).getWebAuthnSignupOptionsUrl(email));
}

case "webauthn/signin/options": {
const email = searchParams.get("email");
if (!email) {
throw new InvalidDataError("email missing");
}
return redirect(302, (await core).getWebAuthnSigninOptionsUrl(email));
}

case "webauthn/verify": {
if (!onEmailVerify) {
throw new ConfigurationError(
`'onEmailVerify' auth route handler not configured`
);
}

const verificationToken = searchParams.get("verification_token");
if (!verificationToken) {
return onEmailVerify({
error: new InvalidDataError("verification_token missing"),
});
}
const verifier = cookies.get(config.pkceVerifierCookieName);
if (!verifier) {
return onEmailVerify({
error: new PKCEError("no pkce verifier cookie found"),
verificationToken,
});
}
let tokenData: TokenData;
try {
tokenData = await (
await core
).verifyWebAuthnSignup(verificationToken, verifier);
} catch (err) {
return onEmailVerify({
error: err instanceof Error ? err : new Error(String(err)),
verificationToken,
});
}

cookies.set(config.authCookieName, tokenData.auth_token, {
httpOnly: true,
sameSite: "strict",
path: "/",
});

return onEmailVerify({
error: null,
tokenData,
});
}

case "signout": {
if (!onSignout) {
throw new ConfigurationError(
Expand Down
Loading