From b2322bc1783851492d34643126361a21a1c6a0cb Mon Sep 17 00:00:00 2001 From: TakuyaYagam1 Date: Wed, 7 Oct 2026 13:02:16 +0300 Subject: [PATCH] feat(auth): add registration and verification browser flow --- deploy/docker/docker-compose.e2e-mail.yml | 2 + deploy/scripts/test_e2e_mail.py | 2 + docs/en/ARCHITECTURE.md | 29 +- docs/en/DEPLOY.md | 6 +- docs/en/TESTING.md | 6 +- docs/ru/ARCHITECTURE.md | 29 +- docs/ru/DEPLOY.md | 6 +- docs/ru/TESTING.md | 6 +- frontend/e2e/auth-registration.spec.ts | 237 +++++++++++ .../src/app/router/candidate-home-route.tsx | 13 + frontend/src/app/router/routes.test.tsx | 27 +- frontend/src/app/router/routes.tsx | 108 +++-- frontend/src/entities/session/index.ts | 2 + .../model/onboarding-destination.test.ts | 26 ++ .../session/model/onboarding-destination.ts | 25 ++ .../src/entities/session/ui/session-gate.tsx | 57 +++ frontend/src/features/confirm-email/index.ts | 1 + .../model/consume-verification-token.test.ts | 76 ++++ .../model/consume-verification-token.ts | 35 ++ .../ui/confirm-email-form.module.css | 66 ++++ .../confirm-email/ui/confirm-email-form.tsx | 242 ++++++++++++ .../src/features/register-account/index.ts | 2 + .../register-account/model/validation.test.ts | 34 ++ .../register-account/model/validation.ts | 43 ++ .../ui/register-form.module.css | 150 +++++++ .../register-account/ui/register-form.tsx | 369 ++++++++++++++++++ .../resend-email-verification/index.ts | 1 + .../ui/resend-verification-form.module.css | 48 +++ .../ui/resend-verification-form.tsx | 87 +++++ frontend/src/features/sign-in/index.ts | 1 + .../sign-in/model/establish-session.test.ts | 38 ++ .../sign-in/model/establish-session.ts | 9 + .../sign-in/ui/sign-in-form.module.css | 60 +++ .../src/features/sign-in/ui/sign-in-form.tsx | 153 ++++++++ frontend/src/pages/auth/index.ts | 3 + .../pages/auth/model/registration-context.ts | 48 +++ frontend/src/pages/auth/ui/login-page.tsx | 26 ++ frontend/src/pages/auth/ui/register-page.tsx | 68 ++++ .../src/pages/auth/ui/verify-email-page.tsx | 35 ++ .../src/pages/candidate-onboarding/index.ts | 1 + .../ui/candidate-onboarding-page.tsx | 48 +++ 41 files changed, 2144 insertions(+), 81 deletions(-) create mode 100644 frontend/e2e/auth-registration.spec.ts create mode 100644 frontend/src/app/router/candidate-home-route.tsx create mode 100644 frontend/src/entities/session/index.ts create mode 100644 frontend/src/entities/session/model/onboarding-destination.test.ts create mode 100644 frontend/src/entities/session/model/onboarding-destination.ts create mode 100644 frontend/src/entities/session/ui/session-gate.tsx create mode 100644 frontend/src/features/confirm-email/index.ts create mode 100644 frontend/src/features/confirm-email/model/consume-verification-token.test.ts create mode 100644 frontend/src/features/confirm-email/model/consume-verification-token.ts create mode 100644 frontend/src/features/confirm-email/ui/confirm-email-form.module.css create mode 100644 frontend/src/features/confirm-email/ui/confirm-email-form.tsx create mode 100644 frontend/src/features/register-account/index.ts create mode 100644 frontend/src/features/register-account/model/validation.test.ts create mode 100644 frontend/src/features/register-account/model/validation.ts create mode 100644 frontend/src/features/register-account/ui/register-form.module.css create mode 100644 frontend/src/features/register-account/ui/register-form.tsx create mode 100644 frontend/src/features/resend-email-verification/index.ts create mode 100644 frontend/src/features/resend-email-verification/ui/resend-verification-form.module.css create mode 100644 frontend/src/features/resend-email-verification/ui/resend-verification-form.tsx create mode 100644 frontend/src/features/sign-in/index.ts create mode 100644 frontend/src/features/sign-in/model/establish-session.test.ts create mode 100644 frontend/src/features/sign-in/model/establish-session.ts create mode 100644 frontend/src/features/sign-in/ui/sign-in-form.module.css create mode 100644 frontend/src/features/sign-in/ui/sign-in-form.tsx create mode 100644 frontend/src/pages/auth/index.ts create mode 100644 frontend/src/pages/auth/model/registration-context.ts create mode 100644 frontend/src/pages/auth/ui/login-page.tsx create mode 100644 frontend/src/pages/auth/ui/register-page.tsx create mode 100644 frontend/src/pages/auth/ui/verify-email-page.tsx create mode 100644 frontend/src/pages/candidate-onboarding/index.ts create mode 100644 frontend/src/pages/candidate-onboarding/ui/candidate-onboarding-page.tsx diff --git a/deploy/docker/docker-compose.e2e-mail.yml b/deploy/docker/docker-compose.e2e-mail.yml index 5fbba7a..da0928f 100644 --- a/deploy/docker/docker-compose.e2e-mail.yml +++ b/deploy/docker/docker-compose.e2e-mail.yml @@ -10,6 +10,8 @@ services: EMAIL_ACCOUNT: e2e EMAIL_FROM: no-reply@example.com RESEND_API_KEY: re_fixture_key + # Keep real resend coverage bounded within this isolated test stand. + VERIFICATION_MAIL_MIN_INTERVAL: 1s depends_on: mail-fixture: condition: service_healthy diff --git a/deploy/scripts/test_e2e_mail.py b/deploy/scripts/test_e2e_mail.py index a645e4b..45167f6 100644 --- a/deploy/scripts/test_e2e_mail.py +++ b/deploy/scripts/test_e2e_mail.py @@ -97,6 +97,7 @@ class ComposeMailFixtureTest(unittest.TestCase): backend = rendered["services"]["backend"] self.assertEqual(backend["build"]["dockerfile"], "Dockerfile") self.assertEqual(backend["environment"]["EMAIL_PROVIDER"], "disabled") + self.assertEqual(backend["environment"]["VERIFICATION_MAIL_MIN_INTERVAL"], "1m") self.assertNotIn("RESEND_ENDPOINT", backend["environment"]) self.assertNotIn( "E2E_MAIL_FIXTURE", @@ -109,6 +110,7 @@ class ComposeMailFixtureTest(unittest.TestCase): self.assertEqual(backend["build"]["dockerfile"], "Dockerfile.e2e") self.assertEqual(backend["environment"]["EMAIL_PROVIDER"], "resend") self.assertEqual(backend["environment"]["RESEND_API_KEY"], "re_fixture_key") + self.assertEqual(backend["environment"]["VERIFICATION_MAIL_MIN_INTERVAL"], "1s") self.assertNotIn("RESEND_ENDPOINT", backend["environment"]) self.assertEqual( services["playwright"]["environment"]["E2E_MAILBOX_URL"], diff --git a/docs/en/ARCHITECTURE.md b/docs/en/ARCHITECTURE.md index 18ae04c..b5fde12 100644 --- a/docs/en/ARCHITECTURE.md +++ b/docs/en/ARCHITECTURE.md @@ -6,7 +6,7 @@ This document separates the target product architecture from the technical scaff The repository contains a Go HTTP service with PostgreSQL, Redis, and SeaweedFS checks, cache and S3 storage adapters, a React interface scaffold with public pages and two cabinet shells of placeholder screens, a separate Python ML service with health and readiness routes, two OpenAPI contracts, code generation, Compose files, and monitoring configuration. The public API health route is under /api/v1/healthz. The web container uses /healthz. The internal Go /readyz checks PostgreSQL, Redis, and the SeaweedFS bucket. ML uses /healthz and /readyz; readiness returns 503 while inference is unavailable. Go exposes the standard /metrics endpoint on an internal port. -Registration, email confirmation, login, and basic current-session operations work through the backend API. Frontend registration and confirmation screens remain placeholders; the other listed product workflows are not implemented: roles, profiles, assessments, grades, candidate search, invitations, resume processing, PDF generation, and FSP integration. ML does not return invented results. Health checks and the technical smoke do not verify a product workflow. +Registration, email confirmation, login, and basic current-session operations work through the backend API. The frontend implements registration, confirmation, sign-in, and continuation from the server-provided scenario step; local browser E2E covers candidate and employer accounts. Consent settings and organization creation/editing work through the backend API. Other product workflows are not implemented: roles, profiles, assessments, grades, candidate search, invitations, resume processing, PDF generation, and FSP integration. ML does not return invented results. Health checks and the technical smoke do not verify a product workflow. See [development](DEVELOPMENT.md), [deployment](DEPLOY.md), and [testing](TESTING.md) for source layout, commands, and current check coverage. @@ -348,7 +348,7 @@ Scope. The worker claims only the kinds `verification` and `password_reset`. A p Enqueue. `ServiceMailer.EnqueueVerification` and `EnqueuePasswordReset` run in the transaction that inserts the token, with the token record, the raw token, the recipient address, and the lifetime in hours. They check that the token purpose fits the message, render the message once with the current template version, and store a `pending` delivery bound to the token (`email_token_id`) under the token's ID as the delivery ID. A repeated call for the same token stores nothing new, and the stored body stays as it was. -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 confirmation screen is still a placeholder. A client must read and remove the fragment, wait for explicit confirmation, then send the token and registration password in the API 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. +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. One pass of `ServiceMailSender.ProcessNext` takes one delivery through three steps: @@ -650,7 +650,7 @@ The brief references Russian Federal Law 152-FZ. The system design calls for sep ### Identity storage -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 placeholders; see the [API contract](../../api/README.en.md#identity-sessions-cookie-and-csrf). +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. @@ -691,7 +691,7 @@ Implemented and tested: registration and login use the hasher created from confi ### Server-side sessions -Login, current-session and current-account reads, and logout are implemented in the backend. Every contract-protected operation passes through the session boundary, which resolves a verified principal from an active PostgreSQL session; other protected business handlers currently answer 501 after security and request validation. Every unsafe public identity operation (`RegisterAccount`, `ResendEmailVerification`, `ConfirmEmail`, and `Login`) requires the sole `Origin` value to exactly match `APP_PUBLIC_URL`. Protected unsafe operations also require the session-bound `X-CSRF-Token`. Origin is checked at the HTTP boundary and does not trust `Host` or forwarded headers. The CSRF value is a domain-separated HMAC-SHA-256 derived from the session token, bound to that token, and compared in constant time. `GetCurrentSession` returns it again after a page reload. GET `/api/v1/identity/sessions/current` returns the current session and account, GET `/api/v1/identity/me` returns the current account, and DELETE `/api/v1/identity/sessions/current` revokes the session. Guests and unverified sessions answer 401; a valid session with missing or wrong Origin or CSRF on a protected unsafe operation answers 403 `csrf_check_failed`. +Login, current-session and current-account reads, and logout are implemented in the backend. Every contract-protected operation passes through the session boundary, which resolves a verified principal from an active PostgreSQL session; consent and organization handlers implement their documented operations. Contract operations without an implemented business handler answer 501 after security and request validation. Every unsafe public identity operation (`RegisterAccount`, `ResendEmailVerification`, `ConfirmEmail`, and `Login`) requires the sole `Origin` value to exactly match `APP_PUBLIC_URL`. Protected unsafe operations also require the session-bound `X-CSRF-Token`. Origin is checked at the HTTP boundary and does not trust `Host` or forwarded headers. The CSRF value is a domain-separated HMAC-SHA-256 derived from the session token, bound to that token, and compared in constant time. `GetCurrentSession` returns it again after a page reload. GET `/api/v1/identity/sessions/current` returns the current session and account, GET `/api/v1/identity/me` returns the current account, and DELETE `/api/v1/identity/sessions/current` revokes the session. Guests and unverified sessions answer 401; a valid session with missing or wrong Origin or CSRF on a protected unsafe operation answers 403 `csrf_check_failed`. The cookie is named `__Host-lincodex_session` and has `Path=/`, `Secure`, `HttpOnly`, and `SameSite=Strict`, with no `Domain`; `Expires` and `Max-Age` point to the absolute session expiry. PostgreSQL stores only the SHA-256 hash of the random cookie token, never its value; IP addresses and user agents are not stored. `IDENTITY_SESSION_IDLE_TIMEOUT` defaults to `24h` and accepts `1m` to `30d`; `IDENTITY_SESSION_ABSOLUTE_LIFETIME` defaults to `168h` and accepts `1m` to `365d`. The idle timeout cannot exceed the absolute lifetime; invalid values stop startup. Active requests extend the idle deadline, not the absolute deadline. @@ -699,7 +699,7 @@ The cookie is named `__Host-lincodex_session` and has `Path=/`, `Secure`, `HttpO ### Consent ledger -Consent storage, ports, the read contract, and grants through `consent.Service` are implemented: migration `backend/db/migrations/00009_create_consent_ledger.sql`, queries in `backend/db/queries/consents.sql`, domain types in `backend/internal/domain/consent.go`, ports in `backend/internal/port/outbound/consents.go`, the sqlc-backed adapter in `backend/internal/adapter/secondary/postgres/consents.go`, and `ListMyConsents` in the public contract ([api/README.en.md](../../api/README.en.md#consents)). Registration records C1 through `GrantAtRegistration` in the account creation or re-registration transaction; confirmation checks the C1 record for the same registration version as the token. HTTP consent grants and revocation, revocation effects, and C4 at invitation acceptance are not implemented. +Consent storage, registration C1, and the settings read and mutation handlers are implemented: migration `backend/db/migrations/00009_create_consent_ledger.sql`, the deletion-request table in `00018_create_account_deletion_requests.sql`, queries in `backend/db/queries/consents.sql`, domain types in `backend/internal/domain/consent.go`, ports in `backend/internal/port/outbound/consents.go`, and handlers in `backend/internal/adapter/primary/http/v1/consent.go` ([api/README.en.md](../../api/README.en.md#consents)). Public `GET /api/v1/identity/consent-texts/c1` returns only C1; verified sessions can read C1/C2/C3/C5 text and their own history, grant supported purposes, revoke consent, and request account deletion. Registration records C1 in the account creation or re-registration transaction; confirmation checks the C1 record for the token's registration version. The C4 invitation-acceptance handler and the account-deletion worker are not implemented. The consents C1-C5 of PRD FR01 are independent purposes: a grant or a revocation of one never changes another. @@ -711,11 +711,11 @@ Decisions: - Text binding. A foreign key on (`purpose`, `text_version`) refuses a version that was never published for the purpose, and a BEFORE INSERT trigger refuses a version published after the grant time (`consent_records_text_published`). For C1-C3 and C5 a second foreign key over a generated column requires `text_hash` to equal the hash of the published text. For C4 the same trigger requires `text_hash` to equal the SHA-256 of the published text with `organization_name` filled in (`consent_records_c4_text_hash`). The domain computes that hash itself in `domain.NewContactConsentGrant` from the published `ConsentText` and the name, so no caller supplies hash bytes and a client can invent neither a version nor a hash. The stored name is the snapshot that proves the shown text; a later rename of the organization does not change it, and the read model returns it as `ConsentOrganization.name`. - History. The only UPDATE a trigger allows is the revocation stamp on an unrevoked row with every other column unchanged (`consent_records_immutable`). A newer text version is a new row next to the older one; a grant after a revocation is a new row. The state (`active`, `superseded`, `revoked`) is computed by the queries, never stored: among the unrevoked rows of a subject and purpose other than C4, the row granted last (by `granted_at`, then ID) is `active` and the others are `superseded`, whatever their versions. The ledger therefore accepts any published version, and the grant usecase `consent.Service` checks that the version is the current text before it calls `Grant`. A partial unique index keeps one unrevoked row per subject, purpose, and version, so a repeated or concurrent grant returns the existing record; a unique index on `invitation_id` keeps one C4 row per invitation, revoked or not, so a revoked C4 never comes back. -- Revocation. `ConsentLedger.Revoke` stamps every unrevoked row of the purpose, superseded rows included, and for C4 only those of one organization. A repeat finds nothing and keeps the first stamp. A revocation time before the grant time of a row, from clock skew between instances, is stamped at the grant time (`greatest`), so the `consent_records_revocation_stamp` CHECK stays a backstop. The downstream effects of a revocation (deletion request for C1, closing publication and grants for C2 and C4, the manual path for C3, stopping the import for C5) belong to consent revocation and are not implemented. -- Retention and deletion. PRD 7.3 plans to keep consents for three years, which can outlive the account, so `subject_id` references `users` with `ON DELETE RESTRICT`, and a BEFORE DELETE trigger refuses deleting a row whose subject is a confirmed account (`consent_records_retained`). Rows of an unconfirmed account may be deleted, because a registration that the email owner never confirmed is not evidence of anyone's consent: the unverified account cleanup deletes the rows of the accounts it removes in the same statement, and `UpdateRegistration` deletes the registration C1 of the account it re-registers (see below). TRUNCATE fires no row trigger and stays allowed for test isolation. Whether a deleted account leaves its ledger, a tombstone, or nothing is decided by the C1 deletion request and the account deletion procedure that executes it, which has no MVP task yet; the retention rule extends the delete condition in its own migration. +- Revocation. `ConsentLedger.Revoke` stamps every unrevoked row of the purpose, superseded rows included, and for C4 only those of one organization. A repeat finds nothing and keeps the first stamp. A revocation time before the grant time of a row, from clock skew between instances, is stamped at the grant time (`greatest`), so the `consent_records_revocation_stamp` CHECK stays a backstop. C1's `POST /api/v1/me/account-deletion-requests` stores one durable active request, revokes C1, and appends an outbox event in one transaction; repeating it returns the same request, and a later C1 grant does not cancel it. Account deletion is not synchronous. C2 revocation locks a publication only when it still references one of the records revoked in that transaction, then writes a privacy-history event atomically. The stored publication remains linked to that immutable C2 record; the read model hides its fields and reports the effective state as closed with reason `consent_revoked`, and a later C2 grant cannot reopen it. Repeating a revoke or revoking a later C2 record does not create another closure event for the old publication. C3 revocation does not block account or profile use; a separate manual-assessment request is planned but is not implemented. C4 revocation is scoped to the requested organization, and each bounded outbox intent contains organization and fields copied from the revoked records. C5 revocation makes `HasCurrentConsent` fail closed and writes a stop intent, but there is no external FSP adapter and no external deletion is claimed. +- Retention and deletion. PRD 7.3 plans to keep consents for three years, which can outlive the account, so `subject_id` references `users` with `ON DELETE RESTRICT`, and a BEFORE DELETE trigger refuses deleting a row whose subject is a confirmed account (`consent_records_retained`). Rows of an unconfirmed account may be deleted, because a registration that the email owner never confirmed is not evidence of anyone's consent: the unverified account cleanup deletes the rows of the accounts it removes in the same statement, and `UpdateRegistration` deletes the registration C1 of the account it re-registers (see below). TRUNCATE fires no row trigger and stays allowed for test isolation. The durable C1 request record and event are implemented, but the worker that performs account deletion and the policy for ledger retention after that deletion are not; the request does not delete an account or ledger by itself. - Re-registration. An unverified account keeps its `users.id` when the same email registers again, so the earlier registrant's C1 would otherwise stand for the new one. The `UpdateUserRegistration` statement deletes the C1 rows with the source `registration` of the account it updates, and only when the update applies. This is a binding requirement for registration: the registration usecase calls `UpdateRegistration` and records the new C1 with `consent.Service.GrantAtRegistration`, strictly after `UpdateRegistration`, in the same transaction (see [Consent usecase](#consent-usecase)). - C2 and the published field set. A C2 row proves the consent to the publication text, not which fields were published. The published field set and its changes are kept with their times and the C2 record behind each in the candidate visibility history (`candidate_publications` and `candidate_privacy_events`, see [Candidate visibility](#candidate-visibility)). Adding a field scope to C2 rows later is an additive migration and contract change. -- C4 in a business transaction. `UnitOfWork.ConsentLedger().GrantContact` takes a `domain.ContactConsentGrant`, which only `domain.NewContactConsentGrant` builds and which requires the C4 text, the organization and its name, a non-empty field set, the invitation, and its terms version; `domain.NewConsentGrant` refuses C4. The acceptance calls it in the transaction that moves the invitation to `accepted`, creates the grant, and writes the audit event, so all of them commit or roll back together. A repeated acceptance gets the existing record with `created` false and compares its scope; an invitation whose C4 belongs to another subject returns `ErrConsentInvitationTaken`. +- C4 in a business transaction. `UnitOfWork.ConsentLedger().GrantContact` takes a `domain.ContactConsentGrant`, which only `domain.NewContactConsentGrant` builds and which requires the C4 text, the organization and its name, a non-empty field set, the invitation, and its terms version; `domain.NewConsentGrant` refuses C4. The invitation-acceptance handler is not implemented. When it is added, it must call this port in the transaction that accepts the invitation and writes its audit event; a repeated acceptance must compare the existing scope, and an invitation whose C4 belongs to another subject must return `ErrConsentInvitationTaken`. - Cleanup race. The cleanup checks consent rows in its statement snapshot. A consent committed for a candidate account after that snapshot but before the account lock fails the restricting foreign key at the end of the statement (SQLSTATE 23001); the adapter reports it as `ErrTransactionConflict`, nothing is deleted, and the next run sees the consent. - Scoping. Every read and revocation takes the subject, and the contract operation takes it from the session, so the read model returns only the caller's own records. Errors of the adapter keep the SQLSTATE and constraint name only, and `domain.ConsentRecord`, `ConsentGrant`, `ContactConsentGrant`, and `ConsentRevocation` show no subject, organization, name, or fields in `fmt` and `slog` output. @@ -726,12 +726,13 @@ What the ports guarantee (`outbound.ConsentRepositories`, available on `UnitOfWo - `ConsentTexts().Get` and `Current` read published texts and verify the stored hash on every read. - `ConsentLedger().Grant` and `GrantContact` return the new record with `created` true or the existing one with `created` false. An unknown subject returns `ErrUserNotFound`, an unknown version `ErrConsentTextNotFound`, a version published later `ErrConsentTextNotPublished`, and a hash that does not match the published text (for C4 with the stored name) `ErrConsentTextMismatch`; these come from the database and abort a surrounding transaction. A duplicate does not. A grant whose conflicting record was revoked between its two statements returns `ErrTransactionConflict`. - `Revoke` returns the rows it stamped. `Current` returns the newest unrevoked C1-C3 or C5 record or `ErrConsentNotFound`; `CurrentContact` returns the unrevoked C4 records of one organization. `List` pages the subject's ledger newest first, optionally by state. +- `ConsentRevocationEffects.Apply` runs in the same `UnitOfWork` transaction as the ledger revocation. It closes the current publication's effective C2 access only when that publication references one of the revoked records, appends its privacy-history event once, and writes bounded outbox intents from the exact revoked records. A future C2/C4 grant adapter must bind each downstream grant to its source consent-record ID and synchronously close that old grant in this transaction; a later grant may open only a new record-bound grant, never reopen an old one. C5 readers and importers must check the current ledger and fail closed; an outbox message alone does not authorize access or prove that an external system deleted data. ### Consent usecase `consent.Service` in `backend/internal/usecase/consent/` is wired through bootstrap and used by registration to check the text version and grant C1 in the create or re-registration transaction. It is built with `consent.NewService(transactor, clock)`, the `Transactor` and application clock the other usecases receive. A nil transactor or clock panics at construction. -- Entry points fix the source. `GrantAtRegistration(ctx, repositories, subjectID, registrationVersion, textVersion)` records C1 with the source `registration`; `GrantInSettings(ctx, repositories, SettingsGrantInput)` records C1, C2, C3, or C5 with the source `consent_settings`. Neither takes a source or a time, so a handler cannot read either from the client. `repositories` is an `outbound.ConsentRepositories`: pass the `UnitOfWork` of a business operation and the grant commits or rolls back with it. The registration creates the account and records C1 in one transaction on the subject ID alone, so no session is needed. `GrantInSettingsInNewTransaction` opens its own transaction for a grant that is not part of another operation, and retries an `ErrTransactionConflict` up to three attempts in total with a short jittered wait (10 ms plus up to 10 ms) between them, which is safe because a repeat is idempotent; the wait ends at once when the context is canceled. +- Entry points fix the source. `GrantAtRegistration` records C1 with source `registration`; settings grants record C1, C2, C3, or C5 with source `consent_settings`. `RevokeInSettingsInNewTransaction` stamps the subject-scoped ledger rows and applies the publication/history and outbox effects in the same transaction. `RequestAccountDeletionInNewTransaction` stores or returns the one active durable request, revokes C1, and appends its event atomically; a later C1 grant does not cancel that request. Neither operation accepts a source or time from the client. `GrantInSettingsInNewTransaction` and the mutation operations retry transaction conflicts up to three attempts with a short jittered wait, ending immediately when the context is canceled. - Re-registration order. For an unverified account that registers again, call `GrantAtRegistration` strictly after `UserRepository.UpdateRegistration` in the same transaction. `UpdateRegistration` deletes the registration C1 of the earlier registrant, and a grant that ran before it would find that record, return it with `Created` false, and leave the account without any C1 once it is deleted. The integration test shows both orders. - C1 registration version. Migration `00016_bind_registration_consent.sql` adds `registration_version` only to registration-source C1; other grants must leave it NULL. It backfills old C1 rows from the current account version without using tokens. Re-registration deletes the prior registration C1, so an older grant time or multiple active registration C1 rows for one account are inconsistent and stop the migration. The partial unique index `consent_records_registration_version_key` allows at most one unrevoked registration C1 for an account and version. The insert trigger fills the current version when an old backend omits it and rejects a mismatch from the new backend; the immutability trigger also protects the version during revocation. - Version check before the email branch. `CheckTextVersion(ctx, repositories, purpose, version)` returns the current text when `version` is current and fails like a grant otherwise, without writing anything. The registration must call it with C1 and the submitted version before it branches on a new or an existing email; otherwise a stale version would be refused only for new addresses, and the difference would reveal which accounts exist. @@ -739,8 +740,8 @@ What the ports guarantee (`outbound.ConsentRepositories`, available on `UnitOfWo - Server time. The input has no time field. The grant uses one reading of the injected clock for the check and for the record time; a client cannot choose the time. The database still refuses a version published after that time. - Idempotency. A repeat of the same subject, purpose, and current version returns the existing unrevoked record with `Created` false, keeps its first time, stores nothing, and does not abort a surrounding transaction. A grant after a revocation is a new record. A repeat that names an older version after a newer text was published is stale, not a repeat: the subject has to see the new text, and the ledger keeps its one record. - C4 only through its scope. `GrantInSettings` refuses C4 with `ErrScopedConsentRequired` before it reads anything. `GrantContact(ctx, repositories, input)` is the explicitly scoped operation for the invitation acceptance: the input carries the organization and the name shown, the field set, the invitation, the invitation terms version, and the C4 text version. It checks that the C4 text is current, lets `domain.NewContactConsentGrant` hash the text as shown, and calls `ConsentLedger().GrantContact` in the caller's transaction. A repeat of the same subject and invitation returns the existing record with `Created` false; the caller compares its scope. The text check comes first, so a repeat after a newer C4 text was published is stale; the acceptance that wants to answer such a repeat with the earlier result must find its existing record before it calls. -- C3 may be withheld. The purposes are independent: no grant requires, implies, or changes another, and no code path requires an active C3 for the profile, the manual assessment path, or another function. A subject without C3 has no C3 record, and `Current` returns `ErrConsentNotFound` for it, which is not an error state of the account. Whoever reads C3 (the manual assessment request, consent revocation) treats a missing record as "not given" and keeps the manual path open. -- No revocation here. `Revoke` stays on the ledger port, and consent revocation must call it with the downstream effects and the outbox events in one transaction. +- C3 may be withheld. The purposes are independent: no grant requires, implies, or changes another, and no implemented account or profile operation requires active C3. A subject without C3 has no C3 record, and `Current` returns `ErrConsentNotFound`; this is not an account error. A separate manual-assessment request is planned, but its endpoint is not implemented. +- Revocation and deletion request. `RevokeInSettingsInNewTransaction` applies all consent effects inside the transaction that stamps the ledger; repeating an already completed revocation does not append another event. C1 deletion requests are durable and idempotent, but they do not synchronously delete the account or cancel on a later C1 grant. - Errors keep their identity: a stale version, `ErrScopedConsentRequired`, `ErrUserNotFound`, `ErrConsentTextNotFound` (the purpose has no published text), `ErrConsentInvitationTaken`, `domain.ErrInvalidConsent`, and `domain.ErrInvalidConsentText`. `outbound.ErrTransactionConflict` is the one that needs action: the ledger returns it, without aborting the transaction, when the record of a repeat was revoked between its insert and its select. A caller inside a `UnitOfWork` must return it, roll the transaction back, and retry the whole operation; `GrantInSettingsInNewTransaction` does so itself. Mapping the other errors to problem codes belongs to the handlers. - Demo texts need a release gate. The texts that the migration publishes have the kind `demo`: synthetic, without a legal review. Nothing in the usecase distinguishes them from texts of the operator, so a deployment that accepts real data would record consent to a demo text. Before real data are accepted (PRD 7.3), a release gate must check that the current text of every purpose has the kind `operator`; the owner is the release gate or consent revocation, and neither exists yet. @@ -752,7 +753,7 @@ One transaction. A new address creates the account (scenario and the first `onbo 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 still a placeholder. +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. 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. @@ -772,7 +773,7 @@ Known limits. A resend for an unknown or verified address skips the token and me ### Organizations and memberships -Implemented as storage, ports, and a source contract: migration `backend/db/migrations/00010_create_organizations.sql`, queries in `backend/db/queries/organizations.sql`, domain types in `backend/internal/domain/organization.go` and `membership.go`, the ports in `backend/internal/port/outbound/organizations.go`, the sqlc-backed adapter in `backend/internal/adapter/secondary/postgres/organizations.go`, and `ListMyOrganizations`, `CreateOrganization`, `GetOrganization`, and `UpdateOrganization` in the public contract ([api/README.en.md](../../api/README.en.md#organizations)). The create, read, and update usecases with their handlers and the server-side context and membership checks of every tenant operation are planned; until then the operations answer 401 or 501 and nothing in bootstrap calls the repositories. The only implemented behavior is the storage and its constraints. +Organization creation, reads, and owner edits are implemented in `backend/internal/usecase/organization/`, `backend/internal/adapter/primary/http/v1/organization.go`, and `backend/internal/bootstrap/organization.go`. Storage and membership ports remain in `backend/internal/port/outbound/organizations.go` and the PostgreSQL adapter. Migration `00019_create_organization_creation_results.sql` preserves the original create result. General tenant context and the organization directory are planned separately. See [backend documentation](../../backend/README.en.md#organizations) for behavior and validation. Tables: @@ -788,7 +789,7 @@ Decisions: - An organization has an owner. A deferred constraint trigger (`organizations_owner_required`, SQLSTATE 23514) refuses at commit an organization with no `owner` membership in the `active` state, so creating an organization without its owner fails whichever code inserted it, and `CreateWithOwner` stores the organization, its representatives, and the owner in one transaction. Removing or demoting the last owner later is a rule of the member management, not of this constraint, which would otherwise block a platform decision about an abusive organization. - Update. `UpdateProfile` is one statement that applies only when the stored version equals the version the caller read, and advances it by one. The same statement requires an active membership of the actor with a manager role (the roles come from `domain.ManagerRoles`, not from SQL), so a membership that ended after the caller's read still stops the write. When the statement matches nothing, the adapter reads the membership to answer `ErrOrganizationNotFound` (unknown organization or no active membership), `ErrOrganizationManagerRequired`, or `ErrOrganizationVersionConflict`, in that order, so a stale version never tells an outsider anything. The representative list is then replaced in the same transaction under the row lock of the update. The statement locks the organization row (`FOR UPDATE`) and then the actor's membership row `FOR SHARE`, so a revocation that commits while the statement waits for the membership lock is re-evaluated and stops the write (an integration test holds a revocation open, queues the update behind it, and commits it). The lock order of every writer is organizations, then memberships: the member management, which changes a membership and the organization together, and the tenant repository must take the locks in that order, or two transactions can deadlock. - Foreign keys and deletion. `memberships` restricts the deletion of an organization and of an account, so an account with memberships cannot be deleted until a procedure ends them, in the same way as the consent ledger restricts the account. The application never deletes an organization. The consent ledger does not reference `organizations` yet: `consent_records.organization_id` is still a plain column with the snapshot name beside it. Adding the foreign key now would force the consent ledger tests to create real organizations, and the same migration has to add the `invitation_id` key, which needs the invitation table; both arrive with the migration that creates the invitation records, together with the keys of needs. All of them are `ON DELETE RESTRICT`, so an organization with consent history, needs, or invitations stays undeletable, which is the intended protection of consent evidence (PRD 7.3). -- Privacy. Contacts are public company channels; the contract and the domain accept no personal contact of an employee, and the owner answers for the content. Representative names are personal data of employees: `OrganizationRepresentative` hides its fields behind a pointer and redacts itself in `fmt` and `slog` output, `Organization` logs only its identifier, version, and level, and adapter errors keep the SQLSTATE and the constraint name without the failing row. The website is only stored: the server never fetches it, and a later feature that does must resolve the address and refuse private ranges itself. `StoredRepresentative`, `OrganizationRepresentativeInput`, `OrganizationProfileInput`, and the generated sqlc parameter structs of this repository hold names and must never be logged. The idempotency store of `CreateOrganization` keeps the stored 201 for 24 hours, and that response holds the representatives' names: the store must keep it out of logs and metrics, protect it like the other personal data, and delete it at the end of the replay window; its request fingerprint must be a hash, not the body. The candidate card is shown only to a candidate who received an invitation from the organization, and its `representatives` may be absent. The open questions (the publication of representative names, a sphere taxonomy) and the blocking one, a limit of organizations per account, which the PRD does not set and without which an account can multiply quotas by creating organizations (organization creation and quota enforcement need the owner's decision, and the prepared mechanism is a 409 `state_conflict` on create), are in [api/README.en.md](../../api/README.en.md#organizations). +- Privacy. Contacts are public company channels; the contract and the domain accept no personal contact of an employee, and the owner answers for the content. Representative names are personal data of employees: `OrganizationRepresentative` hides its fields behind a pointer and redacts itself in `fmt` and `slog` output, `Organization` logs only its identifier, version, and level, and adapter errors keep the SQLSTATE and the constraint name without the failing row. The website is only stored: the server never fetches it, and a later feature that does must resolve the address and refuse private ranges itself. `StoredRepresentative`, `OrganizationRepresentativeInput`, `OrganizationProfileInput`, and the generated sqlc parameter structs of this repository hold names and must never be logged. The idempotency store of `CreateOrganization` keeps the stored 201 for 24 hours, and that response holds the representatives' names: the store must keep it out of logs and metrics, protect it like the other personal data, and remove it through bounded opportunistic cleanup after the replay window; physical deletion may happen later when create traffic resumes; its request fingerprint must be a hash, not the body. The candidate card is shown only to a candidate who received an invitation from the organization, and its `representatives` may be absent. The open questions (the publication of representative names, a sphere taxonomy) and the blocking one, a limit of organizations per account, which the PRD does not set and without which an account can multiply quotas by creating organizations (organization creation and quota enforcement need the owner's decision, and the prepared mechanism is a 409 `state_conflict` on create), are in [api/README.en.md](../../api/README.en.md#organizations). What the ports guarantee (`outbound.OrganizationRepositories`, available on `UnitOfWork` only, because a write needs the transaction): diff --git a/docs/en/DEPLOY.md b/docs/en/DEPLOY.md index dc43fc8..80cefb5 100644 --- a/docs/en/DEPLOY.md +++ b/docs/en/DEPLOY.md @@ -301,10 +301,10 @@ The backend process runs one sending loop for service identity mail (email verif ### Mail templates -Implemented: the renderer in `backend/internal/usecase/notification/mailtemplate/` with templates for email verification, password reset, and a short notification. The delivery consumer renders notifications when it stores a delivery, and `ServiceMailer` creates verification mail during registration. Email confirmation is implemented in the API; the frontend confirmation screen remains a placeholder. The password reset flow is still planned. +Implemented: the renderer in `backend/internal/usecase/notification/mailtemplate/` with templates for email verification, password reset, and a short notification. The delivery consumer renders notifications when it stores a delivery, and `ServiceMailer` creates verification mail during registration. Email confirmation is implemented in the API and frontend. The password reset flow is still planned. - Templates are embedded in the binary with `go:embed` and parsed once when the renderer is created; a broken template fails its creation. Each version has three files: `.v.subject.tmpl`, `.v.txt.tmpl`, and `.v.html.tmpl`. The HTML part uses `html/template`, the plain-text part and the subject use `text/template`. Every transport sends the same rendering; templates hold no provider settings, keys, or sender address. -- Links start with `APP_PUBLIC_URL`, which the renderer checks again with the same rules. Verification: `/verify-email#token=`; password reset: `/reset-password#token=` (the page and the API for the reset are planned). The token is only in the URL fragment, never in the path or the query: a browser does not send the fragment to a server, so the nginx access log (which records `$uri`) and Referer headers never hold it. The frontend confirmation screen remains a placeholder; a client must read and remove the fragment, wait for explicit user action, then send the token and registration password to the API. A notification link is a path inside the application, such as `/candidate/invitations`; an absolute URL, `//host`, a scheme such as `javascript:`, a query, a fragment, a percent sign, and `.` or `..` segments are rejected. +- Links start with `APP_PUBLIC_URL`, which the renderer checks again with the same rules. Verification: `/verify-email#token=`; password reset: `/reset-password#token=` (the page and the API for the reset are planned). The token is only in the URL fragment, never in the path or the query: a browser does not send the fragment to a server, so the nginx access log (which records `$uri`) and Referer headers never hold it. The frontend reads and removes the fragment, waits for explicit user action, then sends the token and registration password to the API. A notification link is a path inside the application, such as `/candidate/invitations`; an absolute URL, `//host`, a scheme such as `javascript:`, a query, a fragment, a percent sign, and `.` or `..` segments are rejected. - Messages contain no name, email address, or other contact. Caller text in a notification is escaped in the HTML part; control and bidirectional characters are removed from the plain-text part, and the subject becomes one line, so CR and LF cannot add header lines. The notification subject is limited to 100 characters and the body to 2000. - Copy is in Russian. A released version is immutable: changing copy adds the next version, for example `verification.v2`, and switches the current version in code. Versions share no files, so one version cannot change the body of another. Each rendering carries its version and a SHA-256 content hash over the version, subject, and both parts; the same version and data always give the same body. A delivery stores the rendered body with the hash, and a retry sends the stored body instead of rendering again, so a new version applies to new deliveries only and an old version's files are not needed to send a stored delivery. - The renderer does not log. A rendering and notification data print only the kind, version, and content hash in `fmt` and `slog` output; tokens, links, and bodies are never printed. @@ -380,7 +380,7 @@ All names and addresses come from `deploy/edge/edge.env` (copy `deploy/edge/edge The browser sees only `https://`. The SPA and `/api` come from the same origin: the edge forwards every path unchanged, and the frontend container serves the SPA with its `try_files ... /index.html` fallback, so a deep link such as `/some/deep/link` returns the SPA, and proxies `/api/` to Go. The backend issues the `__Host-lincodex_session` cookie with `Path=/`, `Secure`, `HttpOnly`, `SameSite=Strict`, and no `Domain`; `Expires` and `Max-Age` match the absolute session expiry. The edge keeps `Host` as the public name and sets `X-Forwarded-Proto: https`; the frontend container's Nginx keeps that value for the backend (`$forwarded_proto` in `deploy/nginx/conf.d/app.conf`) and otherwise reports its own scheme. `APP_PUBLIC_URL` in the app host `.env` must be `https://`. Unsafe public identity operations and protected unsafe operations require the sole `Origin` value to exactly match `APP_PUBLIC_URL`; protected unsafe operations also require a CSRF token bound to the session cookie. The backend does not derive the allowed origin from `Host` or trust forwarded headers for this check. -Registration, verification resend, email confirmation, login, current-session reading, and logout are available through the backend API. Protected contract operations authenticate a verified account session; operations without business handlers still return 501 after the security boundary passes. Frontend registration and confirmation screens remain placeholders, and the backend does not read `X-Forwarded-Proto` for the Origin check. The browser login path through the edge has not been verified end to end. +Registration, verification resend, email confirmation, login, current-session reading, and logout are available through the backend API. Protected operations require a verified account session; implemented consent operations read texts and history, grant and revoke consents, and queue C1 account deletion without deleting the account immediately. Other operations without business handlers still return 501 after the security boundary passes. Unsafe consent operations also require session-bound CSRF and exact `Origin`; public and protected Origin checks do not read `Host` or forwarded headers. Frontend registration, confirmation, sign-in, and scenario continuation are implemented and verified through the isolated local browser stack. The backend does not read `X-Forwarded-Proto` for the Origin check. The browser login path through the edge has not been verified end to end. ### Request handling at the edge diff --git a/docs/en/TESTING.md b/docs/en/TESTING.md index 564c2a8..b4fa96e 100644 --- a/docs/en/TESTING.md +++ b/docs/en/TESTING.md @@ -42,7 +42,7 @@ Security checks run separately: `make -C security check` scans source/dependenci Existing checks cover health/readiness, backend PostgreSQL, Redis, and SeaweedFS connectivity, migration up, down to zero, and up again on an isolated database, concurrent migration runners that apply each migration once, the transactional outbox (atomic commit, rollback on error, panic, and context cancellation, nested-transaction rejection, an observed row-lock wait between concurrent transactions, edge payloads, and constraints), identity storage (a unique normalized email, hash-only storage of email and session tokens, exactly one successful consumption of a token under parallel confirmations and an observed lock wait between two consumes, rejection of expired, invalidated, and superseded tokens, including a re-registration that commits during a confirmation, session idle, absolute, and revocation limits and touch throttling, batch cleanup of unverified accounts that skips locked accounts without waiting, a deadlock reported as a retryable conflict, cascade deletes, rollback with the surrounding transaction, and constraints), cache operations and TTL, S3 operations and object persistence, the private file layer and SeaweedFS access controls (see [Private file storage tests](#private-file-storage-tests)), the Kafka test harness (keyed records with headers and per-partition order, refusal to create a missing topic on demand, and topic cleanup), the outbox relay (see [Outbox relay tests](#outbox-relay-tests)), the event consumer runtime (see [Event consumer tests](#event-consumer-tests)), mail deliveries (see [Mail delivery tests](#mail-delivery-tests)), metrics, the API client, ML schemas, and current endpoint availability. Registration and email confirmation have API integration coverage; login, assessment, search, invitation, and file workflows are not implemented. Confirmation writes an event to the transactional outbox, with no registered product consumer for that event; mail delivery is tested separately. There is no real model inference to validate as product behavior. -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; frontend registration and confirmation screens remain placeholders, and the test does not send through an external mail provider. +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. 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. @@ -69,7 +69,9 @@ Playwright receives `E2E_MAIL_FIXTURE=1`, `E2E_MAILBOX_URL=http://mail-fixture:8 The current suite (`frontend/e2e/smoke.spec.ts`) checks that the SPA serves `/` with `lang="ru"` and its heading, that `/status` shows the technical page with a live API, that `/api/v1/healthz` returns 200 `{"status":"ok"}` through the frontend proxy, that an unknown SPA route shows the not-found page, and that `/api/v1/missing` returns 404 `application/problem+json` with code `not_found`. It needs no data. Later business tests create their own synthetic users and records through the public API in the fresh stack of each run; they do not use shared fixtures or real data. -The suite does not cover candidate or employer workflows, sign-in, mail delivery, dependency failures (deployment smoke covers those), browsers other than desktop Chromium, layout, or accessibility. CI runs the suite in the `e2e` job after `backend`, `frontend`, and `infrastructure` pass: `make -C frontend install`, then `make -C deploy test-e2e`. The job needs no repository secrets or root `.env`; each run uses its own generated env file and fresh stand. On failure CI uploads the `e2e-diagnostics-attempt-` artifact with `report/`, `results/` (traces and screenshots), and `stand.log` for 14 days. Hidden files and the env file are not uploaded. The `e2e` result is part of the required aggregate. +The ordinary technical suite does not cover candidate or employer workflows, sign-in, mail delivery, dependency failures (deployment smoke covers those), browsers other than desktop Chromium, layout, or accessibility. CI runs the suite in the `e2e` job after `backend`, `frontend`, and `infrastructure` pass: `make -C frontend install`, then `make -C deploy test-e2e`. The job needs no repository secrets or root `.env`; each run uses its own generated env file and fresh stand. On failure CI uploads the `e2e-diagnostics-attempt-` artifact with `report/`, `results/` (traces and screenshots), and `stand.log` for 14 days. Hidden files and the env file are not uploaded. The `e2e` result is part of the required aggregate. + +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. ## Release manifest tests diff --git a/docs/ru/ARCHITECTURE.md b/docs/ru/ARCHITECTURE.md index a0df5ad..c9a5a86 100644 --- a/docs/ru/ARCHITECTURE.md +++ b/docs/ru/ARCHITECTURE.md @@ -6,7 +6,7 @@ Репозиторий содержит Go HTTP-сервис с проверкой PostgreSQL, Redis и SeaweedFS, адаптеры кеша и S3-хранилища, React-каркас интерфейса с публичными страницами и двумя оболочками кабинетов с экранами-заготовками, отдельный Python ML-сервис с health/readiness маршрутами, два OpenAPI-контракта, codegen, Compose и конфигурацию мониторинга. Публичный health endpoint API находится под /api/v1/healthz. /healthz используется для проверки веб-контейнера. Внутренний /readyz Go проверяет PostgreSQL, Redis и доступность bucket SeaweedFS; /readyz ML проверяет готовность модели; ML отвечает 503 на readiness, пока inference не готов. Метрики Go доступны по стандартному /metrics на внутреннем порту. -Регистрация, подтверждение email, вход и базовые операции с текущей сессией работают через API backend. Экраны регистрации и подтверждения во frontend остаются заглушками; остальные перечисленные продуктовые сценарии пока не реализованы: роли, профили, тесты, грейды, поиск, приглашения, загрузка и анализ резюме, PDF и интеграция с ФСП. ML не возвращает вымышленные результаты. Проверки доступности и технический smoke не подтверждают бизнес-сценарий. +Регистрация, подтверждение email, вход и базовые операции с текущей сессией работают через API backend. Во frontend реализованы регистрация, подтверждение, вход и продолжение по серверному шагу сценария; локальный браузерный E2E проверяет кандидата и работодателя. Настройки согласий и создание/редактирование организаций работают через backend API. Остальные продуктовые сценарии пока не реализованы: роли, профили, тесты, грейды, поиск, приглашения, загрузка и анализ резюме, PDF и интеграция с ФСП. ML не возвращает вымышленные результаты. Проверки доступности и технический smoke не подтверждают бизнес-сценарий. Подробности запуска, дерева исходников и проверки собраны в [руководстве разработки](DEVELOPMENT.md), [руководстве по развертыванию](DEPLOY.md) и [руководстве по проверкам](TESTING.md). @@ -348,7 +348,7 @@ Offsets и партиции. Каждый обработчик - один уча Постановка. `ServiceMailer.EnqueueVerification` и `EnqueuePasswordReset` выполняются в транзакции, которая вставляет токен, и получают запись токена, исходный токен, адрес получателя и срок действия в часах. Они проверяют, что назначение токена подходит письму, один раз рендерят письмо текущей версией шаблона и сохраняют доставку `pending`, привязанную к токену (`email_token_id`), с ID токена в роли ID доставки. Повторный вызов для того же токена ничего нового не сохраняет, а сохраненное тело остается прежним. -Ссылки. Токен передается только во фрагменте URL: `/verify-email#token=` и `/reset-password#token=`; ссылки строит `mailtemplate` (`tokenLink`). Браузер никогда не отправляет фрагмент серверу, поэтому токен не попадает в access log nginx, который пишет `$uri`, в заголовки Referer и в журнал запросов Go; его нет ни в пути, ни в query. Экран подтверждения frontend пока остается заглушкой. Клиент должен прочитать токен из фрагмента, удалить его и после явного действия пользователя отправить токен вместе с паролем регистрации. Маршрут и API сброса пароля не реализованы. Renderer отклоняет токен в любом другом месте, golden-файлы и тесты фиксируют формат, а тесты доставок проверяют, что сохраненное тело содержит ссылку с фрагментом и не содержит `?token=`. Тело в `deliveries` хранит действующий токен, пока письмо не отправлено или не отменено; см. "Персональные данные в хранилище". +Ссылки. Токен передается только во фрагменте URL: `/verify-email#token=` и `/reset-password#token=`; ссылки строит `mailtemplate` (`tokenLink`). Браузер никогда не отправляет фрагмент серверу, поэтому токен не попадает в access log nginx, который пишет `$uri`, в заголовки Referer и в журнал запросов Go; его нет ни в пути, ни в query. Frontend читает и удаляет токен из фрагмента, затем после явного действия пользователя отправляет его вместе с паролем регистрации. Новая ссылка в той же вкладке заменяет токен; результат прежнего запроса не меняет новую форму. Маршрут и API сброса пароля не реализованы. Renderer отклоняет токен в любом другом месте, golden-файлы и тесты фиксируют формат, а тесты доставок проверяют, что сохраненное тело содержит ссылку с фрагментом и не содержит `?token=`. Тело в `deliveries` хранит действующий токен, пока письмо не отправлено или не отменено; см. "Персональные данные в хранилище". Один проход `ServiceMailSender.ProcessNext` проводит одну доставку через три шага: @@ -650,7 +650,7 @@ contact_grant относится к паре кандидат-компания ### Хранение identity -Хранение 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). +Хранение 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. @@ -691,7 +691,7 @@ contact_grant относится к паре кандидат-компания ### Журнал согласий -Реализованы хранение, порты, контракт чтения и выдача согласий через `consent.Service`: миграция `backend/db/migrations/00009_create_consent_ledger.sql`, запросы в `backend/db/queries/consents.sql`, доменные типы в `backend/internal/domain/consent.go`, порты в `backend/internal/port/outbound/consents.go`, адаптер на sqlc в `backend/internal/adapter/secondary/postgres/consents.go` и `ListMyConsents` в публичном контракте ([api/README.md](../../api/README.md#согласия)). Регистрация записывает C1 через `GrantAtRegistration` в транзакции создания или повторной регистрации; подтверждение проверяет C1 той же версии регистрации, что и токен. HTTP выдача и отзыв согласий, последствия отзыва и C4 при принятии приглашения пока не реализованы. +Реализованы хранение, регистрационное C1 и обработчики чтения и изменений настроек: миграция `backend/db/migrations/00009_create_consent_ledger.sql`, таблица запросов удаления из `00018_create_account_deletion_requests.sql`, запросы в `backend/db/queries/consents.sql`, доменные типы в `backend/internal/domain/consent.go`, порты в `backend/internal/port/outbound/consents.go` и обработчики в `backend/internal/adapter/primary/http/v1/consent.go` ([api/README.md](../../api/README.md#согласия)). Публичный `GET /api/v1/identity/consent-texts/c1` возвращает только C1; подтвержденная сессия может читать C1/C2/C3/C5 и собственный журнал, выдавать поддерживаемые согласия, отзывать их и запрашивать удаление аккаунта. Регистрация записывает C1 в транзакции создания или повторной регистрации; подтверждение проверяет запись C1 той же версии регистрации, что и токен. Обработчик принятия приглашения C4 и worker удаления аккаунта пока не реализованы. Согласия C1-C5 из PRD FR01 - независимые цели: выдача или отзыв одной цели никогда не меняет другую. @@ -703,12 +703,12 @@ contact_grant относится к паре кандидат-компания - Привязка к тексту. Внешний ключ на (`purpose`, `text_version`) отклоняет версию, которая для цели не публиковалась, а триггер BEFORE INSERT отклоняет версию, опубликованную позже времени выдачи (`consent_records_text_published`). Для C1-C3 и C5 второй внешний ключ через генерируемую колонку требует, чтобы `text_hash` совпадал с хэшем опубликованного текста. Для C4 тот же триггер требует, чтобы `text_hash` был SHA-256 опубликованного текста с подставленным `organization_name` (`consent_records_c4_text_hash`). Домен сам считает этот хэш в `domain.NewContactConsentGrant` из опубликованного `ConsentText` и названия, поэтому вызывающий код не передает байты хэша, а клиент не может придумать ни версию, ни хэш. Сохраненное название - снимок, который доказывает показанный текст; последующее переименование организации его не меняет, и модель чтения возвращает его как `ConsentOrganization.name`. - История. Единственный UPDATE, который пропускает триггер, - отметка отзыва у неотозванной строки без изменения остальных колонок (`consent_records_immutable`). Новая версия текста - новая строка рядом со старой; выдача после отзыва - новая строка. Состояние (`active`, `superseded`, `revoked`) вычисляют запросы, оно не хранится: среди неотозванных строк субъекта и цели, кроме C4, строка, выданная последней (по `granted_at`, затем по ID), - `active`, остальные - `superseded`, независимо от их версий. Поэтому журнал принимает любую опубликованную версию, а usecase выдачи `consent.Service` проверяет, что версия - актуальный текст, до вызова `Grant`. Частичный уникальный индекс оставляет одну неотозванную строку на субъекта, цель и версию, поэтому повторная или конкурентная выдача возвращает существующую запись; уникальный индекс по `invitation_id` оставляет одну строку C4 на приглашение, отозванную или нет, поэтому отозванное C4 не возвращается. -- Отзыв. `ConsentLedger.Revoke` ставит отметку на все неотозванные строки цели, включая `superseded`, а для C4 - только на строки одной организации. Повтор ничего не находит и сохраняет первую отметку. Время отзыва раньше времени выдачи строки, из-за расхождения часов между экземплярами, записывается временем выдачи (`greatest`), поэтому CHECK `consent_records_revocation_stamp` остается последней защитой. Последствия отзыва (запрос удаления для C1, закрытие публикации и grants для C2 и C4, ручной путь для C3, остановка импорта для C5) относятся к отзыву согласий и не реализованы. -- Хранение и удаление. PRD 7.3 планирует хранить согласия три года, и это может быть дольше жизни аккаунта, поэтому `subject_id` ссылается на `users` с `ON DELETE RESTRICT`, а триггер BEFORE DELETE запрещает удалять строку подтвержденного аккаунта (`consent_records_retained`). Строки неподтвержденного аккаунта удалять можно, потому что регистрация, которую владелец адреса не подтвердил, не доказывает чье-либо согласие: очистка неподтвержденных аккаунтов удаляет строки удаляемых аккаунтов в том же запросе, а `UpdateRegistration` удаляет регистрационное C1 повторно регистрируемого аккаунта (см. ниже). TRUNCATE не вызывает строковый триггер и остается разрешенным для изоляции тестов. Оставит ли удаленный аккаунт журнал, tombstone или ничего, решают запрос удаления по C1 и процедура удаления аккаунта, которая его исполняет и пока не имеет задачи в MVP; правило хранения расширит условие удаления своей миграцией. +- Отзыв. `ConsentLedger.Revoke` ставит отметку на все неотозванные строки цели, включая `superseded`, а для C4 - только на строки одной организации. Повтор ничего не находит и сохраняет первую отметку. Время отзыва раньше времени выдачи строки, из-за расхождения часов между экземплярами, записывается временем выдачи (`greatest`), поэтому CHECK `consent_records_revocation_stamp` остается последней защитой. `POST /api/v1/me/account-deletion-requests` создает долговечную активную заявку C1, отзывает C1 и добавляет событие в outbox одной транзакцией; повтор возвращает ту же заявку, а последующая выдача C1 не отменяет ее. Аккаунт не удаляется синхронно. Отзыв C2 блокирует публикацию только если она ссылается на одну из записей, отозванных этой транзакцией, и в той же транзакции записывает событие истории приватности. Сохраненная публикация остается связанной с неизменяемой записью C2; модель чтения скрывает ее поля и возвращает эффективное состояние `closed` с причиной `consent_revoked`, а последующая выдача C2 не открывает публикацию заново. Повторный отзыв или отзыв более новой записи C2 не создает еще одно событие закрытия старой публикации. Отзыв C3 не блокирует аккаунт или профиль; отдельный запрос ручной оценки запланирован, но не реализован. Отзыв C4 ограничен указанной организацией, а каждое ограниченное по размеру outbox-событие содержит организацию и поля из отозванной записи. Отзыв C5 заставляет `HasCurrentConsent` отказывать по умолчанию и записывает intent остановки, но внешнего адаптера ФСП нет и фактическое удаление данных во внешней системе не заявляется. +- Хранение и удаление. PRD 7.3 планирует хранить согласия три года, и это может быть дольше жизни аккаунта, поэтому `subject_id` ссылается на `users` с `ON DELETE RESTRICT`, а триггер BEFORE DELETE запрещает удалять строку подтвержденного аккаунта (`consent_records_retained`). Строки неподтвержденного аккаунта удалять можно, потому что регистрация, которую владелец адреса не подтвердил, не доказывает чье-либо согласие: очистка неподтвержденных аккаунтов удаляет строки удаляемых аккаунтов в том же запросе, а `UpdateRegistration` удаляет регистрационное C1 повторно регистрируемого аккаунта (см. ниже). TRUNCATE не вызывает строковый триггер и остается разрешенным для изоляции тестов. Долговечная запись запроса C1 и событие реализованы, но worker удаления аккаунта и политика хранения журнала после такого удаления еще нет; сам запрос не удаляет аккаунт или журнал. - Повторная регистрация. Неподтвержденный аккаунт сохраняет `users.id`, когда тот же email регистрируется снова, поэтому иначе C1 прежнего регистранта стояло бы за новым. Запрос `UpdateUserRegistration` удаляет строки C1 с источником `registration` обновляемого аккаунта, и только если обновление применилось. Это обязательное требование для регистрации: usecase регистрации вызывает `UpdateRegistration` и записывает новое C1 через `consent.Service.GrantAtRegistration` строго после `UpdateRegistration` в той же транзакции (см. [Usecase согласий](#usecase-согласий)). - Версия регистрации для C1. Миграция `00016_bind_registration_consent.sql` добавляет `registration_version` только к C1 с источником `registration`; другие согласия обязаны оставить поле NULL. Она заполняет старые C1 текущей версией аккаунта, не используя токены. Предыдущая регистрационная C1 удаляется при повторной регистрации, поэтому более старая дата выдачи или несколько активных регистрационных C1 на аккаунт считаются несогласованными данными и останавливают миграцию. Частичный уникальный индекс `consent_records_registration_version_key` разрешает не более одной неотозванной регистрационной C1 для аккаунта и версии. Триггер вставки подставляет текущую версию, если старый backend не передал поле, и отклоняет несовпадение у нового; триггер неизменяемости защищает версию и при отзыве. - C2 и набор публикуемых полей. Строка C2 доказывает согласие с текстом публикации, а не то, какие поля опубликованы. Набор опубликованных полей и его изменения хранятся со временем и записью C2 за каждым в истории видимости кандидата (`candidate_publications` и `candidate_privacy_events`, см. [Видимость кандидата](#видимость-кандидата)). Добавить scope полей в строки C2 позже - аддитивное изменение миграции и контракта. -- C4 в бизнес-транзакции. `UnitOfWork.ConsentLedger().GrantContact` принимает `domain.ContactConsentGrant`, который строит только `domain.NewContactConsentGrant` и который требует текст C4, организацию и ее название, непустой набор полей, приглашение и его версию условий; `domain.NewConsentGrant` отклоняет C4. Принятие приглашения вызывает его в транзакции, которая переводит приглашение в `accepted`, создает grant и пишет событие аудита, поэтому все это фиксируется или откатывается вместе. Повторное принятие получает существующую запись с `created` false и сравнивает ее scope; для приглашения, чье C4 принадлежит другому субъекту, возвращается `ErrConsentInvitationTaken`. +- C4 в бизнес-транзакции. `UnitOfWork.ConsentLedger().GrantContact` принимает `domain.ContactConsentGrant`, который строит только `domain.NewContactConsentGrant` и который требует текст C4, организацию и ее название, непустой набор полей, приглашение и его версию условий; `domain.NewConsentGrant` отклоняет C4. Обработчик принятия приглашения пока не реализован. Когда он появится, он должен вызвать этот порт в транзакции принятия приглашения и записи события аудита; повторное принятие должно сравнивать сохраненную область, а для приглашения, чье C4 принадлежит другому субъекту, возвращать `ErrConsentInvitationTaken`. - Гонка очистки. Очистка проверяет строки согласий в снимке своего запроса. Согласие, зафиксированное для аккаунта-кандидата после этого снимка, но до блокировки аккаунта, нарушает ограничивающий внешний ключ в конце запроса (SQLSTATE 23001); адаптер возвращает его как `ErrTransactionConflict`, ничего не удаляется, а следующий запуск видит согласие. - Ограничение субъектом. Каждое чтение и отзыв принимают субъекта, а операция контракта берет его из сессии, поэтому модель чтения возвращает только собственные записи вызывающего. Ошибки адаптера сохраняют только SQLSTATE и имя ограничения, а `domain.ConsentRecord`, `ConsentGrant`, `ContactConsentGrant` и `ConsentRevocation` не показывают в выводе `fmt` и `slog` субъекта, организацию, название или поля. @@ -719,20 +719,21 @@ contact_grant относится к паре кандидат-компания - `ConsentTexts().Get` и `Current` читают опубликованные тексты и при каждом чтении проверяют сохраненный хэш. - `ConsentLedger().Grant` и `GrantContact` возвращают новую запись с `created` true или существующую с `created` false. Неизвестный субъект возвращает `ErrUserNotFound`, неизвестная версия - `ErrConsentTextNotFound`, версия, опубликованная позже, - `ErrConsentTextNotPublished`, хэш, не совпадающий с опубликованным текстом (для C4 - с сохраненным названием), - `ErrConsentTextMismatch`; эти ошибки приходят из базы и прерывают внешнюю транзакцию. Дубликат ее не прерывает. Выдача, чья конфликтующая запись была отозвана между двумя ее запросами, возвращает `ErrTransactionConflict`. - `Revoke` возвращает строки, на которые поставил отметку. `Current` возвращает новейшую неотозванную запись C1-C3 или C5 либо `ErrConsentNotFound`; `CurrentContact` возвращает неотозванные записи C4 одной организации. `List` выдает журнал субъекта страницами от новых к старым, при необходимости по состоянию. +- `ConsentRevocationEffects.Apply` выполняется в той же транзакции `UnitOfWork`, что и отзыв в журнале. Он закрывает эффективный доступ C2 только когда текущая публикация ссылается на одну из отозванных записей, один раз добавляет событие истории приватности и записывает ограниченные по размеру outbox-intents на основе точных отозванных записей. Будущий адаптер выдачи для C2/C4 должен привязывать grant к ID исходной записи согласия и синхронно закрывать старый grant в этой транзакции; новая выдача может создать только новый grant, но не открыть старый. Читатели и импортеры C5 должны проверять актуальный журнал и отказывать по умолчанию; outbox-сообщение само по себе не дает доступ и не доказывает удаление данных во внешней системе. ### Usecase согласий `consent.Service` в `backend/internal/usecase/consent/` подключен через bootstrap и используется регистрацией для проверки версии текста и выдачи C1 в транзакции создания или повторной регистрации. Экземпляр создается через `consent.NewService(transactor, clock)` с `Transactor` и часами приложения, которые получают остальные usecase. Нулевой transactor или часы вызывают панику при создании. -- Точки входа фиксируют источник. `GrantAtRegistration(ctx, repositories, subjectID, registrationVersion, textVersion)` записывает C1 с источником `registration`; `GrantInSettings(ctx, repositories, SettingsGrantInput)` записывает C1, C2, C3 или C5 с источником `consent_settings`. Ни одна не принимает источник или время, поэтому обработчик не может взять их от клиента. `repositories` - это `outbound.ConsentRepositories`: если передать `UnitOfWork` бизнес-операции, выдача фиксируется или откатывается вместе с ней. Регистрация создает аккаунт и записывает C1 в одной транзакции только по ID субъекта, поэтому сессия не нужна. `GrantInSettingsInNewTransaction` открывает собственную транзакцию для выдачи вне другой операции и повторяет `ErrTransactionConflict` до трех попыток всего с короткой случайной паузой (10 мс плюс до 10 мс) между ними; это безопасно, потому что повтор идемпотентен, а пауза прерывается сразу при отмене контекста. +- Точки входа фиксируют источник. `GrantAtRegistration` записывает C1 с источником `registration`; grants из настроек записывают C1, C2, C3 или C5 с источником `consent_settings`. `RevokeInSettingsInNewTransaction` ставит отметки в строках журнала субъекта и применяет эффекты публикации, истории и outbox в той же транзакции. `RequestAccountDeletionInNewTransaction` создает или возвращает единственную активную долговечную заявку, отзывает C1 и атомарно добавляет событие; последующая выдача C1 не отменяет эту заявку. Ни одна операция не принимает источник или время от клиента. `GrantInSettingsInNewTransaction` и операции изменений повторяют конфликт транзакции максимум три раза с короткой случайной паузой, которая завершается при отмене контекста. - Порядок при повторной регистрации. Для неподтвержденного аккаунта, который регистрируется снова, вызывайте `GrantAtRegistration` строго после `UserRepository.UpdateRegistration` в той же транзакции. `UpdateRegistration` удаляет регистрационное C1 прежнего регистранта, а выдача, выполненная до него, нашла бы эту запись, вернула ее с `Created` false и после удаления оставила бы аккаунт без C1. Интеграционный тест показывает оба порядка. - Проверка версии до ветвления по email. `CheckTextVersion(ctx, repositories, purpose, version)` возвращает актуальный текст, если `version` актуальна, а иначе завершается как выдача, ничего не записывая. Регистрация обязана вызвать ее с C1 и присланной версией до ветвления на новый или существующий email; иначе устаревшая версия отклонялась бы только для новых адресов, и разница выдала бы, какие аккаунты существуют. - Только актуальный текст. Выдача читает `ConsentTexts().Current` на время приложения и отклоняет любую другую версию ошибкой `*StaleConsentTextError`, которая совпадает с `ErrStaleConsentText` и содержит цель, запрошенную и актуальную версии, поэтому обработчик может сопоставить ее одному коду problem и показать новый текст. Устаревшая версия, версия, которая запланирована, но еще не опубликована, и версия, которой никогда не было, считаются устаревшими. Журнал принимает любую опубликованную версию, поэтому именно эта проверка не пускает выдачу устаревшего текста. Проверка и вставка не блокируются от публикации между ними: тексты публикуют миграции, а выдача, назвавшая актуальный текст на момент проверки, допустима. - Серверное время. Во входе нет поля времени. Выдача берет одно чтение внедренных часов для проверки и для времени записи; клиент не выбирает время. База по-прежнему отклоняет версию, опубликованную после этого времени. - Идемпотентность. Повтор того же субъекта, цели и актуальной версии возвращает существующую неотозванную запись с `Created` false, сохраняет ее первое время, ничего не записывает и не прерывает внешнюю транзакцию. Выдача после отзыва - новая запись. Повтор с более старой версией после публикации нового текста - не повтор, а устаревшая версия: субъект должен увидеть новый текст, а в журнале остается одна запись. - C4 только через scope. `GrantInSettings` отклоняет C4 ошибкой `ErrScopedConsentRequired`, ничего не прочитав. `GrantContact(ctx, repositories, input)` - явно ограниченная операция для принятия приглашения: вход содержит организацию и показанное название, набор полей, приглашение, версию условий приглашения и версию текста C4. Она проверяет, что текст C4 актуален, поручает `domain.NewContactConsentGrant` посчитать хэш показанного текста и вызывает `ConsentLedger().GrantContact` в транзакции вызывающего кода. Повтор того же субъекта и приглашения возвращает существующую запись с `Created` false; scope сравнивает вызывающий код. Проверка текста идет первой, поэтому повтор после публикации нового текста C4 считается устаревшим; принятие, которое хочет ответить на такой повтор прежним результатом, должно найти свою запись до вызова. -- C3 можно не давать. Цели независимы: ни одна выдача не требует, не подразумевает и не меняет другую, и ни один путь кода не требует активного C3 для профиля, ручного пути оценки или другой функции. У субъекта без C3 нет записи C3, и `Current` возвращает для него `ErrConsentNotFound`; это не ошибочное состояние аккаунта. Код, который читает C3 (запрос ручной оценки, отзыв согласия), считает отсутствие записи состоянием "не дано" и оставляет ручной путь доступным. -- Отзыва здесь нет. `Revoke` остается на порте журнала, а отзыв согласий должен вызывать его вместе с последующими эффектами и событиями outbox в одной транзакции. +- C3 можно не давать. Цели независимы: ни одна выдача не требует, не подразумевает и не меняет другую, а ни одна реализованная операция аккаунта или профиля не требует активного C3. У субъекта без C3 нет записи C3, `Current` возвращает `ErrConsentNotFound`; это не ошибка аккаунта. Отдельный запрос ручной оценки запланирован, но его endpoint пока не реализован. +- Отзыв и запрос удаления. `RevokeInSettingsInNewTransaction` применяет все последствия в транзакции, которая ставит отметки в журнале; повтор уже выполненного отзыва не добавляет новое событие. Запрос C1 долговечен и идемпотентен, но не удаляет аккаунт синхронно и не отменяется последующей выдачей C1. - Ошибки сохраняют идентичность: устаревшая версия, `ErrScopedConsentRequired`, `ErrUserNotFound`, `ErrConsentTextNotFound` (у цели нет опубликованного текста), `ErrConsentInvitationTaken`, `domain.ErrInvalidConsent` и `domain.ErrInvalidConsentText`. Действия требует `outbound.ErrTransactionConflict`: журнал возвращает его, не прерывая транзакцию, когда запись повтора была отозвана между вставкой и выборкой. Вызывающий код внутри `UnitOfWork` обязан вернуть эту ошибку, откатить транзакцию и повторить всю операцию; `GrantInSettingsInNewTransaction` делает это сам. Сопоставление остальных ошибок с кодами problem - дело обработчиков. - Демо-тексты требуют проверки перед выпуском. Тексты, которые публикует миграция, имеют вид `demo`: синтетические, без юридической проверки. Usecase не отличает их от текстов оператора, поэтому установка, принимающая реальные данные, записала бы согласие на демо-текст. До приема реальных данных (PRD 7.3) проверка перед выпуском должна убедиться, что актуальный текст каждой цели имеет вид `operator`; владелец - проверка перед выпуском или отзыв согласий, и ни той, ни другой пока нет. @@ -744,7 +745,7 @@ contact_grant относится к паре кандидат-компания Отложенные учетные данные (защита от 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 пока остается заглушкой. +Подтверждение почты (`ConfirmEmail`) реализовано. Оно требует пароль, сохраненный для регистрации этого токена, и проверяет его по отложенному хешу. В одной транзакции backend проверяет текущую версию регистрации и запись C1, погашает токен, подтверждает адрес, переносит с токена на аккаунт хеш пароля, сценарий и шаг онбординга, очищает `pending_*` и записывает ровно одно событие `identity.email_verified` без секретов. При любом отказе состояние аккаунта и токена не меняется. Неизвестный, использованный, замененный, устаревший токен, неверный пароль и отсутствие отложенных данных дают `verification_token_invalid`; истекший токен дает `verification_token_expired`. Origin должен точно совпадать с `APP_PUBLIC_URL`. Подтверждение не создает сессию. Экран подтверждения во frontend реализован и проверен локальным браузерным потоком регистрации. Вход принимает только подтвержденный email и проверяет сохраненный пароль аккаунта, а не отложенные данные регистрации. Неизвестный адрес, неверный пароль и некорректный сохраненный хеш получают одинаковый `invalid_credentials`; неизвестный адрес и некорректный хеш дополнительно проходят `VerifyDummy`, а ошибка сохраненного хеша записывается в лог без email или хеша. Верный пароль для неподтвержденного аккаунта отвечает `email_not_verified` и не создает сессию. Успешный вход создает новую сессию; если запрос принес действующую cookie сессии, сервер отзывает ее и создает новую в одной транзакции. Неуспешный вход не отзывает старую сессию, а некорректная cookie не становится principal. @@ -762,7 +763,7 @@ contact_grant относится к паре кандидат-компания ### Серверные сессии -Вход, чтение текущей сессии и аккаунта, выход реализованы на backend. Каждая защищенная контрактом операция проходит session boundary, которая создает verified principal из действующей PostgreSQL-сессии; для остальных защищенных business handlers пока возвращается 501 после security и проверки запроса. Каждая небезопасная публичная identity-операция (`RegisterAccount`, `ResendEmailVerification`, `ConfirmEmail`, `Login`) требует единственный `Origin`, точно равный `APP_PUBLIC_URL`. Защищенные небезопасные операции также требуют session-bound `X-CSRF-Token`. Проверка Origin выполняется на HTTP boundary и не доверяет `Host` или forwarded headers. Токен CSRF выводится через domain-separated HMAC-SHA-256 с ключом из `IDENTITY_KEY_SECRET`, связан с конкретным session token и сравнивается за постоянное время. `GetCurrentSession` возвращает CSRF-токен снова после перезагрузки страницы. GET `/api/v1/identity/sessions/current` возвращает сессию с аккаунтом, GET `/api/v1/identity/me` - текущий аккаунт, DELETE `/api/v1/identity/sessions/current` отзывает сессию. Гость и неподтвержденная сессия получают 401; при валидной сессии неверный или отсутствующий Origin либо CSRF на защищенной небезопасной операции отвечает 403 `csrf_check_failed`. +Вход, чтение текущей сессии и аккаунта, выход реализованы на backend. Каждая защищенная контрактом операция проходит session boundary, которая создает verified principal из действующей PostgreSQL-сессии; consent и organization handlers реализуют документированные для них операции. Операции контракта без реализованного бизнес-обработчика пока возвращают 501 после security и проверки запроса. Каждая небезопасная публичная identity-операция (`RegisterAccount`, `ResendEmailVerification`, `ConfirmEmail`, `Login`) требует единственный `Origin`, точно равный `APP_PUBLIC_URL`. Защищенные небезопасные операции также требуют session-bound `X-CSRF-Token`. Проверка Origin выполняется на HTTP boundary и не доверяет `Host` или forwarded headers. Токен CSRF выводится через domain-separated HMAC-SHA-256 с ключом из `IDENTITY_KEY_SECRET`, связан с конкретным session token и сравнивается за постоянное время. `GetCurrentSession` возвращает CSRF-токен снова после перезагрузки страницы. GET `/api/v1/identity/sessions/current` возвращает сессию с аккаунтом, GET `/api/v1/identity/me` - текущий аккаунт, DELETE `/api/v1/identity/sessions/current` отзывает сессию. Гость и неподтвержденная сессия получают 401; при валидной сессии неверный или отсутствующий Origin либо CSRF на защищенной небезопасной операции отвечает 403 `csrf_check_failed`. Cookie называется `__Host-lincodex_session` и имеет `Path=/`, `Secure`, `HttpOnly`, `SameSite=Strict`, без `Domain`; `Expires` и `Max-Age` указывают на абсолютное завершение сессии. В PostgreSQL сохраняется только SHA-256 хеш случайного cookie token, а не его значение; IP и user agent не сохраняются. `IDENTITY_SESSION_IDLE_TIMEOUT` по умолчанию `24h`, принимает от `1m` до `30d`; `IDENTITY_SESSION_ABSOLUTE_LIFETIME` по умолчанию `168h`, принимает от `1m` до `365d`. Таймаут простоя не может превышать абсолютный срок; неверные значения останавливают запуск. Активный запрос продлевает срок простоя, но не абсолютный срок. @@ -772,7 +773,7 @@ Cookie называется `__Host-lincodex_session` и имеет `Path=/`, `S ### Организации и членства -Реализовано как хранение, порты и исходный контракт: миграция `backend/db/migrations/00010_create_organizations.sql`, запросы в `backend/db/queries/organizations.sql`, доменные типы в `backend/internal/domain/organization.go` и `membership.go`, порты в `backend/internal/port/outbound/organizations.go`, адаптер на sqlc в `backend/internal/adapter/secondary/postgres/organizations.go`, а также `ListMyOrganizations`, `CreateOrganization`, `GetOrganization` и `UpdateOrganization` в публичном контракте ([api/README.md](../../api/README.md#организации)). Usecase создания, чтения и обновления с обработчиками и серверные проверки контекста и членства для каждой tenant-операции запланированы; до этого операции отвечают 401 или 501, а bootstrap не вызывает репозитории. Реализованы только хранение и его ограничения. +Создание, чтение и редактирование организации владельцем реализованы в `backend/internal/usecase/organization/`, `backend/internal/adapter/primary/http/v1/organization.go` и `backend/internal/bootstrap/organization.go`. Порты хранения и членства находятся в `backend/internal/port/outbound/organizations.go` и адаптере PostgreSQL. Миграция `00019_create_organization_creation_results.sql` сохраняет исходный результат создания. Общий tenant-контекст и список организаций запланированы отдельно. Поведение и проверки описаны в [документации backend](../../backend/README.md#организации). Таблицы: @@ -788,7 +789,7 @@ Cookie называется `__Host-lincodex_session` и имеет `Path=/`, `S - У организации есть владелец. Отложенный constraint trigger (`organizations_owner_required`, SQLSTATE 23514) при фиксации отказывает организации без членства `owner` в состоянии `active`, поэтому создание организации без владельца падает, каким бы кодом ее ни вставили, а `CreateWithOwner` сохраняет организацию, представителей и владельца в одной транзакции. Удаление или понижение последнего владельца позже - правило управления участниками, а не этого ограничения, которое иначе блокировало бы решение платформы о недобросовестной организации. - Обновление. `UpdateProfile` - один оператор, который применяется только когда сохраненная версия равна версии, прочитанной вызывающим, и увеличивает ее на единицу. Тот же оператор требует активного членства исполнителя с управляющей ролью (роли берутся из `domain.ManagerRoles`, а не из SQL), поэтому членство, закончившееся после чтения вызывающего, все равно останавливает запись. Если оператор ничего не нашел, адаптер читает членство и отвечает `ErrOrganizationNotFound` (неизвестная организация или нет активного членства), `ErrOrganizationManagerRequired` или `ErrOrganizationVersionConflict` в этом порядке, поэтому устаревшая версия ничего не сообщает постороннему. Затем список представителей заменяется в той же транзакции под блокировкой строки обновления. Оператор блокирует строку организации (`FOR UPDATE`), а затем строку членства исполнителя `FOR SHARE`, поэтому отзыв, зафиксированный, пока оператор ждет блокировку членства, проверяется заново и останавливает запись (интеграционный тест держит отзыв открытым, ставит обновление за ним в очередь и фиксирует отзыв). Порядок блокировок у каждого писателя: сначала организации, затем членства; управление участниками, которое меняет членство и организацию вместе, и tenant-репозиторий обязаны брать блокировки в этом порядке, иначе две транзакции могут взаимно заблокироваться. - Внешние ключи и удаление. `memberships` ограничивает удаление организации и аккаунта, поэтому аккаунт с членствами нельзя удалить, пока процедура их не завершит, так же как журнал согласий ограничивает аккаунт. Приложение никогда не удаляет организацию. Журнал согласий пока не ссылается на `organizations`: `consent_records.organization_id` остается обычным столбцом со снимком названия рядом. Ключ сейчас заставил бы тесты журнала согласий создавать настоящие организации, а та же миграция должна добавить ключ `invitation_id`, которому нужна таблица приглашений; оба появятся с миграцией, создающей записи приглашений, вместе с ключами потребностей. Все они `ON DELETE RESTRICT`, поэтому организацию с историей согласий, потребностями или приглашениями нельзя удалить, что и является задуманной защитой доказательств согласия (7.3 в PRD). -- Приватность. Контакты - публичные каналы компании; контракт и домен не принимают личных контактов сотрудника, а за содержимое отвечает владелец. Имена представителей - персональные данные сотрудников: `OrganizationRepresentative` прячет поля за указателем и скрывает себя в выводе `fmt` и `slog`, `Organization` логирует только идентификатор, версию и уровень, а ошибки адаптера хранят SQLSTATE и имя ограничения без строки с ошибкой. Сайт только хранится: сервер никогда не обращается по его адресу, а будущая функция, которая это делает, обязана сама разрешить адрес и отказать приватным диапазонам. `StoredRepresentative`, `OrganizationRepresentativeInput`, `OrganizationProfileInput` и сгенерированные sqlc-структуры параметров этого репозитория содержат имена и никогда не логируются. Хранилище идемпотентности `CreateOrganization` держит сохраненный ответ 201 24 часа, а в нем имена представителей: хранилище обязано не пускать его в логи и метрики, защищать как остальные персональные данные и удалять по окончании окна повтора; отпечаток запроса должен быть хешем, а не телом. Карточку кандидата видит только кандидат, получивший приглашение от организации, и ее `representatives` может отсутствовать. Открытые вопросы (публикация имен представителей, таксономия сферы) и блокирующий вопрос о лимите организаций на аккаунт, который PRD не задает и без которого аккаунт умножает квоты созданием организаций (для создания организаций и применения квот нужно решение владельца, а подготовленный механизм - 409 `state_conflict` при создании), в [api/README.md](../../api/README.md#организации). +- Приватность. Контакты - публичные каналы компании; контракт и домен не принимают личных контактов сотрудника, а за содержимое отвечает владелец. Имена представителей - персональные данные сотрудников: `OrganizationRepresentative` прячет поля за указателем и скрывает себя в выводе `fmt` и `slog`, `Organization` логирует только идентификатор, версию и уровень, а ошибки адаптера хранят SQLSTATE и имя ограничения без строки с ошибкой. Сайт только хранится: сервер никогда не обращается по его адресу, а будущая функция, которая это делает, обязана сама разрешить адрес и отказать приватным диапазонам. `StoredRepresentative`, `OrganizationRepresentativeInput`, `OrganizationProfileInput` и сгенерированные sqlc-структуры параметров этого репозитория содержат имена и никогда не логируются. Хранилище идемпотентности `CreateOrganization` держит сохраненный ответ 201 24 часа, а в нем имена представителей: хранилище обязано не пускать его в логи и метрики, защищать как остальные персональные данные и удалять ограниченной очисткой после окна повтора; физическое удаление может произойти позже при возобновлении создания организаций; отпечаток запроса должен быть хешем, а не телом. Карточку кандидата видит только кандидат, получивший приглашение от организации, и ее `representatives` может отсутствовать. Открытые вопросы (публикация имен представителей, таксономия сферы) и блокирующий вопрос о лимите организаций на аккаунт, который PRD не задает и без которого аккаунт умножает квоты созданием организаций (для создания организаций и применения квот нужно решение владельца, а подготовленный механизм - 409 `state_conflict` при создании), в [api/README.md](../../api/README.md#организации). Что гарантируют порты (`outbound.OrganizationRepositories`, доступны только через `UnitOfWork`, потому что запись требует транзакции): diff --git a/docs/ru/DEPLOY.md b/docs/ru/DEPLOY.md index adea3ba..a51c3c3 100644 --- a/docs/ru/DEPLOY.md +++ b/docs/ru/DEPLOY.md @@ -303,10 +303,10 @@ Compose передает эти переменные из корневого `.e ### Шаблоны писем -Реализовано: renderer в `backend/internal/usecase/notification/mailtemplate/` с шаблонами подтверждения почты, сброса пароля и короткого уведомления. Обработчик доставки рендерит им уведомления при сохранении доставки, а `ServiceMailer` создает письмо подтверждения при регистрации. Подтверждение email реализовано в API; экран подтверждения во frontend остается заглушкой. Сценарий сброса пароля еще запланирован. +Реализовано: renderer в `backend/internal/usecase/notification/mailtemplate/` с шаблонами подтверждения почты, сброса пароля и короткого уведомления. Обработчик доставки рендерит им уведомления при сохранении доставки, а `ServiceMailer` создает письмо подтверждения при регистрации. Подтверждение email реализовано в API и frontend. Сценарий сброса пароля еще запланирован. - Шаблоны встроены в бинарник через `go:embed` и разбираются один раз при создании renderer; сломанный шаблон останавливает создание. У каждой версии три файла: `.v.subject.tmpl`, `.v.txt.tmpl` и `.v.html.tmpl`. HTML часть использует `html/template`, текстовая часть и тема используют `text/template`. Любой транспорт отправляет один и тот же результат; в шаблонах нет настроек провайдера, ключей и адреса отправителя. -- Ссылки начинаются с `APP_PUBLIC_URL`, который renderer повторно проверяет по тем же правилам. Подтверждение: `/verify-email#token=`; сброс пароля: `/reset-password#token=` (страница и API сброса запланированы). Токен находится только во fragment URL и никогда ни в пути, ни в query: браузер не отправляет fragment серверу, поэтому access log nginx (он пишет `$uri`) и заголовки Referer его никогда не содержат. Экран подтверждения во frontend пока остается заглушкой; клиент должен прочитать и удалить fragment, дождаться явного действия пользователя и отправить в API токен вместе с паролем регистрации. Ссылка уведомления указывает на путь внутри приложения, например `/candidate/invitations`; абсолютный URL, `//host`, схема вроде `javascript:`, query, fragment, знак процента и сегменты `.` или `..` отклоняются. +- Ссылки начинаются с `APP_PUBLIC_URL`, который renderer повторно проверяет по тем же правилам. Подтверждение: `/verify-email#token=`; сброс пароля: `/reset-password#token=` (страница и API сброса запланированы). Токен находится только во fragment URL и никогда ни в пути, ни в query: браузер не отправляет fragment серверу, поэтому access log nginx (он пишет `$uri`) и заголовки Referer его никогда не содержат. Frontend читает и удаляет fragment, дожидается явного действия пользователя и отправляет в API токен вместе с паролем регистрации. Ссылка уведомления указывает на путь внутри приложения, например `/candidate/invitations`; абсолютный URL, `//host`, схема вроде `javascript:`, query, fragment, знак процента и сегменты `.` или `..` отклоняются. - В письмах нет имени, email или других контактов. Текст вызывающего кода в уведомлении экранируется в HTML части; управляющие и bidi символы удаляются из текстовой части, а тема сводится к одной строке, поэтому CR и LF не могут добавить строки заголовка. Тема уведомления ограничена 100 символами, текст 2000. - Тексты на русском языке. Выпущенная версия неизменяема: изменение текста добавляет следующую версию, например `verification.v2`, и переключает текущую версию в коде. Версии не делят файлы, поэтому одна версия не может изменить тело другой. Каждый результат содержит свою версию и SHA-256 content hash по версии, теме и обеим частям; одна и та же версия с теми же данными всегда дает то же тело. Доставка хранит сформированное тело вместе с hash, а повтор отправляет сохраненное тело, а не формирует его заново, поэтому новая версия применяется только к новым доставкам, а файлы старой версии для отправки сохраненной доставки не нужны. - Renderer ничего не пишет в лог. Результат и данные уведомления в выводе `fmt` и `slog` показывают только тип, версию и content hash; токены, ссылки и тела писем не печатаются. @@ -382,7 +382,7 @@ Edge-хост общий с другими сервисами. Здесь все Браузер видит только `https://`. SPA и `/api` приходят с одного origin: edge пересылает каждый путь без изменений, а frontend контейнер отдает SPA с запасным вариантом `try_files ... /index.html`, поэтому глубокая ссылка вроде `/some/deep/link` возвращает SPA, и проксирует `/api/` в Go. Backend выдает cookie `__Host-lincodex_session` с `Path=/`, `Secure`, `HttpOnly`, `SameSite=Strict` и без `Domain`; `Expires` и `Max-Age` равны абсолютному сроку сессии. Edge сохраняет `Host` как публичное имя и ставит `X-Forwarded-Proto: https`; Nginx frontend контейнера сохраняет это значение для backend (`$forwarded_proto` в `deploy/nginx/conf.d/app.conf`), а иначе сообщает собственную схему. `APP_PUBLIC_URL` в `.env` app-хоста должен быть `https://`. Небезопасные публичные identity-операции и защищенные небезопасные операции требуют единственный `Origin`, точно равный `APP_PUBLIC_URL`; защищенные небезопасные операции также требуют CSRF-токен, связанный с cookie сессии. Backend не выводит разрешенный origin из `Host` и не доверяет forwarded headers для этой проверки. -Регистрация, повторная отправка подтверждения, подтверждение email, вход, чтение текущей сессии и выход доступны через backend API. Защищенные операции API требуют сессию подтвержденного аккаунта; операции без бизнес-обработчика после успешной проверки границы безопасности возвращают 501. Экраны регистрации и подтверждения во frontend остаются заглушками, а backend не читает `X-Forwarded-Proto` для проверки origin. Браузерный путь входа через edge не проверен end to end. +Регистрация, повторная отправка подтверждения, подтверждение email, вход, чтение текущей сессии и выход доступны через backend API. Защищенные операции требуют сессию подтвержденного аккаунта; реализованные операции согласий читают тексты и историю, выдают и отзывают согласия, а запрос C1 ставит удаление аккаунта в очередь без немедленного удаления. Остальные операции без business handler после security boundary возвращают 501. Небезопасные операции согласий также проверяют session-bound CSRF и точный `Origin`; публичные и защищенные Origin checks не читают `Host` или forwarded headers. Регистрация, подтверждение, вход и продолжение сценария во frontend реализованы и проверены на изолированном локальном браузерном стенде. Backend не читает `X-Forwarded-Proto` для проверки Origin. Браузерный путь входа через edge не проверен end to end. ### Обработка запросов на edge diff --git a/docs/ru/TESTING.md b/docs/ru/TESTING.md index bce5f2e..0b1121f 100644 --- a/docs/ru/TESTING.md +++ b/docs/ru/TESTING.md @@ -42,7 +42,7 @@ make -C ml check-generated использует datamodel-code-generator --check Существующие проверки относятся к health/readiness, проверке соединения backend с PostgreSQL, Redis и SeaweedFS, миграциям up, down до нуля и повторному up на изолированной базе, конкурентным runner миграций, которые применяют каждую миграцию один раз, transactional outbox (атомарная фиксация, откат при ошибке, panic и отмене контекста, отказ во вложенной транзакции, наблюдаемое ожидание блокировки строки между параллельными транзакциями, граничные payload и ограничения), хранению identity (уникальный нормализованный email, хранение только хешей email-токенов и токенов сессий, ровно одно успешное погашение токена при параллельных подтверждениях и наблюдаемое ожидание блокировки между двумя погашениями, отказ для истекших, аннулированных и замененных токенов, в том числе при повторной регистрации во время подтверждения, пределы простоя, абсолютного срока и отзыва сессии и ограничение частоты записи активности, пакетная очистка неподтвержденных аккаунтов, которая пропускает заблокированные аккаунты без ожидания, взаимная блокировка как повторяемый конфликт, каскадное удаление, откат вместе с внешней транзакцией и ограничения), операциям кеша и TTL, S3-операциям и сохранению объектов, закрытому файловому слою и контролю доступа SeaweedFS (см. [Тесты закрытого файлового хранилища](#тесты-закрытого-файлового-хранилища)), тестовой обвязке Kafka (записи с ключом и заголовками и порядок внутри партиции, отказ создавать отсутствующий топик по запросу и очистка топиков), relay outbox (см. [Тесты relay outbox](#тесты-relay-outbox)), runtime обработчиков событий (см. [Тесты обработчиков событий](#тесты-обработчиков-событий)), доставкам писем (см. [Тесты доставки писем](#тесты-доставки-писем)), метрикам, API client, ML schema и доступности текущих endpoint. Регистрация и подтверждение email проверяются API integration-тестами; вход, тестирование, поиск, приглашения и работа с файлами пока не реализованы. Подтверждение записывает событие в transactional outbox, но для него нет зарегистрированного продуктового обработчика; обработчик доставки писем проверяется отдельно. Реального model inference как бизнес-результата нет. -TestEmailVerificationOverHTTP получает токен из Resend fixture после регистрации. Тест проверяет подтверждение candidate и employer, отсутствие сессии и cookie, неизменность состояния при неизвестном, истекшем, замененном или погашенном токене, неверном пароле и отсутствии отложенных данных. Он также проверяет привязку C1 к версии регистрации, отсутствующий, null и чужой Origin, а также лимиты, истечение срока после ожидания блокировки, откат после сбоя outbox и одно событие при параллельном подтверждении. Тест охватывает только API; экраны регистрации и подтверждения во frontend остаются заглушками, внешний почтовый провайдер не вызывается. +TestEmailVerificationOverHTTP получает токен из Resend fixture после регистрации. Тест проверяет подтверждение candidate и employer, отсутствие сессии и cookie, неизменность состояния при неизвестном, истекшем, замененном или погашенном токене, неверном пароле и отсутствии отложенных данных. Он также проверяет привязку C1 к версии регистрации, отсутствующий, null и чужой Origin, а также лимиты, истечение срока после ожидания блокировки, откат после сбоя outbox и одно событие при параллельном подтверждении. Тест охватывает только API; внешний почтовый провайдер не вызывается. Frontend проверяет отдельный локальный браузерный поток регистрации. API verify проверяет выбранный OpenAPI subset через pinned toolchain; его результат относится только к реально запущенным fixture и контрактам. CI YAML в репозитории не означает, что workflow уже выполнился на GitHub. @@ -69,7 +69,9 @@ Playwright получает `E2E_MAIL_FIXTURE=1`, `E2E_MAILBOX_URL=http://mail-f Текущий набор (`frontend/e2e/smoke.spec.ts`) проверяет, что SPA отдает `/` с `lang="ru"` и заголовком, что `/status` показывает техническую страницу с живым API, что `/api/v1/healthz` через прокси frontend возвращает 200 `{"status":"ok"}`, что неизвестный маршрут SPA показывает страницу "не найдено" и что `/api/v1/missing` возвращает 404 `application/problem+json` с кодом `not_found`. Данные ему не нужны. Будущие бизнес-тесты создают своих синтетических пользователей и записи через публичный API в свежем стеке каждого прогона; общие фикстуры и реальные данные не используются. -Набор не проверяет сценарии кандидата и работодателя, вход, доставку почты, отказы зависимостей (их проверяет deployment smoke), браузеры кроме desktop Chromium, верстку и доступность. CI запускает набор в job `e2e` после успешных `backend`, `frontend` и `infrastructure`: `make -C frontend install`, затем `make -C deploy test-e2e`. Секреты репозитория и корневой `.env` не нужны; каждый прогон использует свой сгенерированный env-файл и свежий стенд. При ошибке CI загружает артефакт `e2e-diagnostics-attempt-` с `report/`, `results/` (трассы и снимки экрана) и `stand.log` на 14 дней. Скрытые файлы и env-файл не загружаются. Результат `e2e` входит в обязательный aggregate. +Обычный технический набор не проверяет сценарии кандидата и работодателя, вход, доставку почты, отказы зависимостей (их проверяет deployment smoke), браузеры кроме desktop Chromium, верстку и доступность. CI запускает набор в job `e2e` после успешных `backend`, `frontend` и `infrastructure`: `make -C frontend install`, затем `make -C deploy test-e2e`. Секреты репозитория и корневой `.env` не нужны; каждый прогон использует свой сгенерированный env-файл и свежий стенд. При ошибке CI загружает артефакт `e2e-diagnostics-attempt-` с `report/`, `results/` (трассы и снимки экрана) и `stand.log` на 14 дней. Скрытые файлы и env-файл не загружаются. Результат `e2e` входит в обязательный aggregate. + +Режим регистрации дополнительно запускает `frontend/e2e/auth-registration.spec.ts`: регистрацию кандидата и работодателя с видимым C1, реальную локальную повторную отправку с получением нового письма, замену ссылки подтверждения в той же вкладке, повтор после неверного пароля, подтверждение без автоматического входа, вход и восстановление серверного шага после обновления. Проверяются фокус клавиатуры и отсутствие переполнения на 360, 768 и 1280 px. Отображение просроченной ссылки использует управляемый problem-ответ; реальное истечение токена проверяют backend integration tests. Только изолированный overlay задает `VERIFICATION_MAIL_MIN_INTERVAL=1s`; обычная среда и выпуск сохраняют свой настроенный интервал. Для auth-тестов отключены трассы, снимки при ошибках и видео; явные снимки для проверки показывают состояния без токенов и синтетические адреса. Внешняя почта и рабочий edge-путь не проверялись. ## Тесты манифеста выпуска diff --git a/frontend/e2e/auth-registration.spec.ts b/frontend/e2e/auth-registration.spec.ts new file mode 100644 index 0000000..f001bb3 --- /dev/null +++ b/frontend/e2e/auth-registration.spec.ts @@ -0,0 +1,237 @@ +import { expect, test, type Page } from "@playwright/test"; + +type InboxMessage = { + id: string; + text?: string; + html?: string; +}; + +type InboxResponse = { + messages: InboxMessage[]; +}; + +const mailFixtureEnabled = process.env.E2E_MAIL_FIXTURE === "1"; + +test.use({ trace: "off", screenshot: "off", video: "off" }); + +test.describe("registration, email confirmation, and onboarding", () => { + async function readInbox(email: string): Promise { + const inboxUrl = process.env.E2E_MAILBOX_URL; + const token = process.env.E2E_MAILBOX_TOKEN; + if (!inboxUrl || !token) { + throw new Error("The local registration mailbox fixture is not configured."); + } + + const url = new URL(inboxUrl); + url.searchParams.set("to", email); + const response = await fetch(url, { headers: { Authorization: `Bearer ${token}` } }); + if (!response.ok) throw new Error("Could not read the local registration mailbox."); + const body = (await response.json()) as InboxResponse; + return body.messages; + } + + async function waitForMessage(email: string, afterId?: string): Promise { + const deadline = Date.now() + 20_000; + while (Date.now() < deadline) { + const messages = await readInbox(email); + const matching = messages.filter((message) => message.id !== afterId).at(-1); + if (matching) return matching; + await new Promise((resolve) => setTimeout(resolve, 250)); + } + throw new Error("The local registration mailbox did not receive the expected message."); + } + + function tokenFromMessage(message: InboxMessage): string { + const content = `${message.text ?? ""}\n${message.html ?? ""}`; + const token = /\/verify-email#token=([A-Za-z0-9_-]{32,128})/.exec(content)?.[1]; + if (!token) throw new Error("The local registration message had no verification link."); + return token; + } + + async function openVerificationLink(page: Page, token: string): Promise { + const target = new URL("/verify-email", process.env.E2E_BASE_URL); + target.hash = `token=${token}`; + try { + await page.goto(target.toString()); + } catch { + throw new Error("Could not open the verification page."); + } + await expect(page.getByLabel("Пароль, выбранный при регистрации")).toBeVisible(); + const fragmentWasRemoved = await page.evaluate(() => window.location.hash === ""); + expect(fragmentWasRemoved).toBe(true); + } + + async function checkResponsiveKeyboardFlow(page: Page): Promise { + for (const width of [360, 768, 1280]) { + await page.setViewportSize({ width, height: 900 }); + await page.evaluate(() => (document.activeElement as HTMLElement | null)?.blur()); + await page.keyboard.press("Tab"); + const hasVisibleKeyboardFocus = await page.evaluate(() => { + const active = document.activeElement; + if (!(active instanceof HTMLElement) || !active.matches(":focus-visible")) return false; + const style = getComputedStyle(active); + return style.outlineStyle !== "none" && Number.parseFloat(style.outlineWidth) > 0; + }); + const hasHorizontalOverflow = await page.evaluate( + () => document.documentElement.scrollWidth > window.innerWidth, + ); + expect(hasVisibleKeyboardFocus).toBe(true); + expect(hasHorizontalOverflow).toBe(false); + } + } + + async function captureReviewScreenshot( + page: Page, + scenario: "candidate" | "employer", + state: "registration-accepted" | "email-confirmed", + ): Promise { + const artifactsDirectory = process.env.E2E_ARTIFACTS_DIR ?? "test-results/e2e"; + const screenshotPath = `${artifactsDirectory}/${scenario}-${state}.png`; + await page.screenshot({ path: screenshotPath, animations: "disabled" }); + } + + async function completeScenario(page: Page, scenario: "candidate" | "employer") { + test.skip(!mailFixtureEnabled, "Requires the local mail fixture target."); + + const email = `auth-${crypto.randomUUID()}@example.test`; + const password = "correct horse battery staple 2026"; + const scenarioLabel = scenario === "candidate" ? "Кандидат" : "Работодатель"; + const nextStep = 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 checkResponsiveKeyboardFlow(page); + await page.getByRole("button", { name: "Создать аккаунт" }).click(); + await expect(page.getByRole("heading", { name: "Запрос принят" })).toBeVisible(); + await expect( + page.getByText(new RegExp(`Выбранный сценарий: ${scenarioLabel.toLowerCase()}`)), + ).toBeVisible(); + const registrationContextIsNonSecret = await page.evaluate(() => { + const raw = sessionStorage.getItem("lincodex-registration-context"); + if (!raw) return false; + try { + const context: unknown = JSON.parse(raw); + if (typeof context !== "object" || context === null) return false; + return Object.keys(context).every((key) => ["email", "scenario", "accepted"].includes(key)); + } catch { + return false; + } + }); + expect(registrationContextIsNonSecret).toBe(true); + + await page.reload(); + await expect(page.getByRole("heading", { name: "Запрос принят" })).toBeVisible(); + await expect( + page.getByText(new RegExp(`Выбранный сценарий: ${scenarioLabel.toLowerCase()}`)), + ).toBeVisible(); + await captureReviewScreenshot(page, scenario, "registration-accepted"); + + const originalMessage = await waitForMessage(email); + const originalToken = tokenFromMessage(originalMessage); + await openVerificationLink(page, originalToken); + + await page.route("**/api/v1/identity/email-verifications", (route) => + route.fulfill({ + status: 400, + contentType: "application/problem+json; charset=utf-8", + body: JSON.stringify({ + type: "urn:lincodex:problem:verification_token_expired", + title: "Verification token expired", + status: 400, + code: "verification_token_expired", + detail: "Request a new verification link.", + }), + }), + ); + await page.getByLabel("Пароль, выбранный при регистрации").fill(password); + await page.getByRole("button", { name: "Подтвердить почту" }).click(); + await expect(page.getByRole("alert")).toContainText("Срок действия ссылки истек"); + await page.unroute("**/api/v1/identity/email-verifications"); + + await page.waitForTimeout(1100); + 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(); + expect((await resendResponse).status()).toBe(202); + await expect(page.getByText(/^Запрос принят\./)).toBeVisible(); + const resentMessage = await waitForMessage(email, originalMessage.id); + await openVerificationLink(page, tokenFromMessage(resentMessage)); + + const rejectedConfirmation = page.waitForResponse( + (response) => + new URL(response.url()).pathname === "/api/v1/identity/email-verifications" && + response.request().method() === "POST", + ); + await page.getByLabel("Пароль, выбранный при регистрации").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); + 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); + + 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 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); + 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"); + }); +}); diff --git a/frontend/src/app/router/candidate-home-route.tsx b/frontend/src/app/router/candidate-home-route.tsx new file mode 100644 index 0000000..a95a334 --- /dev/null +++ b/frontend/src/app/router/candidate-home-route.tsx @@ -0,0 +1,13 @@ +import { Navigate } from "react-router-dom"; +import { getOnboardingDestination } from "../../entities/session"; +import { PlaceholderPage } from "../../pages/placeholder"; +import { useGetCurrentSession } from "../../shared/api/endpoints/identity/identity"; + +export function CandidateHomeRoute() { + const session = useGetCurrentSession(); + if (!session.data) return ; + if (session.data.account.onboarding_step !== "completed") { + return ; + } + return ; +} diff --git a/frontend/src/app/router/routes.test.tsx b/frontend/src/app/router/routes.test.tsx index 042e1d2..a383f5a 100644 --- a/frontend/src/app/router/routes.test.tsx +++ b/frontend/src/app/router/routes.test.tsx @@ -2,6 +2,7 @@ import { QueryClientProvider } from "@tanstack/react-query"; import { renderToString } from "react-dom/server"; import { StaticRouterProvider, createStaticHandler, createStaticRouter } from "react-router-dom"; import { describe, expect, it } from "vitest"; +import { getGetCurrentSessionQueryKey } from "../../shared/api/endpoints/identity/identity"; import { createQueryClient } from "../providers/query-client"; import { routes } from "./routes"; @@ -15,8 +16,32 @@ async function render(path: string): Promise { return context; } const router = createStaticRouter(handler.dataRoutes, context); + const queryClient = createQueryClient(); + const scenario = path.startsWith("/employer") ? "employer" : "candidate"; + if (path.startsWith("/candidate") || path.startsWith("/employer")) { + queryClient.setQueryData(getGetCurrentSessionQueryKey(), { + account: { + id: "11111111-1111-4111-8111-111111111111", + email: "person@example.test", + email_verified: true, + scenario, + onboarding_step: + path === "/candidate/onboarding" + ? "candidate_consents" + : path === "/candidate/profile" + ? "candidate_profile" + : path === "/candidate/assessment" + ? "candidate_assessment" + : scenario === "candidate" + ? "completed" + : "employer_company", + created_at: "2026-10-07T12:00:00Z", + }, + csrf_token: "A".repeat(43), + }); + } return renderToString( - + , ); diff --git a/frontend/src/app/router/routes.tsx b/frontend/src/app/router/routes.tsx index 4aeacd2..a504447 100644 --- a/frontend/src/app/router/routes.tsx +++ b/frontend/src/app/router/routes.tsx @@ -1,4 +1,7 @@ import { redirect, type RouteObject } from "react-router-dom"; +import { LoginPage, RegisterPage, VerifyEmailPage } from "../../pages/auth"; +import { CandidateOnboardingPage } from "../../pages/candidate-onboarding"; +import { SessionGate } from "../../entities/session"; import { NotFoundPage } from "../../pages/not-found"; import { PlaceholderPage } from "../../pages/placeholder"; import { StatusPage } from "../../pages/status"; @@ -9,11 +12,11 @@ import { EmployerShell } from "../../widgets/employer-shell"; import { PublicShell } from "../../widgets/public-shell"; import { RootLayout } from "../ui/root-layout"; import { RouteErrorPage } from "../ui/route-error-page"; +import { CandidateHomeRoute } from "./candidate-home-route"; /** - * Route tree with three groups: public pages, the candidate cabinet, and the - * employer cabinet. Each group has its own shell and its own not-found page. - * Access control is not implemented yet; the server will enforce it. + * Route tree with public pages and role-specific cabinets. Protected shells + * restore the server session before they render any cabinet child. */ export const routes: RouteObject[] = [ { @@ -24,9 +27,9 @@ export const routes: RouteObject[] = [ element: , children: [ { index: true, element: }, - { path: paths.login, element: }, - { path: paths.register, element: }, - { path: paths.verifyEmail, element: }, + { path: paths.login, element: }, + { path: paths.register, element: }, + { path: paths.verifyEmail, element: }, { path: paths.support, element: }, { path: paths.status, element: }, { path: "*", element: }, @@ -36,27 +39,38 @@ export const routes: RouteObject[] = [ path: paths.candidate.root, element: , children: [ - { index: true, element: }, { - path: paths.candidate.onboarding, - element: , - }, - { path: paths.candidate.profile, element: }, - { - path: paths.candidate.assessment, - element: , - }, - { path: paths.candidate.results, element: }, - { - path: paths.candidate.invitations, - element: , - }, - { path: paths.candidate.privacy, element: }, - { - path: "*", - element: ( - - ), + element: , + children: [ + { index: true, element: }, + { path: paths.candidate.onboarding, element: }, + { + path: paths.candidate.profile, + element: , + }, + { + path: paths.candidate.assessment, + element: , + }, + { + path: paths.candidate.results, + element: , + }, + { + path: paths.candidate.invitations, + element: , + }, + { + path: paths.candidate.privacy, + element: , + }, + { + path: "*", + element: ( + + ), + }, + ], }, ], }, @@ -64,23 +78,33 @@ export const routes: RouteObject[] = [ path: paths.employer.root, element: , children: [ - // The employer flow starts with the company profile. - { index: true, loader: () => redirect(paths.employer.company) }, - { path: paths.employer.company, element: }, - { path: paths.employer.needs, element: }, { - path: paths.employer.candidates, - element: , - }, - { - path: paths.employer.invitations, - element: , - }, - { - path: "*", - element: ( - - ), + element: , + children: [ + { index: true, loader: () => redirect(paths.employer.company) }, + { + path: paths.employer.company, + element: , + }, + { path: paths.employer.needs, element: }, + { + path: paths.employer.candidates, + element: , + }, + { + path: paths.employer.invitations, + element: , + }, + { + path: "*", + element: ( + + ), + }, + ], }, ], }, diff --git a/frontend/src/entities/session/index.ts b/frontend/src/entities/session/index.ts new file mode 100644 index 0000000..d212687 --- /dev/null +++ b/frontend/src/entities/session/index.ts @@ -0,0 +1,2 @@ +export { getOnboardingDestination } from "./model/onboarding-destination"; +export { SessionGate } from "./ui/session-gate"; diff --git a/frontend/src/entities/session/model/onboarding-destination.test.ts b/frontend/src/entities/session/model/onboarding-destination.test.ts new file mode 100644 index 0000000..b76d806 --- /dev/null +++ b/frontend/src/entities/session/model/onboarding-destination.test.ts @@ -0,0 +1,26 @@ +import { describe, expect, it } from "vitest"; +import type { Account } from "../../../shared/api/schemas"; +import { paths } from "../../../shared/config"; +import { getOnboardingDestination } from "./onboarding-destination"; + +function account( + scenario: Account["scenario"], + onboarding_step: Account["onboarding_step"], +): Pick { + return { scenario, onboarding_step }; +} + +describe("getOnboardingDestination", () => { + it.each([ + ["candidate", "candidate_consents", paths.candidate.onboarding], + ["candidate", "candidate_profile", paths.candidate.profile], + ["candidate", "candidate_questionnaire", paths.candidate.onboarding], + ["candidate", "candidate_assessment", paths.candidate.assessment], + ["candidate", "completed", paths.candidate.root], + ["employer", "employer_company", paths.employer.company], + ["employer", "completed", paths.employer.root], + ["candidate", "employer_company", paths.candidate.onboarding], + ] as const)("routes %s at %s to the saved step", (scenario, step, expected) => { + expect(getOnboardingDestination(account(scenario, step))).toBe(expected); + }); +}); diff --git a/frontend/src/entities/session/model/onboarding-destination.ts b/frontend/src/entities/session/model/onboarding-destination.ts new file mode 100644 index 0000000..264a5e0 --- /dev/null +++ b/frontend/src/entities/session/model/onboarding-destination.ts @@ -0,0 +1,25 @@ +import type { Account } from "../../../shared/api/schemas"; +import { paths } from "../../../shared/config"; + +/** Resolve the next page from the server-owned onboarding state. */ +export function getOnboardingDestination( + account: Pick, +): string { + if (account.scenario === "employer") { + return account.onboarding_step === "completed" ? paths.employer.root : paths.employer.company; + } + + switch (account.onboarding_step) { + case "candidate_consents": + case "candidate_questionnaire": + return paths.candidate.onboarding; + case "candidate_profile": + return paths.candidate.profile; + case "candidate_assessment": + return paths.candidate.assessment; + case "employer_company": + return paths.candidate.onboarding; + case "completed": + return paths.candidate.root; + } +} diff --git a/frontend/src/entities/session/ui/session-gate.tsx b/frontend/src/entities/session/ui/session-gate.tsx new file mode 100644 index 0000000..d7d1ed1 --- /dev/null +++ b/frontend/src/entities/session/ui/session-gate.tsx @@ -0,0 +1,57 @@ +import { ApiRequestError } from "../../../shared/api"; +import { useGetCurrentSession } from "../../../shared/api/endpoints/identity/identity"; +import type { Account } from "../../../shared/api/schemas"; +import { paths } from "../../../shared/config"; +import { ButtonLink, ErrorState, ForbiddenState, LoadingState } from "../../../shared/ui"; +import { Navigate, Outlet } from "react-router-dom"; + +type SessionGateProps = { + scenario: Account["scenario"]; +}; + +/** Restores the HttpOnly-cookie session and keeps its CSRF token in query memory. */ +export function SessionGate({ scenario }: SessionGateProps) { + const session = useGetCurrentSession(); + + if (session.isPending) { + return ; + } + + if (session.isError) { + if (session.error instanceof ApiRequestError && session.error.status === 401) { + return ; + } + + if (session.error instanceof ApiRequestError && session.error.status === 403) { + return ( + Перейти ко входу} + /> + ); + } + + return ( + void session.refetch()} + title="Не удалось проверить вход" + /> + ); + } + + if (session.data.account.scenario !== scenario) { + return ( + Перейти ко входу} + /> + ); + } + + return ; +} diff --git a/frontend/src/features/confirm-email/index.ts b/frontend/src/features/confirm-email/index.ts new file mode 100644 index 0000000..7cc3401 --- /dev/null +++ b/frontend/src/features/confirm-email/index.ts @@ -0,0 +1 @@ +export { ConfirmEmailForm } from "./ui/confirm-email-form"; diff --git a/frontend/src/features/confirm-email/model/consume-verification-token.test.ts b/frontend/src/features/confirm-email/model/consume-verification-token.test.ts new file mode 100644 index 0000000..7010330 --- /dev/null +++ b/frontend/src/features/confirm-email/model/consume-verification-token.test.ts @@ -0,0 +1,76 @@ +import { describe, expect, it, vi } from "vitest"; +import { + consumeVerificationToken, + watchVerificationTokenChanges, + type VerificationLinkBrowser, +} from "./consume-verification-token"; + +function historyRecorder() { + const replaceState = vi.fn(); + return { history: { state: { key: "route" }, replaceState }, replaceState }; +} + +describe("consumeVerificationToken", () => { + it("returns a valid token and removes the fragment while preserving the path and query", () => { + const { history, replaceState } = historyRecorder(); + const token = "A".repeat(64); + + expect( + consumeVerificationToken( + { hash: `#token=${token}`, pathname: "/verify-email", search: "?source=mail" }, + history, + ), + ).toBe(token); + expect(replaceState).toHaveBeenCalledWith(history.state, "", "/verify-email?source=mail"); + }); + + it("clears malformed and missing tokens without returning them", () => { + for (const hash of ["#token=short", "#other=value", ""]) { + const { history, replaceState } = historyRecorder(); + expect( + consumeVerificationToken({ hash, pathname: "/verify-email", search: "" }, history), + ).toBeNull(); + expect(replaceState).toHaveBeenCalledWith(history.state, "", "/verify-email"); + } + }); + + it("consumes and removes each new link fragment opened on the same page", () => { + let hash = ""; + const listeners = new Set<() => void>(); + const state = { key: "route" }; + const browser: VerificationLinkBrowser = { + location: { + get hash() { + return hash; + }, + pathname: "/verify-email", + search: "", + }, + history: { + state, + replaceState: vi.fn((_state, _title, url) => { + hash = new URL(String(url), "https://app.test").hash; + }), + }, + addEventListener: vi.fn((_type, listener) => listeners.add(listener)), + removeEventListener: vi.fn((_type, listener) => listeners.delete(listener)), + }; + const onTokenChange = vi.fn(); + const stopWatching = watchVerificationTokenChanges(browser, onTokenChange); + const firstToken = "A".repeat(64); + const secondToken = "B".repeat(64); + + hash = `#token=${firstToken}`; + for (const listener of listeners) listener(); + expect(onTokenChange).toHaveBeenLastCalledWith(firstToken); + expect(hash).toBe(""); + + hash = `#token=${secondToken}`; + for (const listener of listeners) listener(); + expect(onTokenChange).toHaveBeenLastCalledWith(secondToken); + expect(hash).toBe(""); + + stopWatching(); + expect(listeners.size).toBe(0); + }); +}); diff --git a/frontend/src/features/confirm-email/model/consume-verification-token.ts b/frontend/src/features/confirm-email/model/consume-verification-token.ts new file mode 100644 index 0000000..3c74aa5 --- /dev/null +++ b/frontend/src/features/confirm-email/model/consume-verification-token.ts @@ -0,0 +1,35 @@ +import { VerificationToken } from "../../../shared/api/schemas"; + +type BrowserLocation = Pick; +type BrowserHistory = Pick; + +export type VerificationLinkBrowser = { + location: BrowserLocation; + history: BrowserHistory; + addEventListener: (type: "hashchange", listener: () => void) => void; + removeEventListener: (type: "hashchange", listener: () => void) => void; +}; + +/** Read the token once, then remove the full fragment from the visible history entry. */ +export function consumeVerificationToken( + location: BrowserLocation, + history: BrowserHistory, +): string | null { + const fragment = location.hash.startsWith("#") ? location.hash.slice(1) : location.hash; + const rawToken = new URLSearchParams(fragment).get("token"); + history.replaceState(history.state, "", `${location.pathname}${location.search}`); + return rawToken && VerificationToken.safeParse(rawToken).success ? rawToken : null; +} + +/** Listen for a verification link opened in the same tab after the first fragment was consumed. */ +export function watchVerificationTokenChanges( + browser: VerificationLinkBrowser, + onTokenChange: (token: string | null) => void, +): () => void { + const handleHashChange = () => { + if (!browser.location.hash) return; + onTokenChange(consumeVerificationToken(browser.location, browser.history)); + }; + browser.addEventListener("hashchange", handleHashChange); + return () => browser.removeEventListener("hashchange", handleHashChange); +} diff --git a/frontend/src/features/confirm-email/ui/confirm-email-form.module.css b/frontend/src/features/confirm-email/ui/confirm-email-form.module.css new file mode 100644 index 0000000..a0d744b --- /dev/null +++ b/frontend/src/features/confirm-email/ui/confirm-email-form.module.css @@ -0,0 +1,66 @@ +.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); +} + +.input[aria-invalid="true"] { + border-color: var(--color-danger); +} + +.hint, +.error { + font-size: var(--font-size-s); +} + +.hint { + color: var(--color-text-secondary); +} + +.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); +} diff --git a/frontend/src/features/confirm-email/ui/confirm-email-form.tsx b/frontend/src/features/confirm-email/ui/confirm-email-form.tsx new file mode 100644 index 0000000..38cca73 --- /dev/null +++ b/frontend/src/features/confirm-email/ui/confirm-email-form.tsx @@ -0,0 +1,242 @@ +import { useCallback, useEffect, useLayoutEffect, useRef, useState, type FormEvent } from "react"; +import { useConfirmEmail } from "../../../shared/api/endpoints/identity/identity"; +import { Button, ButtonLink, TextLink } from "../../../shared/ui"; +import { paths } from "../../../shared/config"; +import { + consumeVerificationToken, + watchVerificationTokenChanges, +} from "../model/consume-verification-token"; +import styles from "./confirm-email-form.module.css"; + +function confirmationError(error: unknown): { message: string; expired: boolean } { + const code = error instanceof Error && "code" in error ? String(error.code) : ""; + if (code === "verification_token_expired") { + return { message: "Срок действия ссылки истек. Запросите новое письмо.", expired: true }; + } + if (code === "verification_token_invalid") { + return { + message: + "Не удалось подтвердить почту. Проверьте введенные данные и попробуйте еще раз или запросите новое письмо.", + expired: false, + }; + } + if (code === "rate_limited") { + return { message: "Слишком много попыток. Подождите и повторите попытку.", expired: false }; + } + if (code === "csrf_check_failed") { + return { + message: "Не удалось проверить источник запроса. Обновите страницу и повторите попытку.", + expired: false, + }; + } + return { + message: "Не удалось подтвердить почту. Проверьте соединение и повторите попытку.", + expired: false, + }; +} + +type ConfirmEmailFormProps = { + onResendNeeded: () => void; + onTokenReady: () => void; + onConfirmed: () => void; +}; + +export function ConfirmEmailForm({ + onResendNeeded, + onTokenReady, + onConfirmed, +}: ConfirmEmailFormProps) { + const tokenRef = useRef(null); + const initialFragmentConsumedRef = useRef(false); + const tokenGenerationRef = useRef(0); + const { + isPending: isConfirmPending, + mutateAsync, + reset, + } = useConfirmEmail({ + mutation: { gcTime: 0 }, + }); + const [ready, setReady] = useState(false); + const [hasToken, setHasToken] = useState(false); + const [password, setPassword] = useState(""); + const [passwordError, setPasswordError] = useState(null); + const [formError, setFormError] = useState(null); + const [confirmed, setConfirmed] = useState(false); + + const handleTokenChange = useCallback( + (token: string | null) => { + tokenGenerationRef.current += 1; + tokenRef.current = token; + reset(); + setHasToken(token !== null); + setPassword(""); + setPasswordError(null); + setFormError(null); + setConfirmed(false); + if (token) onTokenReady(); + else onResendNeeded(); + }, + [onResendNeeded, onTokenReady, reset], + ); + + useLayoutEffect(() => { + if (!initialFragmentConsumedRef.current) { + initialFragmentConsumedRef.current = true; + tokenRef.current = consumeVerificationToken(window.location, window.history); + setHasToken(tokenRef.current !== null); + setReady(true); + if (tokenRef.current) onTokenReady(); + else onResendNeeded(); + } + return watchVerificationTokenChanges(window, handleTokenChange); + }, [handleTokenChange, onResendNeeded, onTokenReady]); + + useEffect( + () => () => { + tokenGenerationRef.current += 1; + reset(); + }, + [reset], + ); + + async function submit(event: FormEvent) { + event.preventDefault(); + const token = tokenRef.current; + if (!token || isConfirmPending) return; + const generation = tokenGenerationRef.current; + + const passwordLength = Array.from(password.normalize("NFKC")).length; + if (passwordLength < 1 || passwordLength > 128) { + setPasswordError( + "Введите пароль регистрации длиной от 1 до 128 символов после нормализации.", + ); + setFormError(null); + return; + } + + setPasswordError(null); + setFormError(null); + try { + await mutateAsync({ data: { token, password } }); + if (generation !== tokenGenerationRef.current) return; + reset(); + tokenRef.current = null; + setHasToken(false); + setPassword(""); + setConfirmed(true); + onConfirmed(); + } catch (error: unknown) { + if (generation !== tokenGenerationRef.current) return; + reset(); + const result = confirmationError(error); + setFormError(result.message); + if (result.expired) { + tokenRef.current = null; + setHasToken(false); + setPassword(""); + onResendNeeded(); + } else if ( + error instanceof Error && + "code" in error && + error.code === "verification_token_invalid" + ) { + setPassword(""); + onResendNeeded(); + } + } + } + + if (!ready) { + return ( +

+ Открываем безопасную ссылку... +

+ ); + } + + if (confirmed) { + return ( +
+
+ Почта подтверждена. Войдите с паролем, который вы выбрали при регистрации. После входа + сервис откроет сохраненный шаг. +
+ Перейти ко входу +
+ ); + } + + if (!hasToken) { + return ( +
+ {formError ? ( +

+ {formError} +

+ ) : ( +

+ В ссылке нет действующего токена. Укажите адрес, чтобы запросить новое письмо. +

+ )} + Перейти ко входу +
+ ); + } + + return ( +
+ {formError ? ( +

+ {formError} +

+ ) : null} +
void submit(event)} noValidate> +
+
+ + { + setPassword(event.currentTarget.value); + setPasswordError(null); + setFormError(null); + }} + /> + {passwordError ? ( +

+ {passwordError} +

+ ) : ( +

+ Для подтверждения нужно ввести пароль, указанный в этой регистрации. +

+ )} +
+
+ + Уже подтвердили? Войти +
+

+ {isConfirmPending ? "Проверяем ссылку..." : ""} +

+
+
+
+ ); +} diff --git a/frontend/src/features/register-account/index.ts b/frontend/src/features/register-account/index.ts new file mode 100644 index 0000000..1c54d0d --- /dev/null +++ b/frontend/src/features/register-account/index.ts @@ -0,0 +1,2 @@ +export { RegisterForm } from "./ui/register-form"; +export type { RegistrationDraft } from "./ui/register-form"; diff --git a/frontend/src/features/register-account/model/validation.test.ts b/frontend/src/features/register-account/model/validation.test.ts new file mode 100644 index 0000000..55ddc44 --- /dev/null +++ b/frontend/src/features/register-account/model/validation.test.ts @@ -0,0 +1,34 @@ +import { describe, expect, it } from "vitest"; +import { validateNewPassword, validateRegistration } from "./validation"; + +describe("registration validation", () => { + it("counts NFKC-normalized Unicode code points", () => { + expect(validateNewPassword("😀".repeat(15))).toBeUndefined(); + expect(validateNewPassword("12345678901234")).toContain("не менее 15"); + expect(validateNewPassword("😀".repeat(129))).toContain("не более 128"); + }); + + it("requires a valid address, scenario, and separately accepted consent", () => { + expect( + validateRegistration({ + email: "person@example.test", + password: "a secure phrase with enough length", + scenario: "candidate", + acceptedConsent: true, + }), + ).toEqual({}); + + expect( + validateRegistration({ + email: "not-an-email", + password: "a secure phrase with enough length", + scenario: "", + acceptedConsent: false, + }), + ).toEqual({ + email: "Введите корректный адрес электронной почты.", + scenario: "Выберите сценарий.", + consent: "Подтвердите согласие после прочтения текста.", + }); + }); +}); diff --git a/frontend/src/features/register-account/model/validation.ts b/frontend/src/features/register-account/model/validation.ts new file mode 100644 index 0000000..dc3a9a4 --- /dev/null +++ b/frontend/src/features/register-account/model/validation.ts @@ -0,0 +1,43 @@ +import { EmailAddress } from "../../../shared/api/schemas"; + +export type RegistrationErrors = { + email?: string; + password?: string; + scenario?: string; + consent?: string; +}; + +/** Apply the server's NFKC and Unicode code-point length rules before sending. */ +export function validateNewPassword(password: string): string | undefined { + const length = Array.from(password.normalize("NFKC")).length; + if (length < 15) { + return "Введите не менее 15 символов после нормализации."; + } + if (length > 128) { + return "Введите не более 128 символов после нормализации."; + } + return undefined; +} + +export function validateRegistration(input: { + email: string; + password: string; + scenario: string; + acceptedConsent: boolean; +}): RegistrationErrors { + const errors: RegistrationErrors = {}; + if (!EmailAddress.safeParse(input.email).success) { + errors.email = "Введите корректный адрес электронной почты."; + } + const passwordError = validateNewPassword(input.password); + if (passwordError) { + errors.password = passwordError; + } + if (input.scenario !== "candidate" && input.scenario !== "employer") { + errors.scenario = "Выберите сценарий."; + } + if (!input.acceptedConsent) { + errors.consent = "Подтвердите согласие после прочтения текста."; + } + return errors; +} diff --git a/frontend/src/features/register-account/ui/register-form.module.css b/frontend/src/features/register-account/ui/register-form.module.css new file mode 100644 index 0000000..c2f884e --- /dev/null +++ b/frontend/src/features/register-account/ui/register-form.module.css @@ -0,0 +1,150 @@ +.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); +} + +.input[aria-invalid="true"] { + border-color: var(--color-danger); +} + +.hint, +.error, +.choice-description { + color: var(--color-text-secondary); + font-size: var(--font-size-s); +} + +.error { + color: var(--color-danger); +} + +.choices { + display: grid; + gap: var(--space-3); + padding: var(--space-4); + border: var(--line-thin) solid var(--color-divider); + border-radius: var(--radius-m); +} + +.choices legend { + padding-inline: var(--space-2); + font-weight: var(--font-weight-bold); +} + +.choice { + display: grid; + grid-template-columns: auto minmax(0, 1fr); + gap: var(--space-3); + align-items: start; + min-width: 0; + padding: var(--space-3); + border: var(--line-thin) solid var(--color-divider); + border-radius: var(--radius-s); + cursor: pointer; +} + +.choice input { + width: 1.1rem; + height: 1.1rem; + margin-top: 0.2rem; + accent-color: var(--color-accent); +} + +.choice-body { + display: grid; + gap: var(--space-1); +} + +.consent { + display: grid; + gap: var(--space-3); + padding: var(--space-4); + border: var(--line-thin) solid var(--color-divider); + border-radius: var(--radius-m); + background: var(--color-surface); +} + +.consent-title { + font-size: var(--font-size-m); + font-weight: var(--font-weight-bold); +} + +.consent-text { + max-height: 16rem; + overflow: auto; + padding: var(--space-3); + border: var(--line-thin) solid var(--color-divider); + border-radius: var(--radius-s); + background: var(--color-canvas); + white-space: pre-wrap; + overflow-wrap: anywhere; +} + +.consent-choice { + display: grid; + grid-template-columns: auto minmax(0, 1fr); + gap: var(--space-3); + align-items: start; +} + +.consent-choice input { + width: 1.1rem; + height: 1.1rem; + margin-top: 0.2rem; + accent-color: var(--color-accent); +} + +.actions { + display: flex; + flex-wrap: wrap; + gap: var(--space-3); + align-items: center; +} + +.notice { + padding: var(--space-4); + border-left: var(--line-strong) solid var(--color-accent); + background: var(--color-surface); +} + +.notice p + p { + margin-top: var(--space-2); +} + +.alert { + padding: var(--space-3); + border-left: var(--line-strong) solid var(--color-danger); + background: var(--color-surface); + color: var(--color-text); +} + +.status { + min-height: 1.5em; + color: var(--color-text-secondary); +} + +@media (width >= 48rem) { + .consent-text { + max-height: 20rem; + } +} diff --git a/frontend/src/features/register-account/ui/register-form.tsx b/frontend/src/features/register-account/ui/register-form.tsx new file mode 100644 index 0000000..91ca2a9 --- /dev/null +++ b/frontend/src/features/register-account/ui/register-form.tsx @@ -0,0 +1,369 @@ +import { useEffect, useId, useRef, useState, type FormEvent } from "react"; +import { + useGetConsentText, + useRegisterAccount, +} from "../../../shared/api/endpoints/identity/identity"; +import type { Account } from "../../../shared/api/schemas"; +import { Button, ErrorState, LoadingState, TextLink } from "../../../shared/ui"; +import { paths } from "../../../shared/config"; +import { validateRegistration } from "../model/validation"; +import styles from "./register-form.module.css"; + +type Scenario = Account["scenario"]; + +export type RegistrationDraft = { + email: string; + scenario: Scenario | ""; +}; + +type RegisterFormProps = { + initialEmail?: string; + initialScenario?: Scenario | ""; + onDraftChange?: (draft: RegistrationDraft) => void; + onAccepted: (draft: RegistrationDraft) => void; +}; + +type FieldErrors = { + email?: string; + password?: string; + scenario?: string; + consent?: string; +}; + +function createIdempotencyKey(): string { + return window.crypto.randomUUID(); +} + +function registrationError(error: unknown): { + message: string; + refreshConsent: boolean; + clearIdempotencyKey: boolean; +} { + if (!(error instanceof Error) || !("code" in error)) { + return { + message: "Не удалось отправить запрос. Повторите попытку.", + refreshConsent: false, + clearIdempotencyKey: false, + }; + } + const code = String(error.code); + if (code === "validation_failed" && "fieldErrors" in error) { + const fields = error.fieldErrors as readonly { pointer?: string }[]; + if (fields.some((field) => field.pointer === "/consent_c1/text_version")) { + return { + message: "Текст согласия обновился. Прочитайте новую версию и подтвердите ее.", + refreshConsent: true, + clearIdempotencyKey: true, + }; + } + if (fields.some((field) => field.pointer === "/password")) { + return { + message: "Этот пароль не подходит. Выберите другой пароль и повторите попытку.", + refreshConsent: false, + clearIdempotencyKey: false, + }; + } + } + if (code === "rate_limited") { + return { + message: "Слишком много запросов. Подождите и попробуйте снова.", + refreshConsent: false, + clearIdempotencyKey: false, + }; + } + if (code === "idempotency_key_reused") { + return { + message: "Не удалось повторить запрос. Отправьте форму еще раз.", + refreshConsent: false, + clearIdempotencyKey: true, + }; + } + if (code === "csrf_check_failed") { + return { + message: "Не удалось проверить источник запроса. Обновите страницу и попробуйте снова.", + refreshConsent: false, + clearIdempotencyKey: false, + }; + } + return { + message: "Не удалось отправить запрос. Повторите попытку.", + refreshConsent: false, + clearIdempotencyKey: false, + }; +} + +function errorId(id: string, name: keyof FieldErrors): string { + return `${id}-${name}-error`; +} + +export function RegisterForm({ + initialEmail = "", + initialScenario = "", + onDraftChange, + onAccepted, +}: RegisterFormProps) { + const id = useId(); + const consent = useGetConsentText("c1"); + const registration = useRegisterAccount({ mutation: { gcTime: 0 } }); + const idempotencyKey = useRef(null); + const [email, setEmail] = useState(initialEmail); + const [password, setPassword] = useState(""); + const [scenario, setScenario] = useState(initialScenario); + const [acceptedVersion, setAcceptedVersion] = useState(null); + const [fieldErrors, setFieldErrors] = useState({}); + const [formError, setFormError] = useState(null); + const previousConsentVersion = useRef(undefined); + const currentConsentVersion = consent.data?.text_version; + + useEffect(() => { + if ( + currentConsentVersion && + previousConsentVersion.current && + currentConsentVersion !== previousConsentVersion.current + ) { + idempotencyKey.current = null; + setAcceptedVersion(null); + setFormError("Текст согласия обновился. Прочитайте новую версию и подтвердите ее."); + } + if (currentConsentVersion) previousConsentVersion.current = currentConsentVersion; + }, [currentConsentVersion]); + + function changed() { + idempotencyKey.current = null; + setFieldErrors({}); + setFormError(null); + } + + async function submit(event: FormEvent) { + event.preventDefault(); + if (registration.isPending || !consent.data || consent.isError) return; + + const errors = validateRegistration({ + email, + password, + scenario, + acceptedConsent: Boolean(consent.data && acceptedVersion === consent.data.text_version), + }); + setFieldErrors(errors); + setFormError(null); + if (Object.keys(errors).length > 0 || !scenario) return; + + const body = { + email, + password, + scenario, + consent_c1: { text_version: consent.data.text_version, accepted: true as const }, + }; + idempotencyKey.current ??= createIdempotencyKey(); + + try { + await registration.mutateAsync({ + data: body, + headers: { "Idempotency-Key": idempotencyKey.current }, + }); + setPassword(""); + onAccepted({ email, scenario }); + } catch (error: unknown) { + const result = registrationError(error); + setFormError(result.message); + if (result.clearIdempotencyKey) idempotencyKey.current = null; + if (result.refreshConsent) { + setAcceptedVersion(null); + await consent.refetch(); + } + } + } + + return ( +
void submit(event)} noValidate> + {consent.isPending ? : null} + {consent.isError ? ( + void consent.refetch()} + title="Не удалось загрузить текст согласия" + /> + ) : null} + +
+ + { + changed(); + const nextEmail = event.currentTarget.value; + setEmail(nextEmail); + onDraftChange?.({ email: nextEmail, scenario }); + }} + /> + {fieldErrors.email ? ( +

+ {fieldErrors.email} +

+ ) : null} +
+ +
+ + { + changed(); + setPassword(event.currentTarget.value); + }} + /> +

+ От 15 до 128 символов после нормализации. Допустима фраза из нескольких слов. +

+ {fieldErrors.password ? ( +

+ {fieldErrors.password} +

+ ) : null} +
+ +
+ Сценарий + {( + [ + ["candidate", "Кандидат", "Ищу работу и хочу подтвердить навыки."], + ["employer", "Работодатель", "Представляю компанию и ищу кандидатов."], + ] as const + ).map(([value, label, description]) => ( + + ))} + {fieldErrors.scenario ? ( +

+ {fieldErrors.scenario} +

+ ) : null} +
+ + {consent.data ? ( +
+ +

Версия текста: {consent.data.text_version}

+
+ {consent.data.text} +
+ + {acceptedVersion && acceptedVersion !== currentConsentVersion ? ( + + ) : null} + {fieldErrors.consent ? ( +

+ {fieldErrors.consent} +

+ ) : null} +
+ ) : null} + + {formError ? ( +

+ {formError} +

+ ) : null} + {consent.isError && consent.error ? ( +

Без опубликованного текста C1 отправить регистрацию нельзя.

+ ) : null} + +
+ + Уже есть аккаунт? Войти +
+

+ {registration.isPending ? "Отправляем запрос на регистрацию..." : ""} +

+ + ); +} diff --git a/frontend/src/features/resend-email-verification/index.ts b/frontend/src/features/resend-email-verification/index.ts new file mode 100644 index 0000000..04918d9 --- /dev/null +++ b/frontend/src/features/resend-email-verification/index.ts @@ -0,0 +1 @@ +export { ResendVerificationForm } from "./ui/resend-verification-form"; diff --git a/frontend/src/features/resend-email-verification/ui/resend-verification-form.module.css b/frontend/src/features/resend-email-verification/ui/resend-verification-form.module.css new file mode 100644 index 0000000..028fdb4 --- /dev/null +++ b/frontend/src/features/resend-email-verification/ui/resend-verification-form.module.css @@ -0,0 +1,48 @@ +.form { + display: grid; + gap: var(--space-3); + min-width: 0; +} + +.field { + display: grid; + gap: var(--space-2); +} + +.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); +} + +.input[aria-invalid="true"] { + border-color: var(--color-danger); +} + +.error, +.message { + font-size: var(--font-size-s); +} + +.error { + color: var(--color-danger); +} + +.message { + min-height: 1.5em; + color: var(--color-text-secondary); +} + +.actions { + display: flex; + flex-wrap: wrap; + gap: var(--space-3); + align-items: center; +} diff --git a/frontend/src/features/resend-email-verification/ui/resend-verification-form.tsx b/frontend/src/features/resend-email-verification/ui/resend-verification-form.tsx new file mode 100644 index 0000000..cf08e54 --- /dev/null +++ b/frontend/src/features/resend-email-verification/ui/resend-verification-form.tsx @@ -0,0 +1,87 @@ +import { useId, useState, type FormEvent } from "react"; +import { useResendEmailVerification } from "../../../shared/api/endpoints/identity/identity"; +import { EmailAddress } from "../../../shared/api/schemas"; +import { Button } from "../../../shared/ui"; +import styles from "./resend-verification-form.module.css"; + +type ResendVerificationFormProps = { + initialEmail?: string; +}; + +export function ResendVerificationForm({ initialEmail = "" }: ResendVerificationFormProps) { + const id = useId(); + const resend = useResendEmailVerification({ mutation: { gcTime: 0 } }); + const [email, setEmail] = useState(initialEmail); + const [fieldError, setFieldError] = useState(null); + const [message, setMessage] = useState(""); + + async function submit(event: FormEvent) { + event.preventDefault(); + if (resend.isPending) return; + + if (!EmailAddress.safeParse(email).success) { + setFieldError("Введите корректный адрес электронной почты."); + setMessage(""); + return; + } + + setFieldError(null); + setMessage(""); + try { + await resend.mutateAsync({ data: { email } }); + setMessage( + "Запрос принят. Если для этого адреса доступна повторная отправка, письмо будет отправлено.", + ); + } catch (error: unknown) { + const code = error instanceof Error && "code" in error ? String(error.code) : ""; + if (code === "rate_limited") { + setMessage("Слишком много запросов. Подождите и повторите попытку."); + } else if (code === "csrf_check_failed") { + setMessage("Не удалось проверить источник запроса. Обновите страницу и повторите попытку."); + } else { + setMessage("Не удалось отправить запрос. Повторите попытку."); + } + } + } + + return ( +
void submit(event)} noValidate> +
+ + { + setEmail(event.currentTarget.value); + setFieldError(null); + setMessage(""); + }} + /> + {fieldError ? ( +

+ {fieldError} +

+ ) : null} +
+
+ +
+

+ {resend.isPending ? "Отправляем запрос..." : message} +

+
+ ); +} diff --git a/frontend/src/features/sign-in/index.ts b/frontend/src/features/sign-in/index.ts new file mode 100644 index 0000000..fa3d8d6 --- /dev/null +++ b/frontend/src/features/sign-in/index.ts @@ -0,0 +1 @@ +export { SignInForm } from "./ui/sign-in-form"; diff --git a/frontend/src/features/sign-in/model/establish-session.test.ts b/frontend/src/features/sign-in/model/establish-session.test.ts new file mode 100644 index 0000000..a137f0d --- /dev/null +++ b/frontend/src/features/sign-in/model/establish-session.test.ts @@ -0,0 +1,38 @@ +import { QueryClient } from "@tanstack/react-query"; +import { describe, expect, it } from "vitest"; +import { getGetCurrentSessionQueryKey } from "../../../shared/api/endpoints/identity/identity"; +import { establishSession } from "./establish-session"; + +describe("establishSession", () => { + it("removes cached account data before keeping the new session in memory", () => { + const queryClient = new QueryClient(); + const previousProfileKey = ["/api/v1/candidate/profile"] as const; + const nextSession = { + account: { + id: "22222222-2222-4222-8222-222222222222", + email: "new@example.test", + email_verified: true, + scenario: "employer", + onboarding_step: "employer_company", + created_at: "2026-10-07T12:00:00Z", + }, + csrf_token: "B".repeat(43), + } as const; + + queryClient.setQueryData(previousProfileKey, { + accountId: "11111111-1111-4111-8111-111111111111", + privateNotes: ["previous account data"], + }); + queryClient.setQueryData(getGetCurrentSessionQueryKey(), { + ...nextSession, + account: { ...nextSession.account, id: "11111111-1111-4111-8111-111111111111" }, + csrf_token: "A".repeat(43), + }); + + establishSession(queryClient, nextSession); + + expect(queryClient.getQueryData(previousProfileKey)).toBeUndefined(); + expect(queryClient.getQueryData(getGetCurrentSessionQueryKey())).toEqual(nextSession); + expect(queryClient.getQueryCache().getAll()).toHaveLength(1); + }); +}); diff --git a/frontend/src/features/sign-in/model/establish-session.ts b/frontend/src/features/sign-in/model/establish-session.ts new file mode 100644 index 0000000..24d74aa --- /dev/null +++ b/frontend/src/features/sign-in/model/establish-session.ts @@ -0,0 +1,9 @@ +import type { QueryClient } from "@tanstack/react-query"; +import { getGetCurrentSessionQueryKey } from "../../../shared/api/endpoints/identity/identity"; +import type { Session } from "../../../shared/api/schemas"; + +/** Drop data from any previous account before caching the new in-memory session. */ +export function establishSession(queryClient: QueryClient, session: Session): void { + queryClient.clear(); + queryClient.setQueryData(getGetCurrentSessionQueryKey(), session); +} diff --git a/frontend/src/features/sign-in/ui/sign-in-form.module.css b/frontend/src/features/sign-in/ui/sign-in-form.module.css new file mode 100644 index 0000000..c8b43da --- /dev/null +++ b/frontend/src/features/sign-in/ui/sign-in-form.module.css @@ -0,0 +1,60 @@ +.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); +} + +.input[aria-invalid="true"] { + border-color: var(--color-danger); +} + +.error, +.hint { + font-size: var(--font-size-s); +} + +.error, +.alert { + color: var(--color-danger); +} + +.alert { + padding: var(--space-3); + border-left: var(--line-strong) solid var(--color-danger); + background: var(--color-surface); +} + +.hint { + color: var(--color-text-secondary); +} + +.actions { + display: flex; + flex-wrap: wrap; + gap: var(--space-3); + align-items: center; +} + +.status { + min-height: 1.5em; + color: var(--color-text-secondary); +} diff --git a/frontend/src/features/sign-in/ui/sign-in-form.tsx b/frontend/src/features/sign-in/ui/sign-in-form.tsx new file mode 100644 index 0000000..e5bbc86 --- /dev/null +++ b/frontend/src/features/sign-in/ui/sign-in-form.tsx @@ -0,0 +1,153 @@ +import { useQueryClient } from "@tanstack/react-query"; +import { useId, useState, type FormEvent } from "react"; +import { useNavigate } from "react-router-dom"; +import { ApiRequestError } from "../../../shared/api"; +import { useLogin } from "../../../shared/api/endpoints/identity/identity"; +import { EmailAddress } from "../../../shared/api/schemas"; +import { paths } from "../../../shared/config"; +import { getOnboardingDestination } from "../../../entities/session"; +import { Button, TextLink } from "../../../shared/ui"; +import { establishSession } from "../model/establish-session"; +import styles from "./sign-in-form.module.css"; + +type SignInFormProps = { + onUnverified: (email: string) => void; + onSignedIn: () => void; +}; + +export function SignInForm({ onUnverified, onSignedIn }: SignInFormProps) { + const id = useId(); + const queryClient = useQueryClient(); + const navigate = useNavigate(); + const login = useLogin({ mutation: { gcTime: 0 } }); + const [email, setEmail] = useState(""); + const [password, setPassword] = useState(""); + const [fieldError, setFieldError] = useState<{ email?: string; password?: string }>({}); + const [formError, setFormError] = useState(null); + + async function submit(event: FormEvent) { + event.preventDefault(); + if (login.isPending) return; + + const errors: typeof fieldError = {}; + if (!EmailAddress.safeParse(email).success) { + errors.email = "Введите корректный адрес электронной почты."; + } + const passwordLength = Array.from(password.normalize("NFKC")).length; + if (passwordLength < 1 || passwordLength > 128) { + errors.password = "Введите пароль длиной не более 128 символов."; + } + setFieldError(errors); + setFormError(null); + if (Object.keys(errors).length > 0) return; + + try { + const session = await login.mutateAsync({ data: { email, password } }); + establishSession(queryClient, session); + setPassword(""); + onSignedIn(); + await navigate(getOnboardingDestination(session.account), { replace: true }); + } catch (error: unknown) { + if (error instanceof ApiRequestError && error.code === "email_not_verified") { + onUnverified(email); + setFormError("Почта не подтверждена. Запросите новое письмо и перейдите по ссылке."); + } else if (error instanceof ApiRequestError && error.code === "invalid_credentials") { + setFormError("Не удалось войти. Проверьте адрес и пароль."); + } else if (error instanceof ApiRequestError && error.code === "rate_limited") { + setFormError("Слишком много попыток. Подождите и попробуйте снова."); + } else if (error instanceof ApiRequestError && error.code === "csrf_check_failed") { + setFormError( + "Не удалось проверить источник запроса. Обновите страницу и попробуйте снова.", + ); + } else { + setFormError("Не удалось выполнить вход. Проверьте соединение и повторите попытку."); + } + } + } + + function changed() { + setFieldError({}); + setFormError(null); + onUnverified(""); + } + + return ( +
+
void submit(event)} noValidate> +
+
+ + { + changed(); + setEmail(event.currentTarget.value); + }} + /> + {fieldError.email ? ( +

+ {fieldError.email} +

+ ) : null} +
+ +
+ + { + changed(); + setPassword(event.currentTarget.value); + }} + /> + {fieldError.password ? ( +

+ {fieldError.password} +

+ ) : null} +
+ + {formError ? ( +

+ {formError} +

+ ) : null} + +
+ + Создать аккаунт +
+

+ {login.isPending ? "Проверяем учетные данные..." : ""} +

+
+
+
+ ); +} diff --git a/frontend/src/pages/auth/index.ts b/frontend/src/pages/auth/index.ts new file mode 100644 index 0000000..b447e2f --- /dev/null +++ b/frontend/src/pages/auth/index.ts @@ -0,0 +1,3 @@ +export { LoginPage } from "./ui/login-page"; +export { RegisterPage } from "./ui/register-page"; +export { VerifyEmailPage } from "./ui/verify-email-page"; diff --git a/frontend/src/pages/auth/model/registration-context.ts b/frontend/src/pages/auth/model/registration-context.ts new file mode 100644 index 0000000..97e8634 --- /dev/null +++ b/frontend/src/pages/auth/model/registration-context.ts @@ -0,0 +1,48 @@ +import type { RegistrationDraft } from "../../../features/register-account"; + +const storageKey = "lincodex-registration-context"; + +export type RegistrationContext = RegistrationDraft & { + accepted: boolean; +}; + +const emptyContext: RegistrationContext = { email: "", scenario: "", accepted: false }; + +export function readRegistrationContext(): RegistrationContext { + if (typeof window === "undefined") return emptyContext; + try { + const raw = window.sessionStorage.getItem(storageKey); + if (!raw) return emptyContext; + const parsed: unknown = JSON.parse(raw); + if (typeof parsed !== "object" || parsed === null) return emptyContext; + const value = parsed as Record; + const email = typeof value.email === "string" ? value.email : ""; + const scenario = + value.scenario === "candidate" || value.scenario === "employer" ? value.scenario : ""; + return { + email, + scenario, + accepted: value.accepted === true && email.length > 0 && scenario !== "", + }; + } catch { + return emptyContext; + } +} + +export function writeRegistrationContext(context: RegistrationContext): void { + if (typeof window === "undefined") return; + try { + window.sessionStorage.setItem(storageKey, JSON.stringify(context)); + } catch { + // Registration remains usable when the browser blocks session storage. + } +} + +export function clearRegistrationContext(): void { + if (typeof window === "undefined") return; + try { + window.sessionStorage.removeItem(storageKey); + } catch { + // Registration remains usable when the browser blocks session storage. + } +} diff --git a/frontend/src/pages/auth/ui/login-page.tsx b/frontend/src/pages/auth/ui/login-page.tsx new file mode 100644 index 0000000..3800c02 --- /dev/null +++ b/frontend/src/pages/auth/ui/login-page.tsx @@ -0,0 +1,26 @@ +import { useCallback, useState } from "react"; +import { ResendVerificationForm } from "../../../features/resend-email-verification"; +import { SignInForm } from "../../../features/sign-in"; +import { Page, Section } from "../../../shared/ui"; +import { clearRegistrationContext } from "../model/registration-context"; + +export function LoginPage() { + const [unverifiedEmail, setUnverifiedEmail] = useState(""); + const clearPendingRegistration = useCallback(() => { + setUnverifiedEmail(""); + clearRegistrationContext(); + }, []); + + return ( + +
+ +
+ {unverifiedEmail ? ( +
+ +
+ ) : null} +
+ ); +} diff --git a/frontend/src/pages/auth/ui/register-page.tsx b/frontend/src/pages/auth/ui/register-page.tsx new file mode 100644 index 0000000..4bd8558 --- /dev/null +++ b/frontend/src/pages/auth/ui/register-page.tsx @@ -0,0 +1,68 @@ +import { useState } from "react"; +import { RegisterForm, type RegistrationDraft } from "../../../features/register-account"; +import { ResendVerificationForm } from "../../../features/resend-email-verification"; +import { Button, Page, Section, TextLink } from "../../../shared/ui"; +import { paths } from "../../../shared/config"; +import { + clearRegistrationContext, + readRegistrationContext, + writeRegistrationContext, + type RegistrationContext, +} from "../model/registration-context"; + +function scenarioLabel(scenario: RegistrationDraft["scenario"]): string { + return scenario === "employer" ? "работодатель" : "кандидат"; +} + +export function RegisterPage() { + const [context, setContext] = useState(readRegistrationContext); + + function saveDraft(draft: RegistrationDraft) { + const next = { ...draft, accepted: false }; + setContext(next); + writeRegistrationContext(next); + } + + function markAccepted(draft: RegistrationDraft) { + const next = { ...draft, accepted: true }; + setContext(next); + writeRegistrationContext(next); + } + + function startAgain() { + clearRegistrationContext(); + setContext({ email: "", scenario: "", accepted: false }); + } + + return ( + + {context.accepted ? ( +
+
+

+ Если для этого адреса требуется подтверждение, письмо будет отправлено. Выбранный + сценарий: {scenarioLabel(context.scenario)}. +

+ + Перейти ко входу + +
+
+ ) : ( +
+ +
+ )} +
+ ); +} diff --git a/frontend/src/pages/auth/ui/verify-email-page.tsx b/frontend/src/pages/auth/ui/verify-email-page.tsx new file mode 100644 index 0000000..5db07ba --- /dev/null +++ b/frontend/src/pages/auth/ui/verify-email-page.tsx @@ -0,0 +1,35 @@ +import { useCallback, useState } from "react"; +import { ConfirmEmailForm } from "../../../features/confirm-email"; +import { ResendVerificationForm } from "../../../features/resend-email-verification"; +import { Page, Section } from "../../../shared/ui"; +import { clearRegistrationContext } from "../model/registration-context"; + +export function VerifyEmailPage() { + const [needsResend, setNeedsResend] = useState(false); + const requestResend = useCallback(() => setNeedsResend(true), []); + const linkReady = useCallback(() => setNeedsResend(false), []); + const finishConfirmation = useCallback(() => { + setNeedsResend(false); + clearRegistrationContext(); + }, []); + + return ( + +
+ +
+ {needsResend ? ( +
+ +
+ ) : null} +
+ ); +} diff --git a/frontend/src/pages/candidate-onboarding/index.ts b/frontend/src/pages/candidate-onboarding/index.ts new file mode 100644 index 0000000..9b60bc5 --- /dev/null +++ b/frontend/src/pages/candidate-onboarding/index.ts @@ -0,0 +1 @@ +export { CandidateOnboardingPage } from "./ui/candidate-onboarding-page"; diff --git a/frontend/src/pages/candidate-onboarding/ui/candidate-onboarding-page.tsx b/frontend/src/pages/candidate-onboarding/ui/candidate-onboarding-page.tsx new file mode 100644 index 0000000..14216b0 --- /dev/null +++ b/frontend/src/pages/candidate-onboarding/ui/candidate-onboarding-page.tsx @@ -0,0 +1,48 @@ +import { Navigate } from "react-router-dom"; +import { useGetCurrentSession } from "../../../shared/api/endpoints/identity/identity"; +import { getOnboardingDestination } from "../../../entities/session"; +import { paths } from "../../../shared/config"; +import { LoadingState, Page, Section, StatusView } from "../../../shared/ui"; + +export function CandidateOnboardingPage() { + const session = useGetCurrentSession(); + if (!session.data) return ; + + const { onboarding_step: step, scenario } = session.data.account; + if (scenario !== "candidate") { + return ( + + ); + } + if (step !== "candidate_consents" && step !== "candidate_questionnaire") { + const destination = getOnboardingDestination(session.data.account); + if (destination === paths.candidate.onboarding) { + return ( + + ); + } + return ; + } + + const stepTitle = step === "candidate_consents" ? "Согласия" : "Анкета"; + const description = + step === "candidate_consents" + ? "Следующий сохраненный шаг - согласия кандидата. Согласие C1 уже было показано отдельно при регистрации." + : "Следующий сохраненный шаг - анкета кандидата. После ее сохранения сервер откроет следующий этап."; + + return ( + +
+

Этот шаг сохранен в аккаунте и будет открыт после следующего входа.

+
+
+ ); +}