feat(identity): confirm registration email atomically
This commit is contained in:
1 parent
8e7ce8d71c
commit
fade4e76e4
75 files changed
+4188
-403
No files matched your search
+8
-7
@@ -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` and `ResendEmailVerification` are implemented; the other public operations still answer 501 `not_implemented` after request validation, and the backend's `v1.DenyAllSecurity` rejects every session, so operations that require one answer 401 `unauthenticated`. Values marked as planned come from the planned email confirmation, login, and session configuration.
|
||||
The `identity` tag covers registration, email verification, login, logout, and the current account. All operations are in the contract. `RegisterAccount`, `ResendEmailVerification`, and `ConfirmEmail` are implemented. Login still answers 501 `not_implemented`, and `v1.DenyAllSecurity` rejects every request to a protected operation with 401 `unauthenticated`. Frontend registration and confirmation screens remain placeholders, and login is not implemented.
|
||||
|
||||
| Method and path | operationId | Security | Success | Specific errors |
|
||||
| --- | --- | --- | --- | --- |
|
||||
@@ -119,14 +119,15 @@ Every operation also declares the `default` problem response.
|
||||
|
||||
Registration and verification:
|
||||
|
||||
- Accounts are not enumerated. Registration and resend answer the same neutral 202 for a new, unverified, verified, or unknown email, and login answers 401 `invalid_credentials` for both an unknown email and a wrong password.
|
||||
- Accounts are not enumerated. Registration and resend answer the same neutral 202 for a new, unverified, verified, or unknown email. Login is not implemented yet, so its contract behavior of answering 401 `invalid_credentials` for both an unknown email and a wrong password is not available.
|
||||
- Before the server looks up the email, it validates the whole registration body (password bounds after NFKC normalization, the password blocklist, the C1 version) and computes the Argon2id hash on every branch, so neither a 400 nor the response time depends on whether the account exists.
|
||||
- Registering an unverified email again never changes the password hash, the scenario, or the onboarding step of the account row. Every registration, the first and each repeat, stores its own pending credentials (password hash and scenario) on its own verification token, replaces the C1 record, advances the registration version, and invalidates every earlier verification token. Confirming a token (`ConfirmEmail`) must apply the pending credentials of that token only, and must require the password of that registration to confirm a token that carries pending credentials; the current `EmailVerificationRequest` has no password field, so email confirmation requires a contract change. This stops a pre-registration with someone else's password from being adopted by the address owner who clicks the attacker's link, and the reverse. The account row of an unverified account cannot be used to sign in: login refuses every unverified account and never compares a password with the row or the pending credentials of an unverified account. For a verified email nothing changes; the server sends nothing.
|
||||
- Implementation of registration and resend. Verified address: nothing changes and nothing is sent (the "you already have an account" notice is not implemented). Limits per address (shared by registration and resend, keyed by an HMAC of the normalized address, counted whether or not an account exists): at least `VERIFICATION_MAIL_MIN_INTERVAL` (default 60 s) between messages and at most `VERIFICATION_MAIL_DAILY_LIMIT` (default 5) per 24 hours; per client: `IDENTITY_CLIENT_HOURLY_LIMIT` (default 30 per hour). A refused request answers 429 `rate_limited` with `Retry-After` in whole seconds and issues no token. Token replacement policy: every issue first invalidates all unused verification tokens of the account, so one link works at a time; resend changes only the token. `IDENTITY_KEY_SECRET` (at least 32 bytes, required; `IDENTITY_ALLOW_EPHEMERAL_KEY=true` allows a random one on a development stand) keys the idempotency scope, the fingerprint, and the limiter keys. A concurrent request with the same key waits for the first and is replayed, so `idempotency_in_progress` is not produced. Details: [ARCHITECTURE.md](../docs/en/ARCHITECTURE.md#registration-and-verification-resend).
|
||||
- Registering an unverified email again never changes the password hash, scenario, or onboarding step of the account row. Every registration, the first and each repeat, stores its pending credentials (password hash, scenario, and first onboarding step) on its own verification token, replaces the C1 record, advances the registration version, and invalidates earlier verification tokens. `ConfirmEmail` requires the password chosen for that registration and checks it against the pending hash on the clicked token. In one transaction the server checks the current registration version and its C1 record, consumes the token, verifies the email, applies that token's pending credentials to the account, clears its `pending_*` fields, and records exactly one `identity.email_verified` event. Any refusal leaves the account and token unchanged. An unknown, used, replaced, or superseded token, a wrong password, or missing pending credentials answers 400 `verification_token_invalid`; an expired token answers 400 `verification_token_expired`. This prevents an address owner who clicks someone else's link from accepting that registrant's password, and vice versa. Confirmation does not create a session or cookie. Login is not implemented. The planned login rule is that an unverified account cannot sign in.
|
||||
- Implementation of registration and resend. Verified address: nothing changes and nothing is sent (the "you already have an account" notice is not implemented). Limits per address (shared by registration and resend, keyed by an HMAC of the normalized address, counted whether or not an account exists): at least `VERIFICATION_MAIL_MIN_INTERVAL` (default 60 s) between messages and at most `VERIFICATION_MAIL_DAILY_LIMIT` (default 5) per 24 hours; per client: `IDENTITY_CLIENT_HOURLY_LIMIT` (default 30 per hour). `ConfirmEmail` also limits each token to 5 attempts per hour and uses the same client limit. A refused request answers 429 `rate_limited` with `Retry-After` in whole seconds and issues no token. Token replacement policy: every issue first invalidates all unused verification tokens of the account, so one link works at a time; resend changes only the token. `IDENTITY_KEY_SECRET` (at least 32 bytes, required; `IDENTITY_ALLOW_EPHEMERAL_KEY=true` allows a random one on a development stand) keys the idempotency scope, the fingerprint, and the limiter keys. A concurrent request with the same key waits for the first and is replayed, so `idempotency_in_progress` is not produced. Details: [ARCHITECTURE.md](../docs/en/ARCHITECTURE.md#registration-email-verification-and-resend).
|
||||
- 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.
|
||||
- The verification link is `<frontend origin>/verify-email#token=<token>`. The page removes the fragment with `history.replaceState` and posts the token only after an explicit user action, so the token stays out of server logs and Referer headers and a link scanner does not consume it. Verification does not start a session.
|
||||
- An expired token answers `verification_token_expired`; an unknown, used, replaced, or superseded token answers `verification_token_invalid`. The client offers a new link and sign-in for both. A repeated confirmation with a used token is deliberately not an idempotent 200: exactly one request succeeds per token.
|
||||
- `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`.
|
||||
- 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, and can offer sign-in after login is implemented. A repeated confirmation with a used token is deliberately not an idempotent 200: exactly one request succeeds per token.
|
||||
|
||||
Consent C1 and the account:
|
||||
|
||||
@@ -137,7 +138,7 @@ Consent C1 and the account:
|
||||
|
||||
Sessions and CSRF:
|
||||
|
||||
- The `sessionCookie` scheme is the cookie `__Host-lincodex_session` with `Path=/; Secure; HttpOnly; SameSite=Strict` and no Domain. The server keeps sessions in PostgreSQL and takes the caller only from the session. Only a verified account gets a session. Login revokes the session the request carried and issues a new identifier and CSRF token; logout revokes the session server-side. Planned timeouts: 24 hours idle and 7 days absolute; activity extends only the idle deadline. Both come from the versioned product policy, not from configuration.
|
||||
- Planned session behavior: the `sessionCookie` scheme uses `__Host-lincodex_session` with `Path=/; Secure; HttpOnly; SameSite=Strict` and no Domain; the server will keep sessions in PostgreSQL and identify the caller from the session. Once login is implemented, only a verified account will receive a session, and login will revoke the session from the request and issue a new identifier and CSRF token. Logout will revoke the session server-side. Policy timeouts are 24 hours idle and 7 days absolute; activity extends only the idle deadline. Configuration does not override these values.
|
||||
- The `sessionCsrf` scheme is the `X-CSRF-Token` header with the session-bound token from `Session.csrf_token`. Every unsafe operation that requires `sessionCookie` must also require `sessionCsrf`; `TestUnsafeSessionOperationsRequireCSRFToken` in the backend enforces it on the bundle. The client keeps the token in memory and restores it with `GetCurrentSession` after a reload or after 403 `csrf_check_failed`.
|
||||
- Every unsafe request, including the public ones, must carry an `Origin` from the configured allowlist, otherwise 403 `csrf_check_failed` (planned; see the [development guide](../docs/en/DEVELOPMENT.md#sessions-on-local-http)). Public identity operations are rate-limited (429 with `Retry-After`).
|
||||
- Responses with a session or account carry `Cache-Control: no-store`.
|
||||
|
||||
+8
-7
@@ -102,7 +102,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro
|
||||
|
||||
### Identity: сессии, cookie и CSRF
|
||||
|
||||
Тег `identity` описывает регистрацию, подтверждение email, вход, выход и текущий аккаунт. Все операции есть в контракте. `RegisterAccount` и `ResendEmailVerification` реализованы; остальные публичные операции после валидации запроса по-прежнему отвечают 501 `not_implemented`, а `v1.DenyAllSecurity` в backend отклоняет любую сессию, поэтому операции, которым она нужна, отвечают 401 `unauthenticated`. Значения, отмеченные как запланированные, задаются конфигурацией подтверждения почты, входа и сессий.
|
||||
Тег `identity` описывает регистрацию, подтверждение email, вход, выход и текущий аккаунт. Все операции есть в контракте. `RegisterAccount`, `ResendEmailVerification` и `ConfirmEmail` реализованы. Вход еще отвечает 501 `not_implemented`, а `v1.DenyAllSecurity` отклоняет все запросы к защищенным операциям с 401 `unauthenticated`. Экраны регистрации и подтверждения во frontend остаются заглушками, вход еще не реализован.
|
||||
|
||||
| Метод и путь | operationId | Защита | Успех | Конкретные ошибки |
|
||||
| --- | --- | --- | --- | --- |
|
||||
@@ -119,14 +119,15 @@ ML-сервис отвечает на ошибки той же схемой `Pro
|
||||
|
||||
Регистрация и подтверждение:
|
||||
|
||||
- Аккаунты не перечисляются. Регистрация и повторная отправка отвечают одинаковым нейтральным 202 для нового, неподтвержденного, подтвержденного и неизвестного email, а вход отвечает 401 `invalid_credentials` и для неизвестного email, и для неверного пароля.
|
||||
- Аккаунты не перечисляются. Регистрация и повторная отправка отвечают одинаковым нейтральным 202 для нового, неподтвержденного, подтвержденного и неизвестного email. Вход пока не реализован: его предусмотренный контрактом ответ 401 `invalid_credentials` для неизвестного email и неверного пароля пока не доступен.
|
||||
- До поиска email сервер проверяет все тело регистрации (длину пароля после нормализации NFKC, blocklist паролей, версию C1) и в каждой ветке вычисляет хеш Argon2id, поэтому ни 400, ни время ответа не зависят от существования аккаунта.
|
||||
- Повторная регистрация неподтвержденного email никогда не меняет хеш пароля, сценарий и шаг онбординга строки аккаунта. Каждая регистрация, первая и каждая повторная, хранит свои отложенные учетные данные (хеш пароля и сценарий) на своем токене подтверждения, заменяет запись C1, увеличивает версию регистрации и аннулирует все прежние токены подтверждения. Подтверждение токена (`ConfirmEmail`) обязано применять отложенные данные только этого токена и требовать пароль этой регистрации, чтобы подтвердить токен с отложенными данными; в текущем `EmailVerificationRequest` поля пароля нет, поэтому подтверждение почты требует изменения контракта. Это не дает владельцу адреса, перешедшему по ссылке злоумышленника, принять предрегистрацию с чужим паролем, и наоборот. Строкой неподтвержденного аккаунта нельзя войти: вход отклоняет любой неподтвержденный аккаунт и никогда не сравнивает пароль со строкой или с отложенными данными неподтвержденного аккаунта. Для подтвержденного email ничего не меняется; сервер ничего не отправляет.
|
||||
- Реализация регистрации и повторной отправки. Подтвержденный адрес: ничего не меняется и ничего не отправляется (уведомление "у вас уже есть аккаунт" не реализовано). Лимиты на адрес (общие для регистрации и повторной отправки, ключ - HMAC нормализованного адреса, считаются независимо от наличия аккаунта): не реже `VERIFICATION_MAIL_MIN_INTERVAL` (по умолчанию 60 с) между письмами и не больше `VERIFICATION_MAIL_DAILY_LIMIT` (по умолчанию 5) за 24 часа; на клиента: `IDENTITY_CLIENT_HOURLY_LIMIT` (по умолчанию 30 в час). Отклоненный запрос дает 429 `rate_limited` с `Retry-After` в целых секундах и не выпускает токен. Политика замены токена: каждый выпуск сначала аннулирует все неиспользованные токены подтверждения аккаунта, поэтому работает одна ссылка; повторная отправка меняет только токен. `IDENTITY_KEY_SECRET` (не меньше 32 байт, обязателен; `IDENTITY_ALLOW_EPHEMERAL_KEY=true` разрешает случайный на стенде разработки) ключует область идемпотентности, отпечаток и ключи лимитера. Параллельный запрос с тем же ключом ждет первый и воспроизводится, поэтому `idempotency_in_progress` не возникает. Подробности: [ARCHITECTURE.md](../docs/ru/ARCHITECTURE.md#регистрация-и-повторная-отправка-подтверждения).
|
||||
- Повторная регистрация неподтвержденного email никогда не меняет хеш пароля, сценарий и шаг онбординга строки аккаунта. Каждая регистрация, первая и каждая повторная, хранит свои отложенные учетные данные (хеш пароля, сценарий и первый шаг онбординга) на своем токене подтверждения, заменяет запись C1, увеличивает версию регистрации и аннулирует прежние токены. `ConfirmEmail` требует пароль этой регистрации и проверяет его по отложенному хешу именно нажатого токена. В одной транзакции сервер проверяет текущую версию регистрации и связанную с ней запись C1, погашает токен, отмечает email подтвержденным, применяет отложенные данные токена к аккаунту, очищает поля `pending_*` и записывает ровно одно событие `identity.email_verified`. При любом отказе состояние аккаунта и токена не меняется. Неизвестный, использованный, замененный или устаревший токен, неверный пароль и отсутствие отложенных данных дают 400 `verification_token_invalid`; истекший токен дает 400 `verification_token_expired`. Так владелец адреса, перешедший по чужой ссылке, не принимает пароль, выбранный другим регистрантом, и наоборот. Подтверждение не создает сессию или cookie. Вход еще не реализован. Планируемое правило для входа: неподтвержденный аккаунт нельзя будет использовать для входа.
|
||||
- Реализация регистрации и повторной отправки. Подтвержденный адрес: ничего не меняется и ничего не отправляется (уведомление "у вас уже есть аккаунт" не реализовано). Лимиты на адрес (общие для регистрации и повторной отправки, ключ - HMAC нормализованного адреса, считаются независимо от наличия аккаунта): не реже `VERIFICATION_MAIL_MIN_INTERVAL` (по умолчанию 60 с) между письмами и не больше `VERIFICATION_MAIL_DAILY_LIMIT` (по умолчанию 5) за 24 часа; на клиента: `IDENTITY_CLIENT_HOURLY_LIMIT` (по умолчанию 30 в час). `ConfirmEmail` дополнительно ограничивает каждый токен до 5 попыток в час и использует тот же лимит клиента. Отклоненный запрос дает 429 `rate_limited` с `Retry-After` в целых секундах и не выпускает токен. Политика замены токена: каждый выпуск сначала аннулирует все неиспользованные токены подтверждения аккаунта, поэтому работает одна ссылка; повторная отправка меняет только токен. `IDENTITY_KEY_SECRET` (не меньше 32 байт, обязателен; `IDENTITY_ALLOW_EPHEMERAL_KEY=true` разрешает случайный на стенде разработки) ключует область идемпотентности, отпечаток и ключи лимитера. Параллельный запрос с тем же ключом ждет первый и воспроизводится, поэтому `idempotency_in_progress` не возникает. Подробности: [ARCHITECTURE.md](../docs/ru/ARCHITECTURE.md#регистрация-подтверждение-и-повторная-отправка).
|
||||
- Каждый токен подтверждения привязан к версии регистрации, для которой выпущен, поэтому токен, выпущенный до повторной регистрации, никогда не подтверждает новые учетные данные. Повторная отправка выпускает токен для текущей версии с отложенными данными этой регистрации, аннулирует прежние и больше ничего не меняет. Запланированные значения: токен живет 24 часа; аккаунт, оставшийся неподтвержденным, удаляется вместе с записью согласия и токенами через 7 дней после последней регистрации. Эти сроки берутся из версионированной продуктовой политики (демонстрационная версия 1 семейства `product`), а не из конфигурации; см. [ARCHITECTURE.md](../docs/ru/ARCHITECTURE.md#версии-продуктовой-политики).
|
||||
- Регистрация требует Idempotency-Key. Для этой анонимной операции ключ ограничивается операцией, самим ключом и HMAC нормализованного email; отпечаток - HMAC-SHA-256 с серверным секретом над каноническим JSON тела. Тело, пароль и их простые хеши не хранятся, а секрет не дает использовать отпечаток для офлайн-проверки пароля.
|
||||
- Ссылка подтверждения имеет вид `<frontend origin>/verify-email#token=<token>`. Страница удаляет фрагмент через `history.replaceState` и отправляет токен только после явного действия пользователя, поэтому токен не попадает в логи сервера и заголовок Referer, а сканер ссылок его не расходует. Подтверждение не создает сессию.
|
||||
- Истекший токен дает `verification_token_expired`; неизвестный, использованный, замененный или устаревший по версии - `verification_token_invalid`. В обоих случаях клиент предлагает новую ссылку и вход. Повторное подтверждение использованным токеном намеренно не дает идемпотентный 200: по одному токену успешен ровно один запрос.
|
||||
- Запрос `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`.
|
||||
- Ссылка подтверждения имеет вид `<frontend origin>/verify-email#token=<token>`. Экран подтверждения во frontend пока остается заглушкой. Клиентская страница должна удалить фрагмент через `history.replaceState`, запросить явное действие пользователя и отправить токен вместе с паролем регистрации; сканер ссылок, который только открывает страницу, не расходует токен.
|
||||
- Истекший токен дает `verification_token_expired`; неизвестный, использованный, замененный или устаревший по версии, неверный пароль и отсутствие отложенных данных дают `verification_token_invalid`. В обоих случаях клиент предлагает новую ссылку и вход, когда вход будет реализован. Повторное подтверждение использованным токеном намеренно не дает идемпотентный 200: по одному токену успешен ровно один запрос.
|
||||
|
||||
Согласие C1 и аккаунт:
|
||||
|
||||
@@ -137,7 +138,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro
|
||||
|
||||
Сессии и CSRF:
|
||||
|
||||
- Схема `sessionCookie` - cookie `__Host-lincodex_session` с `Path=/; Secure; HttpOnly; SameSite=Strict` и без Domain. Сервер хранит сессии в PostgreSQL и берет вызывающего только из сессии. Сессию получает только подтвержденный аккаунт. Вход отзывает сессию, пришедшую с запросом, и выдает новый идентификатор и CSRF-токен; выход отзывает сессию на сервере. Запланированные тайм-ауты: 24 часа простоя и 7 дней абсолютного срока; активность продлевает только срок простоя. Оба значения берутся из версионированной продуктовой политики, а не из конфигурации.
|
||||
- Планируемое поведение сессий: cookie `__Host-lincodex_session` с `Path=/; Secure; HttpOnly; SameSite=Strict` и без Domain; сервер хранит сессии в PostgreSQL и берет вызывающего только из сессии. Когда вход будет реализован, сессию сможет получить только подтвержденный аккаунт, а вход будет отзывать сессию из запроса и выдавать новый идентификатор и CSRF-токен. Выход будет отзывать сессию на сервере. Тайм-ауты по продуктовой политике: 24 часа простоя и 7 дней абсолютного срока; активность продлевает только срок простоя. Эти значения не настраиваются через конфигурацию.
|
||||
- Схема `sessionCsrf` - заголовок `X-CSRF-Token` с привязанным к сессии токеном из `Session.csrf_token`. Любая небезопасная операция, требующая `sessionCookie`, обязана требовать и `sessionCsrf`; это проверяет `TestUnsafeSessionOperationsRequireCSRFToken` в backend по bundle. Клиент хранит токен только в памяти и восстанавливает его через `GetCurrentSession` после перезагрузки страницы или после 403 `csrf_check_failed`.
|
||||
- Любой небезопасный запрос, включая публичные, должен нести `Origin` из настроенного allowlist, иначе 403 `csrf_check_failed` (запланировано; см. [руководство по разработке](../docs/ru/DEVELOPMENT.md#сессии-на-локальном-http)). Публичные операции identity ограничены по частоте (429 с `Retry-After`).
|
||||
- Ответы с сессией или аккаунтом несут `Cache-Control: no-store`.
|
||||
|
||||
@@ -2680,13 +2680,19 @@ VerificationToken:
|
||||
description: 'One-time raw token copied from the verification link. It is request input only: the server stores only its hash and never returns a token.'
|
||||
EmailVerificationRequest:
|
||||
type: object
|
||||
description: Token from the email verification link.
|
||||
description: One-time token copied from the verification link and the password chosen for the registration that issued it. The password is never included in the link.
|
||||
additionalProperties: false
|
||||
required:
|
||||
- token
|
||||
- password
|
||||
properties:
|
||||
token:
|
||||
$ref: '#/VerificationToken'
|
||||
password:
|
||||
type: string
|
||||
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.
|
||||
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`.
|
||||
|
||||
@@ -187,13 +187,26 @@ schemas:
|
||||
input only: the server stores only its hash and never returns a token.
|
||||
EmailVerificationRequest:
|
||||
type: object
|
||||
description: Token from the email verification link.
|
||||
description: >-
|
||||
One-time token copied from the verification link and the password chosen
|
||||
for the registration that issued it. The password is never included in
|
||||
the link.
|
||||
additionalProperties: false
|
||||
required:
|
||||
- token
|
||||
- password
|
||||
properties:
|
||||
token:
|
||||
$ref: "#/schemas/VerificationToken"
|
||||
password:
|
||||
type: string
|
||||
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.
|
||||
EmailVerificationResult:
|
||||
type: object
|
||||
description: >-
|
||||
|
||||
@@ -97,8 +97,8 @@ paths:
|
||||
|
||||
The answer is the same 202 whether the email is new, registered but not verified, or verified, so registration does not enumerate accounts:
|
||||
|
||||
- New email: the server creates an unverified account with the scenario and the first onboarding step, records C1 with its text version and text hash, stores only the hash of a one-time verification token, and queues the verification message, all in one transaction.
|
||||
- Registered but not verified: the server treats the request as a new registration of that address. In one transaction it replaces the password hash, the scenario, the onboarding step, and the C1 record, advances the registration version, invalidates every earlier verification token, and queues a message with a new token. A pre-registration with someone else's password therefore never survives the address owner's own registration.
|
||||
- New email: the server creates an unverified account with the scenario and the first onboarding step, records C1 with its text version and text hash, stores only the hash of a one-time verification token plus the pending registration credentials, and queues the verification message, all in one transaction.
|
||||
- Registered but not verified: the server treats the request as a new registration of that address. In one transaction it advances the registration version, replaces the C1 record, invalidates every earlier verification token, and queues a message with a new token carrying the pending password hash, scenario, and onboarding step. The account's saved credentials and scenario change only when the address owner confirms that token with its registration password, so a pre-registration with someone else's password cannot take over the account.
|
||||
- Verified: nothing changes. The server may queue a rate-limited "you already have an account" notice to the address.
|
||||
|
||||
Every verification token is bound to the registration version it was issued for, so a token issued before a re-registration can never confirm the newer credentials. An account that stays unverified is deleted with its consent record and tokens 7 days after its last registration (planned value from configuration). Verification tokens live 24 hours (planned value from configuration).
|
||||
@@ -202,14 +202,25 @@ paths:
|
||||
description: |-
|
||||
Public operation without a session. The verification link has the form `<frontend origin>/verify-email#token=<token>`: the token travels in the URL fragment, so it never reaches a server log or a Referer header. The page first removes the fragment with `history.replaceState`, then waits for an explicit user action, such as a Confirm button, before it posts the token here. A link scanner that only fetches the page therefore does not consume the token.
|
||||
|
||||
The server looks up the token by its hash and, in one transaction, checks that it is unused, not expired, and bound to the current registration version, marks it used, and marks the email verified. Only one of several parallel requests with the same token succeeds. An expired token answers verification_token_expired; an unknown, used, replaced, or superseded token answers verification_token_invalid; neither changes anything. For both, the client offers a new link and sign-in, because the address may already be verified.
|
||||
The server looks up the token by its hash and, in one transaction, checks that it is unused, not expired, and bound to the current registration version, marks it used, and marks the email verified. Only one of several parallel requests with the same token succeeds. An expired token of the current registration answers verification_token_expired; an unknown, used, replaced, or superseded token answers verification_token_invalid, even when that token is also expired. Neither refusal changes anything. For both, the client offers a new link and sign-in, because the address may already be verified.
|
||||
|
||||
Confirmation also requires the password chosen for the registration that issued this token. A token from a replaced registration cannot apply another registration's password or scenario. The server checks the password against the token's pending password hash before consuming the token, then applies that token's password, scenario, and onboarding step only if the current registration's C1 consent matches its registration version. A wrong password or token without pending registration data answers verification_token_invalid and leaves the account and token unchanged.
|
||||
|
||||
A repeated confirmation with an already used token is not an idempotent 200: exactly one request may succeed for a token, so the outcome of parallel requests stays unambiguous, and the next step after either outcome is sign-in anyway.
|
||||
|
||||
Success does not start a session: the link may be opened on another device or by a mail scanner, and a session must come only from the password. The response returns the scenario and the saved onboarding step so the client can continue after sign-in. The operation is rate-limited and requires an allowed Origin.
|
||||
Success does not start a session: the link may be opened on another device or by a mail scanner, and a session must come only from the password. The response returns the scenario and the saved onboarding step so the client can continue after sign-in. The operation is rate-limited and requires an allowed Origin. Missing Origin, the special value `null`, or an Origin other than the configured public application origin answers csrf_check_failed.
|
||||
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:
|
||||
@@ -218,9 +229,10 @@ paths:
|
||||
$ref: '#/components/schemas/EmailVerificationRequest'
|
||||
examples:
|
||||
token:
|
||||
summary: Token from the link
|
||||
summary: Token from the link and password chosen during registration
|
||||
value:
|
||||
token: q3Zt9b2Kx7LmP4vR8sW1yC6nD0fH5jA2eG9uI3oT7kE
|
||||
password: correct horse battery staple
|
||||
responses:
|
||||
'200':
|
||||
description: The email is verified.
|
||||
@@ -2983,13 +2995,19 @@ components:
|
||||
description: 'One-time raw token copied from the verification link. It is request input only: the server stores only its hash and never returns a token.'
|
||||
EmailVerificationRequest:
|
||||
type: object
|
||||
description: Token from the email verification link.
|
||||
description: One-time token copied from the verification link and the password chosen for the registration that issued it. The password is never included in the link.
|
||||
additionalProperties: false
|
||||
required:
|
||||
- token
|
||||
- password
|
||||
properties:
|
||||
token:
|
||||
$ref: '#/components/schemas/VerificationToken'
|
||||
password:
|
||||
type: string
|
||||
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.
|
||||
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`.
|
||||
|
||||
@@ -4,14 +4,29 @@ post:
|
||||
description: |-
|
||||
Public operation without a session. The verification link has the form `<frontend origin>/verify-email#token=<token>`: the token travels in the URL fragment, so it never reaches a server log or a Referer header. The page first removes the fragment with `history.replaceState`, then waits for an explicit user action, such as a Confirm button, before it posts the token here. A link scanner that only fetches the page therefore does not consume the token.
|
||||
|
||||
The server looks up the token by its hash and, in one transaction, checks that it is unused, not expired, and bound to the current registration version, marks it used, and marks the email verified. Only one of several parallel requests with the same token succeeds. An expired token answers verification_token_expired; an unknown, used, replaced, or superseded token answers verification_token_invalid; neither changes anything. For both, the client offers a new link and sign-in, because the address may already be verified.
|
||||
The server looks up the token by its hash and, in one transaction, checks that it is unused, not expired, and bound to the current registration version, marks it used, and marks the email verified. Only one of several parallel requests with the same token succeeds. An expired token of the current registration answers verification_token_expired; an unknown, used, replaced, or superseded token answers verification_token_invalid, even when that token is also expired. Neither refusal changes anything. For both, the client offers a new link and sign-in, because the address may already be verified.
|
||||
|
||||
Confirmation also requires the password chosen for the registration that issued this token. A token from a replaced registration cannot apply another registration's password or scenario. The server checks the password against the token's pending password hash before consuming the token, then applies that token's password, scenario, and onboarding step only if the current registration's C1 consent matches its registration version. A wrong password or token without pending registration data answers verification_token_invalid and leaves the account and token unchanged.
|
||||
|
||||
A repeated confirmation with an already used token is not an idempotent 200: exactly one request may succeed for a token, so the outcome of parallel requests stays unambiguous, and the next step after either outcome is sign-in anyway.
|
||||
|
||||
Success does not start a session: the link may be opened on another device or by a mail scanner, and a session must come only from the password. The response returns the scenario and the saved onboarding step so the client can continue after sign-in. The operation is rate-limited and requires an allowed Origin.
|
||||
Success does not start a session: the link may be opened on another device or by a mail scanner, and a session must come only from the password. The response returns the scenario and the saved onboarding step so the client can continue after sign-in. The operation is rate-limited and requires an allowed Origin. Missing Origin, the special value `null`, or an Origin other than the configured public application origin answers csrf_check_failed.
|
||||
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:
|
||||
@@ -20,9 +35,10 @@ post:
|
||||
$ref: ../components/schemas.yml#/EmailVerificationRequest
|
||||
examples:
|
||||
token:
|
||||
summary: Token from the link
|
||||
summary: Token from the link and password chosen during registration
|
||||
value:
|
||||
token: q3Zt9b2Kx7LmP4vR8sW1yC6nD0fH5jA2eG9uI3oT7kE
|
||||
password: "correct horse battery staple"
|
||||
responses:
|
||||
"200":
|
||||
description: The email is verified.
|
||||
|
||||
@@ -6,8 +6,8 @@ post:
|
||||
|
||||
The answer is the same 202 whether the email is new, registered but not verified, or verified, so registration does not enumerate accounts:
|
||||
|
||||
- New email: the server creates an unverified account with the scenario and the first onboarding step, records C1 with its text version and text hash, stores only the hash of a one-time verification token, and queues the verification message, all in one transaction.
|
||||
- Registered but not verified: the server treats the request as a new registration of that address. In one transaction it replaces the password hash, the scenario, the onboarding step, and the C1 record, advances the registration version, invalidates every earlier verification token, and queues a message with a new token. A pre-registration with someone else's password therefore never survives the address owner's own registration.
|
||||
- New email: the server creates an unverified account with the scenario and the first onboarding step, records C1 with its text version and text hash, stores only the hash of a one-time verification token plus the pending registration credentials, and queues the verification message, all in one transaction.
|
||||
- Registered but not verified: the server treats the request as a new registration of that address. In one transaction it advances the registration version, replaces the C1 record, invalidates every earlier verification token, and queues a message with a new token carrying the pending password hash, scenario, and onboarding step. The account's saved credentials and scenario change only when the address owner confirms that token with its registration password, so a pre-registration with someone else's password cannot take over the account.
|
||||
- Verified: nothing changes. The server may queue a rate-limited "you already have an account" notice to the address.
|
||||
|
||||
Every verification token is bound to the registration version it was issued for, so a token issued before a re-registration can never confirm the newer credentials. An account that stays unverified is deleted with its consent record and tokens 7 days after its last registration (planned value from configuration). Verification tokens live 24 hours (planned value from configuration).
|
||||
|
||||
Reference in new issue
Block a user