diff --git a/lib/ts/recipe/accountlinking/types.ts b/lib/ts/recipe/accountlinking/types.ts index 83aec5230..5559796c9 100644 --- a/lib/ts/recipe/accountlinking/types.ts +++ b/lib/ts/recipe/accountlinking/types.ts @@ -192,10 +192,13 @@ export type AccountInfo = { id: string; userId: string; }; + webauthn?: { + credentialIds: string[]; + }; }; export type AccountInfoWithRecipeId = { - recipeId: "emailpassword" | "thirdparty" | "passwordless"; + recipeId: "emailpassword" | "thirdparty" | "passwordless" | "webauthn"; } & AccountInfo; export type RecipeLevelUser = { diff --git a/lib/ts/recipe/multifactorauth/types.ts b/lib/ts/recipe/multifactorauth/types.ts index a7e340662..693e8e646 100644 --- a/lib/ts/recipe/multifactorauth/types.ts +++ b/lib/ts/recipe/multifactorauth/types.ts @@ -154,6 +154,7 @@ export type GetPhoneNumbersForFactorsFromOtherRecipesFunc = ( export const FactorIds = { EMAILPASSWORD: "emailpassword", + WEBAUTHN: "webauthn", OTP_EMAIL: "otp-email", OTP_PHONE: "otp-phone", LINK_EMAIL: "link-email", diff --git a/lib/ts/recipe/multitenancy/types.ts b/lib/ts/recipe/multitenancy/types.ts index 3dfb26a7a..e0d56dff3 100644 --- a/lib/ts/recipe/multitenancy/types.ts +++ b/lib/ts/recipe/multitenancy/types.ts @@ -173,6 +173,9 @@ export type APIInterface = { passwordless: { enabled: boolean; }; + webauthn: { + credentialIds: string[]; + }; firstFactors: string[]; } | GeneralErrorResponse diff --git a/lib/ts/recipe/webauthn/api/implementation.ts b/lib/ts/recipe/webauthn/api/implementation.ts new file mode 100644 index 000000000..2408114ff --- /dev/null +++ b/lib/ts/recipe/webauthn/api/implementation.ts @@ -0,0 +1,1059 @@ +import { APIInterface, APIOptions } from ".."; +import { GeneralErrorResponse, User, UserContext } from "../../../types"; +import AccountLinking from "../../accountlinking/recipe"; +import { AuthUtils } from "../../../authUtils"; +import { isFakeEmail } from "../../thirdparty/utils"; +import { SessionContainerInterface } from "../../session/types"; +import { + DEFAULT_REGISTER_ATTESTATION, + DEFAULT_REGISTER_OPTIONS_TIMEOUT, + DEFAULT_SIGNIN_OPTIONS_TIMEOUT, +} from "../constants"; + +export default function getAPIImplementation(): APIInterface { + return { + signInOptionsPOST: async function ({ + tenantId, + options, + userContext, + }: { + tenantId: string; + options: APIOptions; + userContext: UserContext; + }): Promise< + | { + status: "OK"; + webauthnGeneratedOptionsId: string; + challenge: string; + timeout: number; + userVerification: "required" | "preferred" | "discouraged"; + } + | GeneralErrorResponse + > { + // todo move to recipe implementation + const timeout = DEFAULT_SIGNIN_OPTIONS_TIMEOUT; + + const relyingPartyId = options.config.relyingPartyId({ request: options.req, userContext: userContext }); + + // use this to get the full url instead of only the domain url + const origin = options.appInfo + .getOrigin({ request: options.req, userContext: userContext }) + .getAsStringDangerous(); + + let response = await options.recipeImplementation.signInOptions({ + origin, + relyingPartyId, + timeout, + tenantId, + userContext, + }); + + return { + status: "OK", + webauthnGeneratedOptionsId: response.webauthnGeneratedOptionsId, + challenge: response.challenge, + timeout: response.timeout, + userVerification: response.userVerification, + }; + }, + registerOptionsPOST: async function ({ + email, + tenantId, + options, + userContext, + }: { + email: string; + tenantId: string; + options: APIOptions; + userContext: UserContext; + }): Promise< + | { + status: "OK"; + webauthnGeneratedOptionsId: string; + rp: { + id: string; + name: string; + }; + user: { + id: string; + name: string; + displayName: string; + }; + challenge: string; + timeout: number; + excludeCredentials: { + id: string; + type: string; + transports: ("ble" | "hybrid" | "internal" | "nfc" | "usb")[]; + }[]; + attestation: "none" | "indirect" | "direct" | "enterprise"; + pubKeyCredParams: { + alg: number; + type: string; + }[]; + authenticatorSelection: { + requireResidentKey: boolean; + residentKey: "required" | "preferred" | "discouraged"; + userVerification: "required" | "preferred" | "discouraged"; + }; + } + | GeneralErrorResponse + > { + // todo move to recipe implementation + const timeout = DEFAULT_REGISTER_OPTIONS_TIMEOUT; + // todo move to recipe implementation + const attestation = DEFAULT_REGISTER_ATTESTATION; + + const relyingPartyId = options.config.relyingPartyId({ request: options.req, userContext: userContext }); + const relyingPartyName = options.config.relyingPartyName({ + request: options.req, + userContext: userContext, + }); + + const origin = options.appInfo + .getOrigin({ request: options.req, userContext: userContext }) + .getAsStringDangerous(); + + let response = await options.recipeImplementation.registerOptions({ + email, + attestation, + origin, + relyingPartyId, + relyingPartyName, + timeout, + tenantId, + userContext, + }); + + return { + status: "OK", + webauthnGeneratedOptionsId: response.webauthnGeneratedOptionsId, + challenge: response.challenge, + timeout: response.timeout, + attestation: response.attestation, + pubKeyCredParams: response.pubKeyCredParams, + excludeCredentials: response.excludeCredentials, + rp: response.rp, + user: response.user, + authenticatorSelection: response.authenticatorSelection, + }; + }, + signUpPOST: async function ({ + email, + webauthnGeneratedOptionsId, + credential, + tenantId, + session, + shouldTryLinkingWithSessionUser, + options, + userContext, + }: { + email: string; + webauthnGeneratedOptionsId: string; + credential: { + id: string; + rawId: string; + response: { + clientDataJSON: string; + attestationObject: string; + transports?: ("ble" | "cable" | "hybrid" | "internal" | "nfc" | "smart-card" | "usb")[]; + userHandle: string; + }; + authenticatorAttachment: "platform" | "cross-platform"; + clientExtensionResults: Record; + type: "public-key"; + }; + tenantId: string; + session?: SessionContainerInterface; + shouldTryLinkingWithSessionUser: boolean | undefined; + options: APIOptions; + userContext: UserContext; + }): Promise< + | { + status: "OK"; + session: SessionContainerInterface; + user: User; + } + | { + status: "SIGN_UP_NOT_ALLOWED"; + reason: string; + } + | { + status: "EMAIL_ALREADY_EXISTS_ERROR"; + } + | GeneralErrorResponse + > { + const errorCodeMap = { + SIGN_UP_NOT_ALLOWED: + "Cannot sign up due to security reasons. Please try logging in, use a different login method or contact support. (ERR_CODE_007)", + LINKING_TO_SESSION_USER_FAILED: { + EMAIL_VERIFICATION_REQUIRED: + "Cannot sign in / up due to security reasons. Please contact support. (ERR_CODE_013)", + RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR: + "Cannot sign in / up due to security reasons. Please contact support. (ERR_CODE_014)", + ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR: + "Cannot sign in / up due to security reasons. Please contact support. (ERR_CODE_015)", + SESSION_USER_ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR: + "Cannot sign in / up due to security reasons. Please contact support. (ERR_CODE_016)", + }, + }; + + // NOTE: Following checks will likely never throw an error as the + // check for type is done in a parent function but they are kept + // here to be on the safe side. + if (typeof email !== "string") + throw new Error( + "Should never come here since we already check that the email value is a string in validateFormFieldsOrThrowError" + ); + + const preAuthCheckRes = await AuthUtils.preAuthChecks({ + authenticatingAccountInfo: { + recipeId: "webauthn", + email, + }, + factorIds: ["webauthn"], + isSignUp: true, + isVerified: isFakeEmail(email), + signInVerifiesLoginMethod: false, + skipSessionUserUpdateInCore: false, + authenticatingUser: undefined, // since this a sign up, this is undefined + tenantId, + userContext, + session, + shouldTryLinkingWithSessionUser, + }); + + if (preAuthCheckRes.status === "SIGN_UP_NOT_ALLOWED") { + const conflictingUsers = await AccountLinking.getInstance().recipeInterfaceImpl.listUsersByAccountInfo({ + tenantId, + accountInfo: { + email, + }, + doUnionOfAccountInfo: false, + userContext, + }); + if ( + conflictingUsers.some((u) => + u.loginMethods.some((lm) => lm.recipeId === "webauthn" && lm.hasSameEmailAs(email)) + ) + ) { + return { + status: "EMAIL_ALREADY_EXISTS_ERROR", + }; + } + } + if (preAuthCheckRes.status !== "OK") { + return AuthUtils.getErrorStatusResponseWithReason(preAuthCheckRes, errorCodeMap, "SIGN_UP_NOT_ALLOWED"); + } + + if (isFakeEmail(email) && preAuthCheckRes.isFirstFactor) { + // Fake emails cannot be used as a first factor + return { + status: "EMAIL_ALREADY_EXISTS_ERROR", + }; + } + + // we are using the email from the register options + const signUpResponse = await options.recipeImplementation.signUp({ + webauthnGeneratedOptionsId, + credential, + tenantId, + session, + shouldTryLinkingWithSessionUser, + userContext, + }); + + if (signUpResponse.status === "EMAIL_ALREADY_EXISTS_ERROR") { + return signUpResponse; + } + if (signUpResponse.status !== "OK") { + return AuthUtils.getErrorStatusResponseWithReason(signUpResponse, errorCodeMap, "SIGN_UP_NOT_ALLOWED"); + } + + const postAuthChecks = await AuthUtils.postAuthChecks({ + authenticatedUser: signUpResponse.user, + recipeUserId: signUpResponse.recipeUserId, + isSignUp: true, + factorId: "emailpassword", + session, + req: options.req, + res: options.res, + tenantId, + userContext, + }); + + if (postAuthChecks.status !== "OK") { + // It should never actually come here, but we do it cause of consistency. + // If it does come here (in case there is a bug), it would make this func throw + // anyway, cause there is no SIGN_IN_NOT_ALLOWED in the errorCodeMap. + AuthUtils.getErrorStatusResponseWithReason(postAuthChecks, errorCodeMap, "SIGN_UP_NOT_ALLOWED"); + throw new Error("This should never happen"); + } + + return { + status: "OK", + session: postAuthChecks.session, + user: postAuthChecks.user, + }; + }, + + signInPOST: async function ({ + webauthnGeneratedOptionsId, + credential, + tenantId, + session, + shouldTryLinkingWithSessionUser, + options, + userContext, + }: { + webauthnGeneratedOptionsId: string; + credential: { + id: string; + rawId: string; + response: { + clientDataJSON: string; + attestationObject: string; + transports?: ("ble" | "cable" | "hybrid" | "internal" | "nfc" | "smart-card" | "usb")[]; + userHandle: string; + }; + authenticatorAttachment: "platform" | "cross-platform"; + clientExtensionResults: Record; + type: "public-key"; + }; + tenantId: string; + session?: SessionContainerInterface; + shouldTryLinkingWithSessionUser: boolean | undefined; + options: APIOptions; + userContext: UserContext; + }): Promise< + | { + status: "OK"; + session: SessionContainerInterface; + user: User; + } + | { + status: "WRONG_CREDENTIALS_ERROR"; + } + | { + status: "SIGN_IN_NOT_ALLOWED"; + reason: string; + } + | GeneralErrorResponse + > { + const errorCodeMap = { + SIGN_IN_NOT_ALLOWED: + "Cannot sign in due to security reasons. Please try resetting your password, use a different login method or contact support. (ERR_CODE_008)", + LINKING_TO_SESSION_USER_FAILED: { + EMAIL_VERIFICATION_REQUIRED: + "Cannot sign in / up due to security reasons. Please contact support. (ERR_CODE_009)", + RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR: + "Cannot sign in / up due to security reasons. Please contact support. (ERR_CODE_010)", + ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR: + "Cannot sign in / up due to security reasons. Please contact support. (ERR_CODE_011)", + SESSION_USER_ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR: + "Cannot sign in / up due to security reasons. Please contact support. (ERR_CODE_012)", + }, + }; + + const recipeId = "webauthn"; + + // do the verification before in order to retrieve the user email + const verifyCredentialsResponse = await options.recipeImplementation.verifyCredentials({ + credential, + webauthnGeneratedOptionsId, + tenantId, + userContext, + }); + const checkCredentialsOnTenant = async () => { + return verifyCredentialsResponse.status === "OK"; + }; + + // todo check if this is the correct way to retrieve the email + let email: string; + if (verifyCredentialsResponse.status == "OK") { + email = verifyCredentialsResponse.user.emails[0]; + } else { + return { + status: "WRONG_CREDENTIALS_ERROR", + }; + } + + const authenticatingUser = await AuthUtils.getAuthenticatingUserAndAddToCurrentTenantIfRequired({ + accountInfo: { email }, + userContext, + recipeId, + session, + tenantId, + checkCredentialsOnTenant, + }); + + const isVerified = authenticatingUser !== undefined && authenticatingUser.loginMethod!.verified; + // We check this before preAuthChecks, because that function assumes that if isSignUp is false, + // then authenticatingUser is defined. While it wouldn't technically cause any problems with + // the implementation of that function, this way we can guarantee that either isSignInAllowed or + // isSignUpAllowed will be called as expected. + if (authenticatingUser === undefined) { + return { + status: "WRONG_CREDENTIALS_ERROR", + }; + } + const preAuthChecks = await AuthUtils.preAuthChecks({ + authenticatingAccountInfo: { + recipeId, + email, + }, + factorIds: ["webauthn"], + isSignUp: false, + authenticatingUser: authenticatingUser?.user, + isVerified, + signInVerifiesLoginMethod: false, + skipSessionUserUpdateInCore: false, + tenantId, + userContext, + session, + shouldTryLinkingWithSessionUser, + }); + if (preAuthChecks.status === "SIGN_UP_NOT_ALLOWED") { + throw new Error("This should never happen: pre-auth checks should not fail for sign in"); + } + if (preAuthChecks.status !== "OK") { + return AuthUtils.getErrorStatusResponseWithReason(preAuthChecks, errorCodeMap, "SIGN_IN_NOT_ALLOWED"); + } + + if (isFakeEmail(email) && preAuthChecks.isFirstFactor) { + // Fake emails cannot be used as a first factor + return { + status: "WRONG_CREDENTIALS_ERROR", + }; + } + + const signInResponse = await options.recipeImplementation.signIn({ + webauthnGeneratedOptionsId, + credential, + session, + shouldTryLinkingWithSessionUser, + tenantId, + userContext, + }); + + if (signInResponse.status === "WRONG_CREDENTIALS_ERROR") { + return signInResponse; + } + if (signInResponse.status !== "OK") { + return AuthUtils.getErrorStatusResponseWithReason(signInResponse, errorCodeMap, "SIGN_IN_NOT_ALLOWED"); + } + + const postAuthChecks = await AuthUtils.postAuthChecks({ + authenticatedUser: signInResponse.user, + recipeUserId: signInResponse.recipeUserId, + isSignUp: false, + factorId: "webauthn", + session, + req: options.req, + res: options.res, + tenantId, + userContext, + }); + + if (postAuthChecks.status !== "OK") { + return AuthUtils.getErrorStatusResponseWithReason(postAuthChecks, errorCodeMap, "SIGN_IN_NOT_ALLOWED"); + } + + return { + status: "OK", + session: postAuthChecks.session, + user: postAuthChecks.user, + }; + }, + + // emailExistsGET: async function ({ + // email, + // tenantId, + // userContext, + // }: { + // email: string; + // tenantId: string; + // options: APIOptions; + // userContext: UserContext; + // }): Promise< + // | { + // status: "OK"; + // exists: boolean; + // } + // | GeneralErrorResponse + // > { + // // even if the above returns true, we still need to check if there + // // exists an email password user with the same email cause the function + // // above does not check for that. + // let users = await AccountLinking.getInstance().recipeInterfaceImpl.listUsersByAccountInfo({ + // tenantId, + // accountInfo: { + // email, + // }, + // doUnionOfAccountInfo: false, + // userContext, + // }); + // let emailPasswordUserExists = + // users.find((u) => { + // return ( + // u.loginMethods.find((lm) => lm.recipeId === "emailpassword" && lm.hasSameEmailAs(email)) !== + // undefined + // ); + // }) !== undefined; + + // return { + // status: "OK", + // exists: emailPasswordUserExists, + // }; + // }, + // generatePasswordResetTokenPOST: async function ({ + // formFields, + // tenantId, + // options, + // userContext, + // }): Promise< + // | { + // status: "OK"; + // } + // | { status: "PASSWORD_RESET_NOT_ALLOWED"; reason: string } + // | GeneralErrorResponse + // > { + // // NOTE: Check for email being a non-string value. This check will likely + // // never evaluate to `true` as there is an upper-level check for the type + // // in validation but kept here to be safe. + // const emailAsUnknown = formFields.filter((f) => f.id === "email")[0].value; + // if (typeof emailAsUnknown !== "string") + // throw new Error( + // "Should never come here since we already check that the email value is a string in validateFormFieldsOrThrowError" + // ); + // const email: string = emailAsUnknown; + + // // this function will be reused in different parts of the flow below.. + // async function generateAndSendPasswordResetToken( + // primaryUserId: string, + // recipeUserId: RecipeUserId | undefined + // ): Promise< + // | { + // status: "OK"; + // } + // | { status: "PASSWORD_RESET_NOT_ALLOWED"; reason: string } + // | GeneralErrorResponse + // > { + // // the user ID here can be primary or recipe level. + // let response = await options.recipeImplementation.createResetPasswordToken({ + // tenantId, + // userId: recipeUserId === undefined ? primaryUserId : recipeUserId.getAsString(), + // email, + // userContext, + // }); + // if (response.status === "UNKNOWN_USER_ID_ERROR") { + // logDebugMessage( + // `Password reset email not sent, unknown user id: ${ + // recipeUserId === undefined ? primaryUserId : recipeUserId.getAsString() + // }` + // ); + // return { + // status: "OK", + // }; + // } + + // let passwordResetLink = getPasswordResetLink({ + // appInfo: options.appInfo, + // token: response.token, + // tenantId, + // request: options.req, + // userContext, + // }); + + // logDebugMessage(`Sending password reset email to ${email}`); + // await options.emailDelivery.ingredientInterfaceImpl.sendEmail({ + // tenantId, + // type: "PASSWORD_RESET", + // user: { + // id: primaryUserId, + // recipeUserId, + // email, + // }, + // passwordResetLink, + // userContext, + // }); + + // return { + // status: "OK", + // }; + // } + + // /** + // * check if primaryUserId is linked with this email + // */ + // let users = await AccountLinking.getInstance().recipeInterfaceImpl.listUsersByAccountInfo({ + // tenantId, + // accountInfo: { + // email, + // }, + // doUnionOfAccountInfo: false, + // userContext, + // }); + + // // we find the recipe user ID of the email password account from the user's list + // // for later use. + // let emailPasswordAccount: RecipeLevelUser | undefined = undefined; + // for (let i = 0; i < users.length; i++) { + // let emailPasswordAccountTmp = users[i].loginMethods.find( + // (l) => l.recipeId === "emailpassword" && l.hasSameEmailAs(email) + // ); + // if (emailPasswordAccountTmp !== undefined) { + // emailPasswordAccount = emailPasswordAccountTmp; + // break; + // } + // } + + // // we find the primary user ID from the user's list for later use. + // let primaryUserAssociatedWithEmail = users.find((u) => u.isPrimaryUser); + + // // first we check if there even exists a primary user that has the input email + // // if not, then we do the regular flow for password reset. + // if (primaryUserAssociatedWithEmail === undefined) { + // if (emailPasswordAccount === undefined) { + // logDebugMessage(`Password reset email not sent, unknown user email: ${email}`); + // return { + // status: "OK", + // }; + // } + // return await generateAndSendPasswordResetToken( + // emailPasswordAccount.recipeUserId.getAsString(), + // emailPasswordAccount.recipeUserId + // ); + // } + + // // Next we check if there is any login method in which the input email is verified. + // // If that is the case, then it's proven that the user owns the email and we can + // // trust linking of the email password account. + // let emailVerified = + // primaryUserAssociatedWithEmail.loginMethods.find((lm) => { + // return lm.hasSameEmailAs(email) && lm.verified; + // }) !== undefined; + + // // finally, we check if the primary user has any other email / phone number + // // associated with this account - and if it does, then it means that + // // there is a risk of account takeover, so we do not allow the token to be generated + // let hasOtherEmailOrPhone = + // primaryUserAssociatedWithEmail.loginMethods.find((lm) => { + // // we do the extra undefined check below cause + // // hasSameEmailAs returns false if the lm.email is undefined, and + // // we want to check that the email is different as opposed to email + // // not existing in lm. + // return (lm.email !== undefined && !lm.hasSameEmailAs(email)) || lm.phoneNumber !== undefined; + // }) !== undefined; + + // if (!emailVerified && hasOtherEmailOrPhone) { + // return { + // status: "PASSWORD_RESET_NOT_ALLOWED", + // reason: + // "Reset password link was not created because of account take over risk. Please contact support. (ERR_CODE_001)", + // }; + // } + + // let shouldDoAccountLinkingResponse = await AccountLinking.getInstance().config.shouldDoAutomaticAccountLinking( + // emailPasswordAccount !== undefined + // ? emailPasswordAccount + // : { + // recipeId: "emailpassword", + // email, + // }, + // primaryUserAssociatedWithEmail, + // undefined, + // tenantId, + // userContext + // ); + + // // Now we need to check that if there exists any email password user at all + // // for the input email. If not, then it implies that when the token is consumed, + // // then we will create a new user - so we should only generate the token if + // // the criteria for the new user is met. + // if (emailPasswordAccount === undefined) { + // // this means that there is no email password user that exists for the input email. + // // So we check for the sign up condition and only go ahead if that condition is + // // met. + + // // But first we must check if account linking is enabled at all - cause if it's + // // not, then the new email password user that will be created in password reset + // // code consume cannot be linked to the primary user - therefore, we should + // // not generate a password reset token + // if (!shouldDoAccountLinkingResponse.shouldAutomaticallyLink) { + // logDebugMessage( + // `Password reset email not sent, since email password user didn't exist, and account linking not enabled` + // ); + // return { + // status: "OK", + // }; + // } + + // let isSignUpAllowed = await AccountLinking.getInstance().isSignUpAllowed({ + // newUser: { + // recipeId: "emailpassword", + // email, + // }, + // isVerified: true, // cause when the token is consumed, we will mark the email as verified + // session: undefined, + // tenantId, + // userContext, + // }); + // if (isSignUpAllowed) { + // // notice that we pass in the primary user ID here. This means that + // // we will be creating a new email password account when the token + // // is consumed and linking it to this primary user. + // return await generateAndSendPasswordResetToken(primaryUserAssociatedWithEmail.id, undefined); + // } else { + // logDebugMessage( + // `Password reset email not sent, isSignUpAllowed returned false for email: ${email}` + // ); + // return { + // status: "OK", + // }; + // } + // } + + // // At this point, we know that some email password user exists with this email + // // and also some primary user ID exist. We now need to find out if they are linked + // // together or not. If they are linked together, then we can just generate the token + // // else we check for more security conditions (since we will be linking them post token generation) + // let areTheTwoAccountsLinked = + // primaryUserAssociatedWithEmail.loginMethods.find((lm) => { + // return lm.recipeUserId.getAsString() === emailPasswordAccount!.recipeUserId.getAsString(); + // }) !== undefined; + + // if (areTheTwoAccountsLinked) { + // return await generateAndSendPasswordResetToken( + // primaryUserAssociatedWithEmail.id, + // emailPasswordAccount.recipeUserId + // ); + // } + + // // Here we know that the two accounts are NOT linked. We now need to check for an + // // extra security measure here to make sure that the input email in the primary user + // // is verified, and if not, we need to make sure that there is no other email / phone number + // // associated with the primary user account. If there is, then we do not proceed. + + // /* + // This security measure helps prevent the following attack: + // An attacker has email A and they create an account using TP and it doesn't matter if A is verified or not. Now they create another account using EP with email A and verifies it. Both these accounts are linked. Now the attacker changes the email for EP recipe to B which makes the EP account unverified, but it's still linked. + + // If the real owner of B tries to signup using EP, it will say that the account already exists so they may try to reset password which should be denied because then they will end up getting access to attacker's account and verify the EP account. + + // The problem with this situation is if the EP account is verified, it will allow further sign-ups with email B which will also be linked to this primary account (that the attacker had created with email A). + + // It is important to realize that the attacker had created another account with A because if they hadn't done that, then they wouldn't have access to this account after the real user resets the password which is why it is important to check there is another non-EP account linked to the primary such that the email is not the same as B. + + // Exception to the above is that, if there is a third recipe account linked to the above two accounts and has B as verified, then we should allow reset password token generation because user has already proven that the owns the email B + // */ + + // // But first, this only matters it the user cares about checking for email verification status.. + + // if (!shouldDoAccountLinkingResponse.shouldAutomaticallyLink) { + // // here we will go ahead with the token generation cause + // // even when the token is consumed, we will not be linking the accounts + // // so no need to check for anything + // return await generateAndSendPasswordResetToken( + // emailPasswordAccount.recipeUserId.getAsString(), + // emailPasswordAccount.recipeUserId + // ); + // } + + // if (!shouldDoAccountLinkingResponse.shouldRequireVerification) { + // // the checks below are related to email verification, and if the user + // // does not care about that, then we should just continue with token generation + // return await generateAndSendPasswordResetToken( + // primaryUserAssociatedWithEmail.id, + // emailPasswordAccount.recipeUserId + // ); + // } + + // return await generateAndSendPasswordResetToken( + // primaryUserAssociatedWithEmail.id, + // emailPasswordAccount.recipeUserId + // ); + // }, + // passwordResetPOST: async function ({ + // formFields, + // token, + // tenantId, + // options, + // userContext, + // }: { + // formFields: { + // id: string; + // value: unknown; + // }[]; + // token: string; + // tenantId: string; + // options: APIOptions; + // userContext: UserContext; + // }): Promise< + // | { + // status: "OK"; + // user: User; + // email: string; + // } + // | { status: "RESET_PASSWORD_INVALID_TOKEN_ERROR" } + // | { status: "PASSWORD_POLICY_VIOLATED_ERROR"; failureReason: string } + // | GeneralErrorResponse + // > { + // async function markEmailAsVerified(recipeUserId: RecipeUserId, email: string) { + // const emailVerificationInstance = EmailVerification.getInstance(); + // if (emailVerificationInstance) { + // const tokenResponse = await emailVerificationInstance.recipeInterfaceImpl.createEmailVerificationToken( + // { + // tenantId, + // recipeUserId, + // email, + // userContext, + // } + // ); + + // if (tokenResponse.status === "OK") { + // await emailVerificationInstance.recipeInterfaceImpl.verifyEmailUsingToken({ + // tenantId, + // token: tokenResponse.token, + // attemptAccountLinking: false, // we pass false here cause + // // we anyway do account linking in this API after this function is + // // called. + // userContext, + // }); + // } + // } + // } + + // async function doUpdatePasswordAndVerifyEmailAndTryLinkIfNotPrimary( + // recipeUserId: RecipeUserId + // ): Promise< + // | { + // status: "OK"; + // user: User; + // email: string; + // } + // | { status: "RESET_PASSWORD_INVALID_TOKEN_ERROR" } + // | { status: "PASSWORD_POLICY_VIOLATED_ERROR"; failureReason: string } + // | GeneralErrorResponse + // > { + // let updateResponse = await options.recipeImplementation.updateEmailOrPassword({ + // tenantIdForPasswordPolicy: tenantId, + // // we can treat userIdForWhomTokenWasGenerated as a recipe user id cause + // // whenever this function is called, + // recipeUserId, + // password: newPassword, + // userContext, + // }); + // if ( + // updateResponse.status === "EMAIL_ALREADY_EXISTS_ERROR" || + // updateResponse.status === "EMAIL_CHANGE_NOT_ALLOWED_ERROR" + // ) { + // throw new Error("This should never come here because we are not updating the email"); + // } else if (updateResponse.status === "UNKNOWN_USER_ID_ERROR") { + // // This should happen only cause of a race condition where the user + // // might be deleted before token creation and consumption. + // return { + // status: "RESET_PASSWORD_INVALID_TOKEN_ERROR", + // }; + // } else if (updateResponse.status === "PASSWORD_POLICY_VIOLATED_ERROR") { + // return { + // status: "PASSWORD_POLICY_VIOLATED_ERROR", + // failureReason: updateResponse.failureReason, + // }; + // } else { + // // status: "OK" + + // // If the update was successful, we try to mark the email as verified. + // // We do this because we assume that the password reset token was delivered by email (and to the appropriate email address) + // // so consuming it means that the user actually has access to the emails we send. + + // // We only do this if the password update was successful, otherwise the following scenario is possible: + // // 1. User M: signs up using the email of user V with their own password. They can't validate the email, because it is not their own. + // // 2. User A: tries signing up but sees the email already exists message + // // 3. User A: resets their password, but somehow this fails (e.g.: password policy issue) + // // If we verified (and linked) the existing user with the original password, User M would get access to the current user and any linked users. + // await markEmailAsVerified(recipeUserId, emailForWhomTokenWasGenerated); + // // We refresh the user information here, because the verification status may be updated, which is used during linking. + // const updatedUserAfterEmailVerification = await getUser(recipeUserId.getAsString(), userContext); + // if (updatedUserAfterEmailVerification === undefined) { + // throw new Error("Should never happen - user deleted after during password reset"); + // } + + // if (updatedUserAfterEmailVerification.isPrimaryUser) { + // // If the user is already primary, we do not need to do any linking + // return { + // status: "OK", + // email: emailForWhomTokenWasGenerated, + // user: updatedUserAfterEmailVerification, + // }; + // } + + // // If the user was not primary: + + // // Now we try and link the accounts. + // // The function below will try and also create a primary user of the new account, this can happen if: + // // 1. the user was unverified and linking requires verification + // // We do not take try linking by session here, since this is supposed to be called without a session + // // Still, the session object is passed around because it is a required input for shouldDoAutomaticAccountLinking + // const linkRes = await AccountLinking.getInstance().tryLinkingByAccountInfoOrCreatePrimaryUser({ + // tenantId, + // inputUser: updatedUserAfterEmailVerification, + // session: undefined, + // userContext, + // }); + // const userAfterWeTriedLinking = + // linkRes.status === "OK" ? linkRes.user : updatedUserAfterEmailVerification; + + // return { + // status: "OK", + // email: emailForWhomTokenWasGenerated, + // user: userAfterWeTriedLinking, + // }; + // } + // } + + // // NOTE: Check for password being a non-string value. This check will likely + // // never evaluate to `true` as there is an upper-level check for the type + // // in validation but kept here to be safe. + // const newPasswordAsUnknown = formFields.filter((f) => f.id === "password")[0].value; + // if (typeof newPasswordAsUnknown !== "string") + // throw new Error( + // "Should never come here since we already check that the password value is a string in validateFormFieldsOrThrowError" + // ); + // let newPassword: string = newPasswordAsUnknown; + + // let tokenConsumptionResponse = await options.recipeImplementation.consumePasswordResetToken({ + // token, + // tenantId, + // userContext, + // }); + + // if (tokenConsumptionResponse.status === "RESET_PASSWORD_INVALID_TOKEN_ERROR") { + // return tokenConsumptionResponse; + // } + + // let userIdForWhomTokenWasGenerated = tokenConsumptionResponse.userId; + // let emailForWhomTokenWasGenerated = tokenConsumptionResponse.email; + + // let existingUser = await getUser(tokenConsumptionResponse.userId, userContext); + + // if (existingUser === undefined) { + // // This should happen only cause of a race condition where the user + // // might be deleted before token creation and consumption. + // // Also note that this being undefined doesn't mean that the email password + // // user does not exist, but it means that there is no recipe or primary user + // // for whom the token was generated. + // return { + // status: "RESET_PASSWORD_INVALID_TOKEN_ERROR", + // }; + // } + + // // We start by checking if the existingUser is a primary user or not. If it is, + // // then we will try and create a new email password user and link it to the primary user (if required) + + // if (existingUser.isPrimaryUser) { + // // If this user contains an email password account for whom the token was generated, + // // then we update that user's password. + // let emailPasswordUserIsLinkedToExistingUser = + // existingUser.loginMethods.find((lm) => { + // // we check based on user ID and not email because the only time + // // the primary user ID is used for token generation is if the email password + // // user did not exist - in which case the value of emailPasswordUserExists will + // // resolve to false anyway, and that's what we want. + + // // there is an edge case where if the email password recipe user was created + // // after the password reset token generation, and it was linked to the + // // primary user id (userIdForWhomTokenWasGenerated), in this case, + // // we still don't allow password update, cause the user should try again + // // and the token should be regenerated for the right recipe user. + // return ( + // lm.recipeUserId.getAsString() === userIdForWhomTokenWasGenerated && + // lm.recipeId === "emailpassword" + // ); + // }) !== undefined; + + // if (emailPasswordUserIsLinkedToExistingUser) { + // return doUpdatePasswordAndVerifyEmailAndTryLinkIfNotPrimary( + // new RecipeUserId(userIdForWhomTokenWasGenerated) + // ); + // } else { + // // this means that the existingUser does not have an emailpassword user associated + // // with it. It could now mean that no emailpassword user exists, or it could mean that + // // the the ep user exists, but it's not linked to the current account. + // // If no ep user doesn't exists, we will create one, and link it to the existing account. + // // If ep user exists, then it means there is some race condition cause + // // then the token should have been generated for that user instead of the primary user, + // // and it shouldn't have come into this branch. So we can simply send a password reset + // // invalid error and the user can try again. + + // // NOTE: We do not ask the dev if we should do account linking or not here + // // cause we already have asked them this when generating an password reset token. + // // In the edge case that the dev changes account linking allowance from true to false + // // when it comes here, only a new recipe user id will be created and not linked + // // cause createPrimaryUserIdOrLinkAccounts will disallow linking. This doesn't + // // really cause any security issue. + + // let createUserResponse = await options.recipeImplementation.createNewRecipeUser({ + // tenantId, + // email: tokenConsumptionResponse.email, + // password: newPassword, + // userContext, + // }); + // if (createUserResponse.status === "EMAIL_ALREADY_EXISTS_ERROR") { + // // this means that the user already existed and we can just return an invalid + // // token (see the above comment) + // return { + // status: "RESET_PASSWORD_INVALID_TOKEN_ERROR", + // }; + // } else { + // // we mark the email as verified because password reset also requires + // // access to the email to work.. This has a good side effect that + // // any other login method with the same email in existingAccount will also get marked + // // as verified. + // await markEmailAsVerified( + // createUserResponse.user.loginMethods[0].recipeUserId, + // tokenConsumptionResponse.email + // ); + // const updatedUser = await getUser(createUserResponse.user.id, userContext); + // if (updatedUser === undefined) { + // throw new Error("Should never happen - user deleted after during password reset"); + // } + // createUserResponse.user = updatedUser; + // // Now we try and link the accounts. The function below will try and also + // // create a primary user of the new account, and if it does that, it's OK.. + // // But in most cases, it will end up linking to existing account since the + // // email is shared. + // // We do not take try linking by session here, since this is supposed to be called without a session + // // Still, the session object is passed around because it is a required input for shouldDoAutomaticAccountLinking + // const linkRes = await AccountLinking.getInstance().tryLinkingByAccountInfoOrCreatePrimaryUser({ + // tenantId, + // inputUser: createUserResponse.user, + // session: undefined, + // userContext, + // }); + // const userAfterLinking = linkRes.status === "OK" ? linkRes.user : createUserResponse.user; + // if (linkRes.status === "OK" && linkRes.user.id !== existingUser.id) { + // // this means that the account we just linked to + // // was not the one we had expected to link it to. This can happen + // // due to some race condition or the other.. Either way, this + // // is not an issue and we can just return OK + // } + // return { + // status: "OK", + // email: tokenConsumptionResponse.email, + // user: userAfterLinking, + // }; + // } + // } + // } else { + // // This means that the existing user is not a primary account, which implies that + // // it must be a non linked email password account. In this case, we simply update the password. + // // Linking to an existing account will be done after the user goes through the email + // // verification flow once they log in (if applicable). + // return doUpdatePasswordAndVerifyEmailAndTryLinkIfNotPrimary( + // new RecipeUserId(userIdForWhomTokenWasGenerated) + // ); + // } + // }, + }; +} diff --git a/lib/ts/recipe/webauthn/api/registerOptions.ts b/lib/ts/recipe/webauthn/api/registerOptions.ts new file mode 100644 index 000000000..74d309a48 --- /dev/null +++ b/lib/ts/recipe/webauthn/api/registerOptions.ts @@ -0,0 +1,50 @@ +/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. + * + * This software is licensed under the Apache License, Version 2.0 (the + * "License") as published by the Apache Software Foundation. + * + * You may not use this file except in compliance with the License. You may + * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ + +import { send200Response } from "../../../utils"; +import STError from "../error"; +import { APIInterface, APIOptions } from ".."; +import { UserContext } from "../../../types"; + +export default async function registerOptions( + apiImplementation: APIInterface, + tenantId: string, + options: APIOptions, + userContext: UserContext +): Promise { + if (apiImplementation.registerOptionsPOST === undefined) { + return false; + } + + const requestBody = await options.req.getJSONBody(); + + let email = requestBody.email; + if (email === undefined || typeof email !== "string") { + throw new STError({ + type: STError.BAD_INPUT_ERROR, + message: "Please provide the email", + }); + } + + let result = await apiImplementation.registerOptionsPOST({ + email, + tenantId, + options, + userContext, + }); + + send200Response(options.res, result); + return true; +} diff --git a/lib/ts/recipe/webauthn/api/signInOptions.ts b/lib/ts/recipe/webauthn/api/signInOptions.ts new file mode 100644 index 000000000..2e2736aa5 --- /dev/null +++ b/lib/ts/recipe/webauthn/api/signInOptions.ts @@ -0,0 +1,38 @@ +/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. + * + * This software is licensed under the Apache License, Version 2.0 (the + * "License") as published by the Apache Software Foundation. + * + * You may not use this file except in compliance with the License. You may + * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ + +import { send200Response } from "../../../utils"; +import { APIInterface, APIOptions } from ".."; +import { UserContext } from "../../../types"; + +export default async function signInOptions( + apiImplementation: APIInterface, + tenantId: string, + options: APIOptions, + userContext: UserContext +): Promise { + if (apiImplementation.signInOptionsPOST === undefined) { + return false; + } + + let result = await apiImplementation.signInOptionsPOST({ + tenantId, + options, + userContext, + }); + + send200Response(options.res, result); + return true; +} diff --git a/lib/ts/recipe/webauthn/api/signin.ts b/lib/ts/recipe/webauthn/api/signin.ts new file mode 100644 index 000000000..b834ecb84 --- /dev/null +++ b/lib/ts/recipe/webauthn/api/signin.ts @@ -0,0 +1,75 @@ +/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. + * + * This software is licensed under the Apache License, Version 2.0 (the + * "License") as published by the Apache Software Foundation. + * + * You may not use this file except in compliance with the License. You may + * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ + +import { + getBackwardsCompatibleUserInfo, + getNormalisedShouldTryLinkingWithSessionUserFlag, + send200Response, +} from "../../../utils"; +import { validatewebauthnGeneratedOptionsIdOrThrowError, validateCredentialOrThrowError } from "./utils"; +import { APIInterface, APIOptions } from ".."; +import { UserContext } from "../../../types"; +import { AuthUtils } from "../../../authUtils"; + +export default async function signInAPI( + apiImplementation: APIInterface, + tenantId: string, + options: APIOptions, + userContext: UserContext +): Promise { + // Logic as per https://github.com/supertokens/supertokens-node/issues/20#issuecomment-710346362 + if (apiImplementation.signInPOST === undefined) { + return false; + } + + const requestBody = await options.req.getJSONBody(); + const webauthnGeneratedOptionsId = await validatewebauthnGeneratedOptionsIdOrThrowError( + requestBody.webauthnGeneratedOptionsId + ); + const credential = await validateCredentialOrThrowError(requestBody.credential); + + const shouldTryLinkingWithSessionUser = getNormalisedShouldTryLinkingWithSessionUserFlag(options.req, requestBody); + + const session = await AuthUtils.loadSessionInAuthAPIIfNeeded( + options.req, + options.res, + shouldTryLinkingWithSessionUser, + userContext + ); + + if (session !== undefined) { + tenantId = session.getTenantId(); + } + + let result = await apiImplementation.signInPOST({ + webauthnGeneratedOptionsId, + credential, + tenantId, + session, + shouldTryLinkingWithSessionUser, + options, + userContext, + }); + + if (result.status === "OK") { + send200Response(options.res, { + status: "OK", + ...getBackwardsCompatibleUserInfo(options.req, result, userContext), + }); + } else { + send200Response(options.res, result); + } + return true; +} diff --git a/lib/ts/recipe/webauthn/api/signup.ts b/lib/ts/recipe/webauthn/api/signup.ts new file mode 100644 index 000000000..3695cbe3e --- /dev/null +++ b/lib/ts/recipe/webauthn/api/signup.ts @@ -0,0 +1,92 @@ +/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. + * + * This software is licensed under the Apache License, Version 2.0 (the + * "License") as published by the Apache Software Foundation. + * + * You may not use this file except in compliance with the License. You may + * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ + +import { + getBackwardsCompatibleUserInfo, + getNormalisedShouldTryLinkingWithSessionUserFlag, + send200Response, +} from "../../../utils"; +import { + validateEmailOrThrowError, + validatewebauthnGeneratedOptionsIdOrThrowError, + validateCredentialOrThrowError, +} from "./utils"; +import { APIInterface, APIOptions } from ".."; +import STError from "../error"; +import { UserContext } from "../../../types"; +import { AuthUtils } from "../../../authUtils"; + +export default async function signUpAPI( + apiImplementation: APIInterface, + tenantId: string, + options: APIOptions, + userContext: UserContext +): Promise { + if (apiImplementation.signUpPOST === undefined) { + return false; + } + + const requestBody = await options.req.getJSONBody(); + const email = await validateEmailOrThrowError(requestBody.email); + const webauthnGeneratedOptionsId = await validatewebauthnGeneratedOptionsIdOrThrowError( + requestBody.webauthnGeneratedOptionsId + ); + const credential = await validateCredentialOrThrowError(requestBody.credential); + + const shouldTryLinkingWithSessionUser = getNormalisedShouldTryLinkingWithSessionUserFlag(options.req, requestBody); + + const session = await AuthUtils.loadSessionInAuthAPIIfNeeded( + options.req, + options.res, + shouldTryLinkingWithSessionUser, + userContext + ); + if (session !== undefined) { + tenantId = session.getTenantId(); + } + + let result = await apiImplementation.signUpPOST({ + email, + credential, + webauthnGeneratedOptionsId, + tenantId, + session, + shouldTryLinkingWithSessionUser, + options, + userContext: userContext, + }); + if (result.status === "OK") { + send200Response(options.res, { + status: "OK", + ...getBackwardsCompatibleUserInfo(options.req, result, userContext), + }); + } else if (result.status === "GENERAL_ERROR") { + send200Response(options.res, result); + } else if (result.status === "EMAIL_ALREADY_EXISTS_ERROR") { + throw new STError({ + type: STError.FIELD_ERROR, + payload: [ + { + id: "email", + error: "This email already exists. Please sign in instead.", + }, + ], + message: "Error in input formFields", + }); + } else { + send200Response(options.res, result); + } + return true; +} diff --git a/lib/ts/recipe/webauthn/api/utils.ts b/lib/ts/recipe/webauthn/api/utils.ts new file mode 100644 index 000000000..4b1ecaaf8 --- /dev/null +++ b/lib/ts/recipe/webauthn/api/utils.ts @@ -0,0 +1,50 @@ +/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. + * + * This software is licensed under the Apache License, Version 2.0 (the + * "License") as published by the Apache Software Foundation. + * + * You may not use this file except in compliance with the License. You may + * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +import STError from "../error"; +import { defaultEmailValidator } from "../utils"; + +export async function validateEmailOrThrowError(email: string): Promise { + const error = await defaultEmailValidator(email); + if (error) { + throw newBadRequestError(error); + } + + return email; +} + +export async function validatewebauthnGeneratedOptionsIdOrThrowError( + webauthnGeneratedOptionsId: string +): Promise { + if (webauthnGeneratedOptionsId === undefined) { + throw newBadRequestError("webauthnGeneratedOptionsId is required"); + } + + return webauthnGeneratedOptionsId; +} + +export async function validateCredentialOrThrowError(credential: T): Promise { + if (credential === undefined) { + throw newBadRequestError("credential is required"); + } + + return credential; +} + +function newBadRequestError(message: string) { + return new STError({ + type: STError.BAD_INPUT_ERROR, + message, + }); +} diff --git a/lib/ts/recipe/webauthn/constants.ts b/lib/ts/recipe/webauthn/constants.ts new file mode 100644 index 000000000..d23bf8dd7 --- /dev/null +++ b/lib/ts/recipe/webauthn/constants.ts @@ -0,0 +1,34 @@ +/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. + * + * This software is licensed under the Apache License, Version 2.0 (the + * "License") as published by the Apache Software Foundation. + * + * You may not use this file except in compliance with the License. You may + * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ + +export const DEFAULT_REGISTER_ATTESTATION = "none"; + +export const DEFAULT_REGISTER_OPTIONS_TIMEOUT = 5000; + +export const DEFAULT_SIGNIN_OPTIONS_TIMEOUT = 5000; + +export const REGISTER_OPTIONS_API = "/webauthn/options/register"; + +export const SIGNIN_OPTIONS_API = "/webauthn/options/signin"; + +export const SIGN_UP_API = "/webauthn/signup"; + +export const SIGN_IN_API = "/webauthn/signin"; + +export const GENERATE_RECOVER_ACCOUNT_TOKEN_API = "/user/webauthn/reset/token"; + +export const RECOVER_ACCOUNT_API = "/user/webauthn/reset"; + +export const SIGNUP_EMAIL_EXISTS_API = "/webauthn/email/exists"; diff --git a/lib/ts/recipe/webauthn/core-mock.ts b/lib/ts/recipe/webauthn/core-mock.ts new file mode 100644 index 000000000..f6e725433 --- /dev/null +++ b/lib/ts/recipe/webauthn/core-mock.ts @@ -0,0 +1,84 @@ +import NormalisedURLPath from "../../normalisedURLPath"; +import { Querier } from "../../querier"; +import { UserContext } from "../../types"; + +export const getMockQuerier = (recipeId: string) => { + const querier = Querier.getNewInstanceOrThrowError(recipeId); + + const sendPostRequest = async ( + path: NormalisedURLPath, + body: any, + userContext: UserContext + ): Promise => { + if (path.getAsStringDangerous().includes("/recipe/webauthn/options/register")) { + // @ts-ignore + return { + status: "OK", + webauthnGeneratedOptionsId: "7ab03f6a-61b8-4f65-992f-b8b8469bc18f", + rp: { id: "example.com", name: "Example App" }, + user: { id: "dummy-user-id", name: "user@example.com", displayName: "User" }, + challenge: "dummy-challenge", + timeout: 60000, + excludeCredentials: [], + attestation: "none", + pubKeyCredParams: [{ alg: -7, type: "public-key" }], + authenticatorSelection: { + requireResidentKey: false, + residentKey: "preferred", + userVerification: "preferred", + }, + }; + } else if (path.getAsStringDangerous().includes("/recipe/webauthn/options/signin")) { + // @ts-ignore + return { + status: "OK", + webauthnGeneratedOptionsId: "18302759-87c6-4d88-990d-c7cab43653cc", + challenge: "dummy-signin-challenge", + timeout: 60000, + userVerification: "preferred", + }; + // } else if (path.getAsStringDangerous().includes("/recipe/webauthn/user/recover/token")) { + // // @ts-ignore + // return { + // status: "OK", + // token: "dummy-recovery-token", + // }; + // } else if (path.getAsStringDangerous().includes("/recipe/webauthn/user/recover/token/consume")) { + // // @ts-ignore + // return { + // status: "OK", + // userId: "dummy-user-id", + // email: "user@example.com", + // }; + // } + } else if (path.getAsStringDangerous().includes("/recipe/webauthn/signup")) { + // @ts-ignore + return { + status: "OK", + user: { + id: "dummy-user-id", + email: "user@example.com", + timeJoined: Date.now(), + }, + recipeUserId: "dummy-recipe-user-id", + }; + } else if (path.getAsStringDangerous().includes("/recipe/webauthn/signin")) { + // @ts-ignore + return { + status: "OK", + user: { + id: "dummy-user-id", + email: "user@example.com", + timeJoined: Date.now(), + }, + recipeUserId: "dummy-recipe-user-id", + }; + } + + throw new Error(`Unmocked endpoint: ${path}`); + }; + + querier.sendPostRequest = sendPostRequest; + + return querier; +}; diff --git a/lib/ts/recipe/webauthn/error.ts b/lib/ts/recipe/webauthn/error.ts new file mode 100644 index 000000000..7b984cbaf --- /dev/null +++ b/lib/ts/recipe/webauthn/error.ts @@ -0,0 +1,41 @@ +/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. + * + * This software is licensed under the Apache License, Version 2.0 (the + * "License") as published by the Apache Software Foundation. + * + * You may not use this file except in compliance with the License. You may + * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ + +import STError from "../../error"; + +export default class SessionError extends STError { + static FIELD_ERROR: "FIELD_ERROR" = "FIELD_ERROR"; + + constructor( + options: + | { + type: "FIELD_ERROR"; + payload: { + id: string; + error: string; + }[]; + message: string; + } + | { + type: "BAD_INPUT_ERROR"; + message: string; + } + ) { + super({ + ...options, + }); + this.fromRecipe = "webauthn"; + } +} diff --git a/lib/ts/recipe/webauthn/index.ts b/lib/ts/recipe/webauthn/index.ts new file mode 100644 index 000000000..78ad6385b --- /dev/null +++ b/lib/ts/recipe/webauthn/index.ts @@ -0,0 +1,386 @@ +/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. + * + * This software is licensed under the Apache License, Version 2.0 (the + * "License") as published by the Apache Software Foundation. + * + * You may not use this file except in compliance with the License. You may + * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ + +import Recipe from "./recipe"; +import SuperTokensError from "./error"; +import { RecipeInterface, APIOptions, APIInterface, TypeWebauthnEmailDeliveryInput } from "./types"; +import RecipeUserId from "../../recipeUserId"; +import { DEFAULT_TENANT_ID } from "../multitenancy/constants"; +import { getPasswordResetLink } from "./utils"; +import { getRequestFromUserContext, getUser } from "../.."; +import { getUserContext } from "../../utils"; +import { SessionContainerInterface } from "../session/types"; +import { User, UserContext } from "../../types"; + +export default class Wrapper { + static init = Recipe.init; + + static Error = SuperTokensError; + + static registerOptions( + email: string, + relyingPartyId: string, + relyingPartyName: string, + origin: string, + timeout: number, + attestation: "none" | "indirect" | "direct" | "enterprise" = "none", + tenantId: string, + userContext: Record + ): Promise<{ + status: "OK"; + webauthnGeneratedOptionsId: string; + rp: { + id: string; + name: string; + }; + user: { + id: string; + name: string; + displayName: string; + }; + challenge: string; + timeout: number; + excludeCredentials: { + id: string; + type: string; + transports: ("ble" | "hybrid" | "internal" | "nfc" | "usb")[]; + }[]; + attestation: "none" | "indirect" | "direct" | "enterprise"; + pubKeyCredParams: { + alg: number; + type: string; + }[]; + authenticatorSelection: { + requireResidentKey: boolean; + residentKey: "required" | "preferred" | "discouraged"; + userVerification: "required" | "preferred" | "discouraged"; + }; + }> { + return Recipe.getInstanceOrThrowError().recipeInterfaceImpl.registerOptions({ + email, + relyingPartyId, + relyingPartyName, + origin, + timeout, + attestation, + tenantId: tenantId === undefined ? DEFAULT_TENANT_ID : tenantId, + userContext: getUserContext(userContext), + }); + } + + static signInOptions( + relyingPartyId: string, + origin: string, + timeout: number, + tenantId: string, + userContext: Record + ): Promise<{ + status: "OK"; + webauthnGeneratedOptionsId: string; + challenge: string; + timeout: number; + userVerification: "required" | "preferred" | "discouraged"; + }> { + return Recipe.getInstanceOrThrowError().recipeInterfaceImpl.signInOptions({ + relyingPartyId, + origin, + timeout, + tenantId: tenantId === undefined ? DEFAULT_TENANT_ID : tenantId, + userContext: getUserContext(userContext), + }); + } + + // static signIn( + // tenantId: string, + // email: string, + // password: string, + // session?: undefined, + // userContext?: Record + // ): Promise<{ status: "OK"; user: User; recipeUserId: RecipeUserId } | { status: "WRONG_CREDENTIALS_ERROR" }>; + // static signIn( + // tenantId: string, + // email: string, + // password: string, + // session: SessionContainerInterface, + // userContext?: Record + // ): Promise< + // | { status: "OK"; user: User; recipeUserId: RecipeUserId } + // | { status: "WRONG_CREDENTIALS_ERROR" } + // | { + // status: "LINKING_TO_SESSION_USER_FAILED"; + // reason: + // | "EMAIL_VERIFICATION_REQUIRED" + // | "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" + // | "ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" + // | "SESSION_USER_ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + // } + // >; + // static signIn( + // tenantId: string, + // email: string, + // password: string, + // session?: SessionContainerInterface, + // userContext?: Record + // ): Promise< + // | { status: "OK"; user: User; recipeUserId: RecipeUserId } + // | { status: "WRONG_CREDENTIALS_ERROR" } + // | { + // status: "LINKING_TO_SESSION_USER_FAILED"; + // reason: + // | "EMAIL_VERIFICATION_REQUIRED" + // | "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" + // | "ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" + // | "SESSION_USER_ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + // } + // > { + // return Recipe.getInstanceOrThrowError().recipeInterfaceImpl.signIn({ + // email, + // password, + // session, + // shouldTryLinkingWithSessionUser: !!session, + // tenantId: tenantId === undefined ? DEFAULT_TENANT_ID : tenantId, + // userContext: getUserContext(userContext), + // }); + // } + + // static async verifyCredentials( + // tenantId: string, + // email: string, + // password: string, + // userContext?: Record + // ): Promise<{ status: "OK" | "WRONG_CREDENTIALS_ERROR" }> { + // const resp = await Recipe.getInstanceOrThrowError().recipeInterfaceImpl.verifyCredentials({ + // email, + // password, + // tenantId: tenantId === undefined ? DEFAULT_TENANT_ID : tenantId, + // userContext: getUserContext(userContext), + // }); + + // // Here we intentionally skip the user and recipeUserId props, because we do not want apps to accidentally use this to sign in + // return { + // status: resp.status, + // }; + // } + + // /** + // * We do not make email optional here cause we want to + // * allow passing in primaryUserId. If we make email optional, + // * and if the user provides a primaryUserId, then it may result in two problems: + // * - there is no recipeUserId = input primaryUserId, in this case, + // * this function will throw an error + // * - There is a recipe userId = input primaryUserId, but that recipe has no email, + // * or has wrong email compared to what the user wanted to generate a reset token for. + // * + // * And we want to allow primaryUserId being passed in. + // */ + // static createResetPasswordToken( + // tenantId: string, + // userId: string, + // email: string, + // userContext?: Record + // ): Promise<{ status: "OK"; token: string } | { status: "UNKNOWN_USER_ID_ERROR" }> { + // return Recipe.getInstanceOrThrowError().recipeInterfaceImpl.createResetPasswordToken({ + // userId, + // email, + // tenantId: tenantId === undefined ? DEFAULT_TENANT_ID : tenantId, + // userContext: getUserContext(userContext), + // }); + // } + + // static async resetPasswordUsingToken( + // tenantId: string, + // token: string, + // newPassword: string, + // userContext?: Record + // ): Promise< + // | { + // status: "OK" | "UNKNOWN_USER_ID_ERROR" | "RESET_PASSWORD_INVALID_TOKEN_ERROR"; + // } + // | { status: "PASSWORD_POLICY_VIOLATED_ERROR"; failureReason: string } + // > { + // const consumeResp = await Wrapper.consumePasswordResetToken(tenantId, token, userContext); + + // if (consumeResp.status !== "OK") { + // return consumeResp; + // } + + // let result = await Wrapper.updateEmailOrPassword({ + // recipeUserId: new RecipeUserId(consumeResp.userId), + // email: consumeResp.email, + // password: newPassword, + // tenantIdForPasswordPolicy: tenantId, + // userContext, + // }); + + // if (result.status === "EMAIL_ALREADY_EXISTS_ERROR" || result.status === "EMAIL_CHANGE_NOT_ALLOWED_ERROR") { + // throw new global.Error("Should never come here cause we are not updating email"); + // } + // if (result.status === "PASSWORD_POLICY_VIOLATED_ERROR") { + // return { + // status: "PASSWORD_POLICY_VIOLATED_ERROR", + // failureReason: result.failureReason, + // }; + // } + // return { + // status: result.status, + // }; + // } + + // static consumePasswordResetToken( + // tenantId: string, + // token: string, + // userContext?: Record + // ): Promise< + // | { + // status: "OK"; + // email: string; + // userId: string; + // } + // | { status: "RESET_PASSWORD_INVALID_TOKEN_ERROR" } + // > { + // return Recipe.getInstanceOrThrowError().recipeInterfaceImpl.consumePasswordResetToken({ + // token, + // tenantId: tenantId === undefined ? DEFAULT_TENANT_ID : tenantId, + // userContext: getUserContext(userContext), + // }); + // } + + // static updateEmailOrPassword(input: { + // recipeUserId: RecipeUserId; + // email?: string; + // password?: string; + // userContext?: Record; + // applyPasswordPolicy?: boolean; + // tenantIdForPasswordPolicy?: string; + // }): Promise< + // | { + // status: "OK" | "UNKNOWN_USER_ID_ERROR" | "EMAIL_ALREADY_EXISTS_ERROR"; + // } + // | { + // status: "EMAIL_CHANGE_NOT_ALLOWED_ERROR"; + // reason: string; + // } + // | { status: "PASSWORD_POLICY_VIOLATED_ERROR"; failureReason: string } + // > { + // return Recipe.getInstanceOrThrowError().recipeInterfaceImpl.updateEmailOrPassword({ + // ...input, + // userContext: getUserContext(input.userContext), + // tenantIdForPasswordPolicy: + // input.tenantIdForPasswordPolicy === undefined ? DEFAULT_TENANT_ID : input.tenantIdForPasswordPolicy, + // }); + // } + + // static async createResetPasswordLink( + // tenantId: string, + // userId: string, + // email: string, + // userContext?: Record + // ): Promise<{ status: "OK"; link: string } | { status: "UNKNOWN_USER_ID_ERROR" }> { + // const ctx = getUserContext(userContext); + // let token = await createResetPasswordToken(tenantId, userId, email, ctx); + // if (token.status === "UNKNOWN_USER_ID_ERROR") { + // return token; + // } + + // const recipeInstance = Recipe.getInstanceOrThrowError(); + // return { + // status: "OK", + // link: getPasswordResetLink({ + // appInfo: recipeInstance.getAppInfo(), + // token: token.token, + // tenantId: tenantId === undefined ? DEFAULT_TENANT_ID : tenantId, + // request: getRequestFromUserContext(ctx), + // userContext: ctx, + // }), + // }; + // } + + // static async sendResetPasswordEmail( + // tenantId: string, + // userId: string, + // email: string, + // userContext?: Record + // ): Promise<{ status: "OK" | "UNKNOWN_USER_ID_ERROR" }> { + // const user = await getUser(userId, userContext); + // if (!user) { + // return { status: "UNKNOWN_USER_ID_ERROR" }; + // } + + // const loginMethod = user.loginMethods.find((m) => m.recipeId === "emailpassword" && m.hasSameEmailAs(email)); + // if (!loginMethod) { + // return { status: "UNKNOWN_USER_ID_ERROR" }; + // } + + // let link = await createResetPasswordLink(tenantId, userId, email, userContext); + // if (link.status === "UNKNOWN_USER_ID_ERROR") { + // return link; + // } + + // await sendEmail({ + // passwordResetLink: link.link, + // type: "PASSWORD_RESET", + // user: { + // id: user.id, + // recipeUserId: loginMethod.recipeUserId, + // email: loginMethod.email!, + // }, + // tenantId, + // userContext, + // }); + + // return { + // status: "OK", + // }; + // } + + // static async sendEmail( + // input: TypeWebauthnEmailDeliveryInput & { userContext?: Record } + // ): Promise { + // let recipeInstance = Recipe.getInstanceOrThrowError(); + // return await recipeInstance.emailDelivery.ingredientInterfaceImpl.sendEmail({ + // ...input, + // tenantId: input.tenantId === undefined ? DEFAULT_TENANT_ID : input.tenantId, + // userContext: getUserContext(input.userContext), + // }); + // } +} + +export let init = Wrapper.init; + +export let Error = Wrapper.Error; + +export let registerOptions = Wrapper.registerOptions; + +export let signInOptions = Wrapper.signInOptions; + +// export let signIn = Wrapper.signIn; + +// export let verifyCredentials = Wrapper.verifyCredentials; + +// export let createResetPasswordToken = Wrapper.createResetPasswordToken; + +// export let resetPasswordUsingToken = Wrapper.resetPasswordUsingToken; + +// export let consumePasswordResetToken = Wrapper.consumePasswordResetToken; + +// export let updateEmailOrPassword = Wrapper.updateEmailOrPassword; + +export type { RecipeInterface, APIOptions, APIInterface }; + +// export let createResetPasswordLink = Wrapper.createResetPasswordLink; + +// export let sendResetPasswordEmail = Wrapper.sendResetPasswordEmail; + +// export let sendEmail = Wrapper.sendEmail; diff --git a/lib/ts/recipe/webauthn/recipe.ts b/lib/ts/recipe/webauthn/recipe.ts new file mode 100644 index 000000000..779855fc6 --- /dev/null +++ b/lib/ts/recipe/webauthn/recipe.ts @@ -0,0 +1,357 @@ +/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. + * + * This software is licensed under the Apache License, Version 2.0 (the + * "License") as published by the Apache Software Foundation. + * + * You may not use this file except in compliance with the License. You may + * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ + +import RecipeModule from "../../recipeModule"; +import { TypeInput, TypeNormalisedInput, RecipeInterface, APIInterface } from "./types"; +import { NormalisedAppinfo, APIHandled, HTTPMethod, RecipeListFunction, UserContext } from "../../types"; +import STError from "./error"; +import { validateAndNormaliseUserInput } from "./utils"; +import NormalisedURLPath from "../../normalisedURLPath"; +import { SIGN_UP_API, SIGN_IN_API, REGISTER_OPTIONS_API, SIGNIN_OPTIONS_API } from "./constants"; +import signUpAPI from "./api/signup"; +import signInAPI from "./api/signin"; +import registerOptionsAPI from "./api/registerOptions"; +import signInOptionsAPI from "./api/signInOptions"; +import { isTestEnv, send200Response } from "../../utils"; +import RecipeImplementation from "./recipeImplementation"; +import APIImplementation from "./api/implementation"; +import type { BaseRequest, BaseResponse } from "../../framework"; +import OverrideableBuilder from "supertokens-js-override"; +import EmailDeliveryIngredient from "../../ingredients/emaildelivery"; +import { TypeWebauthnEmailDeliveryInput } from "./types"; +import { PostSuperTokensInitCallbacks } from "../../postSuperTokensInitCallbacks"; +import MultiFactorAuthRecipe from "../multifactorauth/recipe"; +import MultitenancyRecipe from "../multitenancy/recipe"; +import { User } from "../../user"; +import { isFakeEmail } from "../thirdparty/utils"; +import { FactorIds } from "../multifactorauth"; +import { getMockQuerier } from "./core-mock"; + +export default class Recipe extends RecipeModule { + private static instance: Recipe | undefined = undefined; + static RECIPE_ID = "webauthn"; + + config: TypeNormalisedInput; + + recipeInterfaceImpl: RecipeInterface; + + apiImpl: APIInterface; + + isInServerlessEnv: boolean; + + emailDelivery: EmailDeliveryIngredient; + + constructor( + recipeId: string, + appInfo: NormalisedAppinfo, + isInServerlessEnv: boolean, + config: TypeInput | undefined, + ingredients: { + emailDelivery: EmailDeliveryIngredient | undefined; + } + ) { + super(recipeId, appInfo); + this.isInServerlessEnv = isInServerlessEnv; + this.config = validateAndNormaliseUserInput(this, appInfo, config); + { + const getWebauthnConfig = () => this.config; + // const querier = Querier.getNewInstanceOrThrowError(recipeId); + const querier = getMockQuerier(recipeId); + let builder = new OverrideableBuilder(RecipeImplementation(querier, getWebauthnConfig)); + this.recipeInterfaceImpl = builder.override(this.config.override.functions).build(); + } + { + let builder = new OverrideableBuilder(APIImplementation()); + this.apiImpl = builder.override(this.config.override.apis).build(); + } + + /** + * emailDelivery will always needs to be declared after isInServerlessEnv + * and recipeInterfaceImpl values are set + */ + this.emailDelivery = + ingredients.emailDelivery === undefined + ? new EmailDeliveryIngredient(this.config.getEmailDeliveryConfig(this.isInServerlessEnv)) + : ingredients.emailDelivery; + + PostSuperTokensInitCallbacks.addPostInitCallback(() => { + const mfaInstance = MultiFactorAuthRecipe.getInstance(); + if (mfaInstance !== undefined) { + mfaInstance.addFuncToGetAllAvailableSecondaryFactorIdsFromOtherRecipes(() => { + return ["webauthn"]; + }); + mfaInstance.addFuncToGetFactorsSetupForUserFromOtherRecipes(async (user: User) => { + for (const loginMethod of user.loginMethods) { + // We don't check for tenantId here because if we find the user + // with emailpassword loginMethod from different tenant, then + // we assume the factor is setup for this user. And as part of factor + // completion, we associate that loginMethod with the session's tenantId + if (loginMethod.recipeId === Recipe.RECIPE_ID) { + return ["webauthn"]; + } + } + return []; + }); + + mfaInstance.addFuncToGetEmailsForFactorFromOtherRecipes((user: User, sessionRecipeUserId) => { + // This function is called in the MFA info endpoint API. + // Based on https://github.com/supertokens/supertokens-node/pull/741#discussion_r1432749346 + + // preparing some reusable variables for the logic below... + let sessionLoginMethod = user.loginMethods.find((lM) => { + return lM.recipeUserId.getAsString() === sessionRecipeUserId.getAsString(); + }); + if (sessionLoginMethod === undefined) { + // this can happen maybe cause this login method + // was unlinked from the user or deleted entirely... + return { + status: "UNKNOWN_SESSION_RECIPE_USER_ID", + }; + } + + // We order the login methods based on timeJoined (oldest first) + const orderedLoginMethodsByTimeJoinedOldestFirst = user.loginMethods.sort((a, b) => { + return a.timeJoined - b.timeJoined; + }); + // Then we take the ones that belong to this recipe + const recipeLoginMethodsOrderedByTimeJoinedOldestFirst = orderedLoginMethodsByTimeJoinedOldestFirst.filter( + (lm) => lm.recipeId === Recipe.RECIPE_ID + ); + + let result: string[]; + if (recipeLoginMethodsOrderedByTimeJoinedOldestFirst.length !== 0) { + // If there are login methods belonging to this recipe, the factor is set up + // In this case we only list email addresses that have a password associated with them + result = [ + // First we take the verified real emails associated with emailpassword login methods ordered by timeJoined (oldest first) + ...recipeLoginMethodsOrderedByTimeJoinedOldestFirst + .filter((lm) => !isFakeEmail(lm.email!) && lm.verified === true) + .map((lm) => lm.email!), + // Then we take the non-verified real emails associated with emailpassword login methods ordered by timeJoined (oldest first) + ...recipeLoginMethodsOrderedByTimeJoinedOldestFirst + .filter((lm) => !isFakeEmail(lm.email!) && lm.verified === false) + .map((lm) => lm.email!), + // Lastly, fake emails associated with emailpassword login methods ordered by timeJoined (oldest first) + // We also add these into the list because they already have a password added to them so they can be a valid choice when signing in + // We do not want to remove the previously added "MFA password", because a new email password user was linked + // E.g.: + // 1. A discord user adds a password for MFA (which will use the fake email associated with the discord user) + // 2. Later they also sign up and (manually) link a full emailpassword user that they intend to use as a first factor + // 3. The next time they sign in using Discord, they could be asked for a secondary password. + // In this case, they'd be checked against the first user that they originally created for MFA, not the one later linked to the account + ...recipeLoginMethodsOrderedByTimeJoinedOldestFirst + .filter((lm) => isFakeEmail(lm.email!)) + .map((lm) => lm.email!), + ]; + // We handle moving the session email to the top of the list later + } else { + // This factor hasn't been set up, we list all emails belonging to the user + if ( + orderedLoginMethodsByTimeJoinedOldestFirst.some( + (lm) => lm.email !== undefined && !isFakeEmail(lm.email) + ) + ) { + // If there is at least one real email address linked to the user, we only suggest real addresses + result = orderedLoginMethodsByTimeJoinedOldestFirst + .filter((lm) => lm.email !== undefined && !isFakeEmail(lm.email)) + .map((lm) => lm.email!); + } else { + // Else we use the fake ones + result = orderedLoginMethodsByTimeJoinedOldestFirst + .filter((lm) => lm.email !== undefined && isFakeEmail(lm.email)) + .map((lm) => lm.email!); + } + // We handle moving the session email to the top of the list later + + // Since in this case emails are not guaranteed to be unique, we de-duplicate the results, keeping the oldest one in the list. + // The Set constructor keeps the original insertion order (OrderedByTimeJoinedOldestFirst), but de-duplicates the items, + // keeping the first one added (so keeping the older one if there are two entries with the same email) + // e.g.: [4,2,3,2,1] -> [4,2,3,1] + result = Array.from(new Set(result)); + } + + // If the loginmethod associated with the session has an email address, we move it to the top of the list (if it's already in the list) + if (sessionLoginMethod.email !== undefined && result.includes(sessionLoginMethod.email)) { + result = [ + sessionLoginMethod.email, + ...result.filter((email) => email !== sessionLoginMethod!.email), + ]; + } + + // todo how to implement this? + + // If the list is empty we generate an email address to make the flow where the user is never asked for + // an email address easier to implement. In many cases when the user adds an email-password factor, they + // actually only want to add a password and do not care about the associated email address. + // Custom implementations can choose to ignore this, and ask the user for the email anyway. + if (result.length === 0) { + result.push(`${sessionRecipeUserId.getAsString()}@stfakeemail.supertokens.com`); + } + + return { + status: "OK", + factorIdToEmailsMap: { + emailpassword: result, + }, + }; + }); + } + + const mtRecipe = MultitenancyRecipe.getInstance(); + if (mtRecipe !== undefined) { + mtRecipe.allAvailableFirstFactors.push(FactorIds.WEBAUTHN); + } + }); + } + + static getInstanceOrThrowError(): Recipe { + if (Recipe.instance !== undefined) { + return Recipe.instance; + } + throw new Error("Initialisation not done. Did you forget to call the Webauthn.init function?"); + } + + static init(config?: TypeInput): RecipeListFunction { + return (appInfo, isInServerlessEnv) => { + if (Recipe.instance === undefined) { + Recipe.instance = new Recipe(Recipe.RECIPE_ID, appInfo, isInServerlessEnv, config, { + emailDelivery: undefined, + }); + + return Recipe.instance; + } else { + throw new Error("Webauthn recipe has already been initialised. Please check your code for bugs."); + } + }; + } + + static reset() { + if (!isTestEnv()) { + throw new Error("calling testing function in non testing env"); + } + Recipe.instance = undefined; + } + + // abstract instance functions below............... + + getAPIsHandled = (): APIHandled[] => { + return [ + { + method: "post", + pathWithoutApiBasePath: new NormalisedURLPath(REGISTER_OPTIONS_API), + id: REGISTER_OPTIONS_API, + disabled: this.apiImpl.registerOptionsPOST === undefined, + }, + { + method: "post", + pathWithoutApiBasePath: new NormalisedURLPath(SIGNIN_OPTIONS_API), + id: SIGNIN_OPTIONS_API, + disabled: this.apiImpl.signInOptionsPOST === undefined, + }, + { + method: "post", + pathWithoutApiBasePath: new NormalisedURLPath(SIGN_UP_API), + id: SIGN_UP_API, + disabled: this.apiImpl.signUpPOST === undefined, + }, + { + method: "post", + pathWithoutApiBasePath: new NormalisedURLPath(SIGN_IN_API), + id: SIGN_IN_API, + disabled: this.apiImpl.signInPOST === undefined, + }, + + // { + // method: "post", + // pathWithoutApiBasePath: new NormalisedURLPath(GENERATE_RECOVER_ACCOUNT_TOKEN_API), + // id: GENERATE_RECOVER_ACCOUNT_TOKEN_API, + // disabled: this.apiImpl.generateRecoverAccountTokenPOST === undefined, + // }, + // { + // method: "post", + // pathWithoutApiBasePath: new NormalisedURLPath(RECOVER_ACCOUNT_API), + // id: RECOVER_ACCOUNT_API, + // disabled: this.apiImpl.recoverAccountPOST === undefined, + // }, + // { + // method: "get", + // pathWithoutApiBasePath: new NormalisedURLPath(SIGNUP_EMAIL_EXISTS_API), + // id: SIGNUP_EMAIL_EXISTS_API, + // disabled: this.apiImpl.emailExistsGET === undefined, + // }, + ]; + }; + + handleAPIRequest = async ( + id: string, + tenantId: string, + req: BaseRequest, + res: BaseResponse, + _path: NormalisedURLPath, + _method: HTTPMethod, + userContext: UserContext + ): Promise => { + let options = { + config: this.config, + recipeId: this.getRecipeId(), + isInServerlessEnv: this.isInServerlessEnv, + recipeImplementation: this.recipeInterfaceImpl, + req, + res, + emailDelivery: this.emailDelivery, + appInfo: this.getAppInfo(), + }; + if (id === REGISTER_OPTIONS_API) { + return await registerOptionsAPI(this.apiImpl, tenantId, options, userContext); + } else if (id === SIGNIN_OPTIONS_API) { + return await signInOptionsAPI(this.apiImpl, tenantId, options, userContext); + } else if (id === SIGN_UP_API) { + return await signUpAPI(this.apiImpl, tenantId, options, userContext); + } else if (id === SIGN_IN_API) { + return await signInAPI(this.apiImpl, tenantId, options, userContext); + } + //else if (id === GENERATE_RECOVER_ACCOUNT_TOKEN_API) { + // return await generateRecoverAccountTokenAPI(this.apiImpl, tenantId, options, userContext); + // } else if (id === RECOVER_ACCOUNT_API) { + // return await recoverAccountAPI(this.apiImpl, tenantId, options, userContext); + // } else if (id === SIGNUP_EMAIL_EXISTS_API) { + // return await emailExistsAPI(this.apiImpl, tenantId, options, userContext); + // } + else return false; + }; + + handleError = async (err: STError, _request: BaseRequest, response: BaseResponse): Promise => { + if (err.fromRecipe === Recipe.RECIPE_ID) { + if (err.type === STError.FIELD_ERROR) { + return send200Response(response, { + status: "FIELD_ERROR", + formFields: err.payload, + }); + } else { + throw err; + } + } else { + throw err; + } + }; + + getAllCORSHeaders = (): string[] => { + return []; + }; + + isErrorFromThisRecipe = (err: any): err is STError => { + return STError.isErrorFromSuperTokens(err) && err.fromRecipe === Recipe.RECIPE_ID; + }; +} diff --git a/lib/ts/recipe/webauthn/recipeImplementation.ts b/lib/ts/recipe/webauthn/recipeImplementation.ts new file mode 100644 index 000000000..026e6b63a --- /dev/null +++ b/lib/ts/recipe/webauthn/recipeImplementation.ts @@ -0,0 +1,376 @@ +import { RecipeInterface, TypeNormalisedInput } from "./types"; +import AccountLinking from "../accountlinking/recipe"; +import { Querier } from "../../querier"; +import NormalisedURLPath from "../../normalisedURLPath"; +import { getUser } from "../.."; +import RecipeUserId from "../../recipeUserId"; +import { DEFAULT_TENANT_ID } from "../multitenancy/constants"; +import { UserContext, User as UserType } from "../../types"; +import { LoginMethod, User } from "../../user"; +import { AuthUtils } from "../../authUtils"; + +export default function getRecipeInterface( + querier: Querier, + getWebauthnConfig: () => TypeNormalisedInput +): RecipeInterface { + return { + registerOptions: async function ({ + email, + relyingPartyId, + relyingPartyName, + origin, + timeout, + attestation = "none", + tenantId, + userContext, + }: { + email: string; + timeout: number; + attestation: "none" | "indirect" | "direct" | "enterprise"; + relyingPartyId: string; + relyingPartyName: string; + origin: string; + tenantId: string; + userContext: UserContext; + }): Promise<{ + status: "OK"; + webauthnGeneratedOptionsId: string; + rp: { + id: string; + name: string; + }; + user: { + id: string; + name: string; + displayName: string; + }; + challenge: string; + timeout: number; + excludeCredentials: { + id: string; + type: string; + transports: ("ble" | "hybrid" | "internal" | "nfc" | "usb")[]; + }[]; + attestation: "none" | "indirect" | "direct" | "enterprise"; + pubKeyCredParams: { + alg: number; + type: string; + }[]; + authenticatorSelection: { + requireResidentKey: boolean; + residentKey: "required" | "preferred" | "discouraged"; + userVerification: "required" | "preferred" | "discouraged"; + }; + }> { + // the input user ID can be a recipe or a primary user ID. + return await querier.sendPostRequest( + new NormalisedURLPath( + `/${tenantId === undefined ? DEFAULT_TENANT_ID : tenantId}/recipe/webauthn/options/register` + ), + { + email, + relyingPartyName, + relyingPartyId, + origin, + timeout, + attestation, + }, + userContext + ); + }, + + signInOptions: async function ({ + relyingPartyId, + origin, + timeout, + tenantId, + userContext, + }: { + relyingPartyId: string; + origin: string; + timeout: number; + tenantId: string; + userContext: UserContext; + }): Promise<{ + status: "OK"; + webauthnGeneratedOptionsId: string; + challenge: string; + timeout: number; + userVerification: "required" | "preferred" | "discouraged"; + }> { + // todo crrectly retrieve relying party id and origin + // the input user ID can be a recipe or a primary user ID. + return await querier.sendPostRequest( + new NormalisedURLPath( + `/${tenantId === undefined ? DEFAULT_TENANT_ID : tenantId}/recipe/webauthn/options/signin` + ), + { + relyingPartyId, + origin, + timeout, + }, + userContext + ); + }, + + signUp: async function ( + this: RecipeInterface, + { webauthnGeneratedOptionsId, credential, tenantId, session, shouldTryLinkingWithSessionUser, userContext } + ): Promise< + | { + status: "OK"; + user: UserType; + recipeUserId: RecipeUserId; + } + | { status: "EMAIL_ALREADY_EXISTS_ERROR" } + | { + status: "LINKING_TO_SESSION_USER_FAILED"; + reason: + | "EMAIL_VERIFICATION_REQUIRED" + | "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" + | "ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" + | "SESSION_USER_ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + } + > { + const response = await this.createNewRecipeUser({ + credential, + webauthnGeneratedOptionsId, + tenantId, + userContext, + }); + if (response.status !== "OK") { + return response; + } + + let updatedUser = response.user; + + const linkResult = await AuthUtils.linkToSessionIfRequiredElseCreatePrimaryUserIdOrLinkByAccountInfo({ + tenantId, + inputUser: response.user, + recipeUserId: response.recipeUserId, + session, + shouldTryLinkingWithSessionUser, + userContext, + }); + + if (linkResult.status != "OK") { + return linkResult; + } + updatedUser = linkResult.user; + + return { + status: "OK", + user: updatedUser, + recipeUserId: response.recipeUserId, + }; + }, + + createNewRecipeUser: async function (input: { + tenantId: string; + credential: { + id: string; + rawId: string; + response: { + clientDataJSON: string; + attestationObject: string; + transports?: ("ble" | "cable" | "hybrid" | "internal" | "nfc" | "smart-card" | "usb")[]; + userHandle: string; + }; + authenticatorAttachment: "platform" | "cross-platform"; + clientExtensionResults: Record; + type: "public-key"; + }; + webauthnGeneratedOptionsId: string; + userContext: UserContext; + }): Promise< + | { + status: "OK"; + user: User; + recipeUserId: RecipeUserId; + } + | { status: "EMAIL_ALREADY_EXISTS_ERROR" } + > { + const resp = await querier.sendPostRequest( + new NormalisedURLPath( + `/${input.tenantId === undefined ? DEFAULT_TENANT_ID : input.tenantId}/recipe/webauthn/signup` + ), + { + webauthnGeneratedOptionsId: input.webauthnGeneratedOptionsId, + credential: input.credential, + }, + input.userContext + ); + + if (resp.status === "OK") { + return { + status: "OK", + user: new User(resp.user), + recipeUserId: new RecipeUserId(resp.recipeUserId), + }; + } + + return resp; + }, + + verifyCredentials: async function ({ + credential, + webauthnGeneratedOptionsId, + tenantId, + userContext, + }): Promise< + | { + status: "OK"; + user: User; + recipeUserId: RecipeUserId; + } + | { status: "WRONG_CREDENTIALS_ERROR" } + > { + const response = await querier.sendPostRequest( + new NormalisedURLPath( + `/${tenantId === undefined ? DEFAULT_TENANT_ID : tenantId}/recipe/webauthn/signin` + ), + { + credential, + webauthnGeneratedOptionsId, + }, + userContext + ); + + if (response.status === "OK") { + return { + status: "OK", + user: new User(response.user), + recipeUserId: new RecipeUserId(response.recipeUserId), + }; + } + + return { + status: "WRONG_CREDENTIALS_ERROR", + }; + }, + + signIn: async function ( + this: RecipeInterface, + { credential, webauthnGeneratedOptionsId, tenantId, session, shouldTryLinkingWithSessionUser, userContext } + ) { + const response = await this.verifyCredentials({ + credential, + webauthnGeneratedOptionsId, + tenantId, + userContext, + }); + + if (response.status === "OK") { + const loginMethod: LoginMethod = response.user.loginMethods.find( + (lm: LoginMethod) => lm.recipeUserId.getAsString() === response.recipeUserId.getAsString() + )!; + + if (!loginMethod.verified) { + await AccountLinking.getInstance().verifyEmailForRecipeUserIfLinkedAccountsAreVerified({ + user: response.user, + recipeUserId: response.recipeUserId, + userContext, + }); + + // Unlike in the sign up recipe function, we do not do account linking here + // cause we do not want sign in to change the potentially user ID of a user + // due to linking when this function is called by the dev in their API - + // for example in their update password API. If we did account linking + // then we would have to ask the dev to also change the session + // in such API calls. + // In the case of sign up, since we are creating a new user, it's fine + // to link there since there is no user id change really from the dev's + // point of view who is calling the sign up recipe function. + + // We do this so that we get the updated user (in case the above + // function updated the verification status) and can return that + response.user = (await getUser(response.recipeUserId!.getAsString(), userContext))!; + } + + const linkResult = await AuthUtils.linkToSessionIfRequiredElseCreatePrimaryUserIdOrLinkByAccountInfo({ + tenantId, + inputUser: response.user, + recipeUserId: response.recipeUserId, + session, + shouldTryLinkingWithSessionUser, + userContext, + }); + if (linkResult.status === "LINKING_TO_SESSION_USER_FAILED") { + return linkResult; + } + response.user = linkResult.user; + } + + return response; + }, + + // generateRecoverAccountToken: async function ({ + // userId, + // email, + // tenantId, + // userContext, + // }: { + // userId: string; + // email: string; + // tenantId: string; + // userContext: UserContext; + // }): Promise<{ status: "OK"; token: string } | { status: "UNKNOWN_USER_ID_ERROR" }> { + // // the input user ID can be a recipe or a primary user ID. + // return await querier.sendPostRequest( + // new NormalisedURLPath( + // `/${tenantId === undefined ? DEFAULT_TENANT_ID : tenantId}/recipe/webauthn/user/recover/token` + // ), + // { + // userId, + // email, + // }, + // userContext + // ); + // }, + + // consumeRecoverAccountToken: async function ({ + // token, + // webauthnGeneratedOptionsId, + // credential, + // tenantId, + // userContext, + // }: { + // token: string; + // webauthnGeneratedOptionsId: string; + // credential: { + // id: string; + // rawId: string; + // response: { + // clientDataJSON: string; + // attestationObject: string; + // transports?: ("ble" | "cable" | "hybrid" | "internal" | "nfc" | "smart-card" | "usb")[]; + // userHandle: string; + // }; + // authenticatorAttachment: "platform" | "cross-platform"; + // clientExtensionResults: Record; + // type: "public-key"; + // }; + // tenantId: string; + // userContext: UserContext; + // }): Promise< + // | { + // status: "OK"; + // userId: string; + // email: string; + // } + // | { status: "RECOVER_ACCOUNT_INVALID_TOKEN_ERROR" } + // > { + // return await querier.sendPostRequest( + // new NormalisedURLPath( + // `/${tenantId === undefined ? DEFAULT_TENANT_ID : tenantId}/recipe/paskey/user/recover/token/consume` + // ), + // { + // webauthnGeneratedOptionsId, + // credential, + // token, + // }, + // userContext + // ); + // }, + }; +} diff --git a/lib/ts/recipe/webauthn/types.ts b/lib/ts/recipe/webauthn/types.ts new file mode 100644 index 000000000..c3f93f7bc --- /dev/null +++ b/lib/ts/recipe/webauthn/types.ts @@ -0,0 +1,735 @@ +/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. + * + * This software is licensed under the Apache License, Version 2.0 (the + * "License") as published by the Apache Software Foundation. + * + * You may not use this file except in compliance with the License. You may + * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ + +import type { BaseRequest, BaseResponse } from "../../framework"; +import OverrideableBuilder from "supertokens-js-override"; +import { SessionContainerInterface } from "../session/types"; +import { + TypeInput as EmailDeliveryTypeInput, + TypeInputWithService as EmailDeliveryTypeInputWithService, +} from "../../ingredients/emaildelivery/types"; +import EmailDeliveryIngredient from "../../ingredients/emaildelivery"; +import { GeneralErrorResponse, NormalisedAppinfo, User, UserContext } from "../../types"; +import RecipeUserId from "../../recipeUserId"; + +export type TypeNormalisedInput = { + relyingPartyId: TypeNormalisedInputRelyingPartyId; + relyingPartyName: TypeNormalisedInputRelyingPartyName; + getOrigin: TypeNormalisedInputGetOrigin; + getEmailDeliveryConfig: ( + isInServerlessEnv: boolean + ) => EmailDeliveryTypeInputWithService; + override: { + functions: ( + originalImplementation: RecipeInterface, + builder?: OverrideableBuilder + ) => RecipeInterface; + apis: (originalImplementation: APIInterface, builder?: OverrideableBuilder) => APIInterface; + }; +}; + +export type TypeNormalisedInputRelyingPartyId = (input: { + request: BaseRequest | undefined; + userContext: UserContext; +}) => string; // should return the domain of the origin + +export type TypeNormalisedInputRelyingPartyName = (input: { + tenantId: string; + userContext: UserContext; +}) => Promise; // should return the app name + +export type TypeNormalisedInputGetOrigin = (input: { + tenantId: string; + request: BaseRequest; + userContext: UserContext; +}) => Promise; // should return the app name + +export type TypeInput = { + emailDelivery?: EmailDeliveryTypeInput; + relyingPartyId?: TypeInputRelyingPartyId; + relyingPartyName?: TypeInputRelyingPartyName; + getOrigin?: TypeInputGetOrigin; + override?: { + functions?: ( + originalImplementation: RecipeInterface, + builder?: OverrideableBuilder + ) => RecipeInterface; + apis?: (originalImplementation: APIInterface, builder?: OverrideableBuilder) => APIInterface; + }; +}; + +export type TypeInputRelyingPartyId = + | string + | ((input: { tenantId: string; request: BaseRequest | undefined; userContext: UserContext }) => Promise); + +export type TypeInputRelyingPartyName = + | string + | ((input: { tenantId: string; userContext: UserContext }) => Promise); + +export type TypeInputGetOrigin = (input: { + tenantId: string; + request: BaseRequest; + userContext: UserContext; +}) => Promise; + +// centralize error types in order to prevent missing cascading errors +type RegisterCredentialErrorResponse = + | { status: "WRONG_CREDENTIALS_ERROR" } + // when the attestation is checked and is not valid or other cases in whcih the authenticator is not correct + | { status: "INVALID_AUTHENTICATOR_ERROR" }; + +type VerifyCredentialsErrorResponse = + | { status: "WRONG_CREDENTIALS_ERROR" } + // when the attestation is checked and is not valid or other cases in which the authenticator is not correct + | { status: "INVALID_AUTHENTICATOR_ERROR" }; + +type CreateNewRecipeUserErrorResponse = RegisterCredentialErrorResponse | { status: "EMAIL_ALREADY_EXISTS_ERROR" }; + +type GetUserFromRecoverAccountTokenErrorResponse = { status: "RECOVER_ACCOUNT_TOKEN_INVALID_ERROR" }; + +type RegisterOptionsErrorResponse = GetUserFromRecoverAccountTokenErrorResponse | { status: "EMAIL_MISSING_ERROR" }; + +type SignUpErrorResponse = CreateNewRecipeUserErrorResponse; + +type SignInErrorResponse = VerifyCredentialsErrorResponse; + +type GenerateRecoverAccountTokenErrorResponse = { status: "UNKNOWN_USER_ID_ERROR" } | { status: "UNKNOWN_EMAIL_ERROR" }; + +type ConsumeRecoverAccountTokenErrorResponse = + | RegisterCredentialErrorResponse + | { status: "RECOVER_ACCOUNT_TOKEN_INVALID_ERROR" }; + +type AddCredentialErrorResponse = RegisterCredentialErrorResponse; + +type RemoveCredentialErrorResponse = { status: "CREDENTIAL_NOT_FOUND_ERROR" }; + +export type RecipeInterface = { + // should have a way to access the user email: passed as a param, through session, or using recoverAccountToken + // it should have at least one of those 3 options + registerOptions( + input: { + relyingPartyId: string; + relyingPartyName: string; + origin: string; + requireResidentKey: boolean | undefined; // should default to false in order to allow multiple authenticators to be used; see https://auth0.com/blog/a-look-at-webauthn-resident-credentials/ + // default to 'required' in order store the private key locally on the device and not on the server + residentKey: "required" | "preferred" | "discouraged" | undefined; + // default to 'preferred' in order to verify the user (biometrics, pin, etc) based on the device preferences + userVerification: "required" | "preferred" | "discouraged" | undefined; + // default to 'none' in order to allow any authenticator and not verify attestation + attestation: "none" | "indirect" | "direct" | "enterprise" | undefined; + // default to 5 seconds + timeout: number | undefined; + tenantId: string; + userContext: UserContext; + } & ( + | { + recoverAccountToken: string; + } + | { + email: string; + } + | { + session: SessionContainerInterface; + } + ) + ): Promise< + | { + status: "OK"; + webauthnGeneratedOptionsId: string; + rp: { + id: string; + name: string; + }; + user: { + id: string; + name: string; // user email + displayName: string; //user email + }; + challenge: string; + timeout: number; + excludeCredentials: { + id: string; + type: "public-key"; + transports: ("ble" | "hybrid" | "internal" | "nfc" | "usb")[]; + }[]; + attestation: "none" | "indirect" | "direct" | "enterprise"; + pubKeyCredParams: { + // we will default to [-8, -7, -257] as supported algorithms. See https://www.iana.org/assignments/cose/cose.xhtml#algorithms + alg: number; + type: "public-key"; + }[]; + authenticatorSelection: { + requireResidentKey: boolean; + residentKey: "required" | "preferred" | "discouraged"; + userVerification: "required" | "preferred" | "discouraged"; + }; + } + | RegisterOptionsErrorResponse + >; + + signInOptions(input: { + relyingPartyId: string; + origin: string; + userVerification: "required" | "preferred" | "discouraged" | undefined; // see register options + timeout: number | undefined; + tenantId: string; + userContext: UserContext; + }): Promise<{ + status: "OK"; + webauthnGeneratedOptionsId: string; + challenge: string; + timeout: number; + userVerification: "required" | "preferred" | "discouraged"; + }>; + + signUp(input: { + webauthnGeneratedOptionsId: string; + credential: { + id: string; + rawId: string; + response: { + clientDataJSON: string; + attestationObject: string; + transports?: ("ble" | "cable" | "hybrid" | "internal" | "nfc" | "smart-card" | "usb")[]; + userHandle: string; + }; + authenticatorAttachment: "platform" | "cross-platform"; + clientExtensionResults: Record; + type: "public-key"; + }; + session: SessionContainerInterface | undefined; + shouldTryLinkingWithSessionUser: boolean | undefined; + tenantId: string; + userContext: UserContext; + }): Promise< + | { + status: "OK"; + user: User; + recipeUserId: RecipeUserId; + } + | SignUpErrorResponse + | { + status: "LINKING_TO_SESSION_USER_FAILED"; + reason: + | "EMAIL_VERIFICATION_REQUIRED" + | "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" + | "ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" + | "SESSION_USER_ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + } + >; + + signIn(input: { + webauthnGeneratedOptionsId: string; + credential: { + id: string; + rawId: string; + response: { + clientDataJSON: string; + attestationObject: string; + transports?: ("ble" | "cable" | "hybrid" | "internal" | "nfc" | "smart-card" | "usb")[]; + userHandle: string; + }; + authenticatorAttachment: "platform" | "cross-platform"; + clientExtensionResults: Record; + type: "public-key"; + }; + session: SessionContainerInterface | undefined; + shouldTryLinkingWithSessionUser: boolean | undefined; + tenantId: string; + userContext: UserContext; + }): Promise< + | { status: "OK"; user: User; recipeUserId: RecipeUserId } + | SignInErrorResponse + | { + status: "LINKING_TO_SESSION_USER_FAILED"; + reason: + | "EMAIL_VERIFICATION_REQUIRED" + | "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" + | "ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" + | "SESSION_USER_ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + } + >; + + /** + * We pass in the email as well to this function cause the input userId + * may not be associated with an webauthn account. In this case, we + * need to know which email to use to create an webauthn account later on. + */ + generateRecoverAccountToken(input: { + userId: string; // the id can be either recipeUserId or primaryUserId + email: string; + tenantId: string; + userContext: UserContext; + }): Promise<{ status: "OK"; token: string } | GenerateRecoverAccountTokenErrorResponse>; + + // make sure the email maps to options email + consumeRecoverAccountToken(input: { + token: string; + webauthnGeneratedOptionsId: string; + credential: { + id: string; + rawId: string; + response: { + clientDataJSON: string; + attestationObject: string; + transports?: ("ble" | "cable" | "hybrid" | "internal" | "nfc" | "smart-card" | "usb")[]; + userHandle: string; + }; + authenticatorAttachment: "platform" | "cross-platform"; + clientExtensionResults: Record; + type: "public-key"; + }; + tenantId: string; + userContext: UserContext; + }): Promise< + | { + status: "OK"; + email: string; + userId: string; + } + | ConsumeRecoverAccountTokenErrorResponse + >; + + // used internally for creating a credential during account recovery flow or when adding a credential to an existing user + // email will be taken from the options + // no need for recoverAccountToken, as that will be used upstream + // (in consumeRecoverAccountToken invalidating the token and in registerOptions for storing the email in the generated options) + registerCredential(input: { + webauthnGeneratedOptionsId: string; + credential: { + id: string; + rawId: string; + response: { + clientDataJSON: string; + attestationObject: string; + transports?: ("ble" | "cable" | "hybrid" | "internal" | "nfc" | "smart-card" | "usb")[]; + userHandle: string; + }; + authenticatorAttachment: "platform" | "cross-platform"; + clientExtensionResults: Record; + type: "public-key"; + }; + tenantId: string; + userContext: UserContext; + }): Promise< + | { + status: "OK"; + user: User; + recipeUserId: RecipeUserId; + } + | RegisterCredentialErrorResponse + >; + + // this function is meant only for creating the recipe in the core and nothing else. + // we added this even though signUp exists cause devs may override signup expecting it + // to be called just during sign up. But we also need a version of signing up which can be + // called during operations like creating a user during password reset flow. + createNewRecipeUser(input: { + webauthnGeneratedOptionsId: string; + credential: { + id: string; + rawId: string; + response: { + clientDataJSON: string; + attestationObject: string; + transports?: ("ble" | "cable" | "hybrid" | "internal" | "nfc" | "smart-card" | "usb")[]; + userHandle: string; + }; + authenticatorAttachment: "platform" | "cross-platform"; + clientExtensionResults: Record; + type: "public-key"; + }; + tenantId: string; + userContext: UserContext; + }): Promise< + | { + status: "OK"; + user: User; + recipeUserId: RecipeUserId; + } + | CreateNewRecipeUserErrorResponse + >; + + verifyCredentials(input: { + webauthnGeneratedOptionsId: string; + credential: { + id: string; + rawId: string; + response: { + clientDataJSON: string; + attestationObject: string; + transports?: ("ble" | "cable" | "hybrid" | "internal" | "nfc" | "smart-card" | "usb")[]; + userHandle: string; + }; + authenticatorAttachment: "platform" | "cross-platform"; + clientExtensionResults: Record; + type: "public-key"; + }; + tenantId: string; + userContext: UserContext; + }): Promise<{ status: "OK"; user: User; recipeUserId: RecipeUserId } | VerifyCredentialsErrorResponse>; + + // used for retrieving the user details (email) from the recover account token + // should be used in the registerOptions function when the user recovers the account and generates the credentials + getUserFromRecoverAccountToken(input: { + token: string; + tenantId: string; + userContext: UserContext; + }): Promise<{ status: "OK"; user: User; recipeUserId: RecipeUserId } | GetUserFromRecoverAccountTokenErrorResponse>; + + // credentials CRUD + + // this will call registerCredential internally + addCredential(input: { + webauthnGeneratedOptionsId: string; + credential: { + id: string; + rawId: string; + response: { + clientDataJSON: string; + attestationObject: string; + transports?: ("ble" | "cable" | "hybrid" | "internal" | "nfc" | "smart-card" | "usb")[]; + userHandle: string; + }; + authenticatorAttachment: "platform" | "cross-platform"; + clientExtensionResults: Record; + type: "public-key"; + }; + tenantId: string; + userContext: UserContext; + }): Promise< + | { + status: "OK"; + } + | AddCredentialErrorResponse + >; + + // credentials CRUD + removeCredential(input: { + webauthnCredentialId: string; + tenantId: string; + userContext: UserContext; + }): Promise< + | { + status: "OK"; + } + | RemoveCredentialErrorResponse + >; +}; + +export type APIOptions = { + recipeImplementation: RecipeInterface; + appInfo: NormalisedAppinfo; + config: TypeNormalisedInput; + recipeId: string; + isInServerlessEnv: boolean; + req: BaseRequest; + res: BaseResponse; + emailDelivery: EmailDeliveryIngredient; +}; + +type RegisterOptionsPOSTErrorResponse = + | RegisterOptionsErrorResponse + | { status: "REGISTER_OPTIONS_NOT_ALLOWED"; reason: string }; + +type SignInOptionsPOSTErrorResponse = { status: "SIGN_IN_OPTIONS_NOT_ALLOWED"; reason: string }; + +type SignUpPOSTErrorResponse = + | { + status: "SIGN_UP_NOT_ALLOWED"; + reason: string; + } + | SignUpErrorResponse; + +type SignInPOSTErrorResponse = + | { + status: "SIGN_IN_NOT_ALLOWED"; + reason: string; + } + | SignInErrorResponse; + +type GenerateRecoverAccountTokenPOSTErrorResponse = { + status: "ACCOUNT_RECOVERY_NOT_ALLOWED"; + reason: string; +}; + +type RecoverAccountPOSTErrorResponse = + | { + status: "ACCOUNT_RECOVERY_NOT_ALLOWED"; + reason: string; + } + | ConsumeRecoverAccountTokenErrorResponse; + +type AddCredentialPOSTErrorResponse = + | { + status: "ADD_CREDENTIAL_NOT_ALLOWED"; + reason: string; + } + | AddCredentialErrorResponse; + +type RemoveCredentialPOSTErrorResponse = + | { + status: "REMOVE_CREDENTIAL_NOT_ALLOWED"; + reason: string; + } + | RemoveCredentialErrorResponse; +export type APIInterface = { + registerOptionsPOST: + | undefined + | (( + input: { + tenantId: string; + options: APIOptions; + userContext: UserContext; + } & ({ email: string } | { recoverAccountToken: string } | { session: SessionContainerInterface }) + ) => Promise< + | { + status: "OK"; + webauthnGeneratedOptionsId: string; + rp: { + id: string; + name: string; + }; + user: { + id: string; + name: string; + displayName: string; + }; + challenge: string; + timeout: number; + excludeCredentials: { + id: string; + type: "public-key"; + transports: ("ble" | "hybrid" | "internal" | "nfc" | "usb")[]; + }[]; + attestation: "none" | "indirect" | "direct" | "enterprise"; + pubKeyCredParams: { + alg: number; + type: string; + }[]; + authenticatorSelection: { + requireResidentKey: boolean; + residentKey: "required" | "preferred" | "discouraged"; + userVerification: "required" | "preferred" | "discouraged"; + }; + } + | GeneralErrorResponse + | RegisterOptionsPOSTErrorResponse + >); + + signInOptionsPOST: + | undefined + | ((input: { + tenantId: string; + options: APIOptions; + userContext: UserContext; + }) => Promise< + | { + status: "OK"; + webauthnGeneratedOptionsId: string; + challenge: string; + timeout: number; + userVerification: "required" | "preferred" | "discouraged"; + } + | GeneralErrorResponse + | SignInOptionsPOSTErrorResponse + >); + + signUpPOST: + | undefined + | ((input: { + webauthnGeneratedOptionsId: string; + credential: { + id: string; + rawId: string; + response: { + clientDataJSON: string; + attestationObject: string; + transports?: ("ble" | "cable" | "hybrid" | "internal" | "nfc" | "smart-card" | "usb")[]; + userHandle: string; + }; + authenticatorAttachment: "platform" | "cross-platform"; + clientExtensionResults: Record; + type: "public-key"; + }; + tenantId: string; + session: SessionContainerInterface | undefined; + shouldTryLinkingWithSessionUser: boolean | undefined; + options: APIOptions; + userContext: UserContext; + }) => Promise< + | { + status: "OK"; + user: User; + session: SessionContainerInterface; + } + | GeneralErrorResponse + | SignUpPOSTErrorResponse + >); + + signInPOST: + | undefined + | ((input: { + webauthnGeneratedOptionsId: string; + credential: { + id: string; + rawId: string; + response: { + clientDataJSON: string; + attestationObject: string; + transports?: ("ble" | "cable" | "hybrid" | "internal" | "nfc" | "smart-card" | "usb")[]; + userHandle: string; + }; + authenticatorAttachment: "platform" | "cross-platform"; + clientExtensionResults: Record; + type: "public-key"; + }; + tenantId: string; + session: SessionContainerInterface | undefined; + shouldTryLinkingWithSessionUser: boolean | undefined; + options: APIOptions; + userContext: UserContext; + }) => Promise< + | { + status: "OK"; + user: User; + session: SessionContainerInterface; + } + | GeneralErrorResponse + | SignInPOSTErrorResponse + >); + + generateRecoverAccountTokenPOST: + | undefined + | ((input: { + email: string; + tenantId: string; + options: APIOptions; + userContext: UserContext; + }) => Promise< + | { + status: "OK"; + } + | GenerateRecoverAccountTokenPOSTErrorResponse + | GeneralErrorResponse + >); + + recoverAccountPOST: + | undefined + | ((input: { + webauthnGeneratedOptionsId: string; + credential: { + id: string; + rawId: string; + response: { + clientDataJSON: string; + attestationObject: string; + transports?: ("ble" | "cable" | "hybrid" | "internal" | "nfc" | "smart-card" | "usb")[]; + userHandle: string; + }; + authenticatorAttachment: "platform" | "cross-platform"; + clientExtensionResults: Record; + type: "public-key"; + }; + token: string; + tenantId: string; + options: APIOptions; + userContext: UserContext; + }) => Promise< + | { + status: "OK"; + email: string; + user: User; + } + | RecoverAccountPOSTErrorResponse + | GeneralErrorResponse + >); + + // used for checking if the email already exists before generating the credential + emailExistsGET: + | undefined + | ((input: { + email: string; + tenantId: string; + options: APIOptions; + userContext: UserContext; + }) => Promise< + | { + status: "OK"; + exists: boolean; + } + | GeneralErrorResponse + >); + + //credentials CRUD + addCredentialPOST: + | undefined + | ((input: { + webauthnGeneratedOptionsId: string; + credential: { + id: string; + rawId: string; + response: { + clientDataJSON: string; + attestationObject: string; + transports?: ("ble" | "cable" | "hybrid" | "internal" | "nfc" | "smart-card" | "usb")[]; + userHandle: string; + }; + authenticatorAttachment: "platform" | "cross-platform"; + clientExtensionResults: Record; + type: "public-key"; + }; + tenantId: string; + session: SessionContainerInterface; + options: APIOptions; + userContext: UserContext; + }) => Promise< + | { + status: "OK"; + } + | AddCredentialPOSTErrorResponse + | GeneralErrorResponse + >); + + removeCredentialPOST: + | undefined + | ((input: { + webauthnCredentialId: string; + tenantId: string; + session: SessionContainerInterface; + options: APIOptions; + userContext: UserContext; + }) => Promise< + | { + status: "OK"; + } + | RemoveCredentialPOSTErrorResponse + | GeneralErrorResponse + >); +}; + +export type TypeWebauthnRecoverAccountEmailDeliveryInput = { + type: "RECOVER_ACCOUNT"; + user: { + id: string; + recipeUserId: RecipeUserId | undefined; + email: string; + }; + recoverAccountLink: string; + tenantId: string; +}; + +export type TypeWebauthnEmailDeliveryInput = TypeWebauthnRecoverAccountEmailDeliveryInput; diff --git a/lib/ts/recipe/webauthn/utils.ts b/lib/ts/recipe/webauthn/utils.ts new file mode 100644 index 000000000..278da3a9b --- /dev/null +++ b/lib/ts/recipe/webauthn/utils.ts @@ -0,0 +1,171 @@ +/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. + * + * This software is licensed under the Apache License, Version 2.0 (the + * "License") as published by the Apache Software Foundation. + * + * You may not use this file except in compliance with the License. You may + * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ + +import Recipe from "./recipe"; +import { + TypeInput, + TypeInputGetOrigin, + TypeInputRelyingPartyId, + TypeInputRelyingPartyName, + TypeNormalisedInput, + TypeNormalisedInputGetOrigin, + TypeNormalisedInputRelyingPartyId, + TypeNormalisedInputRelyingPartyName, +} from "./types"; +import { NormalisedAppinfo, UserContext } from "../../types"; +import { RecipeInterface, APIInterface } from "./types"; +import { BaseRequest } from "../../framework"; + +export function validateAndNormaliseUserInput( + recipeInstance: Recipe, + appInfo: NormalisedAppinfo, + config?: TypeInput +): TypeNormalisedInput { + let relyingPartyId = validateAndNormaliseRelyingPartyIdConfig(recipeInstance, appInfo, config?.relyingPartyId); + let relyingPartyName = validateAndNormaliseRelyingPartyNameConfig( + recipeInstance, + appInfo, + config?.relyingPartyName + ); + let getOrigin = validateAndNormaliseGetOriginConfig(recipeInstance, appInfo, config?.getOrigin); + + let override = { + functions: (originalImplementation: RecipeInterface) => originalImplementation, + apis: (originalImplementation: APIInterface) => originalImplementation, + ...config?.override, + }; + + function getEmailDeliveryConfig(isInServerlessEnv: boolean) { + let emailService = config?.emailDelivery?.service; + /** + * If the user has not passed even that config, we use the default + * createAndSendCustomEmail implementation which calls our supertokens API + */ + // if (emailService === undefined) { + // emailService = new BackwardCompatibilityService(appInfo, isInServerlessEnv); + // } + return { + ...config?.emailDelivery, + /** + * if we do + * let emailDelivery = { + * service: emailService, + * ...config.emailDelivery, + * }; + * + * and if the user has passed service as undefined, + * it it again get set to undefined, so we + * set service at the end + */ + // todo implemenet this + service: null as any, + }; + } + return { + override, + getOrigin, + relyingPartyId, + relyingPartyName, + getEmailDeliveryConfig, + }; +} + +function validateAndNormaliseRelyingPartyIdConfig( + _: Recipe, + __: NormalisedAppinfo, + relyingPartyIdConfig: TypeInputRelyingPartyId | undefined +): TypeNormalisedInputRelyingPartyId { + return (props) => { + if (typeof relyingPartyIdConfig === "string") { + return relyingPartyIdConfig; + } else if (typeof relyingPartyIdConfig === "function") { + return relyingPartyIdConfig(props); + } else { + return __.getOrigin({ request: props.request, userContext: props.userContext }).getAsStringDangerous(); + } + }; +} + +function validateAndNormaliseRelyingPartyNameConfig( + _: Recipe, + __: NormalisedAppinfo, + relyingPartyNameConfig: TypeInputRelyingPartyName | undefined +): TypeNormalisedInputRelyingPartyName { + return (props) => { + if (typeof relyingPartyNameConfig === "string") { + return relyingPartyNameConfig; + } else if (typeof relyingPartyNameConfig === "function") { + return relyingPartyNameConfig(props); + } else { + return __.appName; + } + }; +} + +function validateAndNormaliseGetOriginConfig( + _: Recipe, + __: NormalisedAppinfo, + getOriginConfig: TypeInputGetOrigin | undefined +): TypeNormalisedInputGetOrigin { + return (props) => { + if (typeof getOriginConfig === "function") { + return getOriginConfig(props); + } else { + return __.getOrigin({ request: props.request, userContext: props.userContext }).getAsStringDangerous(); + } + }; +} + +export async function defaultEmailValidator(value: any) { + // We check if the email syntax is correct + // As per https://github.com/supertokens/supertokens-auth-react/issues/5#issuecomment-709512438 + // Regex from https://stackoverflow.com/a/46181/3867175 + + if (typeof value !== "string") { + return "Development bug: Please make sure the email field yields a string"; + } + + if ( + value.match( + /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ + ) === null + ) { + return "Email is invalid"; + } + + return undefined; +} + +export function getPasswordResetLink(input: { + appInfo: NormalisedAppinfo; + token: string; + tenantId: string; + request: BaseRequest | undefined; + userContext: UserContext; +}): string { + return ( + input.appInfo + .getOrigin({ + request: input.request, + userContext: input.userContext, + }) + .getAsStringDangerous() + + input.appInfo.websiteBasePath.getAsStringDangerous() + + "/reset-password?token=" + + input.token + + "&tenantId=" + + input.tenantId + ); +} diff --git a/lib/ts/types.ts b/lib/ts/types.ts index e87e6b2a7..482d41b9d 100644 --- a/lib/ts/types.ts +++ b/lib/ts/types.ts @@ -115,6 +115,9 @@ export type User = { id: string; userId: string; }[]; + webauthn: { + credentialIds: string[]; + }[]; loginMethods: (RecipeLevelUser & { verified: boolean; hasSameEmailAs: (email: string | undefined) => boolean; diff --git a/lib/ts/user.ts b/lib/ts/user.ts index 365e0f846..87213468e 100644 --- a/lib/ts/user.ts +++ b/lib/ts/user.ts @@ -11,6 +11,7 @@ export class LoginMethod implements RecipeLevelUser { public readonly email?: string; public readonly phoneNumber?: string; public readonly thirdParty?: RecipeLevelUser["thirdParty"]; + public readonly webauthn?: RecipeLevelUser["webauthn"]; public readonly verified: boolean; public readonly timeJoined: number; @@ -23,7 +24,7 @@ export class LoginMethod implements RecipeLevelUser { this.email = loginMethod.email; this.phoneNumber = loginMethod.phoneNumber; this.thirdParty = loginMethod.thirdParty; - + this.webauthn = loginMethod.webauthn; this.timeJoined = loginMethod.timeJoined; this.verified = loginMethod.verified; } @@ -73,6 +74,7 @@ export class LoginMethod implements RecipeLevelUser { email: this.email, phoneNumber: this.phoneNumber, thirdParty: this.thirdParty, + webauthn: this.webauthn, timeJoined: this.timeJoined, verified: this.verified, }; @@ -90,6 +92,9 @@ export class User implements UserType { id: string; userId: string; }[]; + public readonly webauthn: { + credentialIds: string[]; + }[]; public readonly loginMethods: LoginMethod[]; public readonly timeJoined: number; // minimum timeJoined value from linkedRecipes @@ -102,7 +107,7 @@ export class User implements UserType { this.emails = user.emails; this.phoneNumbers = user.phoneNumbers; this.thirdParty = user.thirdParty; - + this.webauthn = user.webauthn; this.timeJoined = user.timeJoined; this.loginMethods = user.loginMethods.map((m) => new LoginMethod(m)); @@ -117,6 +122,7 @@ export class User implements UserType { emails: this.emails, phoneNumbers: this.phoneNumbers, thirdParty: this.thirdParty, + webauthn: this.webauthn, loginMethods: this.loginMethods.map((m) => m.toJson()), timeJoined: this.timeJoined, @@ -135,8 +141,11 @@ export type UserWithoutHelperFunctions = { id: string; userId: string; }[]; + webauthn: { + credentialIds: string[]; + }[]; loginMethods: { - recipeId: "emailpassword" | "thirdparty" | "passwordless"; + recipeId: "emailpassword" | "thirdparty" | "passwordless" | "webauthn"; recipeUserId: string; tenantIds: string[]; @@ -146,6 +155,9 @@ export type UserWithoutHelperFunctions = { id: string; userId: string; }; + webauthn?: { + credentialIds: string[]; + }; verified: boolean; timeJoined: number;