Skip to content

Commit

Permalink
feat: Multifactor authentication (#741)
Browse files Browse the repository at this point in the history
* feat(mfa): initial types (#708)

* feat: add (partial) initial types for MFA

* feat: expand the MFA recipe interface

* feat: add export point for mfa

* feat: update based on review discussions

* feat: add extra params to MFARequirements callbacks to help customizations

* feat: implement review feedback

* feat: implement review comments

* feat: implement review comments

* feat: stricter type for first factor/mfa requirement

* feat: remove distinction between built-in and custom factors (#729)

* fix: MFA type updates (#737)

* fix: type fix and account linking functions

* fix: cdi version update

* fix: more type updates

* fix: tests

* fix: TOTP recipe (#739)

* fix: type fix and account linking functions

* fix: cdi version update

* fix: more type updates

* fix: tests

* fix: totp recipe

* fix: totp types

* fix: update types

* fix: totp apis

* fix: user identifier info

* fix: recipe tests

* fix: test

* fix: pr comments

* fix: tests

* fix: PR comment

* fix: MFA implementation (#743)

* fix: type fix and account linking functions

* fix: cdi version update

* fix: more type updates

* fix: tests

* fix: totp recipe

* fix: totp types

* fix: update types

* fix: totp apis

* fix: user identifier info

* fix: recipe tests

* fix: test

* fix: basic mfa impl

* fix: pr comments

* fix: tests

* fix: factors setup from other recipe

* fix: getFactorsSetupForUser impl

* fix: getMFARequirementsForAuth impl

* fix: isAllowedToSetupFactor impl

* fix: addToDefaultRequiredFactorsForUser and getDefaultRequiredFactorsForUser impl

* fix: typo

* fix: build next array

* fix: remove error file

* fix: factorSetupForUser refactor

* fix: next array

* fix: api impl

* fix: typo

* fix: isValidFirstFactorForTenant

* fix: impl

* fix: updated impl

* feat: fix and update mfa imlp to make all e2e tests pass

* fix: adds overwriteSessionDuringSignIn config in session

* fix: error messages in claims

* fix: cleanup

* fix: new errors for sign in up APIs

* fix: add error in totp

* fix: marked MFA TODOs

* fix: new param in createNewSession

* fix: impl cleanup

* fix: remove MFA_ERROR

* fix: cdi version

* fix: test fix

* fix: update/fix mfa impl to match e2e tests

* fix: pr comments

* fix: session user deleted error

* fix: adding cache to getUserById

* fix: get user cache

* caching in querier

* fix: mfa impl

* fix: email selection

* fix: mfa claims

* fix: remove unnecessary file

* fix: pr comment

* fix: PR comments

* fix: session handling

* fix: review comments

* fix: defaultRequiredFactorsForUser is now appwide

* fix: using accountlinking instead of mfa for primary user and link accounts

* fix: overwrite session flag refactor

* fix: race conditions in createOrUpdateSessionForMultifactorAuthAfterFactorCompletion

* fix: race conditions in createOrUpdateSessionForMultifactorAuthAfterFactorCompletion

* fix: recipe functions refactor

* fix: contact support case

* fix: unnecessary file

* fix: test

* refactor: added shouldRefetch + fetchValue building the next array into MFAclaim (#758)

* fix: usercontext type

* fix: test

* fix: test

* feat: add access token payload param to claim.build

* feat: expose addToDefaultRequiredFactorsForUser and remove tenantId param

* fix: remaining TODOs

* fix: auto init tests related to mfa

* fix: recipe function tests

* fix: create new session refactor

* fix: recipe interface refactor

* fix: userContext type fix

* fix: test

* fix: test

* fix: session

* fix: user context and support codes

* fix: type fixes after merge

* fix: test

* fix: pr comments

* fix: pr comment

* fix: test

* fix: available factors

* fix: updated user object

* fix: shouldAttemptAccountLinkingIfAllowed

* fix: missed types and test fixes

* fix: mfa fixes and tests

* fix: more tests

---------

Co-authored-by: Mihaly Lengyel <mihaly@lengyel.tech>

* fix: contact support case when existing user signs in

* fix: shouldAttemptAccountLinkingIfAllowed

* fix: tackling some corner cases with account linking and user sign up

* fix: isSignUpAllowed condition

* fix: branded type explanation

* fix: revert verifyEmailForRecipeUserIfLinkedAccountsAreVerified

* fix: fixing shouldAttemptAccountLinkingIfAllowed typing

* fix: recipe id check in emailpassword

* fix: comment on not checking for tenantId

* fix: remove implicit tenantInfo

* fix: remove implicit tenantInfo

* fix: duplicate factorIds

* fix: not required params in validateForMultifactorAuthBeforeFactorCompletion

* fix: input type of validateForMultifactorAuthBeforeFactorCompletion

* changes impl of getMFARequirementsForAuth to remove oldest factor id

* fix: rename defaultRequiredFactors to requiredSecondaryFactors for user

* fix: update multitenancy core api

* fix: add remove required secondary factors for user

* fix: exposing known factor idsstnbp

* fix: move to recipe impl

* fix: not automatically assuming otp as setup

* fix: update mfa info response

* fix: changed mfa/info to PUT

* fix: user refetch in emailpassword

* fix: updated comments

* fix: constant name

* fix: factor flow impl in emailpassword and passwordless

* fix: factor flow for thirdparty

* fix: totp verification

* fix: remove createNewOrKeepExistingSession

* fix: improve createOrUpdateSessionForMultifactorAuthAfterFactorCompletion

* fix: phoneNumber check

* fix: sign in/up status refactor

* fix: sign in/up status

* fix: tests

* fix: tests

* feat: return email addresses for pwless factors based on the discussed priority order

* fix: firstFactor validation and loginmethods

* fix: userContext types and test

* fix: misc changes

* fix: emails for factor

* fix: param rename

* fix: msg update

* fix: shouldAttemptAccountLinkingIfAllowed in thirdparty

* fix: updated race conditions recursions

* fix: removed tenantId checks for mfa

* fix: recursion for support cases

* fix: revert recursion fix to return 011

* fix: support code flows

* fix: recursion point

* fix: rename allOf to allOfInAnyOrder

* fix: support codes

* fix: copyright update

* fix: copyright update

* fix: implicit check

* fix: support codes

* fix: mfa flow refactor (#771)

mfa flow refactor and support codes

* fix: typo

* fix: comments

* fix: next array (#770)

mfa info endpoint changes

* fix: support code messages

* fix: rename isAllowedToSetup and return claim error

* fix: call checkAllowedToSetupFactorElseThrowInvalidClaimError in createCode and createDevice

* fix: fixed status

* fix: createNewSession param type

* fix: mfa validation only on sign up in createCode

* fix: factor check in create code

* fix: factor check in create code

* fix: remove mfa check in createCode

* fix: removed unused status

* fix: thirdparty api refactor

* fix: passwordless api refactor and thirdparty api refactor fixes

* fix: emailpassword api refactor and fixes in pless and tparty apis

* fix: fixes after refactor

* fix: clean up is valid first factor

* fix: pr comments

* fix: pr comments

* fix: refactor

* fix: refactor

* fix: internal function for get user metadata for MFA

* fix: pr comment

* fix: race conditions

* fix: refactor all factors

* fix: comments

* fix: assertAllowedToSetupFactorElseThrowInvalidClaimError in verify device

* fix: tests

* fix: add comment

* fix: refactor resync api stuff

* fix: refactor missing claims

* fix: dedup code in mfa claim

* fix: pr comments for emailpassword

* fix: pr comments for emailpassword

* fix: pr comments

* fix: pr comments for email password

* fix: pr comments for passwordless

* fix: pr comments for thirdparty

* fix: pr comments

* fix: move recurse outside

* fix: move assert sign in is allowed

* fixes and changes

* thirdparty recipe change

* fix: cyclic dependency

* fix: test

* fix: claim value type

* fix: pr comments from ep to pless

* fix: remove internal functions from usermetadata

* fix: context in session class

* fix: session required in signout

* fix: remove implicit check

* fix: doUnionOfAccountInfo false for consistency

* fix: pr comments from ep in pless

* fix: remove shouldAttemptAccountLinkingIfAllowed in passwordless

* fix: make isValidFirstFactor more readble with comments

* fix: remove tenantId from getFactorsSetupForuser

* fix: PR comments

* fix: refactor totp

* fix: post init callbacks to constructor

* fix: totp PR comments

* fix: error messages, test and fetch failure check

* fix: tests

* fix: tests

* fix: PR comments

* fix: Pr comments

* fix: missed await + test fix

* fix: missed await

* fix: pr comments

* fix: not use splice

* fix: user metadata refactor

* fix: mfa refactor

* fix: self review

* fix: clean up and comments

* fix: comment

* fix: refactor factorIds

* fix: refactor factorIds

* fix: handle unknown user id error in totp

* fix: updated signout

* fix: removed extra code

* fix: session and tenantId in createCode

* fix: first factor computation

* fix: comment

* fix: createRecipeUser in pless

* fix: factor completion in thirdparty signInUp

* fix: updated fake email

* fix: should attempt account linking in third party

* fix: throw unauthorised for tenant not found

* fix: signout api

* fix: cyclic dependency

* fix: shouldAttemptAccountLinkingIfAllowed

* fix: check claims error and throw others

* fix: remove unnecessary session undefined check

* fix: session in create code and resend code POST

* fix: tenant not found

* fix: mfa claim updation in util function

* fix: revert to original :(

* fix: revert to original :(

* fix: cleanup

* fix: pless createRecipeUser type

* fix: pless revert

* fix: querier caching to include headers

* feat: use dynamic signing key switching (#782)

* feat: enable a smooth switch between useDynamicAccessTokenSigningKey true and false

* Merging feat/mfa/base into feat/useDynamicSigningKey_switching

* fix: update prop name

* feat: move account linking related MFA things into account linking recipe (#788)

* feat: move account linking related MFA things into account linking recipe

* test: update test to match new linking logic

* feat(mfa)!: simplifying account linking flows

* feat(mfa): updating impl of other recipe sign in/up endpoints + add createRecipeUserIfNotExists to consume code

* feat: implement updated linking flow + fix tests

* chore: remove unnecessary code

* fix: fix typo/missing update

* refactor: implementing review comments

* refactor: implementing review comments

* fix: add retry logic to createPrimaryUserIdOrLinkAccounts index func

* fix: use hasSameEmailAs instead of ===

* refactor: improve getAuthenticatingUserAndAddToCurrentTenantIfRequired input types & comments

* fix: remove wrong emailverification check from tryLinkAccounts

* refactor: removed unnecessary status + added explanation comments

* refactor: implement review comments

* refactor: implement review comments + move functions

* fix: fix accidentally flipped condition

* fix: tidy up typos

* fix: update func impl after moving

* fix: cleaning up and updating tests

* feat: refactoring for latest review comments

* test: add mock for verifyCode

* fix: cleanup and test fixes

* chore: update error code reason strings

* feat: remove factorIds from createCode input

* fix: properly compare recipeUserIds as strings

* feat: add signInVerifiesLoginMethod and minor cleanup/fixes

* test: add new tests + update cases for new account linking logic/interface

* fix: login methods (#794)

* fix: login methods fix

* fix: cleanup

* fix: cleanup

* fix: pr comments

* fix: pr comment

* fix: better test names

* fix: comparision

* feat: self-review fixes

* chore: update changelog

* feat: self-review fixes

* feat: remove shouldAttemptAccountLinkingIfAllowed

* feat: add verifyCredentials to ep and tpep recipes

* feat: self-review fixes and latest discussions

* fix: return userType instead of the user class consistently in the index files

* feat: properly expose verifyCredentials and verifyCode

* fix: add some missing tests and a related fix

* feat: add call count tests and improve call counts

* refactor: not trying linking if shouldDoAutomaticAccountLinking wasn't defined by the app

* feat: implement review feedback

* chore: add version number and compatibility section into changelog

* feat: update mfa interface to optimize for less core calls

* feat: make the core call cache reset globally if a call was made without usercontext

* feat: ensure the email verification api can update the session if necessary

* feat: verify the user in consume code if possible before trying to make it primary

* feat: update verifyCredentials types to re-use it in signIn

* feat: add disableCoreCallCache

* refactor: remove resolved comment

* chore: update changelog

* feat: move the skipSessionUserUpdateInCore check before we check EV status

* feat: fix tests & update for latest core

* docs: fix jsdocs for pwless

* docs: add explanation comment

* feat: cache the result of checkCode in pwless consume code api

* feat: add new param to revokeCode

* feat: update changelog + consistency

---------

Co-authored-by: Mihály Lengyel <mihaly@lengyel.tech>
Co-authored-by: Rishabh Poddar <rishabh.poddar@gmail.com>
  • Loading branch information
3 people authored Mar 12, 2024
1 parent 3f4f5ec commit 51e1ab2
Show file tree
Hide file tree
Showing 498 changed files with 31,547 additions and 6,758 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,5 @@ apiPassword
releasePassword
.tmp
.idea
/test_report
/test_report
/.nyc_output
228 changes: 228 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,234 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [unreleased]

## [17.0.0] - 2024-03-08

### Changes

- Enable smooth switching between `useDynamicAccessTokenSigningKey` settings by allowing refresh calls to change the signing key type of a session
- Added a core call cache that should reduce traffic to your SuperTokens core instances
- Refactored sign in/up API codes to reduce code duplication
- Added MFA related information to dashboard APIs
- Added a cache to reduce the number of requests made to the core. This can be disabled using the `disableCoreCallCache: true`, in the config.
- Added new `overwriteSessionDuringSignInUp` configuration option to the Session recipe
- Added new function: `checkCode` to Passwordless and ThirdPartyPasswordless recipes
- Added new function: `verifyCredentials` to EmailPassword and ThirdPartyEmailPassword recipes
- Added the `MultiFactorAuth` and `TOTP` recipes. To start using them you'll need compatible versions:
- Core>=8.0.0
- supertokens-node>=17.0.0
- supertokens-website>=18.0.0
- supertokens-web-js>=0.10.0
- supertokens-auth-react>=0.39.0

### Breaking changes

- Now only supporting CDI 5.0. Compatible with core version >= 8.0
- Account linking now takes the active session into account.
- Fixed the typing of the `userContext`:
- All functions now take `Record<string, any>` instead of `any` as `userContext`. This means that primitives (strings, numbers) are no longer allowed as `userContext`.
- All functions overrides that take a `userContext` parameter now get a well typed `userContext` parameter ensuring that the right object is passed to the original implementation calls
- Calling sign in/up APIs with a session will now skip creating a new session by default. This is overrideable through by passing `overwriteSessionDuringSignInUp: true` to the Session recipe config.
- Added new support codes to sign in/up APIs. This means that there are new possible values coming from the default implementation for the `reason` strings of `SIGN_IN_NOT_ALLOWED`, `SIGN_UP_NOT_ALLOWED` and `SIGN_IN_UP_NOT_ALLOWED` responses.
- `AccountLinking` recipe:
- Changed the signature of the following functions, each taking a new (optional) `session` parameter:
- `createPrimaryUserIdOrLinkAccounts`
- `isSignUpAllowed`
- `isSignInAllowed`
- `isEmailChangeAllowed`
- Changed the signature of the `shouldDoAutomaticAccountLinking` callback: it now takes a new (optional) session parameter.
- `EmailPassword`:
- Changed the signature of the following overrideable functions:
- `signUp`
- Takes a new (optional) `session` parameter
- Can now return with `status: "LINKING_TO_SESSION_USER_FAILED"`
- `signIn`
- Takes a new (optional) `session` parameter
- Can now return with `status: "LINKING_TO_SESSION_USER_FAILED"`
- Changed the signature of overrideable APIs, adding a new (optional) session parameter:
- `signInPOST`
- `signUpPOST`
- Changed the signature of functions:
- `signUp`
- Takes a new (optional) `session` parameter
- Can now return with `status: "LINKING_TO_SESSION_USER_FAILED"`
- `signIn`
- Takes a new (optional) `session` parameter
- Can now return with `status: "LINKING_TO_SESSION_USER_FAILED"
- `Multitenancy`:
- Changed the signature of the following functions:
- `createOrUpdateTenant`: Added optional `firstFactors` and `requiredSecondaryFactors` parameters.
- `getTenant`: Added `firstFactors` and `requiredSecondaryFactors` to the return type
- `listAllTenants`: Added `firstFactors` and `requiredSecondaryFactors` to the returned tenants
- Changed the signature of the following overrideable functions:
- `createOrUpdateTenant`: Now gets optional `firstFactors` and `requiredSecondaryFactors` in the input.
- `getTenant`: Added `firstFactors` and `requiredSecondaryFactors` to the return type
- `listAllTenants`: Added `firstFactors` and `requiredSecondaryFactors` to the returned tenants
- Changed the signature of the overrideable apis:
- `loginMethodsGET`: Now returns `firstFactors`
- `Passwordless`:
- `revokeCode` (and the related overrideable func) can now be called with either `preAuthSessionId` or `codeId` instead of only `codeId`.
- Added new email and sms type for MFA
- Changed the signature of the following functions:
- `signInUp`, `createCode`: Takes a new (optional) `session` parameter
- `consumeCode`:
- Takes a new (optional) `session` parameter
- Can now return with `status: "LINKING_TO_SESSION_USER_FAILED"`
- It now also returns `consumedDevice` if the code was successfully consumed
- Changed the signature of the following overrideable functions:
- `createCode`: Takes a new (optional) `session` parameter
- `consumeCode`:
- Takes a new (optional) `session` parameter
- Can now return with `status: "LINKING_TO_SESSION_USER_FAILED"`
- It now also returns `consumedDevice` if the code was successfully consumed
- Changed the signature of overrideable APIs, adding a new (optional) session parameter:
- `createCodePOST`
- `resendCodePOST`
- `consumeCodePOST`
- Custom claims:
- `fetchValue` now also gets the `currentPayload` as a parameter
- `ThirdParty`:
- Changed the signature of the following functions:
- `manuallyCreateOrUpdateUser`:
- Takes a new (optional) `session` parameter
- Can now return with `status: "LINKING_TO_SESSION_USER_FAILED"`
- Changed the signature of the following overrideable functions:
- `signInUp`:
- Takes a new (optional) `session` parameter
- Can now return with `status: "LINKING_TO_SESSION_USER_FAILED"`
- `manuallyCreateOrUpdateUser`
- Takes a new (optional) `session` parameter
- Can now return with `status: "LINKING_TO_SESSION_USER_FAILED"`
- Changed the signature of overrideable APIs, adding a new (optional) session parameter:
- `signInUpPOST`
- `ThirdPartyEmailPassword`:
- Added new function: `emailPasswordVerifyCredentials`
- Changed the signature of the following functions:
- `thirdPartyManuallyCreateOrUpdateUser`:
- Takes a new (optional) `session` parameter
- Can now return with `status: "LINKING_TO_SESSION_USER_FAILED"`
- `emailPasswordSignUp`
- Takes a new (optional) `session` parameter
- Can now return with `status: "LINKING_TO_SESSION_USER_FAILED"`
- Changed the signature of the following overrideable functions:
- `thirdPartySignInUp`:
- Takes a new (optional) `session` parameter
- Can now return with `status: "LINKING_TO_SESSION_USER_FAILED"`
- `thirdPartyManuallyCreateOrUpdateUser`
- Takes a new (optional) `session` parameter
- Can now return with `status: "LINKING_TO_SESSION_USER_FAILED"`
- `emailPasswordSignUp`
- Takes a new (optional) `session` parameter
- Can now return with `status: "LINKING_TO_SESSION_USER_FAILED"`
- Changed the signature of overrideable APIs, adding a new (optional) session parameter:
- `emailPasswordSignInPOST`
- `emailPasswordSignUpPOST`
- `thirdPartySignInUpPOST`
- `ThirdPartyPasswordless`:
- `revokeCode` (and the related overrideable func) can now be called with either `preAuthSessionId` or `codeId` instead of only `codeId`.
- Changed the signature of the following functions:
- `thirdPartyManuallyCreateOrUpdateUser`:
- Takes a new (optional) `session` parameter
- Can now return with `status: "LINKING_TO_SESSION_USER_FAILED"`
- `passwordlessSignInUp`, `createCode`: Takes a new (optional) `session` parameter
- `consumeCode`:
- Takes a new (optional) `session` parameter
- Can now return with `status: "LINKING_TO_SESSION_USER_FAILED"`
- It now also returns `consumedDevice` if the code was successfully consumed
- Changed the signature of the following overrideable functions:
- `thirdPartySignInUp`:
- Takes a new (optional) `session` parameter
- Can now return with `status: "LINKING_TO_SESSION_USER_FAILED"`
- `thirdPartyManuallyCreateOrUpdateUser`
- Takes a new (optional) `session` parameter
- Can now return with `status: "LINKING_TO_SESSION_USER_FAILED"`
- `createCode`: Takes a new (optional) `session` parameter
- `consumeCode`:
- Takes a new (optional) `session` parameter
- Can now return with `status: "LINKING_TO_SESSION_USER_FAILED"`
- It now also returns `consumedDevice` if the code was successfully consumed
- Changed the signature of overrideable APIs, adding a new (optional) session parameter:
- `thirdPartySignInUpPOST`
- `createCodePOST`
- `resendCodePOST`
- `consumeCodePOST`

#### Migration guide

##### shouldDoAutomaticAccountLinking signature change

If you use the `userContext` or `tenantId` parameters passed to `shouldDoAutomaticAccountLinking`, please update your implementation to account for the new parameter.

Before:

```ts
AccountLinking.init({
shouldDoAutomaticAccountLinking: async (newAccountInfo, user, tenantId, userContext) => {
return {
shouldAutomaticallyLink: true,
shouldRequireVerification: true,
};
},
});
```

After:

```ts
AccountLinking.init({
shouldDoAutomaticAccountLinking: async (newAccountInfo, user, session, tenantId, userContext) => {
return {
shouldAutomaticallyLink: true,
shouldRequireVerification: true,
};
},
});
```

##### Optional `session` parameter added to public functions

We've added a new optional `session` parameter to many function calls. In all cases, these have been added as the last parameter before `userContext`, so this should only affect you if you are using that. You only need to pass a session as a parameter if you are using account linking and want to try and link the user signing in/up to the session user.
You can get the necessary session object using `verifySession` in an API call.

Here we use the example of `EmailPassword.signIn` but this fits other functions with changed signatures.

Before:

```ts
const signInResp = await EmailPassword.signIn("public", "asdf@asdf.asfd", "testpw", { myContextVar: true });
```

After:

```ts
const signInResp = await EmailPassword.signIn("public", "asdf@asdf.asfd", "testpw", undefined, { myContextVar: true });
```

##### `fetchValue` signature change

If you use the `userContext` parameter passed to `fetchValue`, please update your implementation to account for the new parameter.

Before:

```ts
const boolClaim = new BooleanClaim({
key: "asdf",
fetchValue: (userId, recipeUserId, tenantId, userContext) => {
return userContext.claimValue;
},
});
```

After:

```ts
const boolClaim = new BooleanClaim({
key: "asdf",
fetchValue: (userId, recipeUserId, tenantId, currentPayload, userContext) => {
return userContext.claimValue;
},
});
```

## [16.7.4] - 2024-03-01

- Adds a user friendly error screen that provides helpful information regarding Content Security Policy (CSP) issues..
Expand Down
2 changes: 1 addition & 1 deletion coreDriverInterfaceSupported.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
{
"_comment": "contains a list of core-driver interfaces branch names that this core supports",
"versions": ["4.0"]
"versions": ["5.0"]
}
Loading

0 comments on commit 51e1ab2

Please sign in to comment.