Ссылка действует {{.View.LifetimeHours}} {{plural .View.LifetimeHours "час" "часа" "часов"}}.
+
Если вы не регистрировались в Lincodex, ничего не делайте: без подтверждения аккаунт не будет активирован.
+
+
Lincodex. Письмо отправлено автоматически, отвечать на него не нужно.
+
+
+
diff --git a/backend/internal/usecase/notification/mailtemplate/templates/verification.v2.subject.tmpl b/backend/internal/usecase/notification/mailtemplate/templates/verification.v2.subject.tmpl
new file mode 100644
index 0000000..e2eafe9
--- /dev/null
+++ b/backend/internal/usecase/notification/mailtemplate/templates/verification.v2.subject.tmpl
@@ -0,0 +1 @@
+Подтвердите почту в Lincodex
diff --git a/backend/internal/usecase/notification/mailtemplate/templates/verification.v2.txt.tmpl b/backend/internal/usecase/notification/mailtemplate/templates/verification.v2.txt.tmpl
new file mode 100644
index 0000000..e3935d2
--- /dev/null
+++ b/backend/internal/usecase/notification/mailtemplate/templates/verification.v2.txt.tmpl
@@ -0,0 +1,18 @@
+Подтвердите адрес почты
+
+Чтобы завершить регистрацию в Lincodex, введите код на странице подтверждения вместе с паролем, который вы выбрали при регистрации:
+
+Код подтверждения: {{.View.Code}}
+
+Код действует {{.View.CodeLifetimeMinutes}} {{plural .View.CodeLifetimeMinutes "минуту" "минуты" "минут"}}.
+
+Или откройте ссылку и подтвердите адрес на открывшейся странице:
+
+{{.View.Link}}
+
+Ссылка действует {{.View.LifetimeHours}} {{plural .View.LifetimeHours "час" "часа" "часов"}}.
+
+Если вы не регистрировались в Lincodex, ничего не делайте: без подтверждения аккаунт не будет активирован.
+
+--
+Lincodex. Письмо отправлено автоматически, отвечать на него не нужно.
diff --git a/backend/internal/usecase/notification/mailtemplate/testdata/verification.v1.txt.golden b/backend/internal/usecase/notification/mailtemplate/testdata/verification.v1.txt.golden
deleted file mode 100644
index 6e9827d..0000000
--- a/backend/internal/usecase/notification/mailtemplate/testdata/verification.v1.txt.golden
+++ /dev/null
@@ -1,14 +0,0 @@
-Subject: Подтвердите почту в Lincodex
-
-Подтвердите адрес почты
-
-Чтобы завершить регистрацию в Lincodex, откройте ссылку и подтвердите адрес на открывшейся странице:
-
-https://lincodex.example/verify-email#token=SyntheticToken_0123456789-abcdefghijklmnopqrstuv
-
-Ссылка действует 24 часа.
-
-Если вы не регистрировались в Lincodex, просто не открывайте ссылку: без подтверждения аккаунт не будет активирован.
-
---
-Lincodex. Письмо отправлено автоматически, отвечать на него не нужно.
diff --git a/backend/internal/usecase/notification/mailtemplate/testdata/verification.v1.html.golden b/backend/internal/usecase/notification/mailtemplate/testdata/verification.v2.html.golden
similarity index 66%
rename from backend/internal/usecase/notification/mailtemplate/testdata/verification.v1.html.golden
rename to backend/internal/usecase/notification/mailtemplate/testdata/verification.v2.html.golden
index bcbdb86..484ba70 100644
--- a/backend/internal/usecase/notification/mailtemplate/testdata/verification.v1.html.golden
+++ b/backend/internal/usecase/notification/mailtemplate/testdata/verification.v2.html.golden
@@ -11,12 +11,16 @@
Lincodex
Подтвердите адрес почты
-
Чтобы завершить регистрацию в Lincodex, откройте ссылку и подтвердите адрес на открывшейся странице.
+
Чтобы завершить регистрацию в Lincodex, введите код на странице подтверждения вместе с паролем, который вы выбрали при регистрации.
+
Код подтверждения:
+
482915
+
Код действует 30 минут.
+
Или откройте ссылку и подтвердите адрес на открывшейся странице:
Если вы не регистрировались в Lincodex, просто не открывайте ссылку: без подтверждения аккаунт не будет активирован.
+
Если вы не регистрировались в Lincodex, ничего не делайте: без подтверждения аккаунт не будет активирован.
Lincodex. Письмо отправлено автоматически, отвечать на него не нужно.
diff --git a/backend/internal/usecase/notification/mailtemplate/testdata/verification.v2.txt.golden b/backend/internal/usecase/notification/mailtemplate/testdata/verification.v2.txt.golden
new file mode 100644
index 0000000..f159799
--- /dev/null
+++ b/backend/internal/usecase/notification/mailtemplate/testdata/verification.v2.txt.golden
@@ -0,0 +1,20 @@
+Subject: Подтвердите почту в Lincodex
+
+Подтвердите адрес почты
+
+Чтобы завершить регистрацию в Lincodex, введите код на странице подтверждения вместе с паролем, который вы выбрали при регистрации:
+
+Код подтверждения: 482915
+
+Код действует 30 минут.
+
+Или откройте ссылку и подтвердите адрес на открывшейся странице:
+
+https://lincodex.example/verify-email#token=SyntheticToken_0123456789-abcdefghijklmnopqrstuv
+
+Ссылка действует 24 часа.
+
+Если вы не регистрировались в Lincodex, ничего не делайте: без подтверждения аккаунт не будет активирован.
+
+--
+Lincodex. Письмо отправлено автоматически, отвечать на него не нужно.
diff --git a/backend/internal/usecase/notification/service_mail.go b/backend/internal/usecase/notification/service_mail.go
index bc52734..fd8d9e4 100644
--- a/backend/internal/usecase/notification/service_mail.go
+++ b/backend/internal/usecase/notification/service_mail.go
@@ -29,6 +29,11 @@ type TokenMailRequest struct {
// Lifetime is the validity of the token that the message states, in
// whole hours.
Lifetime domain.Hours
+ // Code is the six-digit code of an email verification message, and
+ // CodeLifetime its validity as the message states it. Both are required
+ // for email verification and unused by the other kinds.
+ Code domain.VerificationCode
+ CodeLifetime time.Duration
}
// ServiceMailer stores service mail of the account flows (email verification
@@ -65,7 +70,15 @@ func (mailer *ServiceMailer) EnqueueVerification(ctx context.Context, unit outbo
if err := checkTokenMailRequest(location, request, domain.EmailTokenPurposeEmailVerification); err != nil {
return uuid.Nil, err
}
- content, err := mailer.renderer.RenderVerification(mailtemplate.VerificationData{Token: request.RawToken, TokenLifetime: request.Lifetime})
+ if request.Code.IsZero() {
+ return uuid.Nil, fmt.Errorf("%s - verification code must be set: %w", location, domain.ErrInvalidEmailToken)
+ }
+ content, err := mailer.renderer.RenderVerification(mailtemplate.VerificationData{
+ Token: request.RawToken,
+ TokenLifetime: request.Lifetime,
+ Code: request.Code,
+ CodeLifetime: request.CodeLifetime,
+ })
if err != nil {
return uuid.Nil, fmt.Errorf("%s - render message: %w", location, err)
}
diff --git a/backend/internal/usecase/notification/service_mail_test.go b/backend/internal/usecase/notification/service_mail_test.go
index 31352be..c05cb88 100644
--- a/backend/internal/usecase/notification/service_mail_test.go
+++ b/backend/internal/usecase/notification/service_mail_test.go
@@ -47,7 +47,14 @@ func (h *serviceMailHarness) request(t *testing.T, purpose domain.EmailTokenPurp
if err != nil {
t.Fatalf("NewEmailAddress() error = %v", err)
}
- return TokenMailRequest{Recipient: recipient, Token: token, RawToken: raw, Lifetime: 24}
+ code, err := domain.NewVerificationCode()
+ if err != nil {
+ t.Fatalf("NewVerificationCode() error = %v", err)
+ }
+ return TokenMailRequest{
+ Recipient: recipient, Token: token, RawToken: raw, Lifetime: 24,
+ Code: code, CodeLifetime: domain.VerificationCodeLifetime,
+ }
}
func TestServiceMailerStoresATokenBoundDeliveryUnderTheTokenID(t *testing.T) {
@@ -125,6 +132,8 @@ func TestServiceMailerRefusesAWrongTokenBeforeRendering(t *testing.T) {
"no recipient": func(request *TokenMailRequest) { request.Recipient = domain.EmailAddress{} },
"zero lifetime": func(request *TokenMailRequest) { request.Lifetime = 0 },
"lifetime >7d": func(request *TokenMailRequest) { request.Lifetime = 24 * 8 },
+ "no code": func(request *TokenMailRequest) { request.Code = domain.VerificationCode{} },
+ "code lifetime": func(request *TokenMailRequest) { request.CodeLifetime = 90 * time.Second },
} {
request := h.request(t, domain.EmailTokenPurposeEmailVerification)
change(&request)
diff --git a/docs/en/ARCHITECTURE.md b/docs/en/ARCHITECTURE.md
index b58e74d..4425e7a 100644
--- a/docs/en/ARCHITECTURE.md
+++ b/docs/en/ARCHITECTURE.md
@@ -350,6 +350,8 @@ Enqueue. `ServiceMailer.EnqueueVerification` and `EnqueuePasswordReset` run in t
Links. The token travels only in the URL fragment: `/verify-email#token=` and `/reset-password#token=`, built by `mailtemplate` (`tokenLink`). A browser never sends the fragment to a server, so the token stays out of the nginx access log, which records `$uri`, out of Referer headers, and out of the Go request log; it is not in the path and not in the query. The frontend reads and removes the fragment, waits for explicit confirmation, then sends the token and registration password in the API request. It also consumes a new link opened in the same tab and ignores results from an older in-flight request. The password reset route and API are not implemented. The renderer rejects a token in any other place, its golden files and tests fix the format, and the delivery tests check that the stored body holds the link with the fragment and no `?token=`. The body in `deliveries` holds the live token until the mail is sent or cancelled; see Personal data at rest.
+Codes. Each verification message also carries a six-digit code: in the text part as the line `Код подтверждения: ` (the Russian copy), and in the HTML part as a large block. The code lives 30 minutes, or until its token ends when that is sooner, and the message states that lifetime. The code is an alternative to the link, not a replacement: `ConfirmEmailByCode` checks it (see Registration, email verification, and resend). Like the link, the code stays in the body of the delivery until the mail is sent or cancelled, and is then redacted; the token row keeps only a keyed digest of the code, never the code. Read access to `deliveries` before that point exposes the code too.
+
One pass of `ServiceMailSender.ProcessNext` takes one delivery through three steps:
1. Claim transaction. `DeliveryRepository.ClaimDue` takes the most overdue due delivery with `FOR UPDATE SKIP LOCKED`: kind `verification` or `password_reset` (literals that match the predicate of `deliveries_due_idx`, so the poll reads only that small index), status `pending`, `waiting_quota`, or a scheduled `unknown`, `next_attempt_at` passed, pinned to the configured provider account, and held by no live lease. An initial uncertain result is scheduled only while the delivery is inside the automatic cutoff; terminal unknown rows and unknown rows without a due time wait for an operator. A single-use manual authorization also makes an unknown row due. It sets `claim_owner` and `claimed_until` (the lease) without changing the version or the update time, so several processes never take one delivery. The lease is measured by the database clock (`clock_timestamp()` plus the lease length, and live while `claimed_until` is later than `clock_timestamp()`), never by the clock of an application instance, so instances whose clocks differ cannot take over a live lease or hold a dead one; due times stay on the application clock that wrote them. In the same transaction the sender rebinds mail stored while `EMAIL_PROVIDER=disabled` to the configured account (allowed before the first attempt only, so no provider holds its key), runs the check below, and then `QuotaGate.PrepareSend`, which reserves the recipient or parks the delivery in `waiting_quota`. The transaction commits before the transport is called, so a slow provider never holds a row lock. A failure inside it (a deterministic one, such as a row that cannot be restored) rolls the lease back too, so the failure is then recorded for the row in a transaction of its own; see Failing rows.
@@ -765,7 +767,7 @@ The brief references Russian Federal Law 152-FZ. The system design calls for sep
Identity storage is implemented in migration `backend/db/migrations/00002_create_identity_tables.sql`, the queries in `backend/db/queries/identity.sql`, the domain types, outbound ports, and the PostgreSQL adapter. The backend API implements registration, verification resend, `ConfirmEmail`, login, and basic current-session operations. The frontend registration and confirmation screens are implemented; see the [API contract](../../api/README.en.md#identity-sessions-cookie-and-csrf).
- `users`: UUIDv7 `id`; `email`, the delivery form (trimmed ASCII, letter case as typed, returned as `Account.email`), and `email_normalized`, the unique comparison key (the same address with A-Z lowercased); `password_hash`, an Argon2id v19 PHC string; `scenario` and `onboarding_step` with a CHECK that the step belongs to the scenario; nullable `email_verified_at`; `registration_version`; `last_registered_at` with a partial index over unverified accounts for the planned 7-day cleanup; the optimistic `version`; `created_at` and `updated_at`. The delivery form is kept because RFC 5321 allows a case-sensitive local part: mail goes to the address as typed, while uniqueness ignores letter case.
-- `email_tokens`: `token_hash` (SHA-256, 32-byte `bytea`, unique), `purpose` (`email_verification`; a CHECK lists allowed purposes, so password reset can be added later), `user_id`, the `registration_version` the token is bound to, `created_at`, `expires_at`, `consumed_at`, and `invalidated_at`. Migration 00014 adds `pending_password_hash`, `pending_scenario`, and `pending_onboarding_step`, so each token carries its registration data. A CHECK allows at most one of consumed and invalidated.
+- `email_tokens`: `token_hash` (SHA-256, 32-byte `bytea`, unique), `purpose` (`email_verification`; a CHECK lists allowed purposes, so password reset can be added later), `user_id`, the `registration_version` the token is bound to, `created_at`, `expires_at`, `consumed_at`, and `invalidated_at`. Migration 00014 adds `pending_password_hash`, `pending_scenario`, and `pending_onboarding_step`, so each token carries its registration data. A CHECK allows at most one of consumed and invalidated. Migration `00046_add_email_verification_codes.sql` adds `code_hash` (HMAC-SHA-256 of the six-digit code under a server key, NULL when the token carries no code or the code has ended), `code_expires_at`, and `code_failed_attempts` (0 to 5). The code expiry is the earlier of the token expiry and the 30-minute code lifetime, and the application checks both on every use.
- `sessions`: a UUIDv7 `id` that never leaves the server, `token_hash` (SHA-256 of the cookie value, unique), `user_id`, `created_at`, `last_seen_at`, the absolute `expires_at`, and `revoked_at`. No IP address or user agent is stored.
- Tokens and sessions reference `users` with `ON DELETE CASCADE`. Consent records reference it with `ON DELETE RESTRICT` instead; see [Consent ledger](#consent-ledger). CHECK constraints repeat the domain rules as a backstop: the ASCII address and its key, the PHC format, and timestamps (verification, consumption, invalidation, and revocation) not earlier than `created_at`.
@@ -861,12 +863,14 @@ What the ports guarantee (`outbound.ConsentRepositories`, available on `UnitOfWo
Implemented: `RegisterAccount` and `ResendEmailVerification` are served by `backend/internal/usecase/identity/register.go` (`identity.Registration`) behind the handler `backend/internal/adapter/primary/http/v1/auth.go`. Without `DATABASE_URL` both answer 501 as before. The router mounts `middleware.ClientIP` with `TRUSTED_PROXY_CIDRS`.
-One transaction. A new address creates the account (scenario and the first `onboarding_step` of the scenario), the C1 record (`GrantAtRegistration`, current text version and hash, source `registration`), the SHA-256 hash of a one-time token bound to the registration version, and the verification delivery (`ServiceMailer.EnqueueVerification`); the sending worker sends it later through the mail transport. C4 and every other purpose are never recorded: the body accepts only C1. Re-registration of an unverified address follows the lock order of the identity repositories (invalidate tokens, then `AdvanceRegistration`, then the new C1). An address that is already verified changes nothing and receives nothing: the "you already have an account" notice is not implemented, because any message to a verified address needs its own template and its own limit, and silence cannot reveal the account.
+One transaction. A new address creates the account (scenario and the first `onboarding_step` of the scenario), the C1 record (`GrantAtRegistration`, current text version and hash, source `registration`), the SHA-256 hash of a one-time token bound to the registration version, the keyed digest of its six-digit code, and the verification delivery (`ServiceMailer.EnqueueVerification`); the sending worker sends it later through the mail transport. C4 and every other purpose are never recorded: the body accepts only C1. Re-registration of an unverified address follows the lock order of the identity repositories (invalidate tokens, then `AdvanceRegistration`, then the new C1). An address that is already verified changes nothing and receives nothing: the "you already have an account" notice is not implemented, because any message to a verified address needs its own template and its own limit, and silence cannot reveal the account.
Pending credentials (pre-hijack protection). Every registration, the first and each repeat, stores its password hash, scenario, and first onboarding step on its own verification token (columns `pending_*` of `email_tokens`, migration 00014). A repeat registration of an unverified address never changes the credentials, scenario, or onboarding step of the `users` row: `UserRepository.AdvanceRegistration` only advances the registration version and the registration time (and discards the earlier registration C1), and the new token carries the new pending credentials. A resend copies the pending credentials of the newest token of the registration. The `password_hash`, `scenario`, and `onboarding_step` of an unverified account row are not authoritative until a verification applies the clicked token's pending data: they hold the first registrant's values only because the columns are mandatory, and no code may authenticate with them or trust them (see the comment on `domain.User`). Invalidating a token (`InvalidateActive`) clears its `pending_*` columns, and a CHECK constraint keeps an invalidated token from holding a pending hash. A resend that finds no pending credentials for the registration issues nothing.
Email confirmation (`ConfirmEmail`) is implemented. It requires the password saved with that token's registration and checks it against the pending hash. In one transaction the backend checks the current registration version and its C1 record, consumes the token, verifies the address, applies the token's password hash, scenario, and onboarding step to the account, clears `pending_*`, and records exactly one secret-free `identity.email_verified` event. Any refusal leaves the account and token unchanged. Unknown, used, replaced, or superseded tokens, a wrong password, and missing pending credentials answer `verification_token_invalid`; an expired token answers `verification_token_expired`. The Origin must match exactly `APP_PUBLIC_URL`. Confirmation does not create a session. The frontend confirmation screen is implemented and covered by the local registration browser flow.
+Confirmation by code (`ConfirmEmailByCode`) is implemented in `backend/internal/usecase/identity/code_confirmation.go`. It takes the address, the six-digit code, and the password chosen for the registration. The checks run in this order. First the rate limits: per client (`IDENTITY_CLIENT_HOURLY_LIMIT`) and per normalized address, which shares the login counter (`IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT`). Then the newest open verification token of the unverified account at that address, with the current registration version and a code. Then the password against the token's pending hash, then the keyed digest of the code (compared in constant time) and the code expiry. The password is checked on every branch with the same hashing work; with no open code a dummy hash is used, so the response time does not reveal the account. A successful check runs the same transaction as the link confirmation, so one token is consumed once: a code after the link is refused, and a link after the code is refused. Every failed check of an open code (a wrong code, a wrong password, or an expired code) adds one to `code_failed_attempts` in a single conditional UPDATE. The database serializes these updates, so concurrent wrong attempts never count more than five. The fifth failure invalidates the token and clears its code and pending credentials, so the link stops working too, and the user must request a new message. A resend invalidates the earlier codes together with the earlier tokens. Every refusal (an unknown address, no open code, a wrong code, an expired code, a wrong password, or an invalidated token) answers 400 `verification_token_invalid` with the same body, so the answer does not show which addresses have a pending registration. Success answers the same body as the link confirmation and creates no session. The verification message uses the template `verification.v2`; the earlier link-only template `verification.v1` is no longer rendered.
+
Login accepts only a verified email and checks the account's stored password, never pending registration credentials. An unknown address, wrong password, and invalid stored hash receive the same `invalid_credentials`; unknown addresses and invalid hashes also run `VerifyDummy`, and an invalid stored hash is logged without the email or hash. A correct password for an unverified account answers `email_not_verified` and creates no session. Successful login creates a new session; if the request carried a valid session cookie, the backend revokes it and creates the new session in one transaction. Failed login does not revoke an existing session, and a malformed cookie cannot become a principal.
Order of checks in registration: validation of the whole body and the C1 text version, replay check, rate limit, password hash (on every branch, before the account is read), transaction. A validation error (400) never depends on the stored accounts and consumes no limit.
diff --git a/docs/en/DEPLOY.md b/docs/en/DEPLOY.md
index 05557bb..6f01bc9 100644
--- a/docs/en/DEPLOY.md
+++ b/docs/en/DEPLOY.md
@@ -10,7 +10,7 @@ This section is for anyone who starts the MVP on their own machine: the jury, th
Implemented in this build (backend API and frontend screens):
-- Candidate and employer registration with consent C1, email confirmation through the link in the message, sign-in, sign-out, and resuming from the saved step. Mail is sent only with `EMAIL_PROVIDER=resend`.
+- Candidate and employer registration with consent C1, email confirmation with the six-digit code or the link from the message, sign-in, sign-out, and resuming from the saved step. Mail is sent only with `EMAIL_PROVIDER=resend`.
- Candidate cabinet: consents C1-C5, a manual profile without a resume and without an FSP ID, the questionnaire with specializations and self-assessment, and the home page with the next step.
- Skill assessment: the `demo_express` demonstration express run without a grade and the `demo_basic` full test with a result, result history, and skill evidence. On the demo stand a passed full test receives an uncalibrated synthetic category. The operator can read the [review band](#assessment-review-band).
- Privacy: publication of the anonymous card (C2), preview, search status, hidden organizations, and the history of changes and card views.
@@ -347,7 +347,7 @@ The backend sends mail through the `MailSender` port. `EMAIL_PROVIDER` selects e
Current state: this build contains the `disabled` and `resend` transports. With `smtp`, the backend validates the SMTP settings and then exits with `EMAIL_PROVIDER=smtp: mail transport is not available in this build`; under Compose, `restart: unless-stopped` restarts the container repeatedly. SMTP is outside the MVP. `.env.example` and `make -C deploy smoke` use `disabled`, so local runs need no key; the working stand sets `EMAIL_PROVIDER=resend` and `RESEND_API_KEY` explicitly. With `EMAIL_PROVIDER=resend`, the backend runs a worker for service identity mail (email verification and password reset), and registration queues a verification email. Password reset is not implemented, and product notifications are stored as deliveries but not sent until product notification sending is implemented. See [Sending service mail](#sending-service-mail).
-Release compatibility: `ConfirmEmail` requires both `token` and the password selected for that registration. Clients that send only the token must be updated. Migration `00016_bind_registration_consent.sql` adds the registration version to C1 and backfills legacy records from the current account version without requiring a live token. It checks that a registration C1 is not older than the latest registration and that an account has at most one active registration C1; on inconsistency, the migration stops without partial changes. A trigger fills the version when an old backend omits it and rejects a mismatched version sent by the new backend. A partial unique index allows at most one unrevoked registration C1 per account and registration version. Apply the migration before updating the backend. To roll back, deploy the old backend before reverting the migration. No new environment variable is needed. `APP_PUBLIC_URL` also defines the Origin that confirmation requests must send.
+Release compatibility: `ConfirmEmail` requires both `token` and the password selected for that registration. Clients that send only the token must be updated. Migration `00016_bind_registration_consent.sql` adds the registration version to C1 and backfills legacy records from the current account version without requiring a live token. It checks that a registration C1 is not older than the latest registration and that an account has at most one active registration C1; on inconsistency, the migration stops without partial changes. A trigger fills the version when an old backend omits it and rejects a mismatched version sent by the new backend. A partial unique index allows at most one unrevoked registration C1 per account and registration version. Apply the migration before updating the backend. To roll back, deploy the old backend before reverting the migration. No new environment variable is needed. `APP_PUBLIC_URL` also defines the Origin that confirmation requests must send. The new `ConfirmEmailByCode` operation (`POST /api/v1/identity/email-verifications/code`) and migration `00046_add_email_verification_codes.sql` are additive: existing clients keep confirming by link. The migration can be rolled back once no usable code is left; its down step refuses until then.
`resend` sends each message with one request to `https://api.resend.com/emails`. Building the transport makes no network call, so startup checks neither the key nor the sender domain; a wrong key or an unverified domain in `EMAIL_FROM` shows up as a rejected send. One attempt is limited by `EMAIL_TIMEOUT`. The transport follows no redirects, never retries, and logs nothing; the sending worker owns retries, backoff, rate-limit pacing, and outcome records, while the quota gate schedules a known daily or monthly reset (see [Mail quotas](#mail-quotas)). Each request carries the message's idempotency key, and Resend deduplicates the same key and body for 24 hours; after that window a retry may send the mail twice. A success means that Resend accepted the request and returned a message ID, not that the mail was delivered or read. A timeout, a lost answer after the request was sent, or a Resend 500 error is `unknown` (`delivery_uncertain`), not a failure. The backend process follows the standard `HTTPS_PROXY` and `NO_PROXY` variables, but the Compose backend service does not pass them, so under Compose the request goes directly to Resend; a stand that needs an egress proxy must add them to the backend `environment`. The full mapping of answers is in [ARCHITECTURE.md](ARCHITECTURE.md#mail-transport).
diff --git a/docs/en/TESTING.md b/docs/en/TESTING.md
index 55ef6db..88471dd 100644
--- a/docs/en/TESTING.md
+++ b/docs/en/TESTING.md
@@ -44,6 +44,8 @@ Existing checks cover health/readiness, backend PostgreSQL, Redis, and SeaweedFS
TestEmailVerificationOverHTTP obtains a token from the Resend fixture after registration. It checks candidate and employer confirmation, no session or cookie, and unchanged state after an unknown, expired, replaced, or consumed token, a wrong password, or missing pending credentials. It also checks C1 version binding, missing, null, and foreign Origin values, plus rate limits, expiry after a lock wait, rollback after an outbox failure, and one event from concurrent confirmations. It covers the API only and does not send through an external mail provider. The separate local registration browser flow covers the frontend.
+TestEmailVerificationCodeOverHTTP (`backend/integration_test/email_code_test.go`) takes the code and the link from the same fixture message. It checks that the code confirms like the link; that five wrong codes burn the token, after which the right code and the link both fail; that eight concurrent wrong codes count exactly five attempts; that a wrong password counts; that an expired code leaves the link valid; that the link and the code consume one token in either order; that a resend replaces the code; that a registration replaced by another registration cannot be confirmed with its code; that an unknown address and a wrong code give the same refusal; and that the address limit answers 429 after ten requests. Its origin case refuses a foreign Origin before the usecase runs.
+
API verification checks the OpenAPI subset exercised by pinned tools, fixtures, and contracts that actually ran. Its result applies only to those inputs. CI YAML in the repository does not mean a workflow has run on GitHub.
Deployment smoke checks infrastructure routes, Compose startup, PostgreSQL/Redis/SeaweedFS readiness, Redis authentication and cache configuration, rejection of anonymous SeaweedFS bucket access, isolation of SeaweedFS from the frontend (by name and by its storage network address), rejection of filer, master, and volume HTTP requests that do not come from inside the SeaweedFS container, and the backend startup log for `EMAIL_PROVIDER=disabled`. The backend relay connects to Kafka in the smoke stack, but the smoke does not check that it publishes. It stops Redis and SeaweedFS in turn to verify that /readyz returns 503 while /api/v1/healthz remains available, then verifies readiness recovery after each dependency restarts. It sends no mail and does not check mail delivery, contact release, protection of product data, ML robustness, ranking quality, PDF export, or the two-role flow. A separate monitoring check does not verify the core database or end-to-end telemetry from the application.
@@ -75,6 +77,8 @@ The ordinary technical suite does not cover candidate or employer workflows, sig
The registration-mode suite additionally runs `frontend/e2e/auth-registration.spec.ts`: candidate and employer registration with visible C1, real local resend and a distinct received message, same-tab replacement of the verification link, wrong-password retry, confirmation without automatic login, sign-in, and restoring the server step after reload. It checks keyboard focus and overflow at 360, 768, and 1280 pixels. Expired-link rendering uses a controlled problem response; actual token expiry is covered by backend integration tests. Only this isolated overlay sets `VERIFICATION_MAIL_MIN_INTERVAL=1s`; normal and release environments retain their configured interval. Auth traces, failure screenshots, and video are disabled; explicit review screenshots show only token-free states and synthetic addresses. No external mail or production edge flow is verified.
+Since the code step, the same suite confirms each candidate and employer registration with the six-digit code from the message: a wrong code first, a reload that asks for the password again, and a check that no browser storage holds the password. A separate test keeps the link as the fallback: an expired link leads to the code step, which sends a new message, and the link from that message then confirms the registration.
+
In the same mode, the runner invokes `/consent-fixture` from the test backend image before starting the browser. The command exists only with the Go `e2e` build tag, requires `E2E_CONSENT_FIXTURE=1`, and uses domain objects and transactional ports to create a synthetic verified candidate, C1/C2, and two C4 scopes for different companies. A collision with an existing test address stops the run. Ordinary and release images contain neither the command nor its enabled flag. `frontend/e2e/consent-management.spec.ts` uses normal sign-in and real consent APIs to grant C3 independently, revoke C2 and one C4, retain the other scope, reload, and submit a C1 request whose returned status is shown. A controlled 403 exercises the failure UI; successful mutations reach PostgreSQL. Synthetic invitation IDs in the fixture do not prove the invitation acceptance flow. Traces and automatic screenshots are disabled; the explicit review screenshot contains only synthetic data.
The same command also seeds a second synthetic candidate for `frontend/e2e/privacy-visibility.spec.ts`: an active C1 and C2, one C4 for the first of two new companies, and three recorded card reads (a card view and a contact read by the first company, a card view by the second). The reads are inserted through the privacy port because the organization read path needs search results that do not exist yet; they do not prove that path. With the real backend, the suite confirms the search status without publishing, publishes after the explicit C2 step, compares the owner preview with the API response, hides one company and brings it back, revokes C2 and checks the closure explanation, grants C2 again without reopening the card, and republishes with the keyboard alone; in the mail-fixture mode a freshly registered candidate with two declared specializations and no test publishes and sees the not-confirmed grade status for each. A stubbed group renders a confirmed Backend next to unconfirmed specializations, the evidence basis and calibration labels, empty histories, a failed save that keeps the draft, and a revoked C2. No test reads the card as an employer, so the immediate loss of access of a hidden employer is not checked in a browser.
diff --git a/docs/ru/ARCHITECTURE.md b/docs/ru/ARCHITECTURE.md
index bfcde8f..5ae3041 100644
--- a/docs/ru/ARCHITECTURE.md
+++ b/docs/ru/ARCHITECTURE.md
@@ -350,6 +350,8 @@ Offsets и партиции. Каждый обработчик - один уча
Ссылки. Токен передается только во фрагменте URL: `/verify-email#token=` и `/reset-password#token=`; ссылки строит `mailtemplate` (`tokenLink`). Браузер никогда не отправляет фрагмент серверу, поэтому токен не попадает в access log nginx, который пишет `$uri`, в заголовки Referer и в журнал запросов Go; его нет ни в пути, ни в query. Frontend читает и удаляет токен из фрагмента, затем после явного действия пользователя отправляет его вместе с паролем регистрации. Новая ссылка в той же вкладке заменяет токен; результат прежнего запроса не меняет новую форму. Маршрут и API сброса пароля не реализованы. Renderer отклоняет токен в любом другом месте, golden-файлы и тесты фиксируют формат, а тесты доставок проверяют, что сохраненное тело содержит ссылку с фрагментом и не содержит `?token=`. Тело в `deliveries` хранит действующий токен, пока письмо не отправлено или не отменено; см. "Персональные данные в хранилище".
+Коды. Каждое письмо подтверждения содержит также шестизначный код: в текстовой части строкой `Код подтверждения: <код>`, в HTML-части крупным блоком. Код действует 30 минут либо до конца срока токена, если токен заканчивается раньше; письмо называет этот срок. Код - альтернатива ссылке, а не ее замена: его проверяет `ConfirmEmailByCode` (см. раздел о регистрации и подтверждении). Как и ссылка, код остается в теле доставки до отправки или отмены письма и затем очищается; строка токена хранит только keyed-дайджест кода, но не сам код. Чтение `deliveries` до этого момента раскрывает и код.
+
Один проход `ServiceMailSender.ProcessNext` проводит одну доставку через три шага:
1. Транзакция захвата. `DeliveryRepository.ClaimDue` берет самую просроченную доставку с `FOR UPDATE SKIP LOCKED`: вид `verification` или `password_reset` (литералы совпадают с предикатом `deliveries_due_idx`, поэтому опрос читает только этот малый индекс), статус `pending`, `waiting_quota` или запланированный `unknown`, наступивший `next_attempt_at`, доставка закреплена за настроенным аккаунтом провайдера и ее не держит живой lease. Неопределенный исход автоматически ставится на повтор только до cutoff; `unknown` без срока ждет оператора. Однократное разрешение оператора тоже ставит `unknown` в очередь. Захват записывает `claim_owner` и `claimed_until` (lease), не меняя версию и время обновления, поэтому несколько процессов не возьмут одну доставку. Lease измеряется часами базы данных (`clock_timestamp()` плюс длина lease, и он жив, пока `claimed_until` позже `clock_timestamp()`), а не часами экземпляра приложения; сроки доставок остаются на часах приложения, которые их записали. В той же транзакции отправитель переносит на настроенный аккаунт письма, сохраненные при `EMAIL_PROVIDER=disabled` (это разрешено только до первой попытки, пока ключ не видел ни один провайдер), выполняет проверку ниже, а затем `QuotaGate.PrepareSend`, который резервирует получателя или переводит доставку в `waiting_quota`. Транзакция фиксируется до вызова транспорта, поэтому медленный провайдер никогда не держит блокировку строки. Сбой внутри нее (детерминированный, например строка, которую нельзя восстановить) откатывает и lease, поэтому сбой записывается для строки отдельной транзакцией; см. "Сбойные строки".
@@ -765,7 +767,7 @@ contact_grant относится к паре кандидат-компания
Хранение identity реализовано миграцией `backend/db/migrations/00002_create_identity_tables.sql`, запросами `backend/db/queries/identity.sql`, доменными типами, outbound-портами и адаптером Postgres. Backend API реализует регистрацию, повторную отправку подтверждения, `ConfirmEmail`, вход и базовые операции с текущей сессией. Экраны регистрации и подтверждения во frontend реализованы; см. [контракт API](../../api/README.md#identity-сессии-cookie-и-csrf).
- `users`: UUIDv7 `id`; `email` - форма для доставки (ASCII без пробелов по краям, регистр как при вводе, возвращается в `Account.email`), и `email_normalized` - уникальный ключ сравнения (тот же адрес, в котором A-Z переведены в нижний регистр); `password_hash` - строка PHC Argon2id v19; `scenario` и `onboarding_step` с CHECK, что шаг относится к сценарию; nullable `email_verified_at`; `registration_version`; `last_registered_at` с частичным индексом по неподтвержденным аккаунтам для запланированной очистки через 7 дней; оптимистичная `version`; `created_at` и `updated_at`. Форма для доставки хранится, потому что RFC 5321 допускает local part с учетом регистра: письмо уходит на адрес в введенном виде, а уникальность не учитывает регистр.
-- `email_tokens`: `token_hash` (SHA-256, `bytea` из 32 байт, уникальный), `purpose` (`email_verification`; CHECK перечисляет допустимые назначения, поэтому сброс пароля можно добавить позже), `user_id`, `registration_version`, к которой привязан токен, `created_at`, `expires_at`, `consumed_at` и `invalidated_at`. Миграция 00014 добавляет `pending_password_hash`, `pending_scenario` и `pending_onboarding_step`, чтобы каждый токен нес данные своей регистрации. CHECK допускает не больше одного из consumed и invalidated.
+- `email_tokens`: `token_hash` (SHA-256, `bytea` из 32 байт, уникальный), `purpose` (`email_verification`; CHECK перечисляет допустимые назначения, поэтому сброс пароля можно добавить позже), `user_id`, `registration_version`, к которой привязан токен, `created_at`, `expires_at`, `consumed_at` и `invalidated_at`. Миграция 00014 добавляет `pending_password_hash`, `pending_scenario` и `pending_onboarding_step`, чтобы каждый токен нес данные своей регистрации. CHECK допускает не больше одного из consumed и invalidated. Миграция `00046_add_email_verification_codes.sql` добавляет `code_hash` (HMAC-SHA-256 шестизначного кода под серверным ключом; NULL, если у токена нет кода или код закончился), `code_expires_at` и `code_failed_attempts` (от 0 до 5). Срок кода - меньший из срока токена и 30-минутного срока кода; приложение проверяет оба при каждом использовании.
- `sessions`: UUIDv7 `id`, который не покидает сервер, `token_hash` (SHA-256 значения cookie, уникальный), `user_id`, `created_at`, `last_seen_at`, абсолютный `expires_at` и `revoked_at`. IP-адрес и user agent не хранятся.
- Токены и сессии ссылаются на `users` с `ON DELETE CASCADE`. Записи согласий ссылаются на него с `ON DELETE RESTRICT`; см. [Журнал согласий](#журнал-согласий). CHECK-ограничения дублируют доменные правила как последнюю защиту: ASCII-адрес и его ключ, формат PHC и времена (подтверждения, погашения, аннулирования и отзыва) не раньше `created_at`.
@@ -853,12 +855,14 @@ contact_grant относится к паре кандидат-компания
Реализовано: `RegisterAccount` и `ResendEmailVerification` обслуживает `backend/internal/usecase/identity/register.go` (`identity.Registration`) за обработчиком `backend/internal/adapter/primary/http/v1/auth.go`. Без `DATABASE_URL` обе операции по-прежнему отвечают 501. Роутер подключает `middleware.ClientIP` с `TRUSTED_PROXY_CIDRS`.
-Одна транзакция. Новый адрес создает аккаунт (сценарий и первый `onboarding_step` сценария), запись C1 (`GrantAtRegistration`, текущая версия и хеш текста, источник `registration`), SHA-256 хеш одноразового токена, привязанного к версии регистрации, и доставку подтверждения (`ServiceMailer.EnqueueVerification`); отправляет ее позже воркер отправки через почтовый транспорт. C4 и любая другая цель никогда не записываются: тело принимает только C1. Повторная регистрация неподтвержденного адреса соблюдает порядок блокировок репозиториев identity (аннулировать токены, затем `AdvanceRegistration`, затем новая C1). Уже подтвержденный адрес ничего не меняет и ничего не получает: уведомление "у вас уже есть аккаунт" не реализовано, потому что любое письмо на подтвержденный адрес требует своего шаблона и своего лимита, а молчание не раскрывает аккаунт.
+Одна транзакция. Новый адрес создает аккаунт (сценарий и первый `onboarding_step` сценария), запись C1 (`GrantAtRegistration`, текущая версия и хеш текста, источник `registration`), SHA-256 хеш одноразового токена, привязанного к версии регистрации, keyed-дайджест его шестизначного кода и доставку подтверждения (`ServiceMailer.EnqueueVerification`); отправляет ее позже воркер отправки через почтовый транспорт. C4 и любая другая цель никогда не записываются: тело принимает только C1. Повторная регистрация неподтвержденного адреса соблюдает порядок блокировок репозиториев identity (аннулировать токены, затем `AdvanceRegistration`, затем новая C1). Уже подтвержденный адрес ничего не меняет и ничего не получает: уведомление "у вас уже есть аккаунт" не реализовано, потому что любое письмо на подтвержденный адрес требует своего шаблона и своего лимита, а молчание не раскрывает аккаунт.
Отложенные учетные данные (защита от pre-hijack). Каждая регистрация, первая и каждая повторная, хранит хеш пароля, сценарий и первый шаг онбординга на своем токене подтверждения (столбцы `pending_*` таблицы `email_tokens`, миграция 00014). Повторная регистрация неподтвержденного адреса никогда не меняет учетные данные, сценарий и шаг онбординга строки `users`: `UserRepository.AdvanceRegistration` только увеличивает версию регистрации и время регистрации (и удаляет C1 прежней регистрации), а новый токен несет новые отложенные данные. Повторная отправка копирует отложенные данные новейшего токена регистрации. `password_hash`, `scenario` и `onboarding_step` строки неподтвержденного аккаунта не авторитетны, пока подтверждение не применит отложенные данные нажатого токена: в них значения первого регистранта лишь потому, что столбцы обязательны, и никакой код не вправе по ним аутентифицировать или им доверять (см. комментарий к `domain.User`). Аннулирование токена (`InvalidateActive`) очищает его столбцы `pending_*`, а CHECK не дает аннулированному токену хранить отложенный хеш. Повторная отправка, не нашедшая отложенных данных регистрации, ничего не выпускает.
Подтверждение почты (`ConfirmEmail`) реализовано. Оно требует пароль, сохраненный для регистрации этого токена, и проверяет его по отложенному хешу. В одной транзакции backend проверяет текущую версию регистрации и запись C1, погашает токен, подтверждает адрес, переносит с токена на аккаунт хеш пароля, сценарий и шаг онбординга, очищает `pending_*` и записывает ровно одно событие `identity.email_verified` без секретов. При любом отказе состояние аккаунта и токена не меняется. Неизвестный, использованный, замененный, устаревший токен, неверный пароль и отсутствие отложенных данных дают `verification_token_invalid`; истекший токен дает `verification_token_expired`. Origin должен точно совпадать с `APP_PUBLIC_URL`. Подтверждение не создает сессию. Экран подтверждения во frontend реализован и проверен локальным браузерным потоком регистрации.
+Подтверждение кодом (`ConfirmEmailByCode`) реализовано в `backend/internal/usecase/identity/code_confirmation.go`. Оно принимает адрес, шестизначный код и пароль, выбранный при регистрации. Проверки идут в таком порядке. Сначала лимиты запросов: по клиенту (`IDENTITY_CLIENT_HOURLY_LIMIT`) и по нормализованному адресу, который делит счетчик со входом (`IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT`). Затем самый новый открытый токен подтверждения непроверенного аккаунта с этим адресом, с текущей версией регистрации и кодом. Затем пароль по отложенному хешу токена, затем keyed-дайджест кода (сравнение за постоянное время) и срок кода. Пароль проверяется на каждой ветке одинаковой работой хеширования: если открытого кода нет, используется фиктивный хеш, поэтому время ответа не раскрывает аккаунт. Успешная проверка выполняет ту же транзакцию, что и подтверждение по ссылке, поэтому токен погашается один раз: код после ссылки и ссылка после кода оба отказывают. Каждая неудачная проверка открытого кода (неверный код, неверный пароль или истекший код) добавляет единицу в `code_failed_attempts` одним условным UPDATE; база сериализует такие обновления, поэтому параллельные неверные попытки не засчитываются больше пяти. Пятая неудача аннулирует токен и очищает его код и отложенные учетные данные, поэтому перестает работать и ссылка, а пользователю нужно запросить новое письмо. Повторная отправка аннулирует прежние коды вместе с прежними токенами. Любой отказ (неизвестный адрес, нет открытого кода, неверный код, истекший код, неверный пароль или аннулированный токен) отвечает 400 `verification_token_invalid` одним и тем же телом, поэтому ответ не показывает, у каких адресов есть отложенная регистрация. Успех отвечает тем же телом, что и подтверждение по ссылке, и сессию не создает. Письмо подтверждения использует шаблон `verification.v2`; шаблон `verification.v1` (только ссылка) больше не рендерится.
+
Вход принимает только подтвержденный email и проверяет сохраненный пароль аккаунта, а не отложенные данные регистрации. Неизвестный адрес, неверный пароль и некорректный сохраненный хеш получают одинаковый `invalid_credentials`; неизвестный адрес и некорректный хеш дополнительно проходят `VerifyDummy`, а ошибка сохраненного хеша записывается в лог без email или хеша. Верный пароль для неподтвержденного аккаунта отвечает `email_not_verified` и не создает сессию. Успешный вход создает новую сессию; если запрос принес действующую cookie сессии, сервер отзывает ее и создает новую в одной транзакции. Неуспешный вход не отзывает старую сессию, а некорректная cookie не становится principal.
Порядок проверок регистрации: валидация всего тела и версии текста C1, проверка воспроизведения, лимит, хеш пароля (в каждой ветке, до чтения аккаунта), транзакция. Ошибка валидации (400) не зависит от хранимых аккаунтов и не расходует лимит.
diff --git a/docs/ru/DEPLOY.md b/docs/ru/DEPLOY.md
index cda8b6f..389aeb6 100644
--- a/docs/ru/DEPLOY.md
+++ b/docs/ru/DEPLOY.md
@@ -10,7 +10,7 @@
Реализовано в этой сборке (API backend и экраны frontend):
-- Регистрация кандидата и работодателя с согласием C1, подтверждение email по ссылке из письма, вход, выход и продолжение с сохраненного шага. Письмо уходит только при `EMAIL_PROVIDER=resend`.
+- Регистрация кандидата и работодателя с согласием C1, подтверждение email по коду или ссылке из письма, вход, выход и продолжение с сохраненного шага. Письмо уходит только при `EMAIL_PROVIDER=resend`.
- Кабинет кандидата: согласия C1-C5, ручной профиль без резюме и без ФСП ID, анкета со специализациями и самооценкой, главная страница со следующим шагом.
- Проверка навыков: демонстрационный экспресс-запуск `demo_express` без грейда и полный тест `demo_basic` с результатом, историей результатов и доказательством навыка. На демонстрационном стенде пройденный полный тест получает неоткалиброванную синтетическую категорию. Оператору доступна [полоса ручной проверки](#полоса-проверки-оценки).
- Приватность: публикация анонимной карточки (C2), предпросмотр, статус поиска, скрытие организаций, история изменений и просмотров карточки.
@@ -349,7 +349,7 @@ Backend отправляет почту через порт `MailSender`. `EMAIL
Текущее состояние: в этой сборке есть транспорты `disabled` и `resend`. С `smtp` backend проверяет настройки SMTP и затем завершается с ошибкой `EMAIL_PROVIDER=smtp: mail transport is not available in this build`; в Compose `restart: unless-stopped` будет перезапускать контейнер снова и снова. SMTP вне MVP. `.env.example` и `make -C deploy smoke` используют `disabled`, поэтому локальному запуску ключ не нужен; рабочий стенд явно задает `EMAIL_PROVIDER=resend` и `RESEND_API_KEY`. При `EMAIL_PROVIDER=resend` backend запускает worker служебной почты identity (подтверждение почты и сброс пароля); регистрация ставит письмо подтверждения в очередь. Сброс пароля не реализован, а продуктовые уведомления сохраняются как доставки, но не отправляются до реализации их отправки. См. [Отправка служебной почты](#отправка-служебной-почты).
-Совместимость выпуска: `ConfirmEmail` требует `token` и пароль, выбранный при соответствующей регистрации. Клиенты, которые отправляли только токен, нужно обновить. Миграция `00016_bind_registration_consent.sql` добавляет версию регистрации к C1 и заполняет ее для прежних записей по текущей версии аккаунта, без требования живого токена. Она проверяет, что регистрационная C1 не старше последней регистрации и что у аккаунта нет нескольких активных регистрационных C1; при несоответствии миграция останавливается без частичных изменений. Триггер заполняет версию, если старый backend не передал ее, и отклоняет несовпадающую версию от нового backend. Частичный уникальный индекс допускает не больше одной неотозванной регистрационной C1 на аккаунт и версию регистрации. Миграцию можно применить до обновления backend. При откате сначала верните старый backend, затем отмените миграцию. Новые переменные окружения не нужны. `APP_PUBLIC_URL` также задает Origin, который должен передавать запрос подтверждения.
+Совместимость выпуска: `ConfirmEmail` требует `token` и пароль, выбранный при соответствующей регистрации. Клиенты, которые отправляли только токен, нужно обновить. Миграция `00016_bind_registration_consent.sql` добавляет версию регистрации к C1 и заполняет ее для прежних записей по текущей версии аккаунта, без требования живого токена. Она проверяет, что регистрационная C1 не старше последней регистрации и что у аккаунта нет нескольких активных регистрационных C1; при несоответствии миграция останавливается без частичных изменений. Триггер заполняет версию, если старый backend не передал ее, и отклоняет несовпадающую версию от нового backend. Частичный уникальный индекс допускает не больше одной неотозванной регистрационной C1 на аккаунт и версию регистрации. Миграцию можно применить до обновления backend. При откате сначала верните старый backend, затем отмените миграцию. Новые переменные окружения не нужны. `APP_PUBLIC_URL` также задает Origin, который должен передавать запрос подтверждения. Новая операция `ConfirmEmailByCode` (`POST /api/v1/identity/email-verifications/code`) и миграция `00046_add_email_verification_codes.sql` аддитивны: прежние клиенты продолжают подтверждать по ссылке. Откат миграции возможен, когда не осталось действующих кодов; ее down-шаг до этого момента отказывает.
`resend` отправляет каждое письмо одним запросом к `https://api.resend.com/emails`. Создание транспорта не обращается к сети, поэтому при запуске не проверяются ни ключ, ни домен отправителя; неверный ключ или неподтвержденный домен в `EMAIL_FROM` проявятся как отказ при отправке. Одну попытку ограничивает `EMAIL_TIMEOUT`. Транспорт не следует редиректам, никогда не повторяет запрос и ничего не логирует; повторы, backoff, темп при rate limit и учет результатов выполняет worker отправки, а ожидание известного сброса дневной или месячной квоты решает шлюз квот (см. [Квоты почты](#квоты-почты)). Каждый запрос несет ключ идемпотентности письма, и Resend 24 часа не отправляет повторно письмо с тем же ключом и телом; после этого окна повтор может отправить письмо дважды. Успех значит, что Resend принял запрос и вернул идентификатор письма, а не что письмо доставлено или прочитано. Таймаут, потерянный ответ после отправки запроса или ошибка 500 от Resend дают `unknown` (`delivery_uncertain`), а не ошибку. Процесс backend учитывает стандартные переменные `HTTPS_PROXY` и `NO_PROXY`, но сервис backend в Compose их не передает, поэтому под Compose запрос идет в Resend напрямую; если стенду нужен прокси для исходящего трафика, добавьте эти переменные в `environment` сервиса backend. Полное соответствие ответов описано в [ARCHITECTURE.md](ARCHITECTURE.md#почтовый-транспорт).
diff --git a/docs/ru/TESTING.md b/docs/ru/TESTING.md
index 0a13fdf..c1098c4 100644
--- a/docs/ru/TESTING.md
+++ b/docs/ru/TESTING.md
@@ -44,6 +44,8 @@ make -C ml check-generated использует datamodel-code-generator --check
TestEmailVerificationOverHTTP получает токен из Resend fixture после регистрации. Тест проверяет подтверждение candidate и employer, отсутствие сессии и cookie, неизменность состояния при неизвестном, истекшем, замененном или погашенном токене, неверном пароле и отсутствии отложенных данных. Он также проверяет привязку C1 к версии регистрации, отсутствующий, null и чужой Origin, а также лимиты, истечение срока после ожидания блокировки, откат после сбоя outbox и одно событие при параллельном подтверждении. Тест охватывает только API; внешний почтовый провайдер не вызывается. Frontend проверяет отдельный локальный браузерный поток регистрации.
+TestEmailVerificationCodeOverHTTP (`backend/integration_test/email_code_test.go`) берет код и ссылку из одного сообщения фикстуры. Он проверяет, что код подтверждает регистрацию так же, как ссылка; что пять неверных кодов аннулируют токен, после чего правильный код и ссылка не работают; что восемь параллельных неверных кодов засчитываются ровно как пять попыток; что неверный пароль засчитывается; что истекший код не отменяет ссылку; что ссылка и код погашают один токен в любом порядке; что повторная отправка заменяет код; что регистрация, замененная другой регистрацией, не подтверждается своим кодом; что неизвестный адрес и неверный код дают один и тот же отказ; что лимит адреса отвечает 429 после десяти запросов. Тест origin отклоняет чужой Origin до запуска usecase.
+
API verify проверяет выбранный OpenAPI subset через pinned toolchain; его результат относится только к реально запущенным fixture и контрактам. CI YAML в репозитории не означает, что workflow уже выполнился на GitHub.
Deployment smoke проверяет инфраструктурные маршруты, запуск Compose, готовность PostgreSQL/Redis/SeaweedFS, аутентификацию и настройки кеша Redis, отказ SeaweedFS в анонимном доступе к bucket, изоляцию SeaweedFS от frontend (по имени и по адресу в сети хранилища), отказ HTTP API filer, master и volume на запросы не изнутри контейнера SeaweedFS и запись в логе запуска backend о `EMAIL_PROVIDER=disabled`. В smoke-стеке relay backend подключается к Kafka, но smoke не проверяет, что он публикует события. Он поочередно останавливает Redis и SeaweedFS и проверяет, что /readyz возвращает 503, а /api/v1/healthz остается доступным, затем проверяет восстановление готовности после запуска зависимости. Он не отправляет писем и не проверяет доставку почты, получение контактов, защищенность бизнес-данных, устойчивость ML, точность ранжирования, PDF экспорт или сценарий двух ролей. Отдельная проверка мониторинга не подтверждает core database или end-to-end доставку данных от приложения.
@@ -75,6 +77,8 @@ Playwright получает `E2E_MAIL_FIXTURE=1`, `E2E_MAILBOX_URL=http://mail-f
Режим регистрации дополнительно запускает `frontend/e2e/auth-registration.spec.ts`: регистрацию кандидата и работодателя с видимым C1, реальную локальную повторную отправку с получением нового письма, замену ссылки подтверждения в той же вкладке, повтор после неверного пароля, подтверждение без автоматического входа, вход и восстановление серверного шага после обновления. Проверяются фокус клавиатуры и отсутствие переполнения на 360, 768 и 1280 px. Отображение просроченной ссылки использует управляемый problem-ответ; реальное истечение токена проверяют backend integration tests. Только изолированный overlay задает `VERIFICATION_MAIL_MIN_INTERVAL=1s`; обычная среда и выпуск сохраняют свой настроенный интервал. Для auth-тестов отключены трассы, снимки при ошибках и видео; явные снимки для проверки показывают состояния без токенов и синтетические адреса. Внешняя почта и рабочий edge-путь не проверялись.
+С появлением шага кода тот же набор проверяет подтверждение каждой регистрации кандидата и работодателя шестизначным кодом из письма: сначала неверный код, затем перезагрузка страницы, на которой пароль запрашивается снова, и проверка, что браузерное хранилище не содержит пароль. Отдельный тест оставляет ссылку запасным путем: истекшая ссылка ведет на шаг кода, который отправляет новое письмо, и ссылка из этого письма подтверждает регистрацию.
+
В этом же режиме runner перед браузером запускает `/consent-fixture` из тестового backend-образа. Команда доступна только с Go build tag `e2e`, требует `E2E_CONSENT_FIXTURE=1` и через домен и транзакционные порты создает синтетического подтвержденного кандидата, C1/C2 и два C4 для разных компаний. Совпадение тестового адреса с существующим аккаунтом останавливает запуск. Обычный и release-образы не содержат команду и не включают этот флаг. Сценарий `frontend/e2e/consent-management.spec.ts` использует обычный вход и реальные API согласий: отдельную выдачу C3, отзыв C2 и одного C4, сохранение другого scope, перезагрузку и C1 request со статусом из ответа. Отказ сервера для проверки UI задается управляемым 403; успешные изменения идут в PostgreSQL. Синтетические invitation IDs в fixture не доказывают реализацию принятия приглашений. Трассы и автоматические снимки отключены; явный снимок показывает только синтетические данные.
Та же команда создает второго синтетического кандидата для `frontend/e2e/privacy-visibility.spec.ts`: действующие C1 и C2, один C4 для первой из двух новых компаний и три записанных чтения карточки (просмотр карточки и чтение контактов первой компанией, просмотр карточки второй). Чтения вставлены через порт приватности, потому что путь чтения организацией требует результатов поиска, которых еще нет; они не доказывают этот путь. На настоящем backend набор подтверждает статус поиска без публикации, публикует после явного шага C2, сверяет предпросмотр владельца с ответом API, скрывает одну компанию и возвращает ее, отзывает C2 и проверяет объяснение закрытия, снова выдает C2 без открытия карточки и публикует заново только с клавиатуры; в режиме с почтовой фикстурой свежезарегистрированный кандидат с двумя заявленными специализациями и без теста публикуется и видит "Грейд не подтвержден" для каждой. Группа с подменой API показывает подтвержденный Backend рядом с неподтвержденными специализациями, подписи основы и калибровки доказательств, пустые истории, неудачное сохранение с сохранением черновика и отозванный C2. Ни один тест не читает карточку как работодатель, поэтому немедленная потеря доступа скрытого работодателя в браузере не проверяется.
diff --git a/frontend/e2e/auth-registration.spec.ts b/frontend/e2e/auth-registration.spec.ts
index 66cf8ad..fe054f4 100644
--- a/frontend/e2e/auth-registration.spec.ts
+++ b/frontend/e2e/auth-registration.spec.ts
@@ -48,6 +48,17 @@ test.describe("registration, email confirmation, and onboarding", () => {
return token;
}
+ function codeFromMessage(message: InboxMessage): string {
+ const content = `${message.text ?? ""}\n${message.html ?? ""}`;
+ const code = /Код подтверждения: ([0-9]{6})\b/.exec(content)?.[1];
+ if (!code) throw new Error("The local registration message had no verification code.");
+ return code;
+ }
+
+ function wrongCodeFor(code: string): string {
+ return code === "000000" ? "000001" : "000000";
+ }
+
async function openVerificationLink(page: Page, token: string): Promise {
const target = new URL("/verify-email", process.env.E2E_BASE_URL);
target.hash = `token=${token}`;
@@ -90,6 +101,56 @@ test.describe("registration, email confirmation, and onboarding", () => {
await page.screenshot({ path: screenshotPath, animations: "disabled" });
}
+ async function registerThroughForm(
+ page: Page,
+ scenario: "candidate" | "employer",
+ email: string,
+ password: string,
+ ): Promise {
+ const scenarioLabel = scenario === "candidate" ? "Кандидат" : "Работодатель";
+ await page.goto("/register");
+ await expect(
+ page.getByRole("heading", { name: "Согласие C1 на обработку персональных данных" }),
+ ).toBeVisible();
+ await expect(page.getByText(/C4/)).toHaveCount(0);
+ await page.getByLabel("Электронная почта").fill(email);
+ await page.getByLabel("Пароль", { exact: true }).fill(password);
+ await page.getByRole("radio", { name: new RegExp(scenarioLabel) }).check();
+ await page.getByRole("checkbox", { name: /принимаю его/ }).check();
+ await page.getByRole("button", { name: "Создать аккаунт" }).click();
+ await expect(page.getByRole("heading", { name: "Запрос принят" })).toBeVisible();
+ await expect(
+ page.getByText(new RegExp(`Выбранный сценарий: ${scenarioLabel.toLowerCase()}`)),
+ ).toBeVisible();
+ }
+
+ async function signInAndResume(
+ page: Page,
+ scenario: "candidate" | "employer",
+ email: string,
+ password: string,
+ nextStep: string,
+ ): Promise {
+ const noSessionResponse = page.waitForResponse(
+ (response) => new URL(response.url()).pathname === "/api/v1/identity/sessions/current",
+ );
+ await page.goto(scenario === "candidate" ? "/candidate" : "/employer");
+ expect((await noSessionResponse).status()).toBe(401);
+ await expect(page.getByRole("heading", { name: "Вход" })).toBeVisible();
+ await page.getByLabel("Электронная почта").fill(email);
+ await page.getByLabel("Пароль", { exact: true }).fill(password);
+ await page.getByRole("button", { name: "Войти" }).click();
+ await expect(page.getByRole("heading", { name: nextStep })).toBeVisible();
+
+ const restoredSessionResponse = page.waitForResponse(
+ (response) => new URL(response.url()).pathname === "/api/v1/identity/sessions/current",
+ );
+ await page.reload();
+ expect((await restoredSessionResponse).status()).toBe(200);
+ await expect(page.getByRole("heading", { name: nextStep })).toBeVisible();
+ await checkResponsiveKeyboardFlow(page);
+ }
+
async function completeScenario(page: Page, scenario: "candidate" | "employer") {
test.skip(!mailFixtureEnabled, "Requires the local mail fixture target.");
@@ -113,6 +174,15 @@ test.describe("registration, email confirmation, and onboarding", () => {
await expect(
page.getByText(new RegExp(`Выбранный сценарий: ${scenarioLabel.toLowerCase()}`)),
).toBeVisible();
+ await expect(page.getByRole("heading", { name: "Введите код из письма" })).toBeVisible();
+ await expect(page.getByLabel("Код из письма", { exact: true })).toBeVisible();
+
+ // The password is held in memory only: no browser storage keeps it, and
+ // the stored context has only the address, the scenario, and the flag.
+ const storedText = await page.evaluate(() =>
+ JSON.stringify({ ...localStorage, ...sessionStorage }),
+ );
+ expect(storedText.includes(password)).toBe(false);
const registrationContextIsNonSecret = await page.evaluate(() => {
const raw = sessionStorage.getItem("lincodex-registration-context");
if (!raw) return false;
@@ -126,17 +196,79 @@ test.describe("registration, email confirmation, and onboarding", () => {
});
expect(registrationContextIsNonSecret).toBe(true);
+ // A reload drops the memory copy, so the step asks for the password again.
await page.reload();
await expect(page.getByRole("heading", { name: "Запрос принят" })).toBeVisible();
- await expect(
- page.getByText(new RegExp(`Выбранный сценарий: ${scenarioLabel.toLowerCase()}`)),
- ).toBeVisible();
+ await expect(page.getByLabel("Пароль, выбранный при регистрации")).toBeVisible();
await captureReviewScreenshot(page, scenario, "registration-accepted");
- const originalMessage = await waitForMessage(email);
- const originalToken = tokenFromMessage(originalMessage);
- await openVerificationLink(page, originalToken);
+ const message = await waitForMessage(email);
+ const code = codeFromMessage(message);
+ await page.getByLabel("Пароль, выбранный при регистрации").fill(password);
+ await page.getByLabel("Код из письма", { exact: true }).fill(wrongCodeFor(code));
+ const rejectedConfirmation = page.waitForResponse(
+ (response) =>
+ new URL(response.url()).pathname === "/api/v1/identity/email-verifications/code" &&
+ response.request().method() === "POST",
+ );
+ await page.getByRole("button", { name: "Подтвердить код" }).click();
+ const rejectedResult = await rejectedConfirmation;
+ const rejectedProblem = (await rejectedResult.json()) as { code?: string };
+ expect(rejectedResult.status()).toBe(400);
+ expect(rejectedProblem.code).toBe("verification_token_invalid");
+ await expect(page.getByRole("alert")).toContainText("Код не подошел");
+ await expect(page.getByLabel("Код из письма", { exact: true })).toHaveValue("");
+ // Pasted text with a space keeps only the digits, so the code still fits.
+ const confirmation = page.waitForResponse(
+ (response) =>
+ new URL(response.url()).pathname === "/api/v1/identity/email-verifications/code" &&
+ response.request().method() === "POST",
+ );
+ await page
+ .getByLabel("Код из письма", { exact: true })
+ .fill(`${code.slice(0, 3)} ${code.slice(3)}`);
+ await page.getByRole("button", { name: "Подтвердить код" }).click();
+ expect((await confirmation).status()).toBe(200);
+ await expect(page.getByText(/Почта подтверждена/)).toBeVisible();
+ await captureReviewScreenshot(page, scenario, "email-confirmed");
+ const registrationContextWasCleared = await page.evaluate(
+ () => sessionStorage.getItem("lincodex-registration-context") === null,
+ );
+ expect(registrationContextWasCleared).toBe(true);
+
+ await signInAndResume(page, scenario, email, password, nextStep);
+ }
+
+ test("candidate registration confirms with the emailed code and resumes at the saved step", async ({
+ page,
+ }) => {
+ await completeScenario(page, "candidate");
+ });
+
+ test("employer registration confirms with the emailed code and resumes at the saved step", async ({
+ page,
+ }) => {
+ await completeScenario(page, "employer");
+ });
+
+ // The link form is the labelled region "Подтвердить адрес"; the code step has
+ // its own password field with the same label.
+ function linkPassword(page: Page) {
+ return page
+ .getByRole("region", { name: "Подтвердить адрес" })
+ .getByLabel("Пароль, выбранный при регистрации");
+ }
+
+ test("the link from the same message still confirms the registration", async ({ page }) => {
+ test.skip(!mailFixtureEnabled, "Requires the local mail fixture target.");
+
+ const email = `auth-link-${crypto.randomUUID()}@example.test`;
+ const password = "correct horse battery staple 2026";
+ await registerThroughForm(page, "candidate", email, password);
+
+ const originalMessage = await waitForMessage(email);
+ await openVerificationLink(page, tokenFromMessage(originalMessage));
await page.route("**/api/v1/identity/email-verifications", (route) =>
route.fulfill({
status: 400,
@@ -150,19 +282,21 @@ test.describe("registration, email confirmation, and onboarding", () => {
}),
}),
);
- await page.getByLabel("Пароль, выбранный при регистрации").fill(password);
+ await linkPassword(page).fill(password);
await page.getByRole("button", { name: "Подтвердить почту" }).click();
await expect(page.getByRole("alert")).toContainText("Срок действия ссылки истек");
await page.unroute("**/api/v1/identity/email-verifications");
+ // An expired link leads to the code step, which asks for the address and
+ // its own resend. The stand allows one message per second.
await page.waitForTimeout(1100);
+ await page.getByLabel("Электронная почта").fill(email);
const resendResponse = page.waitForResponse(
(response) =>
new URL(response.url()).pathname === "/api/v1/identity/email-verification-requests" &&
response.request().method() === "POST",
);
- await page.getByLabel("Адрес для письма").fill(email);
- await page.getByRole("button", { name: "Отправить письмо повторно" }).click();
+ await page.getByRole("button", { name: "Отправить код повторно" }).click();
expect((await resendResponse).status()).toBe(202);
await expect(page.getByText(/^Запрос принят\./)).toBeVisible();
const resentMessage = await waitForMessage(email, originalMessage.id);
@@ -173,65 +307,25 @@ test.describe("registration, email confirmation, and onboarding", () => {
new URL(response.url()).pathname === "/api/v1/identity/email-verifications" &&
response.request().method() === "POST",
);
- await page.getByLabel("Пароль, выбранный при регистрации").fill("incorrect password test");
+ await linkPassword(page).fill("incorrect password test");
await page.getByRole("button", { name: "Подтвердить почту" }).click();
const rejectedResult = await rejectedConfirmation;
const rejectedProblem = (await rejectedResult.json()) as { code?: string };
expect(rejectedResult.status()).toBe(400);
- expect(rejectedProblem.code === "verification_token_invalid").toBe(true);
- const rejectedToken = String(rejectedResult.request().postDataJSON().token ?? "");
- expect(rejectedToken.length > 0).toBe(true);
+ expect(rejectedProblem.code).toBe("verification_token_invalid");
await expect(page.getByRole("alert")).toContainText("Не удалось подтвердить почту");
- await expect(page.getByLabel("Пароль, выбранный при регистрации")).toBeVisible();
- await expect(page.getByLabel("Адрес для письма")).toBeVisible();
- const fragmentAfterRejectedPassword = await page.evaluate(() => window.location.hash === "");
- expect(fragmentAfterRejectedPassword).toBe(true);
+ await expect(linkPassword(page)).toBeVisible();
const successfulConfirmation = page.waitForResponse(
(response) =>
new URL(response.url()).pathname === "/api/v1/identity/email-verifications" &&
response.request().method() === "POST",
);
- await page.getByLabel("Пароль, выбранный при регистрации").fill(password);
+ await linkPassword(page).fill(password);
await page.getByRole("button", { name: "Подтвердить почту" }).click();
- const retriedToken = String(
- (await successfulConfirmation).request().postDataJSON().token ?? "",
- );
- expect(retriedToken === rejectedToken).toBe(true);
- const fragmentAfterPasswordRetry = await page.evaluate(() => window.location.hash === "");
- expect(fragmentAfterPasswordRetry).toBe(true);
+ expect((await successfulConfirmation).status()).toBe(200);
await expect(page.getByText(/Почта подтверждена/)).toBeVisible();
- await captureReviewScreenshot(page, scenario, "email-confirmed");
- const registrationContextWasCleared = await page.evaluate(
- () => sessionStorage.getItem("lincodex-registration-context") === null,
- );
- expect(registrationContextWasCleared).toBe(true);
- const noSessionResponse = page.waitForResponse(
- (response) => new URL(response.url()).pathname === "/api/v1/identity/sessions/current",
- );
- await page.goto(scenario === "candidate" ? "/candidate" : "/employer");
- expect((await noSessionResponse).status()).toBe(401);
- await expect(page.getByRole("heading", { name: "Вход" })).toBeVisible();
- await page.getByLabel("Электронная почта").fill(email);
- await page.getByLabel("Пароль", { exact: true }).fill(password);
- await page.getByRole("button", { name: "Войти" }).click();
- await expect(page.getByRole("heading", { name: nextStep })).toBeVisible();
-
- const restoredSessionResponse = page.waitForResponse(
- (response) => new URL(response.url()).pathname === "/api/v1/identity/sessions/current",
- );
- await page.reload();
- expect((await restoredSessionResponse).status()).toBe(200);
- await expect(page.getByRole("heading", { name: nextStep })).toBeVisible();
- await checkResponsiveKeyboardFlow(page);
- }
-
- test("candidate registration resumes at the saved candidate step", async ({ page }) => {
- await completeScenario(page, "candidate");
- });
-
- test("employer registration resumes at the saved company step", async ({ page }) => {
- await completeScenario(page, "employer");
+ await signInAndResume(page, "candidate", email, password, "Согласия");
});
});
diff --git a/frontend/src/features/confirm-email/ui/confirm-email-form.tsx b/frontend/src/features/confirm-email/ui/confirm-email-form.tsx
index 38cca73..25e312d 100644
--- a/frontend/src/features/confirm-email/ui/confirm-email-form.tsx
+++ b/frontend/src/features/confirm-email/ui/confirm-email-form.tsx
@@ -175,7 +175,7 @@ export function ConfirmEmailForm({
) : (
- В ссылке нет действующего токена. Укажите адрес, чтобы запросить новое письмо.
+ В ссылке нет действующего токена. Введите адрес, пароль и код из письма ниже.
)}
Перейти ко входу
diff --git a/frontend/src/features/register-account/ui/register-form.tsx b/frontend/src/features/register-account/ui/register-form.tsx
index 91ca2a9..d1afc22 100644
--- a/frontend/src/features/register-account/ui/register-form.tsx
+++ b/frontend/src/features/register-account/ui/register-form.tsx
@@ -20,7 +20,11 @@ type RegisterFormProps = {
initialEmail?: string;
initialScenario?: Scenario | "";
onDraftChange?: (draft: RegistrationDraft) => void;
- onAccepted: (draft: RegistrationDraft) => void;
+ /**
+ * Called after the server accepted the request. The password is passed once,
+ * for the code step held in memory by the caller; it is never stored here.
+ */
+ onAccepted: (draft: RegistrationDraft, password: string) => void;
};
type FieldErrors = {
@@ -155,6 +159,7 @@ export function RegisterForm({
consent_c1: { text_version: consent.data.text_version, accepted: true as const },
};
idempotencyKey.current ??= createIdempotencyKey();
+ const submittedPassword = password;
try {
await registration.mutateAsync({
@@ -162,7 +167,7 @@ export function RegisterForm({
headers: { "Idempotency-Key": idempotencyKey.current },
});
setPassword("");
- onAccepted({ email, scenario });
+ onAccepted({ email, scenario }, submittedPassword);
} catch (error: unknown) {
const result = registrationError(error);
setFormError(result.message);
diff --git a/frontend/src/features/verify-email-code/index.ts b/frontend/src/features/verify-email-code/index.ts
new file mode 100644
index 0000000..02ea065
--- /dev/null
+++ b/frontend/src/features/verify-email-code/index.ts
@@ -0,0 +1 @@
+export { VerificationCodeForm } from "./ui/verification-code-form";
diff --git a/frontend/src/features/verify-email-code/model/verification-code.test.ts b/frontend/src/features/verify-email-code/model/verification-code.test.ts
new file mode 100644
index 0000000..bc68ebd
--- /dev/null
+++ b/frontend/src/features/verify-email-code/model/verification-code.test.ts
@@ -0,0 +1,81 @@
+import { describe, expect, it } from "vitest";
+import {
+ codeConfirmationRefusal,
+ codeFieldError,
+ digitsOnly,
+ emailFieldError,
+ passwordFieldError,
+ resendCooldownSeconds,
+ resendLabel,
+ resendRefusal,
+} from "./verification-code";
+
+function apiError(code: string, retryAfterSeconds?: number): Error {
+ return Object.assign(new Error(code), { code, retryAfterSeconds });
+}
+
+describe("code input", () => {
+ it("keeps only ASCII digits and at most six of them, so a pasted group still fits", () => {
+ expect(digitsOnly("482 915")).toBe("482915");
+ expect(digitsOnly("код: 4829-15 и еще 99")).toBe("482915");
+ expect(digitsOnly("123")).toBe("");
+ expect(digitsOnly("")).toBe("");
+ });
+
+ it("accepts exactly six digits", () => {
+ expect(codeFieldError("000000")).toBeNull();
+ expect(codeFieldError("482915")).toBeNull();
+ expect(codeFieldError("48291")).not.toBeNull();
+ expect(codeFieldError("4829156")).not.toBeNull();
+ expect(codeFieldError("48291a")).not.toBeNull();
+ });
+});
+
+describe("registration fields", () => {
+ it("checks the address and the password bounds of the login", () => {
+ expect(emailFieldError("candidate@example.com")).toBeNull();
+ expect(emailFieldError("candidate")).not.toBeNull();
+ expect(passwordFieldError("correct horse battery staple")).toBeNull();
+ expect(passwordFieldError("")).not.toBeNull();
+ expect(passwordFieldError("p".repeat(129))).not.toBeNull();
+ expect(passwordFieldError("p".repeat(128))).toBeNull();
+ });
+});
+
+describe("confirmation refusals", () => {
+ it("gives every cause of an invalid code the same text and clears the code", () => {
+ const refusal = codeConfirmationRefusal(apiError("verification_token_invalid"));
+ expect(refusal.message).toContain("Код не подошел");
+ expect(refusal.message).toContain("После пяти неверных попыток");
+ expect(refusal.codeRefused).toBe(true);
+ expect(refusal.retryAfterSeconds).toBeUndefined();
+ });
+
+ it("passes the server wait on a rate limit, and keeps the code for other failures", () => {
+ expect(codeConfirmationRefusal(apiError("rate_limited", 42))).toMatchObject({
+ message: "Слишком много попыток. Подождите и повторите попытку.",
+ retryAfterSeconds: 42,
+ });
+ expect(codeConfirmationRefusal(apiError("rate_limited")).retryAfterSeconds).toBeUndefined();
+ expect(codeConfirmationRefusal(apiError("csrf_check_failed")).codeRefused).toBeUndefined();
+ expect(codeConfirmationRefusal(new Error("network")).message).toContain("Проверьте соединение");
+ });
+
+ it("maps a refused resend to its own copy and keeps the server wait", () => {
+ expect(resendRefusal(apiError("rate_limited", 17))).toEqual({
+ message: "Слишком много запросов. Подождите и повторите попытку.",
+ retryAfterSeconds: 17,
+ });
+ expect(resendRefusal(apiError("unknown")).message).toBe(
+ "Не удалось отправить код. Повторите попытку.",
+ );
+ });
+});
+
+describe("resend cooldown", () => {
+ it("shows the time left and the plain label once the wait is over", () => {
+ expect(resendCooldownSeconds).toBe(60);
+ expect(resendLabel(45)).toBe("Отправить код повторно через 45 с");
+ expect(resendLabel(0)).toBe("Отправить код повторно");
+ });
+});
diff --git a/frontend/src/features/verify-email-code/model/verification-code.ts b/frontend/src/features/verify-email-code/model/verification-code.ts
new file mode 100644
index 0000000..7154b10
--- /dev/null
+++ b/frontend/src/features/verify-email-code/model/verification-code.ts
@@ -0,0 +1,113 @@
+import { EmailAddress, VerificationCode } from "../../../shared/api/schemas";
+
+/** Number of digits in the code of a verification message. */
+export const verificationCodeLength = 6;
+
+/**
+ * Wait before a repeated message after one was queued. It matches the
+ * default minimum interval between two verification messages to one address,
+ * so the button is not offered when the server would refuse it.
+ */
+export const resendCooldownSeconds = 60;
+
+const refusedCodeMessage =
+ "Код не подошел. Проверьте код и пароль или запросите новый код. После пяти неверных попыток код перестает действовать.";
+
+/** Keeps the ASCII digits of pasted or typed text, up to the code length. */
+export function digitsOnly(raw: string): string {
+ return raw.replace(/\D/gu, "").slice(0, verificationCodeLength);
+}
+
+export function codeFieldError(code: string): string | null {
+ return VerificationCode.safeParse(code).success ? null : "Введите 6 цифр из письма.";
+}
+
+export function emailFieldError(email: string): string | null {
+ return EmailAddress.safeParse(email).success
+ ? null
+ : "Введите корректный адрес электронной почты.";
+}
+
+/** Same bounds as the login password: 1 to 128 code points after NFKC. */
+export function passwordFieldError(password: string): string | null {
+ const length = Array.from(password.normalize("NFKC")).length;
+ return length >= 1 && length <= 128
+ ? null
+ : "Введите пароль регистрации длиной от 1 до 128 символов после нормализации.";
+}
+
+export type ApiRefusal = {
+ message: string;
+ /** Set when the server asked for a wait with Retry-After. */
+ retryAfterSeconds?: number;
+ /** Set when the code itself is refused, so the field should be cleared. */
+ codeRefused?: boolean;
+};
+
+function errorCode(error: unknown): string {
+ return error instanceof Error && "code" in error ? String(error.code) : "";
+}
+
+function retryAfter(error: unknown): number | undefined {
+ if (error instanceof Error && "retryAfterSeconds" in error) {
+ const value = error.retryAfterSeconds;
+ return typeof value === "number" && value > 0 ? value : undefined;
+ }
+ return undefined;
+}
+
+/**
+ * Maps a refused code confirmation to copy. Every cause of
+ * verification_token_invalid shows the same text, because the server gives
+ * the same answer for each of them.
+ */
+export function codeConfirmationRefusal(error: unknown): ApiRefusal {
+ switch (errorCode(error)) {
+ case "verification_token_invalid":
+ return { message: refusedCodeMessage, codeRefused: true };
+ case "rate_limited":
+ return {
+ message: "Слишком много попыток. Подождите и повторите попытку.",
+ ...optionalWait(error),
+ };
+ case "validation_failed":
+ return {
+ message: "Проверьте введенные данные: код состоит из 6 цифр, адрес и пароль заполнены.",
+ };
+ case "csrf_check_failed":
+ return {
+ message: "Не удалось проверить источник запроса. Обновите страницу и повторите попытку.",
+ };
+ default:
+ return { message: "Не удалось подтвердить почту. Проверьте соединение и повторите попытку." };
+ }
+}
+
+/** Maps a refused request for a new message to copy. */
+export function resendRefusal(error: unknown): ApiRefusal {
+ switch (errorCode(error)) {
+ case "rate_limited":
+ return {
+ message: "Слишком много запросов. Подождите и повторите попытку.",
+ ...optionalWait(error),
+ };
+ case "csrf_check_failed":
+ return {
+ message: "Не удалось проверить источник запроса. Обновите страницу и повторите попытку.",
+ };
+ default:
+ return { message: "Не удалось отправить код. Повторите попытку." };
+ }
+}
+
+function optionalWait(error: unknown): { retryAfterSeconds?: number } {
+ const seconds = retryAfter(error);
+ return seconds === undefined ? {} : { retryAfterSeconds: seconds };
+}
+
+/** Button label that shows the time left before a new message can be asked for. */
+export function resendLabel(secondsLeft: number): string {
+ return secondsLeft > 0
+ ? `Отправить код повторно через ${secondsLeft} с`
+ : "Отправить код повторно";
+}
diff --git a/frontend/src/features/verify-email-code/ui/verification-code-form.module.css b/frontend/src/features/verify-email-code/ui/verification-code-form.module.css
new file mode 100644
index 0000000..45324aa
--- /dev/null
+++ b/frontend/src/features/verify-email-code/ui/verification-code-form.module.css
@@ -0,0 +1,94 @@
+.form {
+ display: grid;
+ gap: var(--space-5);
+ min-width: 0;
+}
+
+.field {
+ display: grid;
+ gap: var(--space-2);
+ min-width: 0;
+}
+
+.label {
+ font-weight: var(--font-weight-bold);
+}
+
+.input {
+ width: 100%;
+ min-height: 2.75rem;
+ padding: var(--space-2) var(--space-3);
+ border: var(--line-thin) solid var(--color-border-strong);
+ border-radius: var(--radius-s);
+ background: var(--color-surface);
+}
+
+/* The code is the one field the user types from the message, so it is large
+ and spaced; it still fits a 360 px viewport because it has no fixed width. */
+.code-input {
+ width: 100%;
+ max-width: 18rem;
+ min-height: 3.25rem;
+ padding: var(--space-2) var(--space-3);
+ border: var(--line-strong) solid var(--color-border-strong);
+ border-radius: var(--radius-s);
+ background: var(--color-surface);
+ font-family: var(--font-mono, ui-monospace, monospace);
+ font-size: 1.75rem;
+ font-variant-numeric: tabular-nums;
+ letter-spacing: 0.3em;
+}
+
+.input[aria-invalid="true"],
+.code-input[aria-invalid="true"] {
+ border-color: var(--color-danger);
+}
+
+.hint,
+.error {
+ font-size: var(--font-size-s);
+}
+
+.hint {
+ color: var(--color-text-secondary);
+}
+
+.address {
+ overflow-wrap: anywhere;
+}
+
+.error,
+.alert {
+ color: var(--color-danger);
+}
+
+.alert {
+ padding: var(--space-3);
+ border-left: var(--line-strong) solid var(--color-danger);
+ background: var(--color-surface);
+}
+
+.actions {
+ display: flex;
+ flex-wrap: wrap;
+ gap: var(--space-3);
+ align-items: center;
+}
+
+.status {
+ min-height: 1.5em;
+ color: var(--color-text-secondary);
+}
+
+.notice {
+ padding: var(--space-4);
+ border-left: var(--line-strong) solid var(--color-accent);
+ background: var(--color-surface);
+}
+
+.resend {
+ display: grid;
+ gap: var(--space-3);
+ padding-top: var(--space-4);
+ border-top: var(--line-thin) solid var(--color-border-strong);
+}
diff --git a/frontend/src/features/verify-email-code/ui/verification-code-form.test.tsx b/frontend/src/features/verify-email-code/ui/verification-code-form.test.tsx
new file mode 100644
index 0000000..e5d39bd
--- /dev/null
+++ b/frontend/src/features/verify-email-code/ui/verification-code-form.test.tsx
@@ -0,0 +1,74 @@
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { renderToStaticMarkup } from "react-dom/server";
+import { MemoryRouter } from "react-router-dom";
+import { describe, expect, it } from "vitest";
+import { VerificationCodeForm } from "./verification-code-form";
+
+function render(props: Partial[0]> = {}): string {
+ const queryClient = new QueryClient();
+ return renderToStaticMarkup(
+
+
+ undefined} {...props} />
+
+ ,
+ );
+}
+
+describe("verification code form after registration", () => {
+ it("asks only for the code when the registration password is held in memory", () => {
+ const html = render({
+ initialEmail: "candidate@example.com",
+ password: "correct horse battery staple",
+ messageJustSent: true,
+ });
+
+ expect(html).toContain("candidate@example.com");
+ expect(html).not.toMatch(/type="password"/);
+ expect(html).not.toContain("Электронная почта");
+ expect(html).not.toContain("correct horse battery staple");
+ });
+
+ it("presents the code input for one-time codes and numeric keyboards", () => {
+ const html = render({ initialEmail: "candidate@example.com", password: "x" });
+
+ expect(html).toMatch(/]*id="[^"]*-code"[^>]*>/);
+ expect(html).toContain('inputMode="numeric"');
+ expect(html).toContain('autoComplete="one-time-code"');
+ // No maxLength: the browser would cut "482 915" to "482 91" before the
+ // digits are kept, so the field keeps every character and digitsOnly trims it.
+ expect(html).not.toContain("maxLength");
+ expect(html).toContain("Код из письма");
+ expect(html).toContain("Подтвердить код");
+ });
+
+ it("starts the resend cooldown when a message was just queued", () => {
+ const html = render({
+ initialEmail: "candidate@example.com",
+ password: "x",
+ messageJustSent: true,
+ });
+
+ expect(html).toMatch(
+ /