-
Notifications
You must be signed in to change notification settings - Fork 112
H-2421: Require email verification for users; add TOTP MFA #8407
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weβll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
37 commits
Select commit
Hold shift + click to select a range
5686c48
add plans
CiaranMn 64ac604
wip: add email verification requirement, optional TOTP MFA
CiaranMn 101e3be
Merge branch 'main' into cm/add-email-verification
CiaranMn 6e3cc17
improve unverified email cleanup logic
CiaranMn a5b862a
tidy up resolver list
CiaranMn ba49360
remove unnecessary code
CiaranMn ae63dde
add HASH account name to TOTP identifier
CiaranMn e17a95d
shorten rate limiter window
CiaranMn b9f69ac
validate password / TOTP before allowing relevant settings change
CiaranMn 9997510
prevent unnecessary re-renders
CiaranMn e9b076d
move / clean up files
CiaranMn 66474b9
update Ory email templates
CiaranMn a0b9608
signup flow UI improvements, bug fixes
CiaranMn 7a1c4e1
improve kratos email formatting
CiaranMn 313a2e1
bug / ui fixes
CiaranMn 49ecd7c
sign up flow fixes, test fixes, email template padding
CiaranMn 434de7b
Merge branch 'main' into cm/add-email-verification
CiaranMn 94e4b02
Update Ory Kratos URLs in external services docker-compose.yml
TimDiekmann a2b6c5d
fix tests
CiaranMn 3163037
fix tests
CiaranMn 4cae255
fix tests(?), incorrect code handling, Kratos continue_as config
CiaranMn 13f1e46
remove unneeded verify button clicks
CiaranMn 32d4260
add mailslurper diagnostics
CiaranMn dbead58
Merge branch 'main' into cm/add-email-verification
CiaranMn 5981b00
disable email verification cleanup for now
CiaranMn c11a507
Merge branch 'cm/add-email-verification' of github.com:hashintel/hashβ¦
CiaranMn cdf0a2f
comment out unused import
CiaranMn 03b771c
handle signup page for already-verified users
CiaranMn 5aae8cd
further tweak signup logic
CiaranMn bb436e7
Merge branch 'main' into cm/add-email-verification
CiaranMn 24ce4cc
more test fixes
CiaranMn 450f4d8
comment out TOTP UI for now
CiaranMn 160ddc7
slightly bump rate limit
CiaranMn 3c513f5
skip TOTP tests
CiaranMn ccc35f6
fix gate on getPendingInvitationByEntityId
CiaranMn 936ba0f
PR feedback
CiaranMn 4c6c4ee
fix docker compose Kratos public URL
CiaranMn File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
221 changes: 221 additions & 0 deletions
221
apps/hash-api/src/auth/create-unverified-email-cleanup-job.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,221 @@ | ||
| import type { Logger } from "@local/hash-backend-utils/logger"; | ||
| import { queryEntities } from "@local/hash-graph-sdk/entity"; | ||
| import { | ||
| currentTimeInstantTemporalAxes, | ||
| generateVersionedUrlMatchingFilter, | ||
| } from "@local/hash-isomorphic-utils/graph-queries"; | ||
| import { systemEntityTypes } from "@local/hash-isomorphic-utils/ontology-type-ids"; | ||
| import type { User as UserEntity } from "@local/hash-isomorphic-utils/system-types/user"; | ||
| import type { Identity } from "@ory/kratos-client"; | ||
|
|
||
| import type { ImpureGraphContext } from "../graph/context-types"; | ||
| import { getUserFromEntity } from "../graph/knowledge/system-types/user"; | ||
| import { systemAccountId } from "../graph/system-account"; | ||
| import { deleteKratosIdentity, kratosIdentityApi } from "./ory-kratos"; | ||
|
|
||
| /** | ||
| * Identities created before this date are excluded from cleanup, preventing | ||
| * retroactive deletion of accounts that existed before email verification | ||
| * was introduced. | ||
| */ | ||
| const DEFAULT_ROLLOUT_AT = new Date("2026-02-14T00:00:00.000Z"); | ||
| const DEFAULT_RELEASE_TTL_HOURS = 24 * 7; | ||
| const DEFAULT_SWEEP_INTERVAL_MINUTES = 60; | ||
|
|
||
| const parsePositiveIntegerEnv = ( | ||
| rawValue: string | undefined, | ||
| fallback: number, | ||
| envVarName: string, | ||
| ) => { | ||
| if (!rawValue) { | ||
| return fallback; | ||
| } | ||
|
|
||
| const parsedValue = Number.parseInt(rawValue, 10); | ||
| if (Number.isNaN(parsedValue) || parsedValue <= 0) { | ||
| throw new Error( | ||
| `${envVarName} must be a positive integer, got "${rawValue}"`, | ||
| ); | ||
| } | ||
|
|
||
| return parsedValue; | ||
| }; | ||
|
|
||
| const parseRolloutDate = (rawValue: string | undefined): Date => { | ||
| if (!rawValue) { | ||
| return DEFAULT_ROLLOUT_AT; | ||
| } | ||
|
|
||
| const parsedDate = new Date(rawValue); | ||
| if (Number.isNaN(parsedDate.getTime())) { | ||
| throw new Error( | ||
| `HASH_EMAIL_VERIFICATION_ROLLOUT_AT must be an ISO-8601 date, got "${rawValue}"`, | ||
| ); | ||
| } | ||
|
|
||
| return parsedDate; | ||
| }; | ||
|
|
||
| const parseIdentityCreatedAt = (identity: Identity): Date | undefined => { | ||
| if (!identity.created_at) { | ||
| return undefined; | ||
| } | ||
|
|
||
| const createdAt = new Date(identity.created_at); | ||
|
|
||
| if (Number.isNaN(createdAt.getTime())) { | ||
| return undefined; | ||
| } | ||
|
|
||
| return createdAt; | ||
| }; | ||
|
|
||
| const isPrimaryEmailVerified = (identity: Identity): boolean => { | ||
| const identityTraits = identity.traits as { emails?: string[] }; | ||
| const primaryEmailAddress = identityTraits.emails?.[0]; | ||
|
|
||
| if (!primaryEmailAddress) { | ||
| return false; | ||
| } | ||
|
|
||
| return ( | ||
| identity.verifiable_addresses?.find( | ||
| ({ value }) => value === primaryEmailAddress, | ||
| )?.verified === true | ||
| ); | ||
| }; | ||
|
|
||
| export const createUnverifiedEmailCleanupJob = ({ | ||
| context, | ||
| logger, | ||
| }: { | ||
| context: ImpureGraphContext; | ||
| logger: Logger; | ||
| }) => { | ||
| const rolloutAt = parseRolloutDate( | ||
| process.env.HASH_EMAIL_VERIFICATION_ROLLOUT_AT, | ||
| ); | ||
|
|
||
| const releaseTtlHours = parsePositiveIntegerEnv( | ||
| process.env.HASH_EMAIL_VERIFICATION_RELEASE_TTL_HOURS, | ||
| DEFAULT_RELEASE_TTL_HOURS, | ||
| "HASH_EMAIL_VERIFICATION_RELEASE_TTL_HOURS", | ||
| ); | ||
|
|
||
| const sweepIntervalMinutes = parsePositiveIntegerEnv( | ||
| process.env.HASH_EMAIL_VERIFICATION_RELEASE_SWEEP_INTERVAL_MINUTES, | ||
| DEFAULT_SWEEP_INTERVAL_MINUTES, | ||
| "HASH_EMAIL_VERIFICATION_RELEASE_SWEEP_INTERVAL_MINUTES", | ||
| ); | ||
|
|
||
| const releaseTtlMs = releaseTtlHours * 60 * 60 * 1_000; | ||
| const sweepIntervalMs = sweepIntervalMinutes * 60 * 1_000; | ||
|
|
||
| const cleanupUnverifiedUsers = async () => { | ||
| const now = Date.now(); | ||
| const authentication = { actorId: systemAccountId }; | ||
|
|
||
| const { entities: userEntities } = await queryEntities<UserEntity>( | ||
| context, | ||
| authentication, | ||
| { | ||
| filter: { | ||
| all: [ | ||
| generateVersionedUrlMatchingFilter( | ||
| systemEntityTypes.user.entityTypeId, | ||
| { | ||
| ignoreParents: true, | ||
| }, | ||
| ), | ||
| { | ||
| equal: [{ path: ["archived"] }, { parameter: false }], | ||
| }, | ||
| ], | ||
| }, | ||
| temporalAxes: currentTimeInstantTemporalAxes, | ||
| includeDrafts: false, | ||
| includePermissions: false, | ||
| }, | ||
| ); | ||
|
|
||
| let releasedEmailCount = 0; | ||
|
|
||
| for (const userEntity of userEntities) { | ||
| const user = getUserFromEntity({ entity: userEntity }); | ||
|
|
||
| if (user.isAccountSignupComplete) { | ||
| continue; | ||
| } | ||
|
|
||
| try { | ||
| const { data: identity } = await kratosIdentityApi.getIdentity({ | ||
| id: user.kratosIdentityId, | ||
| }); | ||
|
|
||
| const createdAt = parseIdentityCreatedAt(identity); | ||
| if (!createdAt || createdAt < rolloutAt) { | ||
| continue; | ||
| } | ||
|
|
||
| if (now - createdAt.getTime() < releaseTtlMs) { | ||
| continue; | ||
| } | ||
|
|
||
| const primaryEmail = user.emails[0]; | ||
| if (!primaryEmail) { | ||
| logger.warn( | ||
| `User ${user.accountId} (${user.kratosIdentityId}) has no email addresses, skipping`, | ||
| ); | ||
| continue; | ||
| } | ||
|
|
||
| if (isPrimaryEmailVerified(identity)) { | ||
| continue; | ||
| } | ||
|
|
||
| await user.entity.archive( | ||
| context.graphApi, | ||
| authentication, | ||
| context.provenance, | ||
| ); | ||
| await deleteKratosIdentity({ | ||
| kratosIdentityId: user.kratosIdentityId, | ||
| }); | ||
|
|
||
| releasedEmailCount += 1; | ||
| } catch (error) { | ||
| logger.warn( | ||
| `Failed to process unverified user ${user.accountId} (${user.kratosIdentityId}) for email release: ${error}`, | ||
| ); | ||
| } | ||
| } | ||
|
|
||
| if (releasedEmailCount > 0) { | ||
| logger.info( | ||
| `Released ${releasedEmailCount} unverified email address${releasedEmailCount === 1 ? "" : "es"}.`, | ||
| ); | ||
| } | ||
| }; | ||
|
|
||
| let interval: NodeJS.Timeout | undefined; | ||
| let inFlightCleanup: Promise<void> | undefined; | ||
|
|
||
| return { | ||
| start: async () => { | ||
| logger.info( | ||
| `Starting unverified-email cleanup job (rolloutAt=${rolloutAt.toISOString()}, ttlHours=${releaseTtlHours}, intervalMinutes=${sweepIntervalMinutes})`, | ||
| ); | ||
|
|
||
| await cleanupUnverifiedUsers(); | ||
| interval = setInterval(() => { | ||
| inFlightCleanup = cleanupUnverifiedUsers(); | ||
| }, sweepIntervalMs); | ||
| }, | ||
| stop: async () => { | ||
| if (interval) { | ||
| clearInterval(interval); | ||
| } | ||
| await inFlightCleanup; | ||
| }, | ||
| }; | ||
| }; | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.