feat(identity): confirm the email address with a six-digit code from the message
This commit is contained in:
1 parent
c94434cd09
commit
d365a05c96
87 files changed
+4764
-224
No files matched your search
+3
-1
@@ -102,7 +102,7 @@ The ML service answers its errors with the same `Problem` schema. Its `ProblemCo
|
||||
|
||||
### Identity: sessions, cookie, and CSRF
|
||||
|
||||
The `identity` tag covers registration, email verification, login, logout, and the current account. All operations are in the contract. `RegisterAccount`, `ResendEmailVerification`, `ConfirmEmail`, `Login`, `GetCurrentSession`, `Logout`, and `GetCurrentAccount` are implemented in the backend. The session boundary authenticates every operation protected by the contract; its principal comes from a verified account and an active PostgreSQL session. Except for identity and the consent operations below, protected business operations currently pass the security boundary and answer 501 `not_implemented` after request validation. Frontend registration and confirmation screens remain placeholders.
|
||||
The `identity` tag covers registration, email verification, login, logout, and the current account. All operations are in the contract. `RegisterAccount`, `ResendEmailVerification`, `ConfirmEmail`, `ConfirmEmailByCode`, `Login`, `GetCurrentSession`, `Logout`, and `GetCurrentAccount` are implemented in the backend. The session boundary authenticates every operation protected by the contract; its principal comes from a verified account and an active PostgreSQL session. Except for identity and the consent operations below, protected business operations currently pass the security boundary and answer 501 `not_implemented` after request validation. Frontend registration and confirmation screens remain placeholders.
|
||||
|
||||
| Method and path | operationId | Security | Success | Specific errors |
|
||||
| --- | --- | --- | --- | --- |
|
||||
@@ -110,6 +110,7 @@ The `identity` tag covers registration, email verification, login, logout, and t
|
||||
| `POST /api/v1/identity/registrations` | `RegisterAccount` | public, Idempotency-Key | 202 `IdentityRequestAccepted` | 400 `validation_failed`, 403 `csrf_check_failed`, 409 `idempotency_in_progress`, 422 `idempotency_key_reused`, 429 |
|
||||
| `POST /api/v1/identity/email-verification-requests` | `ResendEmailVerification` | public | 202 `IdentityRequestAccepted` | 400, 403 `csrf_check_failed`, 429 |
|
||||
| `POST /api/v1/identity/email-verifications` | `ConfirmEmail` | public | 200 `EmailVerificationResult` | 400 `verification_token_expired`, `verification_token_invalid`, or `validation_failed`; 403 `csrf_check_failed`; 429 |
|
||||
| `POST /api/v1/identity/email-verifications/code` | `ConfirmEmailByCode` | public | 200 `EmailVerificationResult` | 400 `verification_token_invalid` or `validation_failed`; 403 `csrf_check_failed`; 429 |
|
||||
| `POST /api/v1/identity/sessions` | `Login` | public | 201 `Session`, `Set-Cookie`, `Cache-Control: no-store` | 400, 401 `invalid_credentials`, 403 `email_not_verified` or `csrf_check_failed`, 429 |
|
||||
| `GET /api/v1/identity/sessions/current` | `GetCurrentSession` | session | 200 `Session`, `Cache-Control: no-store` | 401 `unauthenticated` |
|
||||
| `DELETE /api/v1/identity/sessions/current` | `Logout` | session and CSRF | 204, `Set-Cookie` clears the cookie | 401 `unauthenticated` (also clears the cookie), 403 `csrf_check_failed` |
|
||||
@@ -126,6 +127,7 @@ Registration and verification:
|
||||
- Every verification token is bound to the registration version it was issued for, so a token issued before a re-registration never confirms the newer credentials. Resend issues a token for the current version with the pending credentials of that registration, invalidates the earlier ones, and changes nothing else. Planned values: tokens live 24 hours; an account that stays unverified is deleted with its consent record and tokens 7 days after its last registration. These lifetimes come from the versioned product policy (demo version 1 of the `product` family), not from configuration; see [ARCHITECTURE.md](../docs/en/ARCHITECTURE.md#product-policy-versions).
|
||||
- Registration requires Idempotency-Key. For this anonymous operation the key is scoped by the operation, the key, and an HMAC of the normalized email; the fingerprint is an HMAC-SHA-256 with a server secret over the canonical JSON body. The body, the password, and plain hashes of either are never stored, and the secret keeps the fingerprint from serving as an offline password check.
|
||||
- `ConfirmEmail` takes both `token` and the `password` selected for that registration; clients that sent only a token must be updated. The password follows `LoginPassword`: NFKC normalization and 1 to 128 code points; the registration blocklist is not applied again. `Origin` must match `APP_PUBLIC_URL`; a missing Origin, the literal value null, or a foreign Origin answers 403 `csrf_check_failed`. Confirmation attempts are limited to 5 per token per hour and also use the shared `IDENTITY_CLIENT_HOURLY_LIMIT`; a refused attempt answers 429 `rate_limited` with `Retry-After`.
|
||||
- `ConfirmEmailByCode` takes `email`, `code` (exactly six digits, `VerificationCode`), and `password`, the password of the registration that issued the code. Every refusal, including an unknown address, a wrong or expired code, a wrong password, and an invalidated token, answers 400 `verification_token_invalid`; a malformed body answers 400 `validation_failed` with the pointer `/code`, `/email`, or `/password`. Five failed checks against one open code invalidate its token, and the link stops working too. The code lives 30 minutes, or until the token ends when that is sooner. The address limit is shared with login (`IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT`), and the client limit is `IDENTITY_CLIENT_HOURLY_LIMIT`. Success answers the same body as `ConfirmEmail` and creates no session. Details: [ARCHITECTURE.md](../docs/en/ARCHITECTURE.md#registration-email-verification-and-resend).
|
||||
- The verification link is `<frontend origin>/verify-email#token=<token>`. The frontend confirmation screen is still a placeholder. A client page must remove the fragment with `history.replaceState`, wait for an explicit user action, and post both token and registration password; a link scanner that only opens the page does not consume the token.
|
||||
- An expired token answers `verification_token_expired`; an unknown, used, replaced, or superseded token, a wrong password, or missing pending credentials answers `verification_token_invalid`. The client offers a new link for either error; after confirmation the user can sign in separately. A repeated confirmation with a used token is deliberately not an idempotent 200: exactly one request succeeds per token.
|
||||
|
||||
|
||||
+3
-1
@@ -102,7 +102,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro
|
||||
|
||||
### Identity: сессии, cookie и CSRF
|
||||
|
||||
Тег `identity` описывает регистрацию, подтверждение email, вход, выход и текущий аккаунт. Все операции есть в контракте. `RegisterAccount`, `ResendEmailVerification`, `ConfirmEmail`, `Login`, `GetCurrentSession`, `Logout` и `GetCurrentAccount` реализованы в backend. Session boundary аутентифицирует все операции, защищенные контрактом; principal создается только из действующей PostgreSQL-сессии подтвержденного аккаунта. Помимо identity и перечисленных ниже операций согласий, защищенные бизнес-операции пока проходят security boundary и отвечают 501 `not_implemented` после проверки запроса. Экраны регистрации и подтверждения во frontend остаются заглушками.
|
||||
Тег `identity` описывает регистрацию, подтверждение email, вход, выход и текущий аккаунт. Все операции есть в контракте. `RegisterAccount`, `ResendEmailVerification`, `ConfirmEmail`, `ConfirmEmailByCode`, `Login`, `GetCurrentSession`, `Logout` и `GetCurrentAccount` реализованы в backend. Session boundary аутентифицирует все операции, защищенные контрактом; principal создается только из действующей PostgreSQL-сессии подтвержденного аккаунта. Помимо identity и перечисленных ниже операций согласий, защищенные бизнес-операции пока проходят security boundary и отвечают 501 `not_implemented` после проверки запроса. Экраны регистрации и подтверждения во frontend остаются заглушками.
|
||||
|
||||
| Метод и путь | operationId | Защита | Успех | Конкретные ошибки |
|
||||
| --- | --- | --- | --- | --- |
|
||||
@@ -110,6 +110,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro
|
||||
| `POST /api/v1/identity/registrations` | `RegisterAccount` | публичная, Idempotency-Key | 202 `IdentityRequestAccepted` | 400 `validation_failed`, 403 `csrf_check_failed`, 409 `idempotency_in_progress`, 422 `idempotency_key_reused`, 429 |
|
||||
| `POST /api/v1/identity/email-verification-requests` | `ResendEmailVerification` | публичная | 202 `IdentityRequestAccepted` | 400, 403 `csrf_check_failed`, 429 |
|
||||
| `POST /api/v1/identity/email-verifications` | `ConfirmEmail` | публичная | 200 `EmailVerificationResult` | 400 `verification_token_expired`, `verification_token_invalid` или `validation_failed`; 403 `csrf_check_failed`; 429 |
|
||||
| `POST /api/v1/identity/email-verifications/code` | `ConfirmEmailByCode` | публичная | 200 `EmailVerificationResult` | 400 `verification_token_invalid` или `validation_failed`; 403 `csrf_check_failed`; 429 |
|
||||
| `POST /api/v1/identity/sessions` | `Login` | публичная | 201 `Session`, `Set-Cookie`, `Cache-Control: no-store` | 400, 401 `invalid_credentials`, 403 `email_not_verified` или `csrf_check_failed`, 429 |
|
||||
| `GET /api/v1/identity/sessions/current` | `GetCurrentSession` | сессия | 200 `Session`, `Cache-Control: no-store` | 401 `unauthenticated` |
|
||||
| `DELETE /api/v1/identity/sessions/current` | `Logout` | сессия и CSRF | 204, `Set-Cookie` удаляет cookie | 401 `unauthenticated` (тоже удаляет cookie), 403 `csrf_check_failed` |
|
||||
@@ -126,6 +127,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro
|
||||
- Каждый токен подтверждения привязан к версии регистрации, для которой выпущен, поэтому токен, выпущенный до повторной регистрации, никогда не подтверждает новые учетные данные. Повторная отправка выпускает токен для текущей версии с отложенными данными этой регистрации, аннулирует прежние и больше ничего не меняет. Запланированные значения: токен живет 24 часа; аккаунт, оставшийся неподтвержденным, удаляется вместе с записью согласия и токенами через 7 дней после последней регистрации. Эти сроки берутся из версионированной продуктовой политики (демонстрационная версия 1 семейства `product`), а не из конфигурации; см. [ARCHITECTURE.md](../docs/ru/ARCHITECTURE.md#версии-продуктовой-политики).
|
||||
- Регистрация требует Idempotency-Key. Для этой анонимной операции ключ ограничивается операцией, самим ключом и HMAC нормализованного email; отпечаток - HMAC-SHA-256 с серверным секретом над каноническим JSON тела. Тело, пароль и их простые хеши не хранятся, а секрет не дает использовать отпечаток для офлайн-проверки пароля.
|
||||
- Запрос `ConfirmEmail` принимает и `token`, и выбранный при этой регистрации `password`; прежние клиенты, отправлявшие только токен, нужно обновить. Пароль обрабатывается по правилам `LoginPassword`: NFKC-нормализация и от 1 до 128 кодовых точек; blocklist регистрации повторно не применяется. `Origin` должен совпадать с `APP_PUBLIC_URL`; отсутствующий Origin, значение null или посторонний Origin дают 403 `csrf_check_failed`. Endpoint ограничивает попытки подтверждения одним токеном до 5 в час и применяет общий лимит клиента `IDENTITY_CLIENT_HOURLY_LIMIT`; отказ по лимиту дает 429 `rate_limited` с `Retry-After`.
|
||||
- Запрос `ConfirmEmailByCode` принимает `email`, `code` (ровно шесть цифр, `VerificationCode`) и `password` - пароль регистрации, которая выпустила код. Любой отказ, включая неизвестный адрес, неверный или истекший код, неверный пароль и аннулированный токен, отвечает 400 `verification_token_invalid`; некорректное тело отвечает 400 `validation_failed` с указателем `/code`, `/email` или `/password`. Пять неудачных проверок одного открытого кода аннулируют его токен, и ссылка тоже перестает работать. Код действует 30 минут или до конца срока токена, если токен заканчивается раньше. Лимит адреса общий со входом (`IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT`), лимит клиента - `IDENTITY_CLIENT_HOURLY_LIMIT`. Успех отвечает тем же телом, что и `ConfirmEmail`, и сессию не создает. Подробности: [ARCHITECTURE.md](../docs/ru/ARCHITECTURE.md#регистрация-подтверждение-и-повторная-отправка).
|
||||
- Ссылка подтверждения имеет вид `<frontend origin>/verify-email#token=<token>`. Экран подтверждения во frontend пока остается заглушкой. Клиентская страница должна удалить фрагмент через `history.replaceState`, запросить явное действие пользователя и отправить токен вместе с паролем регистрации; сканер ссылок, который только открывает страницу, не расходует токен.
|
||||
- Истекший токен дает `verification_token_expired`; неизвестный, использованный, замененный или устаревший по версии, неверный пароль и отсутствие отложенных данных дают `verification_token_invalid`. В обоих случаях клиент предлагает новую ссылку; после подтверждения пользователь может отдельно войти. Повторное подтверждение использованным токеном намеренно не дает идемпотентный 200: по одному токену успешен ровно один запрос.
|
||||
|
||||
|
||||
@@ -156,6 +156,29 @@ VerificationTokenExpired:
|
||||
code: verification_token_expired
|
||||
detail: Request a new verification link.
|
||||
trace_id: 4c5d6e7f-8a9b-4c0d-9e1f-2a3b4c5d6e7f
|
||||
VerificationCodeInvalid:
|
||||
summary: The code does not verify the email
|
||||
value:
|
||||
type: urn:lincodex:problem:verification_token_invalid
|
||||
title: Verification code is not valid
|
||||
status: 400
|
||||
code: verification_token_invalid
|
||||
detail: Check the code and the password, or request a new message.
|
||||
trace_id: 6e7f8a9b-0c1d-4e2f-9a3b-4c5d6e7f8a9b
|
||||
VerificationCodeMalformed:
|
||||
summary: The code is not six digits
|
||||
value:
|
||||
type: urn:lincodex:problem:validation_failed
|
||||
title: Request validation failed
|
||||
status: 400
|
||||
code: validation_failed
|
||||
detail: One or more request fields are invalid.
|
||||
trace_id: 7f8a9b0c-1d2e-4f3a-8b4c-5d6e7f8a9b0c
|
||||
errors:
|
||||
- in: body
|
||||
pointer: /code
|
||||
code: invalid
|
||||
message: The value does not match the contract.
|
||||
VerificationTokenMalformed:
|
||||
summary: The token from the link is malformed
|
||||
value:
|
||||
|
||||
@@ -189,6 +189,24 @@ EmailVerificationFailed:
|
||||
$ref: ./examples.yml#/VerificationTokenInvalid
|
||||
validation_failed:
|
||||
$ref: ./examples.yml#/VerificationTokenMalformed
|
||||
EmailVerificationCodeFailed:
|
||||
description: >-
|
||||
The code does not verify the email. Code verification_token_invalid covers
|
||||
every refusal in the same shape: an unknown address, an address without an
|
||||
open code, a wrong code, an expired code, a wrong password, and a code that
|
||||
was burned after five failed attempts. Code validation_failed means the
|
||||
body does not match the contract, such as a code that is not six digits,
|
||||
and carries the pointer `/code`, `/email`, or `/password`. Nothing was
|
||||
changed in any case.
|
||||
content:
|
||||
application/problem+json:
|
||||
schema:
|
||||
$ref: ./schemas.yml#/Problem
|
||||
examples:
|
||||
verification_code_invalid:
|
||||
$ref: ./examples.yml#/VerificationCodeInvalid
|
||||
validation_failed:
|
||||
$ref: ./examples.yml#/VerificationCodeMalformed
|
||||
InvalidCredentials:
|
||||
description: >-
|
||||
The email and password do not match an account; code
|
||||
|
||||
@@ -3729,6 +3729,30 @@ EmailVerificationRequest:
|
||||
minLength: 1
|
||||
maxLength: 128
|
||||
description: Password chosen for the registration that issued this token. It is sent in the request body and never appears in the verification link. The server applies NFKC normalization and the login length bounds, without reapplying the current new-registration blocklist.
|
||||
VerificationCode:
|
||||
type: string
|
||||
minLength: 6
|
||||
maxLength: 6
|
||||
pattern: ^[0-9]{6}$
|
||||
description: Six-digit code from the verification message, with leading zeros. It is request input only; the server keeps a keyed digest of it, never the code.
|
||||
EmailVerificationCodeRequest:
|
||||
type: object
|
||||
description: Address, the six-digit code from its verification message, and the password chosen for the registration that issued the code. The password is checked the same way as in EmailVerificationRequest.
|
||||
additionalProperties: false
|
||||
required:
|
||||
- email
|
||||
- code
|
||||
- password
|
||||
properties:
|
||||
email:
|
||||
$ref: '#/EmailAddress'
|
||||
code:
|
||||
$ref: '#/VerificationCode'
|
||||
password:
|
||||
type: string
|
||||
minLength: 1
|
||||
maxLength: 128
|
||||
description: Password chosen for the registration that issued the code. The server applies NFKC normalization and the login length bounds, without reapplying the current new-registration blocklist.
|
||||
EmailVerificationResult:
|
||||
type: object
|
||||
description: Result of a successful email verification. It does not start a session; the user signs in next and continues from `onboarding_step`.
|
||||
|
||||
@@ -207,6 +207,38 @@ schemas:
|
||||
sent in the request body and never appears in the verification link.
|
||||
The server applies NFKC normalization and the login length bounds,
|
||||
without reapplying the current new-registration blocklist.
|
||||
VerificationCode:
|
||||
type: string
|
||||
minLength: 6
|
||||
maxLength: 6
|
||||
pattern: "^[0-9]{6}$"
|
||||
description: >-
|
||||
Six-digit code from the verification message, with leading zeros. It is
|
||||
request input only; the server keeps a keyed digest of it, never the code.
|
||||
EmailVerificationCodeRequest:
|
||||
type: object
|
||||
description: >-
|
||||
Address, the six-digit code from its verification message, and the
|
||||
password chosen for the registration that issued the code. The password
|
||||
is checked the same way as in EmailVerificationRequest.
|
||||
additionalProperties: false
|
||||
required:
|
||||
- email
|
||||
- code
|
||||
- password
|
||||
properties:
|
||||
email:
|
||||
$ref: "#/schemas/EmailAddress"
|
||||
code:
|
||||
$ref: "#/schemas/VerificationCode"
|
||||
password:
|
||||
type: string
|
||||
minLength: 1
|
||||
maxLength: 128
|
||||
description: >-
|
||||
Password chosen for the registration that issued the code. The server
|
||||
applies NFKC normalization and the login length bounds, without
|
||||
reapplying the current new-registration blocklist.
|
||||
EmailVerificationResult:
|
||||
type: object
|
||||
description: >-
|
||||
|
||||
@@ -291,6 +291,65 @@ paths:
|
||||
$ref: '#/components/responses/TooManyRequests'
|
||||
default:
|
||||
$ref: '#/components/responses/Problem'
|
||||
/api/v1/identity/email-verifications/code:
|
||||
post:
|
||||
operationId: ConfirmEmailByCode
|
||||
summary: Verify an email with the six-digit code from the verification message.
|
||||
description: |-
|
||||
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.
|
||||
security: []
|
||||
tags:
|
||||
- identity
|
||||
parameters:
|
||||
- name: Origin
|
||||
in: header
|
||||
required: false
|
||||
description: The exact configured public application origin. This optional parameter is read by the server as empty when absent, so the operation answers csrf_check_failed rather than treating a missing Origin as an allowed request.
|
||||
schema:
|
||||
type: string
|
||||
minLength: 1
|
||||
maxLength: 2048
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/EmailVerificationCodeRequest'
|
||||
examples:
|
||||
code:
|
||||
summary: Address, code from the message, and the registration password
|
||||
value:
|
||||
email: candidate@example.com
|
||||
code: '482915'
|
||||
password: correct horse battery staple
|
||||
responses:
|
||||
'200':
|
||||
description: The email is verified.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/EmailVerificationResult'
|
||||
examples:
|
||||
candidate:
|
||||
summary: A candidate continues with consents
|
||||
value:
|
||||
email_verified: true
|
||||
scenario: candidate
|
||||
onboarding_step: candidate_consents
|
||||
'400':
|
||||
$ref: '#/components/responses/EmailVerificationCodeFailed'
|
||||
'403':
|
||||
$ref: '#/components/responses/CsrfCheckFailed'
|
||||
'429':
|
||||
$ref: '#/components/responses/TooManyRequests'
|
||||
default:
|
||||
$ref: '#/components/responses/Problem'
|
||||
/api/v1/identity/sessions:
|
||||
post:
|
||||
operationId: Login
|
||||
@@ -10019,6 +10078,30 @@ components:
|
||||
type: string
|
||||
enum:
|
||||
- ok
|
||||
VerificationCode:
|
||||
type: string
|
||||
minLength: 6
|
||||
maxLength: 6
|
||||
pattern: ^[0-9]{6}$
|
||||
description: Six-digit code from the verification message, with leading zeros. It is request input only; the server keeps a keyed digest of it, never the code.
|
||||
EmailVerificationCodeRequest:
|
||||
type: object
|
||||
description: Address, the six-digit code from its verification message, and the password chosen for the registration that issued the code. The password is checked the same way as in EmailVerificationRequest.
|
||||
additionalProperties: false
|
||||
required:
|
||||
- email
|
||||
- code
|
||||
- password
|
||||
properties:
|
||||
email:
|
||||
$ref: '#/components/schemas/EmailAddress'
|
||||
code:
|
||||
$ref: '#/components/schemas/VerificationCode'
|
||||
password:
|
||||
type: string
|
||||
minLength: 1
|
||||
maxLength: 128
|
||||
description: Password chosen for the registration that issued the code. The server applies NFKC normalization and the login length bounds, without reapplying the current new-registration blocklist.
|
||||
AssessmentRealMode:
|
||||
type: string
|
||||
description: Server-selected mode available to a real category assessment.
|
||||
@@ -11863,6 +11946,17 @@ components:
|
||||
examples:
|
||||
limit_reached:
|
||||
$ref: '#/components/examples/HiddenOrganizationLimitReached'
|
||||
EmailVerificationCodeFailed:
|
||||
description: 'The code does not verify the email. Code verification_token_invalid covers every refusal in the same shape: an unknown address, an address without an open code, a wrong code, an expired code, a wrong password, and a code that was burned after five failed attempts. Code validation_failed means the body does not match the contract, such as a code that is not six digits, and carries the pointer `/code`, `/email`, or `/password`. Nothing was changed in any case.'
|
||||
content:
|
||||
application/problem+json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/Problem'
|
||||
examples:
|
||||
verification_code_invalid:
|
||||
$ref: '#/components/examples/VerificationCodeInvalid'
|
||||
validation_failed:
|
||||
$ref: '#/components/examples/VerificationCodeMalformed'
|
||||
securitySchemes:
|
||||
sessionCookie:
|
||||
type: apiKey
|
||||
@@ -12032,6 +12126,29 @@ components:
|
||||
pointer: /token
|
||||
code: invalid
|
||||
message: The value does not match the contract.
|
||||
VerificationCodeInvalid:
|
||||
summary: The code does not verify the email
|
||||
value:
|
||||
type: urn:lincodex:problem:verification_token_invalid
|
||||
title: Verification code is not valid
|
||||
status: 400
|
||||
code: verification_token_invalid
|
||||
detail: Check the code and the password, or request a new message.
|
||||
trace_id: 6e7f8a9b-0c1d-4e2f-9a3b-4c5d6e7f8a9b
|
||||
VerificationCodeMalformed:
|
||||
summary: The code is not six digits
|
||||
value:
|
||||
type: urn:lincodex:problem:validation_failed
|
||||
title: Request validation failed
|
||||
status: 400
|
||||
code: validation_failed
|
||||
detail: One or more request fields are invalid.
|
||||
trace_id: 7f8a9b0c-1d2e-4f3a-8b4c-5d6e7f8a9b0c
|
||||
errors:
|
||||
- in: body
|
||||
pointer: /code
|
||||
code: invalid
|
||||
message: The value does not match the contract.
|
||||
CandidateSession:
|
||||
summary: Session of a verified candidate
|
||||
value:
|
||||
|
||||
@@ -105,6 +105,8 @@ paths:
|
||||
$ref: ./routes/identity_email_verification_requests.yml
|
||||
/api/v1/identity/email-verifications:
|
||||
$ref: ./routes/identity_email_verifications.yml
|
||||
/api/v1/identity/email-verifications/code:
|
||||
$ref: ./routes/identity_email_verification_codes.yml
|
||||
/api/v1/identity/sessions:
|
||||
$ref: ./routes/identity_sessions.yml
|
||||
/api/v1/identity/sessions/current:
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
post:
|
||||
operationId: ConfirmEmailByCode
|
||||
summary: Verify an email with the six-digit code from the verification message.
|
||||
description: |-
|
||||
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.
|
||||
security: []
|
||||
tags:
|
||||
- identity
|
||||
parameters:
|
||||
- name: Origin
|
||||
in: header
|
||||
required: false
|
||||
description: >-
|
||||
The exact configured public application origin. This optional parameter
|
||||
is read by the server as empty when absent, so the operation answers
|
||||
csrf_check_failed rather than treating a missing Origin as an allowed
|
||||
request.
|
||||
schema:
|
||||
type: string
|
||||
minLength: 1
|
||||
maxLength: 2048
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: ../components/schemas.yml#/EmailVerificationCodeRequest
|
||||
examples:
|
||||
code:
|
||||
summary: Address, code from the message, and the registration password
|
||||
value:
|
||||
email: candidate@example.com
|
||||
code: "482915"
|
||||
password: "correct horse battery staple"
|
||||
responses:
|
||||
"200":
|
||||
description: The email is verified.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: ../components/schemas.yml#/EmailVerificationResult
|
||||
examples:
|
||||
candidate:
|
||||
summary: A candidate continues with consents
|
||||
value:
|
||||
email_verified: true
|
||||
scenario: candidate
|
||||
onboarding_step: candidate_consents
|
||||
"400":
|
||||
$ref: ../components/responses.yml#/EmailVerificationCodeFailed
|
||||
"403":
|
||||
$ref: ../components/responses.yml#/CsrfCheckFailed
|
||||
"429":
|
||||
$ref: ../components/responses.yml#/TooManyRequests
|
||||
default:
|
||||
$ref: ../components/responses.yml#/Problem
|
||||
Reference in new issue
Block a user