# Email codes and proofs (backend F7, stage 2)

A one-time code proves that a person can read an address. It is a general mechanism, built first for one purpose: "this address
already takes part in this poll". Plan row: `V3-PARITY-PLAN.md` 9.2. The UI side (code dialog, choice, answer comparison) was
built earlier in `frontend-v3` (`utils/emailCode.ts`, `composables/useEmailCode.ts`, `components/EmailCodeDialog.vue`); the
server side is described here. The original request is finding F7 in `docs/archive/rewrite-repo/docs/kulibri-backend-befunde_1.md`.

## The problem

Someone who signs up through a poll link with an address that already takes part in that poll could use the address freely:
nothing asked, a second row was created, and a new personal link was mailed. Classic asks "continue with the existing one or
create a new one?", but it does so by looking the address up with no proof, which shows other people's rows and links to anybody.

The rule now (new UI only; classic keeps its dialog until it is retired):

> An address that already takes part in a poll may be used again only with proof. One address may have several participants
> (a parent signing up children): after proof the person chooses, the server never refuses a new row.

On the production copy of 6 Oct 2026, 3,501 poll-and-address pairs have more than one participant (1,824 polls), so this case is common.

## Proof is any of these

1. a verified code: a signed `emailProof` for this poll and address (below);
2. the personal link of a row with this address: `viaLink`, the id of an invitation or participant of this poll with this address;
3. a signed-in account whose address is this one and is verified (`email_verified_at`);
4. **a row of this browser with this address**: the cookie the server sets (below), so a returning visitor needs no new code;
5. being an admin of the poll (owner or sub-admin by login, or the admin key as `key`): `PollAdminAccess`.

Addresses are compared trimmed and case-insensitive.

## The routes

| Route | What it does |
|---|---|
| `POST /api/poll/{id}/email-code` `{ email }` | Mails a fresh six-digit code. **202** without content, whether or not the address takes part, so nothing is revealed. Invalid address or unknown poll: 422. A limit: 429. |
| `POST /api/poll/{id}/email-code/verify` `{ email, code }` | Correct: **200** `{ participants: [{ id, name }], emailProof }`, the participants of this address in this poll (id and name only, no address, no answers). Wrong: **422** `emailCode.invalid` (counted). Expired, used or locked: **422** `emailCode.expired`. Limit: 429. |
| `POST /api/invitation` with `selfRegistration`, `requireEmailProof: true` | Address takes part and no proof: **409** `{ error: "participant.emailTaken" }`, nothing is created (no row, no invitation, no account, no contact), and a code is mailed. Otherwise as before. Also reads `viaLink` and `emailProof`. Without `requireEmailProof` (classic) nothing changes. |

## How it works

- **`App\Services\EmailChallenges`** knows no poll. A challenge is for a **purpose** (`poll-address` today), an **address** and a **scope** (the poll id). `issue()` creates a code and stores only its hash (HMAC with the application key); `verify()` checks it; `proof()` signs a proof; `checkProof()` is the only place that accepts one.
- **Limits.** A code is valid 15 minutes, single use, locked after 5 wrong tries; a newer code replaces the older ones (an older code then counts as a wrong one). A proof is valid **30 minutes** and works only for the exact purpose, address and scope it was made for. The proof is an HMAC over its content, so it needs no table.
- **Rate limits** on sending (`PollAddressCheck::sendCode`): 3 an hour per address and poll, 10 per IP, 60 per poll; checking: 30 an hour per IP (`email-code-verify`) plus the code's own lock.
- **`App\Services\PollAddressCheck`** holds the poll rule: which participants an address has, whether the caller has proof, and sending the code mail. **`PollAdminAccess`** is the shared admin check (also used by `cancelBooking` and the waitlist decision).
- **Table** `email_challenges` (purpose, email, scope_id, code_hash, attempts, expires_at, used_at, ip); the command `email-challenges:prune` deletes expired and used rows daily (03:30, GDPR).
- **Mail** from the generic notification template with `emailCodeTitle` / `emailCodeContent` (de, en); the code is in the text, nothing about who takes part is.

Deploy: the migration `create_email_challenges_table` must be run by hand (`php artisan migrate`); the deploy role does not.

## The rows of this browser (cookie)

Decision of 17 Oct: nothing is remembered beyond the flow as a longer-lived proof. Instead, once a person has signed up or confirmed an address, the browser is **recognised by a cookie set by the server** (`App\Services\RowsCookie`).

- Name `kulibri_rows`. It lists, per poll, the participant ids this browser created for itself or confirmed with a code. Nothing else is in it.
- **Encrypted and authenticated** with the application key (Laravel `Crypt`), so it cannot be read or edited, **HttpOnly** (no script reads it), `SameSite=Lax`, `Secure` on https, **one year**. At most 20 rows per poll and 100 polls (the oldest drop out). The lifetime is a constant (`RowsCookie::MINUTES`); the product owner may change it.
- It is encrypted by the service itself and listed in `EncryptCookies::$except`, so it works also for requests the cookie middleware of the api group skips (that middleware applies only to "stateful" Sanctum requests). A request that sends no cookie, or a changed one, simply has no rows.
- **Set when** a visitor signs up for themselves (`POST /invitation` with `selfRegistration`, and `POST /poll/{id}`, which classic uses without an address): the new row is added. **After a verified code** (`email-code/verify`): every row of the address is added. **Never** for an admin who adds somebody else (`PollAdminAccess`).
- **Read by** `PollAddressCheck::hasProof`: if the browser holds a row of this poll that has this address, no code is needed. Another address, another poll, a forged or changed cookie do not count.
- **`localStorage` stays the shared record of both UIs.** Classic and the new UI keep editing the same participants through `localStorage['kulibri.participants']` (same key, same shape `{ poll, participant, invitation }`) and `kulibri-pid-{poll}`; a row made in one is known to the other. The cookie replaces none of it. It is only the server's proof for the sign-up check, so the server does not have to trust `localStorage` (the ids in it are public and editable). Classic does not know the cookie, and the new UI does not need it to edit a row. Side effect: a row classic made in this browser is not in the cookie, so the first sign-up here with that address asks for a code once; after the code the cookie holds every row of the address. When classic is retired, the server's answer (F8, `accessibleParticipantIds`) can replace the `localStorage` lists.
- It is the carrier that finding F8 asks for. It does not yet protect `POST /v2/participant/{id}` and the other write routes; they still check nothing (F7 point 4, F8 point 4). The next step is to let them accept the cookie (and the proof) for the row they change.
- Privacy: functional cookie, only ids per poll, no personal data; it should be named in the privacy notice (the product owner decides the wording).

## Adding another purpose

Pick a purpose name and a scope, send the code with `issue()` (with its own limits and mail text), let a route return `proof()` after `verify()`, and accept the proof with `checkProof()` for exactly that purpose, address and scope. Nothing else changes. Candidates (not built; each needs its own decision): recovering a link ("send me my link"), changing a participant's address (confirm the new one), confirming an address before notifications go to an anonymous participant, the reply address of a message to the admin.

## Not done yet (from the finding F7)

- Point 4: `POST /v2/participant/{id}` accepts an `emailProof` ("continue as an existing participant"). Today this route checks nothing at all (F8), so a proof gains nothing there yet.
- Point 5: `POST /participant/email/{id}` (classic's open lookup, which returns participants with their invitations) for admins only. It would change classic's dialog for visitors, so it waits for the decision on classic.
- Point 6: the mail for a new address is built by the server instead of taking `subject` and `message` from the client (anyone can send any text to any address through the kulibri sender).
- Point 7: a limit on new addresses per device and poll.
- ~~Remembering the proof on the device~~: decided against (17 Oct). The cookie above recognises the browser instead. A one-tap link in the mail instead of typing the code is still an option for later.

## Tests

`tests/Feature/RowsCookieTest.php` (9: the cookie reads back what it wrote and nothing else, adds and keeps the newest, is HttpOnly/Lax/one year; set for a visitor who signs up (both routes), not for an admin, after a verified code with all rows of the address; a row of this browser replaces the code, and does not for another address or poll or a forged cookie). `tests/Feature/EmailChallengesTest.php` (10: single use, only the hash stored, address comparison, 5 tries lock, 15 minutes, newer replaces older, purpose/address/scope binding, proof binding and 30 minutes, forged proofs, prune) and `tests/Feature/PollAddressCodeTest.php` (15: same answer for known and unknown addresses, invalid address, limits, the participants returned, wrong and locked codes, a code of another poll, 409 without proof with nothing created, new address and classic unchanged, a verified code lets a second participant use the address, a proof for another address, a link of a row with the address or another address, signed-in verified and unverified accounts, the owner). With each rule switched off, its tests fail.
