Skip to content

Commit

Permalink
fix: improve rate limit
Browse files Browse the repository at this point in the history
  • Loading branch information
Nicolas Burtey committed Feb 11, 2024
1 parent 7513526 commit 3ab067e
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 6 deletions.
25 changes: 20 additions & 5 deletions core/api/src/app/authentication/totp.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,21 @@
import { createHash } from "crypto"

import { checkLoginAttemptPerLoginIdentifierLimits } from "./ratelimits"

import {
AuthTokenUserIdMismatchError,
IdentifierNotFoundError,
} from "@/domain/authentication/errors"
import {
validateKratosToken,
kratosValidateTotp,
kratosInitiateTotp,
AuthWithEmailPasswordlessService,
AuthWithPhonePasswordlessService,
kratosElevatingSessionWithTotp,
kratosInitiateTotp,
kratosRemoveTotp,
kratosValidateTotp,
logoutSessionByAuthToken,
refreshToken,
AuthWithPhonePasswordlessService,
AuthWithEmailPasswordlessService,
validateKratosToken,
} from "@/services/kratos"
import { kratosAdmin } from "@/services/kratos/private"

Expand Down Expand Up @@ -119,6 +123,17 @@ export const elevatingSessionWithTotp = async ({
authToken: AuthToken
totpCode: TotpCode
}): Promise<boolean | KratosError> => {
// hashing the authToken to use it as a key for the rate limit
// this limit exposure of the authToken in redis
const hashedAuthToken = createHash("sha256")
.update(authToken)
.digest("hex") as HashedAuthToken

{
const limitOk = await checkLoginAttemptPerLoginIdentifierLimits(hashedAuthToken)
if (limitOk instanceof Error) return limitOk
}

return kratosElevatingSessionWithTotp({ authToken, totpCode })
}

Expand Down
3 changes: 3 additions & 0 deletions core/api/src/domain/authentication/index.types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ type UserId = string & { readonly brand: unique symbol }
type PrivilegedClientId = string & { readonly brand: unique symbol }
type AuthToken = string & { readonly brand: unique symbol }

// when used in redis for rate limiting
type HashedAuthToken = string & { readonly brand: unique symbol }

type TotpSecret = string & { readonly brand: unique symbol }
type TotpCode = string & { readonly brand: unique symbol }

Expand Down
2 changes: 1 addition & 1 deletion core/api/src/domain/users/index.types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ type PhoneCode = string & { readonly brand: unique symbol }
type EmailAddress = string & { readonly brand: unique symbol }
type EmailCode = string & { readonly brand: unique symbol }

type LoginIdentifier = PhoneNumber | EmailAddress
type LoginIdentifier = PhoneNumber | EmailAddress | HashedAuthToken

type DeviceId = string & { readonly brand: unique symbol }

Expand Down

0 comments on commit 3ab067e

Please sign in to comment.