feat(assessment): record capture hints and keep one window per attempt

This commit is contained in:
shira committed 2026-10-11 13:16:52 +03:00
1 parent c975a0d506
commit bb917bf62e
108 files changed
+6649 -139

No files matched your search

+15
View File
@@ -710,6 +710,21 @@ Implemented for real attempts (root and corrective). A training run (`demo_expre
- Accessibility. Some speech synthesizers and braille displays may announce zero-width characters or break a word at them; this was not tested with a real screen reader. The page therefore puts every run of invisible characters in an `aria-hidden` element: the accessibility tree holds the words only (a Playwright check reads the tree with `ariaSnapshot`, and a Vitest check strips the hidden elements from the markup), while the document keeps the characters so that anything copied from it carries the mark. The wordings are ordinary words, and no whitespace variants are used, because a non-breaking space is not guaranteed to be silent everywhere.
- What it does not do. A screenshot, a photo of the screen, or retyping cannot be prevented in a browser. The watermark is evidence for a manual review and an appeal, never an automatic decision; no operation shows it to an employer, and the candidate sees only the code of their own attempt.
### Capture hints, one open window, and what they cannot do
Implemented for real attempts (root and corrective). A training run (`demo_express`) has none of it. Hardened proctoring here has no camera, no microphone, no screen recording, no screenshots, and no clipboard contents; it consists of weak signals for a manual review and one rule about open windows. Code: `backend/internal/domain/assessment_signal.go`, `assessment_signal_review.go`, `assessment_signal_policy.go`, and `assessment_work_lease.go`; `backend/internal/usecase/assessment/work_session.go` and the observer in `signal_review.go`; migration `backend/db/migrations/00050_add_assessment_work_leases_and_capture_signals.sql`; the operations `HoldMyAssessmentWorkSession` and `ReleaseMyAssessmentWorkSession`; and `frontend/src/features/assessment-signals/` and `frontend/src/features/assessment-work-session/`.
- A screenshot or a phone photo cannot be prevented. A browser page cannot block the operating system or another program from capturing the screen, cannot see a camera, and cannot see a second device, a remote desktop, or a virtual machine. The page therefore never tries: it does not cancel a key, does not blank the page on a key, and does not read any image. What it can do is report that a screenshot key was pressed, tie a leaked statement or screenshot back to its attempt (see [Watermark of the task text](#watermark-of-the-task-text)), and send both to a manual review.
- Signals lead to a review and an appeal, never to an automatic downgrade. The signals only raise the review band, which changes no result, category, or quota; the employer never sees a signal or a band, and the candidate sees no band. Notice version 4 says all of this plainly.
- Screenshot keys. The page reports `screenshot_key` when it sees PrintScreen (also with Alt), Cmd+Shift+3, 4, or 5 (macOS), or Win+Shift+S, on the key press or release, once per second at most. The operating system takes many of these keys before the page, a key-less screenshot sends nothing, and holding a key is not told from pressing it, so the event proves only that a key was pressed. It carries the item and a client timestamp and no measurement.
- Developer tools. The page reports `devtools_open` when the outer window becomes more than 160 px larger than the page in width or height, which is what a docked panel does, on a resize and on a two-second timer, at most once per minute. It is a heuristic with false positives (a sidebar, zoom, a resized window) and false negatives (a detached panel, other windows), so it too is only a weak hint.
- Policy and band. Both kinds are stored as events (the check constraints of `assessment_signal_events` allow them without a measurement) and counted per attempt (`client_screenshot_keys`, `client_devtools_opens` in `assessment_attempt_reviews`). Thresholds are optional fields of the policy section `assessment.signals`: `client_screenshot_keys_attention` and `client_devtools_attention` are client thresholds, so they raise a normal band to attention and never above it, and `extra_agents_attention` with `extra_agents_review` joins the weak group of parallel sessions and extra networks, which alone reaches attention at most and review only beside a strong signal. A zero or absent threshold leaves the signal out, so a version published before these fields keeps its band, its document, and its content hash (a test checks that its document does not contain the new keys and re-encodes unchanged). The demo policies are not edited; `DemoAssessmentSignalPolicyWithCaptureHints` in `assessment_signal_policy.go` lists agreed starting values (three screenshot keys, one detection, two extra User-Agents), which no study supports, and the integration test publishes them in its own policy version.
- User-Agent digest. The HTTP boundary cuts the User-Agent to 512 bytes and hands it to the usecase, which stores only `HMAC-SHA-256` of it under a key derived from `IDENTITY_KEY_SECRET` (label `lincodex/assessment/signal-agent/v1`) bound to the attempt, in the new column `agent_digest` of `assessment_attempt_origin_marks`. The raw value is never stored or logged. A mark is written when the session, the network, or the User-Agent differs from the last mark, so the list stays short; `extra_agents` counts the distinct digests beyond the first. A browser that updates itself during an attempt, or a candidate who moves to another device, adds one, so it is a weak signal.
- One open window. `assessment_attempt_work_leases` holds one row per real attempt: a keyed digest of an identifier that each open page generates when it loads (`X-Attempt-Client`, 16 to 64 characters of `A-Za-z0-9_-`), when it took the session, when it last renewed it, and when it released it. `PUT .../work-session` holds or renews the session for 120 seconds (`domain.AssessmentWorkLeaseDuration`) and tells the page to renew every 15 seconds; `DELETE .../work-session` releases it and answers 204 whatever it did. The page holds the session before it starts or resumes work, renews it while it works, releases it when it leaves or closes (`pagehide`), and stops with an explanation if a renewal is refused. While another page holds the session, the session start and the answer of any other page, or of a request without the header (one anonymous page), answer 409 `state_conflict` and change nothing; the check runs under the attempt row lock after the database time is read, before any attempt change, and the refusal is not stored under the idempotency key, so the holder can reuse the key. An attempt that nobody holds, a released hold, and a hold that stopped renewing (after at most two minutes) admit every page, and `StartSession` and `SubmitAnswer` of a service built without work sessions are unchanged.
- How it relates to `MaxSessions` and `IdleTimeoutSeconds`. Those attempt policy limits describe the sequential work sessions of an attempt: a new one starts only after the idle timeout, and the count is bounded. The hold is the concurrency dimension inside the current work session. It starts, extends, and consumes no work session of that policy, does not change the attempt version, and is not stored in the attempt row.
- Limits of the rule. It is a one-page-at-a-time rule, not a security boundary: a client that never holds the session is refused only while another page holds it, a candidate can always continue after the hold is released or has expired, and two windows of one candidate are not told from two people. The hold is renewed by a page timer, so a browser that throttles a background tab to one tick a minute still renews within the two minutes.
- Operator reading. `make -C backend assessment-review ARGS='inspect ...'` prints the new counts `extra_agents`, `client_screenshot_keys`, and `client_devtools_opens` next to the old ones; the note at its end repeats that browser signals can be forged and that a screenshot or a phone photo cannot be prevented or seen by the page.
### Skill evidence
Implemented as a stored projection of the immutable assessment results, with two reads: the candidate's own list and the permitted projection of a currently visible card. The match search reads the organization projection (see [Matching and explanations](#matching-and-explanations)); no percentile reads it yet.
+1
View File
@@ -441,6 +441,7 @@ make -C backend assessment-review ARGS='inspect --attempt <uuid> --actor operato
- Every read is recorded in `assessment_review_reads` (attempt ID, actor handle, found or missing, database time) in the same transaction as the read, also when the attempt has no review. The table refuses UPDATE, DELETE, and TRUNCATE. The actor is an audit handle, not authentication: any holder of the database credential can type any handle. Rolling migration 33 back is refused while the audit holds a row; export or resolve it first.
- A band can be missing for a real reason: the policy version of the attempt has no `assessment.signals` section, the review job has not run yet, or the attempt has neither ended nor reached its deadline.
- A review is updated in place when a later attempt matches one of its answers; the policy version and the first evaluation time stay.
- Capture hints and the one-window rule add three counts to this output (`extra_agents`, `client_screenshot_keys`, `client_devtools_opens`) and the reason `extra_agents`; they raise the band only through optional thresholds of the policy section (`client_screenshot_keys_attention`, `client_devtools_attention`, `extra_agents_attention`, `extra_agents_review`), which a version published earlier does not have and the demo policies do not set. The rows that hold them are the same kind of data as the others: keyed digests and counts, and no User-Agent, page identifier, address, or image. A screenshot or a phone photo cannot be prevented or seen, so these signals lead only to a manual check, never to an automatic downgrade ([details](ARCHITECTURE.md#capture-hints-one-open-window-and-what-they-cannot-do)). Rolling migration 50 back is refused while the new events, marks, or counts exist.
- To use thresholds other than the demo values, publish a policy version with an `assessment.signals` section through the policy publisher. `DemoProductPolicyV3` is the demo example and is published only explicitly (the isolated browser fixture does so); the startup seed publishes version 1 only. Attempts that already started keep the version they started with. The demo duplicate thresholds assume a population: a copied pair is flagged only from about 26 answers per family (attention) and 61 (review) at 13 items, or 9 and 14 at 23 items. To try the feature on a smaller stand, publish a policy version with lower `duplicate_bits_attention` and `duplicate_bits_review` (the integration tests use 4 and 6); do not edit the demo policy. A review is a point-in-time evaluation, run again by the job at the deadline. The job logs one line per run with the number of reviews and its duration (`assessment review job finished`).
- The rows hold counts, durations, and keyed digests (HMAC-SHA-256 under keys derived from `IDENTITY_KEY_SECRET`, each with a key version) and no answer text. Rotating the secret keeps the stored rows but makes new fingerprints incomparable with old ones. Deleting an account deletes its attempts and, by cascade, their facts and reviews; the audit rows keep only the attempt ID and the handle. The digests are kept for the lifetime of the attempt; no retention period is defined yet.
+10 -2
View File
@@ -540,16 +540,24 @@ The tests prove the stored facts, the policy pinning, the job-based computation,
## Assessment lockdown tests
Vitest runs in Node without a DOM, so the lockdown is checked in parts. `frontend/src/features/assessment-lockdown/model/fullscreen.test.ts` covers support detection (including a browser without element fullscreen, such as iPhone Safari), that the request is issued synchronously inside the call so it stays in the click, and that a refusal is a result and not an exception. `model/cover.test.ts` is the table of when the task is covered: fullscreen exit, a hidden tab, a window without focus, a request in flight, and the mode without fullscreen. `ui/protected-region.test.tsx` renders the region with a fake lockdown and checks that a covered task leaves no text of the prompt or the options in the markup, that a cover for a left tab has no fullscreen button, and the explanation shown for an unsupported browser; `features/answer-assessment/ui/answer-form.test.tsx` checks that a concealed form renders nothing. The notice text version 3 and its list of measures are checked in `features/assessment-signals/ui/signal-notice.test.tsx`. In the backend, `usecase/assessment/signal_notice_test.go` checks that every version except the current one is refused, and `TestAssessmentSignalNoticeOverHTTP` checks over HTTP with PostgreSQL that a stored acknowledgement of version 1 does not count for the current version, and its versions follow `CurrentSignalNoticeVersion`.
Vitest runs in Node without a DOM, so the lockdown is checked in parts. `frontend/src/features/assessment-lockdown/model/fullscreen.test.ts` covers support detection (including a browser without element fullscreen, such as iPhone Safari), that the request is issued synchronously inside the call so it stays in the click, and that a refusal is a result and not an exception. `model/cover.test.ts` is the table of when the task is covered: fullscreen exit, a hidden tab, a window without focus, a request in flight, and the mode without fullscreen. `ui/protected-region.test.tsx` renders the region with a fake lockdown and checks that a covered task leaves no text of the prompt or the options in the markup, that a cover for a left tab has no fullscreen button, and the explanation shown for an unsupported browser; `features/answer-assessment/ui/answer-form.test.tsx` checks that a concealed form renders nothing. The notice text version 4 and its list of measures are checked in `features/assessment-signals/ui/signal-notice.test.tsx`. In the backend, `usecase/assessment/signal_notice_test.go` checks that every version except the current one is refused, and `TestAssessmentSignalNoticeOverHTTP` checks over HTTP with PostgreSQL that a stored acknowledgement of version 1 does not count for the current version, and its versions follow `CurrentSignalNoticeVersion`.
Unit tests of the task protection: `model/task-guard.test.ts` runs the rules with small fake elements and events: selection, the context menu, and drag are cancelled on the task text and left alone in a field, a drop never fills a field, paste is refused in answer fields (and reported, so the screen can say so) and allowed in the code editor, the `beforeinput` routes of paste and drop are closed while typing and composing are never touched, and a copy or cut is refused when the target or the selection reaches into the task but not when it is inside a field. `features/answer-assessment/ui/answer-form.test.tsx` checks that only the code editor carries the paste exception.
Two browser specs run against a mocked API, so they need no backend data and also run against the Vite server (`E2E_BASE_URL=http://localhost:5173 pnpm exec playwright test e2e/assessment-lockdown.spec.ts e2e/assessment-task-protection.spec.ts --project=chromium`) as well as in `make -C deploy test-e2e`; the mock is in `frontend/e2e/assessment-attempt-mock.ts`. `assessment-lockdown.spec.ts`: leaving fullscreen covers the task (its text is not in the page), sends a `fullscreen_exit` signal, and the continue button restores the task with the typed draft; leaving the tab covers the task and returning in fullscreen shows it; a browser without the fullscreen API shows the explanation and still takes the test from the keyboard; a refused fullscreen request continues without it; closing the notice without confirming leaves fullscreen and stores nothing. `assessment-task-protection.spec.ts`: the task text is not selectable, a select-all or scripted copy leaves no task text in the clipboard, the context menu and drag are cancelled on the task but not in a field, a field copies its own text, the text stays in the accessibility tree, and printing hides the task; an answer field refuses a paste, shows the notice, and the refused paste is sent as a `paste` signal with its size and without its text; the practice code editor accepts a paste and sends its size; an item is answered with the keyboard alone. The notice acknowledgement over the real backend is covered by the existing notice test in `assessment.spec.ts`, which now expects version 3. These specs show the page behavior in Chromium with a mocked server; they do not show behavior in other browsers, on a phone, with a real screen reader, or against a window manager that changes fullscreen on its own. The paste rule cannot see text that an on-screen keyboard inserts as typing.
Two browser specs run against a mocked API, so they need no backend data and also run against the Vite server (`E2E_BASE_URL=http://localhost:5173 pnpm exec playwright test e2e/assessment-lockdown.spec.ts e2e/assessment-task-protection.spec.ts --project=chromium`) as well as in `make -C deploy test-e2e`; the mock is in `frontend/e2e/assessment-attempt-mock.ts`. `assessment-lockdown.spec.ts`: leaving fullscreen covers the task (its text is not in the page), sends a `fullscreen_exit` signal, and the continue button restores the task with the typed draft; leaving the tab covers the task and returning in fullscreen shows it; a browser without the fullscreen API shows the explanation and still takes the test from the keyboard; a refused fullscreen request continues without it; closing the notice without confirming leaves fullscreen and stores nothing. `assessment-task-protection.spec.ts`: the task text is not selectable, a select-all or scripted copy leaves no task text in the clipboard, the context menu and drag are cancelled on the task but not in a field, a field copies its own text, the text stays in the accessibility tree, and printing hides the task; an answer field refuses a paste, shows the notice, and the refused paste is sent as a `paste` signal with its size and without its text; the practice code editor accepts a paste and sends its size; an item is answered with the keyboard alone. The notice acknowledgement over the real backend is covered by the existing notice test in `assessment.spec.ts`, which now expects version 4. These specs show the page behavior in Chromium with a mocked server; they do not show behavior in other browsers, on a phone, with a real screen reader, or against a window manager that changes fullscreen on its own. The paste rule cannot see text that an on-screen keyboard inserts as typing.
## Assessment watermark tests
`backend/internal/domain/assessment_watermark_test.go` covers the mark: two attempts that were served one real generated variant get different marked statements whose canonical text and reference answer are equal; marking is deterministic and idempotent; the invisible run decodes to the visible code, survives a copy of two sentences, and a cut, padded, or mis-checked run is ignored; the accessible text holds the words only; the alignment of a stored statement with a leak reads only the phrases that it finds there (words around the statement, such as a quotation or a message, are ignored), the wording agreement of the attempt that wrote the text holds for every phrase group, other seeds disagree, a fragment yields the phrases of the fragment, an unrelated text aligns nothing, and another variant of the same family aligns for fewer characters than the leaked one; the pieces between the phrases are the same in every copy of a statement; the number guard keeps `at most` at the end of a sentence; codes parse the way an operator or OCR reads them. `usecase/assessment/watermark_test.go` checks that only root and corrective attempts are marked, that the stored snapshot is not changed, that the visible code equals the invisible one, and that a missing `Watermarker` leaves snapshots alone; `adapter/primary/http/v1/assessment_test.go` checks that every attempt response goes through the presenter and that a presenter failure is an error. `TestAssessmentWatermarkOverHTTP` (PostgreSQL) checks over HTTP that a real attempt shows the code derived on the server and a marked prompt on creation, on a read, and on a replay, that a training run shows neither, that the response holds only the code, and that the stored statement has no mark. In the frontend, `features/assessment-watermark` has Vitest tests of the text split, of the accessible text of the rendered markup (everything in `aria-hidden` removed leaves exactly the words), and of the tile (code and UTC time, no `@`, hidden from assistive technology). `e2e/assessment-watermark.spec.ts` runs against the mocked API (also on the Vite server, `E2E_BASE_URL=http://localhost:5173 pnpm exec playwright test e2e/assessment-watermark.spec.ts --project=chromium`): the tile is on the task screen with the code and the time and without the account e-mail, is faint and takes no click, an attempt without a code shows no tile, and the accessibility tree of the marked prompt holds the words and no format character while the document keeps them. These tests do not run a real screen reader, a braille display, or another browser, so they do not show how a reader speaks the text; they do not show how many attempts a leak can be told from either, because the wording channel gives about one bit per phrase group.
## Assessment capture hint and work session tests
Domain and usecase. `assessment_signal_review_test.go` has the band rules: capture hints, extra User-Agents, and every weak signal together stop at attention however large their counts, the extra agents reach review only beside a strong signal, and a policy without the capture thresholds ignores the hints. `assessment_signal_policy_test.go` checks that a version published before these fields decodes with them off and encodes back to the same document (so its content hash holds), that the demo policy was not edited, that the thresholds round-trip, and that out-of-range or inconsistent values are rejected. `assessment_signal_test.go` covers the two new event kinds and their refusal with a measurement. `assessment_work_lease_test.go` covers the hold: one page admitted, a second refused until release or expiry, a renewal that keeps the acquisition time, release only by the holder, and invalid leases. `usecase/assessment/work_session_test.go` runs the steps of the hold and the check of the answer and the session start against in-memory repositories: a second page, a page without the header, and a request after an expiry; a training run and a service without work sessions are never refused; the origin of a hold is recorded with the User-Agent digest only. `signal_review_test.go` checks that the origin mark keeps the User-Agent as a keyed digest, writes a new mark only on a change, and that the review counts the extra agents and capture hints and stops at attention. `keyring_test.go` checks the new digests are keyed, bound to the attempt, and separate from each other. The HTTP adapter tests check the mapping of the hold, the release, the refusal of a held attempt on the session start and the answer, the new event variants and their mismatches, and the User-Agent bound.
Over HTTP with PostgreSQL. `TestAssessmentWorkSessionOverHTTP` creates a real attempt and checks that the first page holds the session, that a second page, and a request without the header, are refused for the hold, the session start, and the answer with 409 and nothing is stored, that the refusal is not stored under the key (the holder reuses both keys), that another page's release changes nothing, that the holder's release frees the session at once, that a hold that stopped renewing ends by itself, that bad page identifiers answer 400 and a missing CSRF token 403, that only digests of the page and the User-Agent are stored (no table text holds a page identifier or a browser string), that the capture events are stored without a measurement and refused with one, and that the review job gives the band attention with the extra agents and capture hints counted. `TestAssessmentSignalNoticeOverHTTP` follows `CurrentSignalNoticeVersion`. The migration 50 constraints are exercised by these tests.
Frontend. Vitest covers the key rules (`capture-keys.test.ts`), the heuristic and its watcher with fake windows and timers (`devtools-heuristic.test.ts`), the collector (one event for a press and its release, no cancelling, no event without an item), the session wiring of the watcher, the work session controller (held, busy, lost at a renewal, a network gap, a release during a renewal, the renewal bounds, `work-session.test.ts`), the page identifier header of the answer command, and the notice version 4 text. `e2e/assessment-capture.spec.ts` runs against the mocked API (also on the Vite server, `E2E_BASE_URL=http://localhost:5173 pnpm exec playwright test e2e/assessment-capture.spec.ts --project=chromium`): PrintScreen and Cmd+Shift+4 are recorded as `screenshot_key` events with no key or image, the key event is not cancelled and the test goes on to an answer; a faked docked panel is recorded as `devtools_open`; a second tab opened on the attempt is refused with the explanation and shows no task, nothing is started in it, the first tab is undisturbed, and after the first tab leaves the second continues; `pagehide` releases the session; a tab that loses the session at a renewal stops and says so. These tests do not show behavior in other browsers or on a phone, whether the operating system hands a shortcut to the page, what a real screenshot looks like, or how often the heuristic is wrong on real windows; the mock server stands for the rules of the real one, which the HTTP test covers.
## Internal notification tests
Unit tests (`make -C backend test`, `make -C frontend test`):
+15
View File
@@ -710,6 +710,21 @@ contact_grant относится к паре кандидат-компания
- Доступность. Некоторые синтезаторы речи и брайлевские дисплеи могут озвучивать символы нулевой ширины или рвать слово на них; с настоящим экранным диктором это не проверялось. Поэтому страница кладет каждый запуск невидимых символов в элемент `aria-hidden`: дерево доступности содержит только слова (проверка Playwright читает дерево через `ariaSnapshot`, проверка Vitest вырезает скрытые элементы из разметки), а документ хранит символы, так что все, что из него скопировано, несет метку. Формулировки - обычные слова, варианты пробелов не используются, потому что неразрывный пробел не везде гарантированно беззвучен.
- Чего знак не делает. Снимок экрана, фото экрана или перепечатку в браузере предотвратить нельзя. Знак - доказательство для ручной проверки и апелляции, но не автоматическое решение; ни одна операция не показывает его работодателю, а кандидат видит только код своей попытки.
### Подсказки о съемке экрана, одно окно и чего они не делают
Реализовано для реальных попыток (root и corrective). У учебного запуска (`demo_express`) этого нет. Усиленный прокторинг здесь без камеры, микрофона, записи экрана, снимков экрана и содержимого буфера обмена: это слабые сигналы для ручной проверки и одно правило об открытых окнах. Код: `backend/internal/domain/assessment_signal.go`, `assessment_signal_review.go`, `assessment_signal_policy.go` и `assessment_work_lease.go`; `backend/internal/usecase/assessment/work_session.go` и наблюдатель в `signal_review.go`; миграция `backend/db/migrations/00050_add_assessment_work_leases_and_capture_signals.sql`; операции `HoldMyAssessmentWorkSession` и `ReleaseMyAssessmentWorkSession`; `frontend/src/features/assessment-signals/` и `frontend/src/features/assessment-work-session/`.
- Снимок экрана и фото экрана телефоном предотвратить нельзя. Страница браузера не может помешать операционной системе или другой программе снять экран, не видит камеру и не видит второе устройство, удаленный рабочий стол и виртуальную машину. Поэтому страница даже не пытается: она не отменяет клавишу, не гасит страницу по клавише и не читает изображения. Она может сообщить, что нажата клавиша снимка, связать утекший текст или снимок с попыткой (см. [Водяной знак текста задания](#водяной-знак-текста-задания)) и отправить и то и другое на ручную проверку.
- Сигналы ведут к проверке и апелляции, но не к автоматическому снижению оценки. Они только поднимают полосу проверки, которая не меняет результат, категорию и квоты; работодатель не видит ни сигналов, ни полосы, а кандидат полосы не видит. Версия 4 уведомления говорит об этом прямо.
- Клавиши снимка экрана. Страница передает `screenshot_key`, когда видит PrintScreen (в том числе с Alt), Cmd+Shift+3, 4 или 5 (macOS) либо Win+Shift+S, при нажатии или отпускании клавиши, не чаще раза в секунду. Операционная система часто забирает эти клавиши раньше страницы, снимок без клавиш ничего не присылает, а удержание не отличается от нажатия, поэтому событие доказывает только нажатие клавиши. В нем есть задание и время клиента, но нет измерений.
- Инструменты разработчика. Страница передает `devtools_open`, когда внешнее окно становится больше страницы по ширине или высоте больше чем на 160 px, как это делает пристыкованная панель, при изменении размера и по таймеру раз в две секунды, не чаще раза в минуту. Это эвристика с ложными срабатываниями (боковая панель, масштаб, изменение размера окна) и пропусками (отдельное окно панели, другие окна), поэтому это тоже лишь слабая подсказка.
- Политика и полоса. Оба вида хранятся как события (проверочные ограничения `assessment_signal_events` разрешают их без измерения) и считаются по попытке (`client_screenshot_keys`, `client_devtools_opens` в `assessment_attempt_reviews`). Пороги - необязательные поля раздела политики `assessment.signals`: `client_screenshot_keys_attention` и `client_devtools_attention` - клиентские пороги, они поднимают нормальную полосу до attention и не выше, а `extra_agents_attention` с `extra_agents_review` входит в слабую группу параллельных сессий и лишних сетей, которая сама достигает не выше attention, а review - только рядом с сильным сигналом. Нулевой или отсутствующий порог исключает сигнал, поэтому версия, опубликованная до этих полей, сохраняет полосу, документ и хеш содержимого (тест проверяет, что в ее документе нет новых ключей и он кодируется обратно без изменений). Демо-политики не менялись; `DemoAssessmentSignalPolicyWithCaptureHints` в `assessment_signal_policy.go` задает согласованные начальные значения (три клавиши снимка, одно обнаружение, два лишних User-Agent), которых никакое исследование не подтверждает, а интеграционный тест публикует их в собственной версии политики.
- Отпечаток User-Agent. HTTP-граница обрезает User-Agent до 512 байт и передает его юзкейсу, который хранит только `HMAC-SHA-256` от него под ключом, выведенным из `IDENTITY_KEY_SECRET` (метка `lincodex/assessment/signal-agent/v1`) и привязанным к попытке, в новой колонке `agent_digest` таблицы `assessment_attempt_origin_marks`. Исходное значение не хранится и не попадает в журнал. Метка пишется, когда сессия, сеть или User-Agent отличаются от последней метки, поэтому список остается коротким; `extra_agents` считает различные отпечатки сверх первого. Браузер, обновившийся во время попытки, или переход кандидата на другое устройство добавляют один, поэтому сигнал слабый.
- Одно открытое окно. `assessment_attempt_work_leases` хранит по строке на реальную попытку: ключевой отпечаток идентификатора, который каждая открытая страница создает при загрузке (`X-Attempt-Client`, от 16 до 64 символов `A-Za-z0-9_-`), время, когда она заняла сеанс, когда в последний раз продлила его и когда освободила. `PUT .../work-session` занимает или продлевает сеанс на 120 секунд (`domain.AssessmentWorkLeaseDuration`) и просит страницу продлевать раз в 15 секунд; `DELETE .../work-session` освобождает его и отвечает 204 при любом исходе. Страница занимает сеанс до начала или продолжения работы, продлевает его, пока работает, освобождает при уходе или закрытии (`pagehide`) и останавливается с объяснением, если продление отклонено. Пока сеанс занят другой страницей, начало сеанса и ответ любой другой страницы или запроса без заголовка (одна анонимная страница) получают 409 `state_conflict` и ничего не меняют; проверка идет под блокировкой строки попытки после чтения времени базы и до любого изменения попытки, а отказ не сохраняется под ключом идемпотентности, поэтому владелец может использовать тот же ключ. Попытка, которую никто не держит, освобожденное и переставшее продлеваться (не позднее чем через две минуты) занятие пускают любую страницу, а `StartSession` и `SubmitAnswer` сервиса, собранного без рабочих сеансов, не меняются.
- Связь с `MaxSessions` и `IdleTimeoutSeconds`. Эти ограничения политики попытки описывают последовательные рабочие сеансы попытки: новый начинается только после простоя, а их число ограничено. Занятие - это измерение одновременности внутри текущего рабочего сеанса. Оно не начинает, не продлевает и не расходует рабочий сеанс этой политики, не меняет версию попытки и не хранится в строке попытки.
- Пределы правила. Это правило "одна страница за раз", а не граница безопасности: клиент, который никогда не занимает сеанс, получает отказ только пока его занимает другая страница, кандидат всегда может продолжить после освобождения или истечения, а два окна одного кандидата не отличаются от двух людей. Занятие продлевает таймер страницы, поэтому браузер, который замедляет фоновую вкладку до одного такта в минуту, все равно продлевает его в пределах двух минут.
- Чтение оператором. `make -C backend assessment-review ARGS='inspect ...'` печатает новые счетчики `extra_agents`, `client_screenshot_keys` и `client_devtools_opens` рядом со старыми; примечание в конце вывода повторяет, что браузерные сигналы можно подделать и что снимок экрана или фото телефоном предотвратить нельзя и страница их не видит.
### Доказательства навыков
Реализовано как сохраняемая проекция неизменяемых результатов оценки с двумя чтениями: собственный список кандидата и разрешенная проекция сейчас видимой карточки. Проекцию для организации читает поиск (см. [Подбор и объяснение](#подбор-и-объяснение)); перцентиль ее пока не читает.
+1
View File
@@ -443,6 +443,7 @@ make -C backend assessment-review ARGS='inspect --attempt <uuid> --actor operato
- Каждое чтение записывается в `assessment_review_reads` (идентификатор попытки, имя оператора, найдено или нет, время базы) в той же транзакции, что и чтение, в том числе когда у попытки нет проверки. Таблица отклоняет UPDATE, DELETE и TRUNCATE. Имя оператора - метка для аудита, а не аутентификация: любой, у кого есть доступ к базе, может ввести любое имя. Откат миграции 33 отклоняется, пока в аудите есть строка; сначала экспортируйте или разберите ее.
- Полосы может не быть по реальной причине: в версии политики попытки нет раздела `assessment.signals`, задание проверки еще не выполнено, либо попытка еще не завершилась и не достигла дедлайна.
- Проверка обновляется на месте, когда более поздняя попытка совпала с одним из ее ответов; версия политики и время первого вычисления остаются.
- Подсказки о съемке и правило одного окна добавляют в этот вывод три счетчика (`extra_agents`, `client_screenshot_keys`, `client_devtools_opens`) и причину `extra_agents`; они поднимают полосу только через необязательные пороги раздела политики (`client_screenshot_keys_attention`, `client_devtools_attention`, `extra_agents_attention`, `extra_agents_review`), которых нет в ранее опубликованной версии и которые не задают демо-политики. Строки с ними - данные того же рода, что и остальные: ключевые отпечатки и счетчики, без User-Agent, идентификатора страницы, адреса и изображения. Снимок экрана или фото телефоном предотвратить нельзя и увидеть тоже, поэтому эти сигналы ведут только к ручной проверке, но не к автоматическому снижению оценки ([подробнее](ARCHITECTURE.md#подсказки-о-съемке-экрана-одно-окно-и-чего-они-не-делают)). Откат миграции 50 отклоняется, пока есть новые события, метки или счетчики.
- Чтобы использовать пороги, отличные от демо, опубликуйте версию политики с разделом `assessment.signals` через публикатор политик. `DemoProductPolicyV3` - демо-пример, он публикуется только явно (так делает изолированная браузерная фикстура); стартовый seed публикует только версию 1. Попытки, которые уже начались, сохраняют версию, с которой начались. Демо-пороги дубликатов рассчитаны на совокупность: скопированная пара помечается лишь примерно от 26 ответов на семейство («внимание») и 61 («проверить») при 13 заданиях или от 9 и 14 при 23. Чтобы попробовать функцию на меньшем стенде, опубликуйте версию политики с меньшими `duplicate_bits_attention` и `duplicate_bits_review` (интеграционные тесты используют 4 и 6); демо-политику не редактируйте. Проверка - оценка на момент, задание на дедлайне запускает ее снова. Задание пишет в журнал одну строку на запуск с числом проверок и длительностью (`assessment review job finished`).
- Строки хранят числа, длительности и ключевые дайджесты (HMAC-SHA-256 под ключами, выведенными из `IDENTITY_KEY_SECRET`, у каждого есть версия ключа) и не хранят текст ответа. Смена секрета сохраняет строки, но делает новые отпечатки несравнимыми со старыми. Удаление аккаунта удаляет его попытки и каскадом их факты и проверки; строки аудита хранят только идентификатор попытки и имя. Дайджесты хранятся столько же, сколько попытка; срок хранения пока не определен.
+10 -2
View File
@@ -540,16 +540,24 @@ Spec не проверяет запланированные переходы б
## Тесты ограничений во время попытки
Vitest работает в Node без DOM, поэтому ограничения проверяются по частям. `frontend/src/features/assessment-lockdown/model/fullscreen.test.ts` покрывает определение поддержки (в том числе браузер без полноэкранного режима элемента, например iPhone Safari), то, что запрос делается синхронно внутри вызова и остается внутри клика, и то, что отказ - это результат, а не исключение. `model/cover.test.ts` - таблица случаев, когда задание закрыто: выход из полноэкранного режима, скрытая вкладка, окно без фокуса, запрос в процессе и режим без полноэкранного режима. `ui/protected-region.test.tsx` рисует область с поддельным состоянием и проверяет, что закрытое задание не оставляет в разметке текста условия и вариантов, что у закрытия из-за ухода с вкладки нет кнопки полноэкранного режима, и объяснение для неподдерживаемого браузера; `features/answer-assessment/ui/answer-form.test.tsx` проверяет, что скрытая форма ничего не рисует. Версия 3 текста уведомления и перечень мер проверяются в `features/assessment-signals/ui/signal-notice.test.tsx`. В бэкенде `usecase/assessment/signal_notice_test.go` проверяет, что любая версия, кроме текущей, отклоняется, а `TestAssessmentSignalNoticeOverHTTP` по HTTP с PostgreSQL проверяет, что сохраненное подтверждение версии 1 не засчитывается для текущей версии, а ее версии следуют за `CurrentSignalNoticeVersion`.
Vitest работает в Node без DOM, поэтому ограничения проверяются по частям. `frontend/src/features/assessment-lockdown/model/fullscreen.test.ts` покрывает определение поддержки (в том числе браузер без полноэкранного режима элемента, например iPhone Safari), то, что запрос делается синхронно внутри вызова и остается внутри клика, и то, что отказ - это результат, а не исключение. `model/cover.test.ts` - таблица случаев, когда задание закрыто: выход из полноэкранного режима, скрытая вкладка, окно без фокуса, запрос в процессе и режим без полноэкранного режима. `ui/protected-region.test.tsx` рисует область с поддельным состоянием и проверяет, что закрытое задание не оставляет в разметке текста условия и вариантов, что у закрытия из-за ухода с вкладки нет кнопки полноэкранного режима, и объяснение для неподдерживаемого браузера; `features/answer-assessment/ui/answer-form.test.tsx` проверяет, что скрытая форма ничего не рисует. Версия 4 текста уведомления и перечень мер проверяются в `features/assessment-signals/ui/signal-notice.test.tsx`. В бэкенде `usecase/assessment/signal_notice_test.go` проверяет, что любая версия, кроме текущей, отклоняется, а `TestAssessmentSignalNoticeOverHTTP` по HTTP с PostgreSQL проверяет, что сохраненное подтверждение версии 1 не засчитывается для текущей версии, а ее версии следуют за `CurrentSignalNoticeVersion`.
Модульные тесты защиты задания: `model/task-guard.test.ts` проверяет правила на небольших поддельных элементах и событиях: выделение, контекстное меню и перетаскивание отменяются на тексте задания и не трогаются в поле, сброс текста мышью никогда не заполняет поле, вставка отклоняется в полях ответа (и об этом сообщается, чтобы экран мог сказать) и разрешена в редакторе кода, пути `beforeinput` для вставки и сброса закрыты, а набор и композиция никогда не затрагиваются, копирование и вырезание отклоняются, когда цель или выделение доходят до задания, и не отклоняются внутри поля. `features/answer-assessment/ui/answer-form.test.tsx` проверяет, что исключение для вставки есть только у редактора кода.
Две браузерные спецификации работают с подставным API, поэтому им не нужны данные бэкенда, и их можно запускать и на сервере Vite (`E2E_BASE_URL=http://localhost:5173 pnpm exec playwright test e2e/assessment-lockdown.spec.ts e2e/assessment-task-protection.spec.ts --project=chromium`), и в `make -C deploy test-e2e`; подставной API лежит в `frontend/e2e/assessment-attempt-mock.ts`. `assessment-lockdown.spec.ts`: выход из полноэкранного режима закрывает задание (его текста нет в странице), отправляет сигнал `fullscreen_exit`, а кнопка продолжения возвращает задание вместе с набранным черновиком; уход с вкладки закрывает задание, а возврат в полноэкранном режиме показывает его; браузер без полноэкранного API показывает объяснение и проходит тест с клавиатуры; отказ в полноэкранном режиме не мешает продолжить; закрытие уведомления без подтверждения выходит из полноэкранного режима и ничего не сохраняет. `assessment-task-protection.spec.ts`: текст задания нельзя выделить, копирование после выделения всего или из скрипта не оставляет текста задания в буфере, контекстное меню и перетаскивание отменяются на задании, но не в поле, поле копирует собственный текст, текст остается в дереве доступности, печать скрывает задание; поле ответа отклоняет вставку и показывает сообщение, а отклоненная вставка уходит сигналом `paste` с размером и без текста; редактор кода принимает вставку и отправляет ее размер; задание отвечается только с клавиатуры. Подтверждение уведомления с настоящим бэкендом покрывает существующий тест уведомления в `assessment.spec.ts`, который теперь ожидает версию 3. Эти спецификации показывают поведение страницы в Chromium с подставным сервером; они не показывают поведение в других браузерах, на телефоне, с настоящим экранным диктором и в оконном менеджере, который сам меняет полноэкранный режим. Правило вставки не видит текст, который экранная клавиатура вставляет как набор.
Две браузерные спецификации работают с подставным API, поэтому им не нужны данные бэкенда, и их можно запускать и на сервере Vite (`E2E_BASE_URL=http://localhost:5173 pnpm exec playwright test e2e/assessment-lockdown.spec.ts e2e/assessment-task-protection.spec.ts --project=chromium`), и в `make -C deploy test-e2e`; подставной API лежит в `frontend/e2e/assessment-attempt-mock.ts`. `assessment-lockdown.spec.ts`: выход из полноэкранного режима закрывает задание (его текста нет в странице), отправляет сигнал `fullscreen_exit`, а кнопка продолжения возвращает задание вместе с набранным черновиком; уход с вкладки закрывает задание, а возврат в полноэкранном режиме показывает его; браузер без полноэкранного API показывает объяснение и проходит тест с клавиатуры; отказ в полноэкранном режиме не мешает продолжить; закрытие уведомления без подтверждения выходит из полноэкранного режима и ничего не сохраняет. `assessment-task-protection.spec.ts`: текст задания нельзя выделить, копирование после выделения всего или из скрипта не оставляет текста задания в буфере, контекстное меню и перетаскивание отменяются на задании, но не в поле, поле копирует собственный текст, текст остается в дереве доступности, печать скрывает задание; поле ответа отклоняет вставку и показывает сообщение, а отклоненная вставка уходит сигналом `paste` с размером и без текста; редактор кода принимает вставку и отправляет ее размер; задание отвечается только с клавиатуры. Подтверждение уведомления с настоящим бэкендом покрывает существующий тест уведомления в `assessment.spec.ts`, который теперь ожидает версию 4. Эти спецификации показывают поведение страницы в Chromium с подставным сервером; они не показывают поведение в других браузерах, на телефоне, с настоящим экранным диктором и в оконном менеджере, который сам меняет полноэкранный режим. Правило вставки не видит текст, который экранная клавиатура вставляет как набор.
## Тесты водяного знака оценки
`backend/internal/domain/assessment_watermark_test.go` покрывает метку: две попытки с одним настоящим сгенерированным вариантом получают разные тексты с меткой, у которых равны канонический текст и эталонный ответ; разметка детерминирована и идемпотентна; невидимый запуск декодируется в видимый код, переживает копию двух предложений, а обрезанный, удлиненный или с неверной контрольной цифрой запуск игнорируется; доступный текст содержит только слова; выравнивание сохраненного условия с утекшим текстом читает только найденные там обороты (слова вокруг условия, например цитата или сообщение, игнорируются), согласование формулировок попытки, которая написала текст, выполняется для каждой группы оборотов, другие затравки не согласуются, фрагмент дает обороты фрагмента, посторонний текст ничего не выравнивает, а другой вариант того же семейства выравнивается на меньшее число символов, чем утекший; части между оборотами одинаковы в каждой копии условия; числовая защита оставляет `at most` в конце предложения; коды разбираются так, как их читает оператор или распознавание. `usecase/assessment/watermark_test.go` проверяет, что размечаются только root и corrective, что сохраненный снимок не меняется, что видимый код равен невидимому и что отсутствие `Watermarker` оставляет снимки как есть; `adapter/primary/http/v1/assessment_test.go` проверяет, что каждый ответ с попыткой проходит через презентер и что отказ презентера - ошибка. `TestAssessmentWatermarkOverHTTP` (PostgreSQL) по HTTP проверяет, что реальная попытка при создании, чтении и повторе показывает код, выведенный на сервере, и текст с меткой, что учебный запуск не показывает ни того, ни другого, что в ответе только код и что в сохраненном условии метки нет. Во фронтенде у `features/assessment-watermark` есть тесты Vitest разбиения текста, доступного текста отрисованной разметки (без всего, что в `aria-hidden`, остаются ровно слова) и плитки (код и время UTC, без `@`, скрыта от вспомогательных технологий). `e2e/assessment-watermark.spec.ts` работает с подставным API (и на сервере Vite, `E2E_BASE_URL=http://localhost:5173 pnpm exec playwright test e2e/assessment-watermark.spec.ts --project=chromium`): плитка есть на экране задания с кодом и временем и без email аккаунта, бледная и не перехватывает клики, у попытки без кода плитки нет, а дерево доступности размеченного условия содержит слова и ни одного символа форматирования, хотя документ их хранит. Эти тесты не запускают настоящий экранный диктор, брайлевский дисплей или другой браузер, поэтому не показывают, как диктор читает текст; они не показывают и того, сколько попыток можно различить по утечке, потому что канал формулировок дает около одного бита на группу оборотов.
## Тесты подсказок о съемке экрана и рабочего сеанса оценки
Домен и юзкейс. `assessment_signal_review_test.go` проверяет правила полосы: подсказки о съемке, лишние User-Agent и все слабые сигналы вместе останавливаются на attention при любых счетчиках, лишние агенты достигают review только рядом с сильным сигналом, а политика без порогов съемки игнорирует подсказки. `assessment_signal_policy_test.go` проверяет, что версия, опубликованная до этих полей, декодируется с ними выключенными и кодируется обратно в тот же документ (поэтому хеш содержимого сохраняется), что демо-политика не менялась, что пороги проходят туда и обратно и что значения вне диапазона или противоречивые отклоняются. `assessment_signal_test.go` покрывает два новых вида событий и отказ при наличии измерения. `assessment_work_lease_test.go` покрывает занятие: одна страница допускается, вторая получает отказ до освобождения или истечения, продление сохраняет время занятия, освобождает только владелец, неверные записи отклоняются. `usecase/assessment/work_session_test.go` прогоняет шаги занятия и проверку ответа и начала сеанса на репозиториях в памяти: вторая страница, страница без заголовка и запрос после истечения; учебный запуск и сервис без рабочих сеансов не получают отказов; источник занятия записывается только с отпечатком User-Agent. `signal_review_test.go` проверяет, что метка источника хранит User-Agent как ключевой отпечаток, пишет новую метку только при изменении, а проверка считает лишние агенты и подсказки о съемке и останавливается на attention. `keyring_test.go` проверяет, что новые отпечатки ключевые, привязаны к попытке и различны между собой. Тесты HTTP-адаптера проверяют отображение занятия, освобождения, отказа для занятой попытки при начале сеанса и ответе, новых вариантов событий и их несовпадений и ограничение User-Agent.
По HTTP с PostgreSQL. `TestAssessmentWorkSessionOverHTTP` создает реальную попытку и проверяет, что первая страница занимает сеанс, что вторая страница и запрос без заголовка получают 409 на занятие, начало сеанса и ответ, при этом ничего не сохраняется, что отказ не сохраняется под ключом (владелец использует оба ключа повторно), что освобождение чужой страницей ничего не меняет, что освобождение владельцем освобождает сеанс сразу, что занятие, переставшее продлеваться, заканчивается само, что неверные идентификаторы страницы дают 400, а отсутствие CSRF-токена - 403, что хранятся только отпечатки страницы и User-Agent (ни один текст таблицы не содержит идентификатор страницы или строку браузера), что события съемки хранятся без измерения и отклоняются с ним и что задание проверки дает полосу attention с учтенными лишними агентами и подсказками о съемке. `TestAssessmentSignalNoticeOverHTTP` следует за `CurrentSignalNoticeVersion`. Ограничения миграции 50 проверяются этими тестами.
Фронтенд. Vitest покрывает правила клавиш (`capture-keys.test.ts`), эвристику и ее наблюдателя с поддельными окнами и таймерами (`devtools-heuristic.test.ts`), сборщик (одно событие на нажатие и отпускание, без отмены, без события без задания), подключение наблюдателя к сеансу, контроллер рабочего сеанса (занято, свободно, потеряно при продлении, обрыв сети, освобождение во время продления, границы продления, `work-session.test.ts`), заголовок идентификатора страницы в команде ответа и текст версии 4 уведомления. `e2e/assessment-capture.spec.ts` работает с подставным API (и на сервере Vite, `E2E_BASE_URL=http://localhost:5173 pnpm exec playwright test e2e/assessment-capture.spec.ts --project=chromium`): PrintScreen и Cmd+Shift+4 записываются как события `screenshot_key` без клавиши и изображения, событие клавиши не отменяется, и тест доходит до ответа; подставная пристыкованная панель записывается как `devtools_open`; вторая вкладка с той же попыткой получает отказ с объяснением и не показывает задание, в ней ничего не начинается, первая вкладка не нарушена, а после ухода первой вкладки вторая продолжает; `pagehide` освобождает сеанс; вкладка, потерявшая сеанс при продлении, останавливается и говорит об этом. Эти тесты не показывают поведение в других браузерах и на телефоне, отдает ли операционная система сочетание странице, как выглядит настоящий снимок и как часто эвристика ошибается на настоящих окнах; подставной сервер изображает правила настоящего, которые покрывает тест HTTP.
## Тесты внутренних уведомлений
Модульные тесты (`make -C backend test`, `make -C frontend test`):