feat(identity): confirm the email address with a six-digit code from the message

This commit is contained in:
shira committed 2026-10-10 00:52:46 +03:00
1 parent c94434cd09
commit d365a05c96
87 files changed
+4764 -224

No files matched your search

@@ -37,6 +37,8 @@ export const getResendEmailVerificationResponseMock = (overrideResponse: Partial
export const getConfirmEmailResponseMock = (overrideResponse: Partial<Extract<EmailVerificationResult, object>> = {}): EmailVerificationResult => ({email_verified: faker.helpers.arrayElement([true] as const), scenario: faker.helpers.arrayElement(['candidate','employer'] as const), onboarding_step: faker.helpers.arrayElement(['candidate_consents','candidate_profile','candidate_questionnaire','candidate_assessment','employer_company','completed'] as const), ...overrideResponse})
export const getConfirmEmailByCodeResponseMock = (overrideResponse: Partial<Extract<EmailVerificationResult, object>> = {}): EmailVerificationResult => ({email_verified: faker.helpers.arrayElement([true] as const), scenario: faker.helpers.arrayElement(['candidate','employer'] as const), onboarding_step: faker.helpers.arrayElement(['candidate_consents','candidate_profile','candidate_questionnaire','candidate_assessment','employer_company','completed'] as const), ...overrideResponse})
export const getLoginResponseMock = (overrideResponse: Partial<Extract<Session, object>> = {}): Session => ({account: {id: faker.string.uuid(), email: faker.internet.email(), email_verified: faker.datatype.boolean(), scenario: faker.helpers.arrayElement(['candidate','employer'] as const), onboarding_step: faker.helpers.arrayElement(['candidate_consents','candidate_profile','candidate_questionnaire','candidate_assessment','employer_company','completed'] as const), created_at: faker.date.past().toISOString().slice(0, 19) + 'Z'}, csrf_token: fakeFromPattern("^[A-Za-z0-9_-]+$", {minLength: 32, maxLength: 128}), ...overrideResponse})
export const getGetCurrentSessionResponseMock = (overrideResponse: Partial<Extract<Session, object>> = {}): Session => ({account: {id: faker.string.uuid(), email: faker.internet.email(), email_verified: faker.datatype.boolean(), scenario: faker.helpers.arrayElement(['candidate','employer'] as const), onboarding_step: faker.helpers.arrayElement(['candidate_consents','candidate_profile','candidate_questionnaire','candidate_assessment','employer_company','completed'] as const), created_at: faker.date.past().toISOString().slice(0, 19) + 'Z'}, csrf_token: fakeFromPattern("^[A-Za-z0-9_-]+$", {minLength: 32, maxLength: 128}), ...overrideResponse})
@@ -92,6 +94,18 @@ export const getConfirmEmailMockHandler = (overrideResponse?: EmailVerificationR
}, options)
}
export const getConfirmEmailByCodeMockHandler = (overrideResponse?: EmailVerificationResult | ((info: Parameters<Parameters<typeof http.post>[1]>[0]) => Promise<EmailVerificationResult> | EmailVerificationResult), options?: RequestHandlerOptions) => {
return http.post('*/api/v1/identity/email-verifications/code', async (info: Parameters<Parameters<typeof http.post>[1]>[0]) => {
return HttpResponse.json(overrideResponse !== undefined
? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse)
: getConfirmEmailByCodeResponseMock(),
{ status: 200
})
}, options)
}
export const getLoginMockHandler = (overrideResponse?: Session | ((info: Parameters<Parameters<typeof http.post>[1]>[0]) => Promise<Session> | Session), options?: RequestHandlerOptions) => {
return http.post('*/api/v1/identity/sessions', async (info: Parameters<Parameters<typeof http.post>[1]>[0]) => {
@@ -142,6 +156,7 @@ export const getIdentityMock = () => [
getRegisterAccountMockHandler(),
getResendEmailVerificationMockHandler(),
getConfirmEmailMockHandler(),
getConfirmEmailByCodeMockHandler(),
getLoginMockHandler(),
getGetCurrentSessionMockHandler(),
getLogoutMockHandler(),
@@ -25,9 +25,11 @@ import type {
import type {
Account,
ConfirmEmailByCodeHeaders,
ConfirmEmailHeaders,
ConsentPurpose,
ConsentText,
EmailVerificationCodeRequest,
EmailVerificationRequest,
EmailVerificationResendRequest,
EmailVerificationResult,
@@ -453,6 +455,101 @@ export const useConfirmEmail = <TError = ErrorType<Problem>,
> => {
return useMutation(getConfirmEmailMutationOptions(options), queryClient);
}
export const getConfirmEmailByCodeUrl = () => {
return `/api/v1/identity/email-verifications/code`
}
/**
* Public operation without a session. The verification message carries a six-digit code next to the link. The client sends the address, the code, and the password chosen for the registration that issued the code, so the user types only the code after registration. A reloaded page has no password in memory, so it asks for the address, the password, and the code together.
*
* The server finds the newest open verification token of the unverified account with this normalized address, whose registration is current and which carries a code. It compares the keyed digest of the code with the stored digest, checks the password against the token's pending password hash, and checks that the code has not expired. The code lives 30 minutes, or until the token ends if the token ends sooner. When all three checks pass, the server consumes the token, verifies the email, and applies the pending credentials in one transaction, exactly as the link confirmation does, and answers 200 with the same body. Success does not start a session.
*
* Each refusal answers 400 `verification_token_invalid` with the same body, whatever the cause: an unknown address, an address without an open code, a wrong code, an expired code, a wrong password, or a code that was burned. This keeps the answer from showing which addresses have a pending registration. Every failed attempt of an open code counts against that token. The fifth failed attempt burns the token: the code and the link stop working, and the user must request a new message. A refused attempt changes nothing else.
*
* The same refusal is returned after the rate limits are checked. The operation is limited per client address (`IDENTITY_CLIENT_HOURLY_LIMIT`) and per normalized email (`IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT`, shared with login); a refused request answers 429 with Retry-After. A body that does not match the contract, such as a code that is not six digits, answers 400 `validation_failed` before any lookup. Like every unsafe public identity operation, it requires an Origin equal to the configured public application origin and answers 403 `csrf_check_failed` otherwise.
* @summary Verify an email with the six-digit code from the verification message.
*/
export const confirmEmailByCode = async (emailVerificationCodeRequest: EmailVerificationCodeRequest,
headers?: ConfirmEmailByCodeHeaders, options?: Parameters<typeof apiRequest>[1]): Promise<EmailVerificationResult> => {
const getHeaders = (h?: NonNullable<RequestInit['headers']>): Record<string, string | readonly string[]> => {
if (!h) return {};
if (h instanceof Headers) return Object.fromEntries(h.entries());
if (Symbol.iterator in h) {
return Object.fromEntries(
Array.from(h as Iterable<Iterable<string>>, (entry) => Array.from(entry) as [string, string]),
);
}
const headers: Record<string, string | readonly string[]> = {};
for (const [name, value] of Object.entries<string | readonly string[] | undefined>(h)) {
if (value !== undefined) headers[name] = value;
}
return headers;
};
return apiRequest<EmailVerificationResult>(getConfirmEmailByCodeUrl(),
{
...options,
method: 'POST',
headers: { 'Content-Type': 'application/json',...headers, ...getHeaders(options?.headers) },
body: JSON.stringify(emailVerificationCodeRequest)
}
);}
export const getConfirmEmailByCodeMutationKey = () => ['confirmEmailByCode'] as const;
export const getConfirmEmailByCodeMutationOptions = <TError = ErrorType<Problem>,
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof confirmEmailByCode>>, TError,ConfirmEmailByCodeMutationVariables, TContext>, request?: SecondParameter<typeof apiRequest>}
): UseMutationOptions<Awaited<ReturnType<typeof confirmEmailByCode>>, TError,ConfirmEmailByCodeMutationVariables, TContext> => {
const mutationKey = getConfirmEmailByCodeMutationKey();
const {mutation: mutationOptions, request: requestOptions} = options ?
options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ?
options
: {...options, mutation: {...options.mutation, mutationKey}}
: {mutation: { mutationKey, }, request: undefined};
const mutationFn: MutationFunction<Awaited<ReturnType<typeof confirmEmailByCode>>, ConfirmEmailByCodeMutationVariables> = (props) => {
const {data,headers} = props ?? {};
return confirmEmailByCode(data,headers,requestOptions)
}
return { mutationFn, ...mutationOptions }}
export type ConfirmEmailByCodeMutationResult = NonNullable<Awaited<ReturnType<typeof confirmEmailByCode>>>
export type ConfirmEmailByCodeMutationBody = EmailVerificationCodeRequest
export type ConfirmEmailByCodeMutationError = ErrorType<Problem>
export type ConfirmEmailByCodeMutationVariables = {data: EmailVerificationCodeRequest;headers?: ConfirmEmailByCodeHeaders}
/**
* @summary Verify an email with the six-digit code from the verification message.
*/
export const useConfirmEmailByCode = <TError = ErrorType<Problem>,
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof confirmEmailByCode>>, TError,ConfirmEmailByCodeMutationVariables, TContext>, request?: SecondParameter<typeof apiRequest>}
, queryClient?: QueryClient): UseMutationResult<
Awaited<ReturnType<typeof confirmEmailByCode>>,
TError,
ConfirmEmailByCodeMutationVariables,
TContext
> => {
return useMutation(getConfirmEmailByCodeMutationOptions(options), queryClient);
}
export const getLoginUrl = () => {