diff --git a/api/README.en.md b/api/README.en.md index 2e0a91b..47ffbb7 100644 --- a/api/README.en.md +++ b/api/README.en.md @@ -259,7 +259,7 @@ The `assessment` tag covers the assessment attempts of the current candidate (PR Every operation also declares the `default` problem response. -The signal notice (`assessment-signal-notice`) lists the signals collected during a real attempt: browser events (focus loss, copy, paste and cut with a size, fullscreen exit; stored only while C3 is current) and server signals (response time, change of network address, parallel sessions, comparison of answer digests; only one-way keyed digests are stored, never addresses or session tokens). `GET` returns the notice version the server requires and whether the candidate acknowledged it; `PUT` stores the acknowledgement for the account and that version. The acknowledgement is a record that the candidate was informed, not a consent: it does not change C3, and the signal operation neither reads it nor refuses a batch without it. `PUT` needs no Idempotency-Key, because a repeat keeps the first time and answers 200; another version answers 409 `state_conflict`. The `demo_express` mode collects no signals and needs no acknowledgement. +The signal notice (`assessment-signal-notice`) lists the signals collected during a real attempt: browser events (focus loss, copy, paste and cut with a size, fullscreen exit; stored only while C3 is current) and server signals (response time, change of network address, parallel sessions, comparison of answer digests; only one-way keyed digests are stored, never addresses or session tokens). `GET` returns the notice version the server requires and whether the candidate acknowledged it; `PUT` stores the acknowledgement for the account and that version. The acknowledgement is a record that the candidate was informed, not a consent: it does not change C3, and the signal operation neither reads it nor refuses a batch without it. `PUT` needs no Idempotency-Key, because a repeat keeps the first time and answers 200; another version answers 409 `state_conflict`. The notice also lists the measures the page applies during a real attempt (fullscreen, covering the task, blocks on copying, selecting, and printing the task text, the paste rule, and a planned watermark); it is text version 2, and an acknowledgement of an earlier version never counts for the current one. The `demo_express` mode collects no signals and needs no acknowledgement. Access: diff --git a/api/README.md b/api/README.md index 7476647..e46752e 100644 --- a/api/README.md +++ b/api/README.md @@ -259,7 +259,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro Каждая операция также объявляет problem-ответ `default`. -Уведомление о сигналах (`assessment-signal-notice`) перечисляет сигналы, которые собираются во время реальной попытки: события браузера (потеря фокуса, копирование, вставка и вырезание с размером, выход из полноэкранного режима, сохраняются только при действующем C3) и серверные (время ответа, смена сетевого адреса, параллельные сессии, сравнение отпечатков ответов; хранятся только односторонние ключевые отпечатки, адреса и токены сессий не хранятся). `GET` возвращает версию уведомления, которую требует сервер, и признак, что кандидат ее подтвердил; `PUT` сохраняет подтверждение для аккаунта и этой версии. Подтверждение - запись о том, что кандидат ознакомлен, а не согласие: оно не меняет C3, и операция приема сигналов его не читает и не отклоняет пакет без него. `PUT` не требует Idempotency-Key: повтор сохраняет первое время и отвечает 200; другая версия отвечает 409 `state_conflict`. Режим `demo_express` сигналы не собирает и подтверждения не требует. +Уведомление о сигналах (`assessment-signal-notice`) перечисляет сигналы, которые собираются во время реальной попытки: события браузера (потеря фокуса, копирование, вставка и вырезание с размером, выход из полноэкранного режима, сохраняются только при действующем C3) и серверные (время ответа, смена сетевого адреса, параллельные сессии, сравнение отпечатков ответов; хранятся только односторонние ключевые отпечатки, адреса и токены сессий не хранятся). `GET` возвращает версию уведомления, которую требует сервер, и признак, что кандидат ее подтвердил; `PUT` сохраняет подтверждение для аккаунта и этой версии. Подтверждение - запись о том, что кандидат ознакомлен, а не согласие: оно не меняет C3, и операция приема сигналов его не читает и не отклоняет пакет без него. `PUT` не требует Idempotency-Key: повтор сохраняет первое время и отвечает 200; другая версия отвечает 409 `state_conflict`. Уведомление также перечисляет меры, которые страница применяет во время реальной попытки (полноэкранный режим, скрытие задания, запрет копирования, выделения и печати текста задания, правило вставки и планируемый водяной знак); это версия 2 текста, и подтверждение более ранней версии для текущей никогда не засчитывается. Режим `demo_express` сигналы не собирает и подтверждения не требует. Доступ: diff --git a/api/core/openapi.bundle.yml b/api/core/openapi.bundle.yml index b46cf51..9bd06c6 100644 --- a/api/core/openapi.bundle.yml +++ b/api/core/openapi.bundle.yml @@ -779,9 +779,9 @@ paths: operationId: GetMyAssessmentSignalNotice summary: Read whether the current candidate acknowledged the signal notice. description: |- - Requires the session cookie of a candidate account with a confirmed email; the candidate comes from the session. Returns the notice version that the server requires now and whether this candidate acknowledged it. The notice lists the signals that are collected during a real assessment attempt and states that images, sound, and clipboard contents are not collected. Client signals are the time away from the tab or window, copy, paste and cut with a size only, and exits from fullscreen mode. Server signals are the response time of each item measured by the server, a change of network address during the attempt, parallel sessions, and the comparison of answers to variants of the same task by candidates. The server stores for these only one-way keyed digests: it stores no network address, no session token, and no answer text. Client signals are stored only while the C3 consent is current. The client shows it before a real attempt starts and does not start the attempt until the notice is acknowledged. + Requires the session cookie of a candidate account with a confirmed email; the candidate comes from the session. Returns the notice version that the server requires now and whether this candidate acknowledged it. The notice lists the signals that are collected during a real assessment attempt and states that images, sound, and clipboard contents are not collected. Client signals are the time away from the tab or window, copy, paste and cut with a size only, and exits from fullscreen mode. Server signals are the response time of each item measured by the server, a change of network address during the attempt, parallel sessions, and the comparison of answers to variants of the same task by candidates. The server stores for these only one-way keyed digests: it stores no network address, no session token, and no answer text. Client signals are stored only while the C3 consent is current. The notice also lists the measures that the page applies during a real attempt: fullscreen mode, hiding the task when the candidate leaves fullscreen, the tab, or the window, blocking copy, selection, the context menu, drag, and printing of the task text, and blocking paste into answer fields (paste into the practice code editor is allowed and recorded as a signal with a size only). A watermark on the task page is announced as planned. These measures are applied by the client and never change a score, a category, or a quota. The client shows the notice before a real attempt starts and does not start the attempt until the notice is acknowledged. - The acknowledgement is stored on the server per account and notice version, so it survives a reload and a new browser. It is not a consent and never changes C3: the signal operation still requires a current C3 consent, and an unacknowledged notice does not make that operation fail. The demo_express training mode collects no signals and needs no acknowledgement. + The acknowledgement is stored on the server per account and notice version, so it survives a reload and a new browser. An acknowledgement of an earlier version never counts for the current one: when the text gains a version, every candidate acknowledges it again. It is not a consent and never changes C3: the signal operation still requires a current C3 consent, and an unacknowledged notice does not make that operation fail. The demo_express training mode collects no signals and needs no acknowledgement. A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account or an unconfirmed email answers 403 forbidden. security: diff --git a/api/core/routes/candidate_assessment_signal_notice.yml b/api/core/routes/candidate_assessment_signal_notice.yml index a45098f..c183519 100644 --- a/api/core/routes/candidate_assessment_signal_notice.yml +++ b/api/core/routes/candidate_assessment_signal_notice.yml @@ -2,9 +2,9 @@ get: operationId: GetMyAssessmentSignalNotice summary: Read whether the current candidate acknowledged the signal notice. description: |- - Requires the session cookie of a candidate account with a confirmed email; the candidate comes from the session. Returns the notice version that the server requires now and whether this candidate acknowledged it. The notice lists the signals that are collected during a real assessment attempt and states that images, sound, and clipboard contents are not collected. Client signals are the time away from the tab or window, copy, paste and cut with a size only, and exits from fullscreen mode. Server signals are the response time of each item measured by the server, a change of network address during the attempt, parallel sessions, and the comparison of answers to variants of the same task by candidates. The server stores for these only one-way keyed digests: it stores no network address, no session token, and no answer text. Client signals are stored only while the C3 consent is current. The client shows it before a real attempt starts and does not start the attempt until the notice is acknowledged. + Requires the session cookie of a candidate account with a confirmed email; the candidate comes from the session. Returns the notice version that the server requires now and whether this candidate acknowledged it. The notice lists the signals that are collected during a real assessment attempt and states that images, sound, and clipboard contents are not collected. Client signals are the time away from the tab or window, copy, paste and cut with a size only, and exits from fullscreen mode. Server signals are the response time of each item measured by the server, a change of network address during the attempt, parallel sessions, and the comparison of answers to variants of the same task by candidates. The server stores for these only one-way keyed digests: it stores no network address, no session token, and no answer text. Client signals are stored only while the C3 consent is current. The notice also lists the measures that the page applies during a real attempt: fullscreen mode, hiding the task when the candidate leaves fullscreen, the tab, or the window, blocking copy, selection, the context menu, drag, and printing of the task text, and blocking paste into answer fields (paste into the practice code editor is allowed and recorded as a signal with a size only). A watermark on the task page is announced as planned. These measures are applied by the client and never change a score, a category, or a quota. The client shows the notice before a real attempt starts and does not start the attempt until the notice is acknowledged. - The acknowledgement is stored on the server per account and notice version, so it survives a reload and a new browser. It is not a consent and never changes C3: the signal operation still requires a current C3 consent, and an unacknowledged notice does not make that operation fail. The demo_express training mode collects no signals and needs no acknowledgement. + The acknowledgement is stored on the server per account and notice version, so it survives a reload and a new browser. An acknowledgement of an earlier version never counts for the current one: when the text gains a version, every candidate acknowledges it again. It is not a consent and never changes C3: the signal operation still requires a current C3 consent, and an unacknowledged notice does not make that operation fail. The demo_express training mode collects no signals and needs no acknowledgement. A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account or an unconfirmed email answers 403 forbidden. security: diff --git a/backend/README.en.md b/backend/README.en.md index 01b22d0..89592c7 100644 --- a/backend/README.en.md +++ b/backend/README.en.md @@ -122,7 +122,7 @@ The candidate-only `POST /api/v1/me/assessment-attempts/{attempt_id}/signals` ac The operation limits the body to 32 KiB, each batch to 50 events, new receipts to 30 per minute per attempt, and stored events to 10,000 per attempt. Capacity is checked for the whole batch. A saturated receipt accepts zero events; idempotent replay returns the original receipt without consuming the receipt budget. Client timestamps are untrusted metadata: a timestamp outside five minutes before the attempt's creation to five minutes after database time rejects the whole batch with 400, so the client moves its timestamps to server time using the `Date` header; rate windows use database time. Migration 28 cascades event, batch, and receipt deletion with the attempt. Existing consent retention constraints still prevent physical account deletion; this cascade does not implement account erasure. Interpretation of these signals is separate work. -The notice about the collected signals is stored separately. `GET` and `PUT /api/v1/me/assessment-signal-notice` read and write the candidate's acknowledgement of a text version (`usecase/assessment/signal_notice.go`, table `assessment_signal_notice_acknowledgements`, migration 34). The server sets the text version; a `PUT` with another version answers 409 and stores nothing, and a repeat keeps the time of the first acknowledgement. The acknowledgement is not a consent: the signal operation does not read it and still requires current C3, so the notice cannot be used to hide a consent. Attempt creation does not check the acknowledgement on the server; the candidate screen enforces the requirement. Rows are deleted by cascade with the user. +The notice about the collected signals is stored separately. `GET` and `PUT /api/v1/me/assessment-signal-notice` read and write the candidate's acknowledgement of a text version (`usecase/assessment/signal_notice.go`, table `assessment_signal_notice_acknowledgements`, migration 34). The server sets the text version (`CurrentSignalNoticeVersion`, now 2: version 2 added the measures the page applies during an attempt to the signal list); an acknowledgement is stored per version, so one given for version 1 stays stored but never counts for version 2 and a new text needs no migration. A `PUT` with another version answers 409 and stores nothing, and a repeat keeps the time of the first acknowledgement. The acknowledgement is not a consent: the signal operation does not read it and still requires current C3, so the notice cannot be used to hide a consent. Attempt creation does not check the acknowledgement on the server; the candidate screen enforces the requirement. Rows are deleted by cascade with the user. ## Anonymous profile projection diff --git a/backend/README.md b/backend/README.md index edc1be1..4d7d462 100644 --- a/backend/README.md +++ b/backend/README.md @@ -122,7 +122,7 @@ Операция ограничивает тело 32 КиБ, пакет 50 событиями, новые квитанции приема 30 в минуту на попытку, а хранение 10 000 событиями на попытку. Вместимость проверяется для всего пакета. При заполнении принимается ноль событий; идемпотентный повтор возвращает исходную квитанцию без расходования лимита. Клиентское время считается недоверенными метаданными: метка вне окна от создания попытки минус пять минут до времени БД плюс пять минут отклоняет весь пакет с 400, поэтому клиент приводит метки к серверному времени по заголовку `Date`; окна частоты используют время БД. Миграция 28 каскадно удаляет события, пакеты и квитанции вместе с попыткой. Действующие ограничения хранения согласий по-прежнему запрещают физическое удаление аккаунта; этот каскад не реализует удаление аккаунта. Интерпретация сигналов относится к отдельной работе. -Уведомление о собираемых сигналах хранится отдельно. `GET` и `PUT /api/v1/me/assessment-signal-notice` читают и записывают подтверждение ознакомления кандидата с версией текста (`usecase/assessment/signal_notice.go`, таблица `assessment_signal_notice_acknowledgements`, миграция 34). Версию текста задает сервер; `PUT` с другой версией отвечает 409 и ничего не сохраняет, а повтор сохраняет время первого подтверждения. Подтверждение не является согласием: операция приема сигналов его не читает и по-прежнему требует действующего C3, поэтому уведомление нельзя использовать, чтобы скрыть согласие. Создание попытки подтверждение на сервере не проверяет; требование задает экран кандидата. Строки удаляются каскадом вместе с пользователем. +Уведомление о собираемых сигналах хранится отдельно. `GET` и `PUT /api/v1/me/assessment-signal-notice` читают и записывают подтверждение ознакомления кандидата с версией текста (`usecase/assessment/signal_notice.go`, таблица `assessment_signal_notice_acknowledgements`, миграция 34). Версию текста задает сервер (`CurrentSignalNoticeVersion`, сейчас 2: версия 2 добавила к перечню сигналов меры, которые страница применяет во время попытки); подтверждение хранится для каждой версии отдельно, поэтому данное для версии 1 остается в таблице, но для версии 2 не засчитывается, а новый текст не требует миграции. `PUT` с другой версией отвечает 409 и ничего не сохраняет, а повтор сохраняет время первого подтверждения. Подтверждение не является согласием: операция приема сигналов его не читает и по-прежнему требует действующего C3, поэтому уведомление нельзя использовать, чтобы скрыть согласие. Создание попытки подтверждение на сервере не проверяет; требование задает экран кандидата. Строки удаляются каскадом вместе с пользователем. ## Анонимная проекция профиля diff --git a/backend/integration_test/assessment_signal_notice_http_test.go b/backend/integration_test/assessment_signal_notice_http_test.go index cd62943..cef6488 100644 --- a/backend/integration_test/assessment_signal_notice_http_test.go +++ b/backend/integration_test/assessment_signal_notice_http_test.go @@ -63,7 +63,7 @@ func TestAssessmentSignalNoticeOverHTTP(t *testing.T) { requireSessionProblem(t, anonymous, http.StatusUnauthorized, "unauthenticated") before := decodeSignalNotice(t, request(http.MethodGet, "", "", cookie.Value, "")) - if before.NoticeVersion != 1 || before.Acknowledged || before.AcknowledgedAt != nil { + if before.NoticeVersion != 2 || before.Acknowledged || before.AcknowledgedAt != nil { t.Fatalf("notice before acknowledgement = %+v", before) } @@ -77,18 +77,21 @@ func TestAssessmentSignalNoticeOverHTTP(t *testing.T) { if rejected := request(http.MethodPut, `{"notice_version":1,"accepted":true}`, sessionHTTPTestOrigin, cookie.Value, csrf); rejected.Code != http.StatusBadRequest { t.Fatalf("unknown field = %d %s, want 400", rejected.Code, rejected.Body.String()) } - requireSessionProblem(t, request(http.MethodPut, `{"notice_version":2}`, sessionHTTPTestOrigin, cookie.Value, csrf), + requireSessionProblem(t, request(http.MethodPut, `{"notice_version":3}`, sessionHTTPTestOrigin, cookie.Value, csrf), + http.StatusConflict, "state_conflict") + // The previous version is no longer the one the server requires. + requireSessionProblem(t, request(http.MethodPut, `{"notice_version":1}`, sessionHTTPTestOrigin, cookie.Value, csrf), http.StatusConflict, "state_conflict") if untouched := decodeSignalNotice(t, request(http.MethodGet, "", "", cookie.Value, "")); untouched.Acknowledged { t.Fatalf("a refused request stored an acknowledgement: %+v", untouched) } - first := decodeSignalNotice(t, request(http.MethodPut, `{"notice_version":1}`, sessionHTTPTestOrigin, cookie.Value, csrf)) - if !first.Acknowledged || first.AcknowledgedAt == nil || first.NoticeVersion != 1 { + first := decodeSignalNotice(t, request(http.MethodPut, `{"notice_version":2}`, sessionHTTPTestOrigin, cookie.Value, csrf)) + if !first.Acknowledged || first.AcknowledgedAt == nil || first.NoticeVersion != 2 { t.Fatalf("first acknowledgement = %+v", first) } time.Sleep(5 * time.Millisecond) - repeat := decodeSignalNotice(t, request(http.MethodPut, `{"notice_version":1}`, sessionHTTPTestOrigin, cookie.Value, csrf)) + repeat := decodeSignalNotice(t, request(http.MethodPut, `{"notice_version":2}`, sessionHTTPTestOrigin, cookie.Value, csrf)) if repeat.AcknowledgedAt == nil || *repeat.AcknowledgedAt != *first.AcknowledgedAt { t.Fatalf("a repeat changed the first acknowledgement time: first %+v, repeat %+v", first, repeat) } @@ -101,12 +104,16 @@ func TestAssessmentSignalNoticeOverHTTP(t *testing.T) { if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM assessment_signal_notice_acknowledgements WHERE user_id = $1", candidate.ID).Scan(&rows); err != nil || rows != 1 { t.Fatalf("stored acknowledgement rows = %d, error %v, want exactly one", rows, err) } + // An acknowledgement of version 1 stays stored but does not count for version 2. + if _, err := harness.pool.Exec(ctx, "INSERT INTO assessment_signal_notice_acknowledgements (user_id, notice_version, acknowledged_at) VALUES ($1, 1, now())", other.ID); err != nil { + t.Fatalf("store a version 1 acknowledgement: %v", err) + } if foreign := decodeSignalNotice(t, request(http.MethodGet, "", "", otherCookie.Value, "")); foreign.Acknowledged { t.Fatalf("another account inherited the acknowledgement: %+v", foreign) } requireSessionProblem(t, request(http.MethodGet, "", "", employerCookie.Value, ""), http.StatusForbidden, "forbidden") - requireSessionProblem(t, request(http.MethodPut, `{"notice_version":1}`, sessionHTTPTestOrigin, employerCookie.Value, employerCSRF), + requireSessionProblem(t, request(http.MethodPut, `{"notice_version":2}`, sessionHTTPTestOrigin, employerCookie.Value, employerCSRF), http.StatusForbidden, "forbidden") // The acknowledgement is a record, not a consent: it creates no ledger row. diff --git a/backend/internal/adapter/primary/http/api/oas_handlers_gen.go b/backend/internal/adapter/primary/http/api/oas_handlers_gen.go index 66a3596..8fdf2c0 100644 --- a/backend/internal/adapter/primary/http/api/oas_handlers_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_handlers_gen.go @@ -4495,13 +4495,20 @@ func (s *Server) handleGetMyAssessmentResultRequest(args [1]string, argsEscaped // address during the attempt, parallel sessions, and the comparison of answers to variants of the same // task by candidates. The server stores for these only one-way keyed digests: it stores no network // address, no session token, and no answer text. Client signals are stored only while the C3 consent -// is current. The client shows it before a real attempt starts and does not start the attempt until -// the notice is acknowledged. +// is current. The notice also lists the measures that the page applies during a real attempt: +// fullscreen mode, hiding the task when the candidate leaves fullscreen, the tab, or the window, +// blocking copy, selection, the context menu, drag, and printing of the task text, and blocking paste +// into answer fields (paste into the practice code editor is allowed and recorded as a signal with a +// size only). A watermark on the task page is announced as planned. These measures are applied by the +// client and never change a score, a category, or a quota. The client shows the notice before a real +// attempt starts and does not start the attempt until the notice is acknowledged. // // The acknowledgement is stored on the server per account and notice version, so it survives a reload -// and a new browser. It is not a consent and never changes C3: the signal operation still requires a -// current C3 consent, and an unacknowledged notice does not make that operation fail. The demo_express -// training mode collects no signals and needs no acknowledgement. +// and a new browser. An acknowledgement of an earlier version never counts for the current one: when +// the text gains a version, every candidate acknowledges it again. It is not a consent and never +// changes C3: the signal operation still requires a current C3 consent, and an unacknowledged notice +// does not make that operation fail. The demo_express training mode collects no signals and needs no +// acknowledgement. // // A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account or // an unconfirmed email answers 403 forbidden. diff --git a/backend/internal/adapter/primary/http/api/oas_server_gen.go b/backend/internal/adapter/primary/http/api/oas_server_gen.go index 3131ce5..01535ae 100644 --- a/backend/internal/adapter/primary/http/api/oas_server_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_server_gen.go @@ -663,13 +663,20 @@ type Handler interface { // address during the attempt, parallel sessions, and the comparison of answers to variants of the same // task by candidates. The server stores for these only one-way keyed digests: it stores no network // address, no session token, and no answer text. Client signals are stored only while the C3 consent - // is current. The client shows it before a real attempt starts and does not start the attempt until - // the notice is acknowledged. + // is current. The notice also lists the measures that the page applies during a real attempt: + // fullscreen mode, hiding the task when the candidate leaves fullscreen, the tab, or the window, + // blocking copy, selection, the context menu, drag, and printing of the task text, and blocking paste + // into answer fields (paste into the practice code editor is allowed and recorded as a signal with a + // size only). A watermark on the task page is announced as planned. These measures are applied by the + // client and never change a score, a category, or a quota. The client shows the notice before a real + // attempt starts and does not start the attempt until the notice is acknowledged. // // The acknowledgement is stored on the server per account and notice version, so it survives a reload - // and a new browser. It is not a consent and never changes C3: the signal operation still requires a - // current C3 consent, and an unacknowledged notice does not make that operation fail. The demo_express - // training mode collects no signals and needs no acknowledgement. + // and a new browser. An acknowledgement of an earlier version never counts for the current one: when + // the text gains a version, every candidate acknowledges it again. It is not a consent and never + // changes C3: the signal operation still requires a current C3 consent, and an unacknowledged notice + // does not make that operation fail. The demo_express training mode collects no signals and needs no + // acknowledgement. // // A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account or // an unconfirmed email answers 403 forbidden. diff --git a/backend/internal/adapter/primary/http/api/oas_unimplemented_gen.go b/backend/internal/adapter/primary/http/api/oas_unimplemented_gen.go index 12610ab..df8a42e 100644 --- a/backend/internal/adapter/primary/http/api/oas_unimplemented_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_unimplemented_gen.go @@ -725,13 +725,20 @@ func (UnimplementedHandler) GetMyAssessmentResult(ctx context.Context, params Ge // address during the attempt, parallel sessions, and the comparison of answers to variants of the same // task by candidates. The server stores for these only one-way keyed digests: it stores no network // address, no session token, and no answer text. Client signals are stored only while the C3 consent -// is current. The client shows it before a real attempt starts and does not start the attempt until -// the notice is acknowledged. +// is current. The notice also lists the measures that the page applies during a real attempt: +// fullscreen mode, hiding the task when the candidate leaves fullscreen, the tab, or the window, +// blocking copy, selection, the context menu, drag, and printing of the task text, and blocking paste +// into answer fields (paste into the practice code editor is allowed and recorded as a signal with a +// size only). A watermark on the task page is announced as planned. These measures are applied by the +// client and never change a score, a category, or a quota. The client shows the notice before a real +// attempt starts and does not start the attempt until the notice is acknowledged. // // The acknowledgement is stored on the server per account and notice version, so it survives a reload -// and a new browser. It is not a consent and never changes C3: the signal operation still requires a -// current C3 consent, and an unacknowledged notice does not make that operation fail. The demo_express -// training mode collects no signals and needs no acknowledgement. +// and a new browser. An acknowledgement of an earlier version never counts for the current one: when +// the text gains a version, every candidate acknowledges it again. It is not a consent and never +// changes C3: the signal operation still requires a current C3 consent, and an unacknowledged notice +// does not make that operation fail. The demo_express training mode collects no signals and needs no +// acknowledgement. // // A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account or // an unconfirmed email answers 403 forbidden. diff --git a/backend/internal/usecase/assessment/signal_notice.go b/backend/internal/usecase/assessment/signal_notice.go index 4a71af6..7945f21 100644 --- a/backend/internal/usecase/assessment/signal_notice.go +++ b/backend/internal/usecase/assessment/signal_notice.go @@ -12,9 +12,14 @@ import ( ) // CurrentSignalNoticeVersion is the version of the notice text that lists the -// collected assessment signals. Change it together with the client text so that -// every candidate acknowledges the new wording. -const CurrentSignalNoticeVersion int32 = 1 +// collected assessment signals and the measures the page applies during an +// attempt (fullscreen, hiding the task when the candidate leaves, copy, print, +// and paste restrictions). Change it together with the client text so that +// every candidate acknowledges the new wording. Acknowledgements are stored per +// version, so one given for an earlier version never counts for this one. +// +// Version 2 added the attempt measures to the text; version 1 listed signals only. +const CurrentSignalNoticeVersion int32 = 2 // ErrSignalNoticeVersionMismatch reports an acknowledgement for a notice // version other than the one the server requires. diff --git a/backend/internal/usecase/assessment/signal_notice_test.go b/backend/internal/usecase/assessment/signal_notice_test.go new file mode 100644 index 0000000..9b84a74 --- /dev/null +++ b/backend/internal/usecase/assessment/signal_notice_test.go @@ -0,0 +1,21 @@ +package assessment + +import ( + "context" + "errors" + "testing" + + "github.com/google/uuid" +) + +func TestAcknowledgeSignalNoticeRefusesEveryVersionButTheCurrentOne(t *testing.T) { + // A refused version returns before the service touches storage, so an + // acknowledgement of an earlier notice text can never count for this one. + service := &SignalService{} + for _, version := range []int32{CurrentSignalNoticeVersion - 1, CurrentSignalNoticeVersion + 1} { + _, err := service.AcknowledgeSignalNotice(context.Background(), uuid.New(), version) + if !errors.Is(err, ErrSignalNoticeVersionMismatch) { + t.Fatalf("AcknowledgeSignalNotice(version %d) error = %v, want %v", version, err, ErrSignalNoticeVersionMismatch) + } + } +} diff --git a/docs/en/ARCHITECTURE.md b/docs/en/ARCHITECTURE.md index eacf5b1..760060d 100644 --- a/docs/en/ARCHITECTURE.md +++ b/docs/en/ARCHITECTURE.md @@ -688,7 +688,7 @@ Code: migration `backend/db/migrations/00033_create_assessment_signal_review.sql - Why the demo thresholds are 48 and 64 bits, and what the figure means. `TestDemoDuplicateThresholdsKeepThePerAttemptFalseFlagRateLow` samples 4000 seeds of each of the four demo families (the three integer families have 36 to 47 distinct answers, the dependency order about 2250), builds the distribution of shared values and their bits, and computes the probability that one pair of honest candidates who answer a 23-item attempt correctly reaches each threshold. Multiplied by 10,000 rivals (union bound), the per-attempt false flag rate is about 4e-5 for attention and 3e-9 for review, against test targets of 1e-3 and 1e-8. The model uses the distribution of reference answers: it does not model the distribution of wrong answers or correlated mistakes (candidates who make the same common error, or a shared tutorial), which can make honest coincidences more likely than computed. These are demo values pending calibration on a real bank, with four AI-drafted families. In the other direction, `TestDemoThresholdsNeedAPopulationBeforeACopiedPairIsFlagged` calculates how many answers per family a copied pair needs before the demo thresholds flag it, when the pair copies every answer and nobody else holds those values: for an attempt of 13 items, attention from 26 answers per family and review from 61; for 23 items, from 9 and from 14. A stand with fewer attempts flags nothing by design. To try the feature on a small stand, publish a policy version with lower thresholds in `assessment.signals` (the integration tests do this with 4 and 6 bits); the demo policy is not changed for that. - Policy. The optional section `assessment.signals` of a schema 2 policy document holds every threshold (`domain.AssessmentSignalPolicy`); a version without it computes no band. `DemoProductPolicyV3` is `DemoProductPolicyV2` plus `DemoAssessmentSignalPolicy`; `DemoProductPolicyV1` and `DemoProductPolicyV2` and the startup seed are unchanged, and a stored version is never rewritten. The band uses the thresholds of the product policy version in `assessment_attempts.product_policy_version_id`, so a policy published later does not change an attempt in progress or a stored review; `assessment_attempt_reviews.policy_version_id` records the version, and a trigger refuses to change it. A matched attempt is re-evaluated under its own pinned version; pairs are selected with the attention level of the evaluating attempt, so across versions with different levels a pair can be missed on the side with the lower level. - When and how. The review never runs in a candidate's transaction. The first accepted answer schedules the job `assessment.signal_review` with the key `:deadline`, due one minute after the deadline of the attempt (so an answer committed right at the deadline is in its facts), and finalization schedules `:ended`, due at once; both are inserts into `scheduled_jobs` in the transaction of the answer or the finalization, and repeats do nothing. The deadline job also covers an attempt that expires or is abandoned, however and whenever its state changes. A review is a point-in-time evaluation: it describes the facts committed when its job ran, and the job at the deadline runs it again for a finalized attempt, which picks up later matches. The job computes the review of its attempt and refreshes the review of every other attempt that has ended (terminal state or past its deadline) and shares answers with it at the attention level or above, at most 50 per job; a ring of more than 50 attempts that share answers is covered because each member runs its own deadline job and sees the others. An attempt that is still running is flagged by its own job when it ends and sees the other facts then. Writers are ordered by a transaction-scoped advisory lock per review: the job locks the review of every attempt it will write, in ascending attempt order, before it reads any fact, so the later of two jobs over one attempt waits and then reads what the earlier committed (no lost update, and no lock cycle). The times of a review come from the database clock inside the upsert and the update time never falls behind the stored times. Nothing else is locked: the facts are append-only and a job is scheduled after its facts are committed. A failure is retried by the runner with backoff and can never block or change a result; without the worker (`JOBS_ENABLED=false`) reviews wait with their jobs. The only review statement in a candidate's transaction is the insert of the job (and the two counter updates of the answer). The job logs one line with the number of reviews it wrote and its duration, and no answer, address, or candidate. Applicability bound: the share is read from the counters in constant time, but the comparison joins the answers of the attempt with the answers that hold the same values, so its cost grows with the number of holders of popular values, at most 23 items times the holders of each; it is fine for background jobs on populations of up to about 100,000 answers per family and needs sampling or a cap above that. -- Limits. Browser signals can be forged or suppressed, so they are a hint only. A helper such as an LLM on another device is not visible. False positives are possible: a shared or changing network (mobile data, NAT), a reload, two tabs, copying the task text, and coinciding answers of a small answer space. The retention period of these facts, whether collecting them needs a separate consent beyond the notice, and who calibrates the thresholds are not decided. +- Limits. Browser signals can be forged or suppressed, so they are a hint only. The client measures of the attempt page (fullscreen, covering the task, blocking copy, selection, print, and paste) stop only the casual route: the task text is in the candidate's browser, so a screenshot, a second device, or an extension takes it out, and they change no score by themselves. A helper such as an LLM on another device is not visible. False positives are possible: a shared or changing network (mobile data, NAT), a reload, two tabs, copying the task text, and coinciding answers of a small answer space. The retention period of these facts, whether collecting them needs a separate consent beyond the notice, and who calibrates the thresholds are not decided. ### Skill evidence diff --git a/docs/en/TESTING.md b/docs/en/TESTING.md index 29183f7..ee392ba 100644 --- a/docs/en/TESTING.md +++ b/docs/en/TESTING.md @@ -536,6 +536,14 @@ Unit tests (`make -C backend test`) check the visibility rules without a databas The tests prove the stored facts, the policy pinning, the job-based computation, and the absence of the band from the contract and from candidate reads. They do not prove detection quality: the thresholds are uncalibrated, the false-positive measurement covers four drafted families, and no study of real candidates exists. The employer reads are covered by the contract walk, not by an HTTP call per operation. +## 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 2 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 version 2. + +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 2. 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. + ## Internal notification tests Unit tests (`make -C backend test`, `make -C frontend test`): diff --git a/docs/ru/ARCHITECTURE.md b/docs/ru/ARCHITECTURE.md index 40e1e7e..ceeff0d 100644 --- a/docs/ru/ARCHITECTURE.md +++ b/docs/ru/ARCHITECTURE.md @@ -688,7 +688,7 @@ contact_grant относится к паре кандидат-компания - Почему демо-пороги равны 48 и 64 битам и что означает эта цифра. `TestDemoDuplicateThresholdsKeepThePerAttemptFalseFlagRateLow` берет по 4000 seed каждого из четырех демо-семейств (у трех целочисленных 36-47 различных ответов, у порядка зависимостей около 2250), строит распределение общих значений и их битов и считает вероятность того, что одна пара честных кандидатов, верно ответивших на попытку из 23 заданий, достигнет каждого порога. Умноженная на 10 000 соперников (граница объединения), доля ложных пометок на попытку - около 4e-5 для «внимание» и 3e-9 для «проверить» при целях теста 1e-3 и 1e-8. Модель использует распределение эталонных ответов: она не моделирует распределение неверных ответов и коррелированные ошибки (одинаковая типичная ошибка многих кандидатов, общий учебник), из-за которых честные совпадения могут быть вероятнее расчетных. Это демо-значения до калибровки на настоящем банке, измеренные на четырех семействах, написанных ИИ. В обратную сторону `TestDemoThresholdsNeedAPopulationBeforeACopiedPairIsFlagged` считает, сколько ответов на семейство нужно скопированной паре, чтобы демо-пороги ее пометили, когда пара копирует все ответы и больше никто эти значения не держит: для попытки из 13 заданий «внимание» от 26 ответов на семейство и «проверить» от 61; для 23 заданий от 9 и от 14. Стенд с меньшим числом попыток по замыслу ничего не помечает. Чтобы попробовать функцию на малом стенде, опубликуйте версию политики с меньшими порогами в `assessment.signals` (интеграционные тесты делают так с 4 и 6 битами); демо-политика для этого не меняется. - Политика. Необязательный раздел `assessment.signals` документа схемы 2 хранит все пороги (`domain.AssessmentSignalPolicy`); версия без него не считает полосу. `DemoProductPolicyV3` - это `DemoProductPolicyV2` плюс `DemoAssessmentSignalPolicy`; `DemoProductPolicyV1`, `DemoProductPolicyV2` и стартовый seed не изменились, сохраненная версия не переписывается. Полоса использует пороги версии продуктовой политики из `assessment_attempts.product_policy_version_id`, поэтому политика, опубликованная позже, не меняет попытку в процессе и сохраненную проверку; `assessment_attempt_reviews.policy_version_id` фиксирует версию, а триггер запрещает ее менять. Попытка из пары пересчитывается под своей закрепленной версией; пары выбираются по уровню «внимание» считающей попытки, поэтому между версиями с разными уровнями пара может быть пропущена на стороне с меньшим уровнем. - Когда и как. Проверка никогда не считается в транзакции кандидата. Первый принятый ответ планирует задание `assessment.signal_review` с ключом `<попытка>:deadline`, срок - через минуту после дедлайна попытки (чтобы ответ, зафиксированный прямо на дедлайне, попал в факты), а завершение планирует `<попытка>:ended`, срок - сразу; оба - вставки в `scheduled_jobs` в транзакции ответа или завершения, повтор ничего не делает. Задание дедлайна покрывает и попытку, которая истекает или брошена, как и когда бы ни менялось ее состояние. Проверка - оценка на момент: она описывает факты, зафиксированные к запуску ее задания, а задание на дедлайне для завершенной попытки запускает ее снова и подхватывает поздние совпадения. Задание считает проверку своей попытки и обновляет проверку каждой другой завершившейся (терминальное состояние или срок прошел) попытки с общими ответами на уровне «внимание» и выше, не более 50 за задание; кольцо больше 50 попыток с общими ответами покрыто тем, что каждый участник запускает свое задание дедлайна и видит остальных. Еще идущую попытку помечает ее собственное задание, когда она закончится и увидит остальные факты. Писатели упорядочены транзакционной advisory-блокировкой на каждую проверку: задание берет блокировки проверок всех попыток, которые будет писать, по возрастанию идентификатора, до чтения любого факта, поэтому более позднее из двух заданий по одной попытке ждет и затем читает то, что зафиксировало раннее (нет потерянного обновления и нет цикла блокировок). Время проверки берется из часов базы внутри upsert, а время обновления не отстает от сохраненного. Больше ничего не блокируется: факты только добавляются, а задание планируется после фиксации его фактов. Сбой повторяется исполнителем с задержкой и никогда не блокирует и не меняет результат; без worker (`JOBS_ENABLED=false`) проверки ждут вместе со своими заданиями. В транзакции кандидата из запросов проверки только вставка задания (и два обновления счетчиков ответа). Задание пишет в журнал одну строку с числом записанных проверок и длительностью, без ответов, адресов и кандидатов. Граница применимости: доля читается из счетчиков за постоянное время, но сравнение соединяет ответы попытки с ответами, у которых те же значения, поэтому цена растет с числом держателей популярных значений, не более 23 заданий на число держателей каждого; для фоновых заданий это нормально на совокупностях до порядка 100 000 ответов на семейство, выше нужна выборка или предел. -- Ограничения. Браузерные сигналы можно подделать или подавить, поэтому это только подсказка. Помощь, например LLM на другом устройстве, не видна. Возможны ложные срабатывания: общая или меняющаяся сеть (мобильный интернет, NAT), перезагрузка страницы, две вкладки, копирование условия и случайные совпадения ответов из малого пространства. Срок хранения этих фактов, нужно ли для их сбора отдельное согласие сверх уведомления и кто калибрует пороги, не решено. +- Ограничения. Браузерные сигналы можно подделать или подавить, поэтому это только подсказка. Клиентские меры страницы попытки (полноэкранный режим, скрытие задания, запрет копирования, выделения, печати и вставки) останавливают только простой путь: текст задания находится в браузере кандидата, поэтому снимок экрана, второе устройство или расширение его выносят, а сами по себе эти меры оценку не меняют. Помощь, например LLM на другом устройстве, не видна. Возможны ложные срабатывания: общая или меняющаяся сеть (мобильный интернет, NAT), перезагрузка страницы, две вкладки, копирование условия и случайные совпадения ответов из малого пространства. Срок хранения этих фактов, нужно ли для их сбора отдельное согласие сверх уведомления и кто калибрует пороги, не решено. ### Доказательства навыков diff --git a/docs/ru/TESTING.md b/docs/ru/TESTING.md index 94a17b3..242bb24 100644 --- a/docs/ru/TESTING.md +++ b/docs/ru/TESTING.md @@ -536,6 +536,14 @@ Spec не проверяет запланированные переходы б Тесты доказывают сохраненные факты, закрепление политики, вычисление заданием и отсутствие полосы в контракте и в чтениях кандидата. Они не доказывают качество обнаружения: пороги не откалиброваны, измерение ложных срабатываний покрывает четыре написанных семейства, исследования на реальных кандидатах нет. Чтения работодателя покрыты обходом контракта, а не HTTP-вызовом каждой операции. +## Тесты ограничений во время попытки + +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` проверяет, что скрытая форма ничего не рисует. Версия 2 текста уведомления и перечень мер проверяются в `features/assessment-signals/ui/signal-notice.test.tsx`. В бэкенде `usecase/assessment/signal_notice_test.go` проверяет, что любая версия, кроме текущей, отклоняется, а `TestAssessmentSignalNoticeOverHTTP` по HTTP с PostgreSQL проверяет, что сохраненное подтверждение версии 1 не засчитывается для версии 2. + +Модульные тесты защиты задания: `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`, который теперь ожидает версию 2. Эти спецификации показывают поведение страницы в Chromium с подставным сервером; они не показывают поведение в других браузерах, на телефоне, с настоящим экранным диктором и в оконном менеджере, который сам меняет полноэкранный режим. Правило вставки не видит текст, который экранная клавиатура вставляет как набор. + ## Тесты внутренних уведомлений Модульные тесты (`make -C backend test`, `make -C frontend test`): diff --git a/frontend/README.en.md b/frontend/README.en.md index b5c14c3..1929693 100644 --- a/frontend/README.en.md +++ b/frontend/README.en.md @@ -69,12 +69,16 @@ The attempt screen focuses on the item: a strip above it names the attempt and s The `Idempotency-Key` of the express start is kept in the tab's sessionStorage per account until the run is finished or expired, and for 24 hours at most. When a new start gets 409 `state_conflict`, the page repeats the start with the key of the active run, and the server returns the stored 201 with that attempt: an unfinished demonstration continues after a reload. The key of a start with an unknown outcome (no response, 5xx) is kept and repeated as well. Without a key (another browser, a closed tab, blocked storage), the screen explains that the demonstration ends by itself within 5 minutes of its start. -Before a real attempt starts, the screen shows a dialog that lists the signals. The browser records tab or window switches, copy, paste and cut, and fullscreen exits; the server measures the answer time per item, a change of network address during the attempt, parallel sessions, and the match of answer digests with other candidates' answers. The dialog states that image, sound, and clipboard contents are not collected, that addresses and session tokens are not stored (only one-way keyed digests), and that browser events are stored only while the C3 consent is current. The attempt cannot start without confirmation: closing the dialog or pressing Escape starts nothing. The confirmation is stored on the server (`/me/assessment-signal-notice`) for the text version, so a reload or a new browser does not ask again; the same dialog opens when an older attempt that was created without the confirmation is resumed. It is a record of being informed, not a consent: C3 stays separate. +Before a real attempt starts, the screen shows a dialog that lists the signals. The browser records tab or window switches, copy, paste and cut, and fullscreen exits; the server measures the answer time per item, a change of network address during the attempt, parallel sessions, and the match of answer digests with other candidates' answers. The dialog states that image, sound, and clipboard contents are not collected, that addresses and session tokens are not stored (only one-way keyed digests), and that browser events are stored only while the C3 consent is current. The attempt cannot start without confirmation: closing the dialog or pressing Escape starts nothing. The dialog also lists the measures the page applies during the attempt (fullscreen, covering the task when the candidate leaves, blocks on copying, selecting, and printing the task text, the paste rule, and a watermark that is announced as planned and not used yet). This is notice text version 2; an acknowledgement of version 1 does not count for it. The confirmation is stored on the server (`/me/assessment-signal-notice`) for the text version, so a reload or a new browser does not ask again; the same dialog opens when an older attempt that was created without the confirmation is resumed. It is a record of being informed, not a consent: C3 stays separate. -During a real attempt, `features/assessment-signals` collects the disclosed signals: focus loss with its duration, copy, paste and cut with a size only, and fullscreen exit. The listeners are passive, block nothing, and show nothing. Events go in batches (every 10 seconds, when the tab is hidden, or at 20 queued events), and each batch keeps one `Idempotency-Key` across retries. When the page is closed (`pagehide`) or the collector unmounts, what remains is sent in one last request with `keepalive`, so closing the tab does not lose the last seconds of events; the result of that request is not awaited and not retried. A network failure never affects answer submission: a failed batch is sent again with the same key and body after a growing pause and is dropped after the attempt limit. A server refusal (no C3, finished attempt) stops collection. The demonstration run collects no signals. +During a real attempt, `features/assessment-signals` collects the disclosed signals: focus loss with its duration, copy, paste and cut with a size only, and fullscreen exit. The collector's listeners are passive, block nothing, and show nothing (the measures of the next paragraph are a separate feature and do not depend on it). Events go in batches (every 10 seconds, when the tab is hidden, or at 20 queued events), and each batch keeps one `Idempotency-Key` across retries. When the page is closed (`pagehide`) or the collector unmounts, what remains is sent in one last request with `keepalive`, so closing the tab does not lose the last seconds of events; the result of that request is not awaited and not retried. A network failure never affects answer submission: a failed batch is sent again with the same key and body after a growing pause and is dropped after the attempt limit. A server refusal (no C3, finished attempt) stops collection. The demonstration run collects no signals. Clipboard contents and typed text are never read into a signal or sent. The paste size comes from the `paste` event: file sizes (`File.size`) plus the UTF-8 length of the plain-text item of `clipboardData`; the string lives in one local variable during the count and is not kept. The Clipboard API (`navigator.clipboard`) is not used. The copy and cut size is the selection length in UTF-16 code units taken from the field offsets without reading its value; when the active field has no numeric offsets the size is zero and the page selection is not read. It is an approximate size, not an exact byte count. The answer time per item is measured by the server and not sent by the client. Event timestamps are moved to server time: the client remembers the difference between the device clock and the `Date` header of API responses, because the server rejects a whole batch when a timestamp is more than five minutes from its own clock. Durations use the device clock and do not depend on that difference. Browser signals are easy to forge and false positives are possible, so they are only a hint for a review. +`features/assessment-lockdown` keeps a real attempt in fullscreen and hides the task when the candidate leaves it. The click on "Start or continue" requests fullscreen: the request has to be made inside the click, before the asynchronous notice check, because the browser accepts it only with a user gesture; closing the notice without confirming leaves fullscreen again. While the work runs, the task is covered when fullscreen is exited, the tab is hidden, or the window loses focus (`fullscreenchange`, `visibilitychange`, `focus` and `blur`). The cover replaces the task instead of blurring it: the prompt, the options, and the answer controls are not rendered, so they are not in the DOM, in a screenshot of the page, or in the accessibility tree. The answer form stays mounted and renders nothing, so the draft survives (and the sessionStorage copy of the draft is still kept). The timer stays the server's and stays on screen. After leaving fullscreen the candidate continues with a button, which is the user gesture the browser needs to enter fullscreen again; leaving only the tab or the window needs no click. These exits are recorded by the collector above (`fullscreen_exit`, `focus_loss`); the cover records nothing itself. A browser without element fullscreen (iPhone Safari) or one that refuses the request gets an information notice and takes the test with the tab watch alone (`fallback` `unsupported` or `denied`), so the screen is never a dead end. The express run and a finished attempt are not protected, and leaving the page or finishing the attempt leaves fullscreen. + +The same panel (`ProtectedRegion`) keeps the task text of a real attempt from being taken out. The text cannot be selected (`user-select`, with the `-webkit-` form that Safari still needs, and a cancelled `selectstart`), the context menu and drag are cancelled on it, copy and cut are cancelled when the target or the selection reaches into the panel (the clipboard text is set to an empty string), and `@media print` hides the panel with the task, the options, and the answer fields. Fields are exempt: a text field keeps selection, its own context menu, and copy and cut of the candidate's own text. Paste into answer fields is refused (the `paste` event, and `beforeinput` of the paste kind), the screen says so with a short status that goes away on the next input, and dropping text into a field is refused everywhere. The code editor of a practice item carries `data-paste="allowed"`: pasting works there and its size goes out as the existing `paste` signal. The collector sees every paste, copy, and cut, including the refused ones, because the guard cancels the default action and never stops propagation, so a refused paste is still a signal with a size. The text stays in the page for screen readers (no canvas, no image text), typing and the focus order are untouched, and the express run is not restricted. These measures stop the casual route only: a screenshot, a second device, or a browser extension still takes the task out, and a paste by an on-screen keyboard that inserts text as typing is not visible to the page. + ## Candidate results `/candidate/results` lists the completed real assessments of the current candidate (`GET /me/assessment-results`, 20 records per page; the cursor comes only from the server response and is never built on the client). `/candidate/results/:attemptId` opens one record by a direct URL. Both screens read data only for a confirmed candidate session: query keys include the account identifier and the session token, data does not outlive the screen (`gcTime: 0`) and is removed when the session changes or ends. A 401, 403, or 404 response shows an "unavailable" screen without data and does not reveal whether another candidate's result exists; the assessment cache is cleared only on 401, while a network or 5xx failure offers a retry and is not treated as lost access. A failed background refresh keeps the data that was already loaded and says so. Dates are shown in the browser time zone with its name. "Show more" moves the focus to the first new row and announces how many were loaded. Loading, empty history, and error states with retry exist. A failed attempt after a successful one, adaptive estimate values, retry dates, and missing-field cases are covered by unit contract fixtures because the stand cannot produce them; the e2e test checks the shape of the flow (a real result, the express run, ownership, sign-out; the session ends through the API, not through the account menu, because the menu reloads the page). By contract, express tests are not part of the history; their result opens from the attempt screen or by a direct URL and is captioned "Экспресс-тест без грейда" (express test without a grade). diff --git a/frontend/README.md b/frontend/README.md index 713d9d6..c76bf57 100644 --- a/frontend/README.md +++ b/frontend/README.md @@ -69,12 +69,16 @@ SPA на React и TypeScript со сборкой Vite и структурой FS `Idempotency-Key` начала экспресс-запуска хранится в sessionStorage вкладки отдельно для каждого аккаунта, пока запуск не завершен или не истек, и не дольше 24 часов. Если новое начало получает 409 `state_conflict`, страница повторяет начало с ключом активного запуска, и сервер возвращает сохраненный ответ 201 с этой попыткой: незавершенная демонстрация продолжается после перезагрузки. Ключ начала с неизвестным исходом (нет ответа, 5xx) тоже сохраняется и повторяется. Если ключа нет (другой браузер, закрытая вкладка, заблокированное хранилище), экран объясняет, что демонстрация закончится сама не позже чем через 5 минут после начала. -Перед началом реальной попытки экран показывает окно с перечнем сигналов. Браузер фиксирует смену вкладки или окна, копирование, вставку и вырезание, выход из полноэкранного режима; сервер измеряет время ответа на задание, смену сетевого адреса во время попытки, параллельные сессии и совпадение отпечатков ответов с ответами других кандидатов. Окно прямо говорит, что изображение, звук и содержимое буфера обмена не собираются, что адреса и токены сессий не хранятся (только односторонние ключевые отпечатки) и что события браузера сохраняются, только пока действует согласие C3. Начало без подтверждения невозможно: закрытие окна или Escape ничего не запускает. Подтверждение сохраняется на сервере (`/me/assessment-signal-notice`) для версии текста, поэтому перезагрузка и новый браузер не спрашивают повторно; такое же окно открывается при продолжении старой попытки, начатой без подтверждения. Это запись об ознакомлении, а не согласие: C3 остается отдельным. +Перед началом реальной попытки экран показывает окно с перечнем сигналов. Браузер фиксирует смену вкладки или окна, копирование, вставку и вырезание, выход из полноэкранного режима; сервер измеряет время ответа на задание, смену сетевого адреса во время попытки, параллельные сессии и совпадение отпечатков ответов с ответами других кандидатов. Окно прямо говорит, что изображение, звук и содержимое буфера обмена не собираются, что адреса и токены сессий не хранятся (только односторонние ключевые отпечатки) и что события браузера сохраняются, только пока действует согласие C3. Начало без подтверждения невозможно: закрытие окна или Escape ничего не запускает. Окно также перечисляет меры, которые страница применяет во время попытки (полноэкранный режим, скрытие задания при уходе, запрет копирования, выделения и печати текста задания, правило вставки и водяной знак, который объявлен как планируемый и пока не используется). Это версия 2 текста уведомления; подтверждение версии 1 для нее не засчитывается. Подтверждение сохраняется на сервере (`/me/assessment-signal-notice`) для версии текста, поэтому перезагрузка и новый браузер не спрашивают повторно; такое же окно открывается при продолжении старой попытки, начатой без подтверждения. Это запись об ознакомлении, а не согласие: C3 остается отдельным. -Во время реальной попытки `features/assessment-signals` собирает отправляемые сигналы: потерю фокуса с длительностью, копирование, вставку и вырезание только с размером, выход из полноэкранного режима. Слушатели пассивные, ничего не блокируют и не показывают; события уходят пакетами (по таймеру в 10 секунд, при скрытии вкладки или накоплении 20 событий), у каждого пакета свой `Idempotency-Key`, который сохраняется при повторах. При закрытии страницы (`pagehide`) и при размонтировании оставшиеся события отправляются последним запросом с `keepalive`, поэтому закрытие вкладки не теряет накопленное за последние секунды; результат такого запроса не ожидается и не повторяется. Сбой сети никогда не мешает отправке ответа: неудачный пакет повторяется с тем же ключом и телом с нарастающей паузой, а после лимита попыток отбрасывается. Ответ сервера об отказе (нет C3, попытка завершена) останавливает сбор. Демонстрационный запуск сигналы не собирает. +Во время реальной попытки `features/assessment-signals` собирает отправляемые сигналы: потерю фокуса с длительностью, копирование, вставку и вырезание только с размером, выход из полноэкранного режима. Слушатели сборщика пассивные, ничего не блокируют и не показывают (меры из следующего абзаца - отдельная функция и от сборщика не зависят); события уходят пакетами (по таймеру в 10 секунд, при скрытии вкладки или накоплении 20 событий), у каждого пакета свой `Idempotency-Key`, который сохраняется при повторах. При закрытии страницы (`pagehide`) и при размонтировании оставшиеся события отправляются последним запросом с `keepalive`, поэтому закрытие вкладки не теряет накопленное за последние секунды; результат такого запроса не ожидается и не повторяется. Сбой сети никогда не мешает отправке ответа: неудачный пакет повторяется с тем же ключом и телом с нарастающей паузой, а после лимита попыток отбрасывается. Ответ сервера об отказе (нет C3, попытка завершена) останавливает сбор. Демонстрационный запуск сигналы не собирает. Содержимое буфера и вводимый текст не читаются в сигнал и не отправляются. Размер вставки берется из события `paste`: размер файлов (`File.size`) и длина обычного текста в байтах UTF-8 из `clipboardData`; строка живет в одной локальной переменной на время подсчета и не сохраняется. Clipboard API (`navigator.clipboard`) не используется. Размер копирования и вырезания - длина выделения в единицах UTF-16 по смещениям поля, без чтения его значения; если у активного поля нет числовых смещений, размер равен нулю, а выделение страницы не читается. Это приблизительный размер, а не точный счет байтов. Время ответа по заданию измеряет сервер, клиент его не присылает. Время событий приводится к серверному: клиент запоминает разницу между часами устройства и заголовком `Date` ответов API, потому что сервер отклоняет весь пакет, если метка времени выходит за пять минут от его часов. Длительности считаются по часам устройства и от этой разницы не зависят. Браузерные сигналы легко подделать, а ложные срабатывания возможны, поэтому они только подсказка для перепроверки. +`features/assessment-lockdown` держит реальную попытку в полноэкранном режиме и скрывает задание, когда кандидат его покидает. Клик по кнопке "Начать или продолжить" запрашивает полноэкранный режим: запрос нужно сделать внутри клика, до асинхронной проверки уведомления, потому что браузер принимает его только при действии пользователя; закрытие уведомления без подтверждения снова выходит из полноэкранного режима. Пока идет работа, задание закрывается при выходе из полноэкранного режима, скрытии вкладки и потере фокуса окном (`fullscreenchange`, `visibilitychange`, `focus` и `blur`). Закрытие заменяет задание, а не размывает его: условие, варианты и поля ответа не отрисовываются, поэтому их нет ни в DOM, ни на снимке страницы, ни в дереве доступности. Форма ответа остается смонтированной и ничего не рисует, поэтому черновик сохраняется (копия черновика в sessionStorage по-прежнему ведется). Таймер остается серверным и виден на экране. После выхода из полноэкранного режима кандидат продолжает кнопкой: это действие пользователя, которое браузер требует для повторного входа; уход только с вкладки или из окна клика не требует. Эти выходы записывает сборщик из абзаца выше (`fullscreen_exit`, `focus_loss`), само закрытие ничего не записывает. Браузер без полноэкранного режима элемента (iPhone Safari) или отказавший в запросе получает информационное сообщение и проходит тест только с контролем вкладки (`fallback` `unsupported` или `denied`), поэтому экран не становится тупиком. Экспресс-запуск и завершенная попытка не защищаются, а уход со страницы или завершение попытки выходят из полноэкранного режима. + +Та же панель (`ProtectedRegion`) не дает вынести текст задания реальной попытки. Текст нельзя выделить (`user-select` вместе с формой `-webkit-`, которая все еще нужна Safari, и отмененный `selectstart`), контекстное меню и перетаскивание на нем отменяются, копирование и вырезание отменяются, когда цель или выделение доходят до панели (в буфер попадает пустая строка), а `@media print` скрывает панель вместе с заданием, вариантами и полями ответа. Поля исключены: текстовое поле сохраняет выделение, собственное контекстное меню, копирование и вырезание собственного текста кандидата. Вставка в поля ответа отклоняется (событие `paste` и `beforeinput` вставки), экран сообщает об этом коротким статусом, который исчезает при следующем вводе, а сброс текста мышью в поле отклоняется везде. Редактор кода практического задания помечен `data-paste="allowed"`: вставка в нем работает, а ее размер уходит существующим сигналом `paste`. Сборщик видит каждую вставку, копирование и вырезание, в том числе отклоненные, потому что защита отменяет действие по умолчанию и никогда не останавливает распространение события, поэтому отклоненная вставка все равно остается сигналом с размером. Текст остается в странице для экранных дикторов (без canvas и текста в картинках), набор и порядок фокуса не затрагиваются, экспресс-запуск не ограничивается. Эти меры останавливают только простой путь: снимок экрана, второе устройство или расширение браузера все равно выносят задание, а вставка экранной клавиатурой, которая вставляет текст как набор, странице не видна. + ## Результаты кандидата `/candidate/results` показывает историю завершенных реальных проверок текущего кандидата (`GET /me/assessment-results`, по 20 записей, курсор берется только из ответа сервера и не строится на клиенте). `/candidate/results/:attemptId` открывает одну запись по прямому URL. Оба экрана читают данные только при подтвержденной сессии кандидата: ключи запросов содержат идентификатор аккаунта и токен сессии, данные не живут после ухода с экрана (`gcTime: 0`) и удаляются при смене или потере сессии. Ответ 401, 403 или 404 дает экран "недоступно" без данных и не раскрывает, существует ли чужой результат; кеш ассессмента очищается только при 401, а сбой сети или 5xx предлагает повтор и не считается потерей доступа. Неудачное фоновое обновление оставляет уже загруженные данные и сообщает об этом. Даты показываются в часовом поясе браузера с его названием. "Показать еще" переносит фокус на первую новую запись и сообщает о числе загруженных. Есть состояния загрузки, пустой истории и ошибки с повтором. Неудачная попытка после успешной, значения адаптивной оценки, даты пересдачи и случаи без полей покрыты модульными фикстурами контракта: на стенде их получить нельзя, e2e проверяет форму потока (реальный результат, экспресс, владение, выход из аккаунта; сессия завершается через API, а не через меню аккаунта, потому что меню перезагружает страницу). Экспресс-тесты по контракту в историю не входят; их результат открывается по ссылке из экрана попытки или по прямому URL и подписан "Экспресс-тест без грейда". diff --git a/frontend/e2e/assessment-attempt-mock.ts b/frontend/e2e/assessment-attempt-mock.ts new file mode 100644 index 0000000..3550063 --- /dev/null +++ b/frontend/e2e/assessment-attempt-mock.ts @@ -0,0 +1,166 @@ +import type { Page, Route } from "@playwright/test"; + +// A fake API for one real attempt, shared by the specs that check what the page +// does while the candidate takes the test (fullscreen, the cover, copy and +// paste rules). The browser talks to a mocked API, so the specs need no data and +// no backend fixtures; they check the page, not the server. + +export const attemptId = "01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d"; +export const itemId = "01928f7b-3333-7a2b-8c3d-4e5f6a7b8c01"; +export const taskPrompt = + "SECRET-PROMPT: which HTTP status code means that a resource was created?"; +export const exampleInput = "SECRET-EXAMPLE-INPUT"; + +export type MockItemContent = + | { format: "number"; unit: null } + | { + format: "practice"; + languages: ["python"]; + public_examples: { input: string; expected_output: string }[]; + max_source_length: number; + }; + +export const numberContent: MockItemContent = { format: "number", unit: null }; +export const practiceContent: MockItemContent = { + format: "practice", + languages: ["python"], + public_examples: [{ input: exampleInput, expected_output: "SECRET-EXAMPLE-OUTPUT" }], + max_source_length: 5000, +}; + +export type SignalEvent = { + kind: string; + size_bytes?: number; + duration_ms?: number; + [field: string]: unknown; +}; + +export type MockedAttempt = { + /** Events of every signal batch the page sent, in order. */ + signals: SignalEvent[]; + /** Bodies of the answers the page sent. */ + answers: unknown[]; + /** Calls to the notice acknowledgement, to see what was stored. */ + acknowledgements: unknown[]; +}; + +type Options = { + content: MockItemContent; + /** The candidate already acknowledged the notice, so the start asks nothing. */ + noticeAcknowledged?: boolean; +}; + +function isoSeconds(ms: number): string { + return `${new Date(ms).toISOString().slice(0, 19)}Z`; +} + +function attemptBody(version: number, content: MockItemContent) { + return { + id: attemptId, + version, + kind: "root", + specialization: "backend", + target_grade: "middle", + task_language: "python", + root_attempt_id: null, + chain_deadline: null, + mode: "adaptive", + state: "in_progress", + versions: { + policy_version: 2, + bank_version: "backend.2026-11.3", + algorithm_version: "irt-1pl-eap.1", + }, + started_at: isoSeconds(Date.now() - 60_000), + expires_at: isoSeconds(Date.now() + 3_600_000), + sessions: { used: 1, max: 2, idle_timeout_seconds: 1800 }, + finished_at: null, + progress: { answered_items: 0, max_items: 5 }, + current_item: { id: itemId, sequence: 1, prompt: taskPrompt, content }, + practices: [], + }; +} + +/** Answers the API calls of the attempt page; every other API call gets a 404. */ +export async function mockAttemptApi(page: Page, options: Options): Promise { + const recorded: MockedAttempt = { signals: [], answers: [], acknowledgements: [] }; + let acknowledged = options.noticeAcknowledged ?? true; + + await page.route("**/api/v1/**", async (route: Route) => { + const request = route.request(); + const path = new URL(request.url()).pathname; + const method = request.method(); + const reply = (body: unknown, status = 200) => + route.fulfill({ + status, + contentType: "application/json", + headers: { date: new Date().toUTCString() }, + body: JSON.stringify(body), + }); + const base = `/api/v1/me/assessment-attempts/${attemptId}`; + + if (path === "/api/v1/identity/sessions/current") { + return reply({ + account: { + id: "01928f7b-0000-7a2b-8c3d-4e5f6a7b8c01", + email: "candidate@example.test", + email_verified: true, + scenario: "candidate", + onboarding_step: "completed", + created_at: "2026-10-01T10:00:00Z", + }, + csrf_token: "c".repeat(40), + }); + } + if (path === "/api/v1/me/assessment-signal-notice") { + if (method === "PUT") { + acknowledged = true; + recorded.acknowledgements.push(JSON.parse(request.postData() ?? "{}")); + } + return reply({ + notice_version: 2, + acknowledged, + acknowledged_at: acknowledged ? "2026-10-10T10:00:00Z" : null, + }); + } + if (path === base && method === "GET") return reply(attemptBody(1, options.content)); + if (path === `${base}/sessions`) return reply(attemptBody(2, options.content)); + if (path === `${base}/answers`) { + recorded.answers.push(JSON.parse(request.postData() ?? "{}")); + return reply(attemptBody(3, options.content)); + } + if (path === `${base}/signals`) { + const body = JSON.parse(request.postData() ?? "{}") as { events: SignalEvent[] }; + recorded.signals.push(...body.events); + return reply({ + status: "accepted", + accepted_events: body.events.length, + received_at: isoSeconds(Date.now()), + }); + } + return reply({ type: "about:blank", title: "Not found", status: 404 }, 404); + }); + return recorded; +} + +/** Hides or shows the tab the way a tab switch does, through visibilitychange. */ +export async function setTabHidden(page: Page, hidden: boolean): Promise { + await page.evaluate((nextHidden) => { + Object.defineProperty(document, "visibilityState", { + configurable: true, + get: () => (nextHidden ? "hidden" : "visible"), + }); + document.hasFocus = () => true; + document.dispatchEvent(new Event("visibilitychange")); + }, hidden); +} + +export async function isFullscreen(page: Page): Promise { + return page.evaluate(() => document.fullscreenElement !== null); +} + +/** Opens the attempt page and starts the work the way a candidate does, with a click. */ +export async function startAttempt(page: Page): Promise { + await page.goto(`/candidate/assessment/${attemptId}`); + await page.getByRole("button", { name: "Начать или продолжить" }).click(); +} diff --git a/frontend/e2e/assessment-lockdown.spec.ts b/frontend/e2e/assessment-lockdown.spec.ts new file mode 100644 index 0000000..0350a29 --- /dev/null +++ b/frontend/e2e/assessment-lockdown.spec.ts @@ -0,0 +1,160 @@ +import { expect, test } from "@playwright/test"; +import { + attemptId, + isFullscreen, + mockAttemptApi, + numberContent, + setTabHidden, + startAttempt, + taskPrompt, +} from "./assessment-attempt-mock"; + +// Fullscreen and the cover of the task during a real attempt. The API is +// mocked: these specs check what the page does, not the server. + +const coverHeading = "Задание скрыто"; +const continueName = "Продолжить в полном экране"; +const answerName = /^Числовой ответ/; + +test.use({ actionTimeout: 10_000, trace: "off", screenshot: "off", video: "off" }); + +test("leaving fullscreen hides the task and sends a signal, and returning restores it with the draft", async ({ + page, +}) => { + const recorded = await mockAttemptApi(page, { content: numberContent }); + await startAttempt(page); + await expect(page.getByRole("heading", { name: "Задание 1" })).toBeVisible(); + + // The click that resumed the work asked for fullscreen. + await expect.poll(() => isFullscreen(page)).toBe(true); + await page.getByRole("textbox", { name: answerName }).fill("73"); + + await page.evaluate(() => document.exitFullscreen()); + await expect(page.getByRole("heading", { name: coverHeading })).toBeVisible(); + // The task is replaced, not blurred: neither its text nor the answer controls are in the page. + expect(await page.locator("body").innerText()).not.toContain(taskPrompt); + expect(await page.content()).not.toContain(taskPrompt); + await expect(page.getByRole("textbox", { name: answerName })).toHaveCount(0); + await expect(page.getByRole("heading", { name: "Задание 1" })).toHaveCount(0); + // The timer is the server's and stays on screen. + await expect(page.getByRole("timer")).toBeVisible(); + // The keyboard focus waits on the way back. + await expect(page.getByRole("button", { name: continueName })).toBeFocused(); + // The collector sends the exit with the next batch (every 10 seconds). + await expect + .poll(() => recorded.signals.some((event) => event.kind === "fullscreen_exit"), { + timeout: 15_000, + }) + .toBe(true); + + await page.getByRole("button", { name: continueName }).click(); + await expect(page.getByRole("heading", { name: "Задание 1" })).toBeVisible(); + await expect(page.getByRole("heading", { name: coverHeading })).toHaveCount(0); + await expect.poll(() => isFullscreen(page)).toBe(true); + await expect(page.getByText(taskPrompt)).toBeVisible(); + await expect(page.getByRole("textbox", { name: answerName })).toHaveValue("73"); +}); + +test("leaving the tab covers the task and returning in fullscreen shows it again", async ({ + page, +}) => { + const recorded = await mockAttemptApi(page, { content: numberContent }); + await startAttempt(page); + await expect(page.getByRole("heading", { name: "Задание 1" })).toBeVisible(); + await expect.poll(() => isFullscreen(page)).toBe(true); + await page.getByRole("textbox", { name: answerName }).fill("5"); + + await setTabHidden(page, true); + await expect(page.getByRole("heading", { name: coverHeading })).toBeVisible(); + expect(await page.locator("body").innerText()).not.toContain(taskPrompt); + // Only the tab was left, so there is nothing to click: returning is enough. + await expect(page.getByRole("button", { name: continueName })).toHaveCount(0); + + await page.waitForTimeout(300); + await setTabHidden(page, false); + await expect(page.getByRole("heading", { name: "Задание 1" })).toBeVisible(); + await expect(page.getByText(taskPrompt)).toBeVisible(); + await expect(page.getByRole("textbox", { name: answerName })).toHaveValue("5"); + await expect + .poll(() => recorded.signals.some((event) => event.kind === "focus_loss"), { timeout: 15_000 }) + .toBe(true); +}); + +test("a browser without fullscreen explains it and still takes the test with the cover on leave", async ({ + page, +}) => { + // iPhone Safari has no element fullscreen. + await page.addInitScript(() => { + Object.defineProperty(document, "fullscreenEnabled", { configurable: true, get: () => false }); + Object.defineProperty(Element.prototype, "requestFullscreen", { + configurable: true, + value: undefined, + }); + }); + const recorded = await mockAttemptApi(page, { content: numberContent }); + await page.goto(`/candidate/assessment/${attemptId}`); + + // The explanation is on screen before the work starts, and the start is not blocked. + await expect(page.getByText(/не поддерживает полноэкранный режим/)).toBeVisible(); + await expect(page.getByText(/Тест можно пройти и без него/)).toBeVisible(); + await page.getByRole("button", { name: "Начать или продолжить" }).click(); + await expect(page.getByRole("heading", { name: "Задание 1" })).toBeVisible(); + expect(await isFullscreen(page)).toBe(false); + + await setTabHidden(page, true); + await expect(page.getByRole("heading", { name: coverHeading })).toBeVisible(); + expect(await page.locator("body").innerText()).not.toContain(taskPrompt); + await setTabHidden(page, false); + await expect(page.getByRole("heading", { name: "Задание 1" })).toBeVisible(); + + // The test can be finished from the keyboard in this mode too. + await page.getByRole("textbox", { name: answerName }).focus(); + await page.keyboard.type("42"); + await page.keyboard.press("Tab"); + await expect(page.getByRole("button", { name: "Отправить ответ" })).toBeFocused(); + await page.keyboard.press("Enter"); + await expect.poll(() => recorded.answers.length).toBe(1); +}); + +test("a browser that refuses the fullscreen request continues without it", async ({ page }) => { + await page.addInitScript(() => { + Element.prototype.requestFullscreen = () => + Promise.reject(new TypeError("Permissions check failed")); + }); + await mockAttemptApi(page, { content: numberContent }); + await startAttempt(page); + + await expect(page.getByRole("heading", { name: "Задание 1" })).toBeVisible(); + await expect(page.getByText(/не включил полноэкранный режим/)).toBeVisible(); + expect(await isFullscreen(page)).toBe(false); + // No cover is waiting for a fullscreen that cannot come. + await expect(page.getByRole("heading", { name: coverHeading })).toHaveCount(0); +}); + +test("closing the notice without confirming leaves fullscreen and starts nothing", async ({ + page, +}) => { + const recorded = await mockAttemptApi(page, { + content: numberContent, + noticeAcknowledged: false, + }); + await startAttempt(page); + + const dialog = page.getByRole("dialog", { name: /какие сигналы собираются/ }); + await expect(dialog).toBeVisible(); + await expect(dialog.getByText("Полноэкранный режим", { exact: false }).first()).toBeVisible(); + await expect.poll(() => isFullscreen(page)).toBe(true); + + await page.getByRole("button", { name: "Закрыть без подтверждения" }).click(); + await expect(dialog).toBeHidden(); + await expect.poll(() => isFullscreen(page)).toBe(false); + await expect(page.getByRole("heading", { name: "Задание 1" })).toHaveCount(0); + expect(recorded.acknowledgements).toHaveLength(0); + + // Confirming goes on to the test in fullscreen. + await page.getByRole("button", { name: "Начать или продолжить" }).click(); + await page.getByRole("button", { name: "Подтверждаю ознакомление и начинаю" }).click(); + await expect(page.getByRole("heading", { name: "Задание 1" })).toBeVisible(); + await expect.poll(() => isFullscreen(page)).toBe(true); + expect(recorded.acknowledgements).toEqual([{ notice_version: 2 }]); +}); diff --git a/frontend/e2e/assessment-task-protection.spec.ts b/frontend/e2e/assessment-task-protection.spec.ts new file mode 100644 index 0000000..6be6e36 --- /dev/null +++ b/frontend/e2e/assessment-task-protection.spec.ts @@ -0,0 +1,198 @@ +import { expect, test, type Page } from "@playwright/test"; +import { + exampleInput, + mockAttemptApi, + numberContent, + practiceContent, + setTabHidden, + startAttempt, + taskPrompt, +} from "./assessment-attempt-mock"; + +// Copy, selection, context menu, drag, print, and paste rules during a real +// attempt. The API is mocked: these specs check what the page does. + +const sentinel = "CLIPBOARD-SENTINEL"; +const modifier = "ControlOrMeta"; +const refusedNotice = "Вставка в поля ответа отключена"; + +test.use({ actionTimeout: 10_000, trace: "off", screenshot: "off", video: "off" }); + +async function allowClipboard(page: Page): Promise { + await page.context().grantPermissions(["clipboard-read", "clipboard-write"]); +} + +async function writeClipboard(page: Page, text: string): Promise { + await page.evaluate((value) => navigator.clipboard.writeText(value), text); +} + +async function readClipboard(page: Page): Promise { + return page.evaluate(() => navigator.clipboard.readText()); +} + +/** Sends the queued signals now: hiding the tab flushes the batch. */ +async function flushSignals(page: Page): Promise { + await setTabHidden(page, true); + await page.waitForTimeout(300); + await setTabHidden(page, false); + await page.waitForTimeout(500); +} + +test("the task text cannot be selected, copied, dragged, or printed, and stays readable by assistive tools", async ({ + page, +}) => { + await allowClipboard(page); + await mockAttemptApi(page, { content: numberContent }); + await startAttempt(page); + const prompt = page.getByText(taskPrompt); + await expect(prompt).toBeVisible(); + + // Selection: the text is not selectable, so a triple click and select-all take none of it. + expect(await prompt.evaluate((element) => getComputedStyle(element).userSelect)).toBe("none"); + await prompt.click({ clickCount: 3 }); + expect(await page.evaluate(() => window.getSelection()?.toString())).toBe(""); + await page.mouse.click(5, 5); + await page.keyboard.press(`${modifier}+a`); + expect(await page.evaluate(() => window.getSelection()?.toString())).not.toContain("SECRET"); + + // Copy: neither the keyboard nor a script that selects the text gets it into the clipboard. + await writeClipboard(page, sentinel); + await page.keyboard.press(`${modifier}+c`); + expect(await readClipboard(page)).not.toContain("SECRET-PROMPT"); + const refused = await page.evaluate(() => { + const element = document.querySelector("article p"); + if (!element) return null; + const range = document.createRange(); + range.selectNodeContents(element); + const selection = window.getSelection(); + selection?.removeAllRanges(); + selection?.addRange(range); + let prevented: boolean | null = null; + const listener = (event: Event) => { + prevented = event.defaultPrevented; + }; + // A bubbling listener on the window runs after the page's own handlers. + window.addEventListener("copy", listener); + document.execCommand("copy"); + window.removeEventListener("copy", listener); + return prevented; + }); + expect(refused).toBe(true); + expect(await readClipboard(page)).not.toContain("SECRET-PROMPT"); + + // Context menu and drag are cancelled on the task; a field keeps its own menu. + const prevented = await page.evaluate(() => { + const element = document.querySelector("article p"); + const field = document.querySelector("input[name=number-answer]"); + const cancelled = (target: Element | null, event: Event) => + target !== null && !target.dispatchEvent(event); + return { + taskMenu: cancelled( + element, + new MouseEvent("contextmenu", { bubbles: true, cancelable: true }), + ), + taskDrag: cancelled(element, new DragEvent("dragstart", { bubbles: true, cancelable: true })), + fieldMenu: cancelled( + field, + new MouseEvent("contextmenu", { bubbles: true, cancelable: true }), + ), + }; + }); + expect(prevented).toEqual({ taskMenu: true, taskDrag: true, fieldMenu: false }); + + // The field's own text can still be copied. + await page.getByRole("textbox", { name: /^Числовой ответ/ }).fill("4242"); + await page.keyboard.press(`${modifier}+a`); + await page.keyboard.press(`${modifier}+c`); + expect(await readClipboard(page)).toBe("4242"); + + // The text stays in the page for a screen reader. + expect(await page.getByRole("article").ariaSnapshot()).toContain("SECRET-PROMPT"); + + // Printing leaves the task out. + await page.emulateMedia({ media: "print" }); + await expect(page.getByRole("article")).toBeHidden(); + expect(await page.locator("body").innerText()).not.toContain("SECRET-PROMPT"); + await page.emulateMedia({ media: "screen" }); + await expect(prompt).toBeVisible(); +}); + +test("an answer field refuses paste, says so, records the attempt as a signal, and still takes typing", async ({ + page, +}) => { + await allowClipboard(page); + const recorded = await mockAttemptApi(page, { content: numberContent }); + await startAttempt(page); + const field = page.getByRole("textbox", { name: /^Числовой ответ/ }); + await expect(field).toBeVisible(); + + await writeClipboard(page, "PASTED123"); + await field.click(); + await page.keyboard.press(`${modifier}+v`); + await expect(field).toHaveValue(""); + await expect(page.getByText(refusedNotice)).toBeVisible(); + + await page.keyboard.type("77"); + await expect(field).toHaveValue("77"); + await expect(page.getByText(refusedNotice)).toHaveCount(0); + + await flushSignals(page); + const pastes = recorded.signals.filter((event) => event.kind === "paste"); + expect(pastes.map((event) => event.size_bytes)).toEqual(["PASTED123".length]); + expect(JSON.stringify(recorded.signals)).not.toContain("PASTED123"); +}); + +test("the practice code editor accepts paste and records its size, and protects its examples", async ({ + page, +}) => { + await allowClipboard(page); + const recorded = await mockAttemptApi(page, { content: practiceContent }); + await startAttempt(page); + const editor = page.getByRole("textbox", { name: "Код решения" }); + await expect(editor).toBeVisible(); + + const code = "print('PASTED-CODE')"; + await writeClipboard(page, code); + await editor.click(); + await page.keyboard.press(`${modifier}+v`); + await expect(editor).toHaveValue(code); + await expect(page.getByText(refusedNotice)).toHaveCount(0); + await page.keyboard.type(" # note"); + await expect(editor).toHaveValue(`${code} # note`); + + // Dropped text is refused even here, because a drop is not a recorded paste. + const dropCancelled = await editor.evaluate( + (element) => !element.dispatchEvent(new DragEvent("drop", { bubbles: true, cancelable: true })), + ); + expect(dropCancelled).toBe(true); + + // The examples are task text: not selectable, not copyable. + const example = page.getByText(exampleInput); + expect(await example.evaluate((element) => getComputedStyle(element).userSelect)).toBe("none"); + + await flushSignals(page); + const pastes = recorded.signals.filter((event) => event.kind === "paste"); + expect(pastes.map((event) => event.size_bytes)).toEqual([code.length]); + expect(JSON.stringify(recorded.signals)).not.toContain("PASTED-CODE"); +}); + +test("an item is answered with the keyboard alone while the protection is on", async ({ page }) => { + const recorded = await mockAttemptApi(page, { content: numberContent }); + await startAttempt(page); + const field = page.getByRole("textbox", { name: /^Числовой ответ/ }); + await expect(field).toBeVisible(); + + for (let step = 0; step < 30; step += 1) { + if (await field.evaluate((element) => element === document.activeElement)) break; + await page.keyboard.press("Tab"); + } + await expect(field).toBeFocused(); + await page.keyboard.type("42"); + await expect(field).toHaveValue("42"); + await page.keyboard.press("Tab"); + await expect(page.getByRole("button", { name: "Отправить ответ" })).toBeFocused(); + await page.keyboard.press("Enter"); + + await expect.poll(() => recorded.answers.length).toBe(1); + expect(recorded.answers[0]).toMatchObject({ answer: { format: "number", number: 42 } }); +}); diff --git a/frontend/e2e/assessment.spec.ts b/frontend/e2e/assessment.spec.ts index 68967d2..0977ced 100644 --- a/frontend/e2e/assessment.spec.ts +++ b/frontend/e2e/assessment.spec.ts @@ -780,6 +780,11 @@ test("closing the notice does not start the attempt and a confirmation is rememb "Смена вкладки или окна", "Копирование, вставка и вырезание", "Выход из полноэкранного режима", + "Полноэкранный режим", + "Скрытие задания", + "Защита текста задания", + "Вставка в поля ответа", + "Водяной знак на странице задания", "Время ответа на каждое задание", "Смена сетевого адреса во время попытки", "Параллельные сессии", @@ -801,7 +806,7 @@ test("closing the notice does not start the attempt and a confirmation is rememb await page.getByRole("button", { name: "Закрыть без подтверждения" }).click(); await expect(dialog).toBeHidden(); expect(creates).toHaveLength(0); - expect(await readNotice(page)).toMatchObject({ acknowledged: false, notice_version: 1 }); + expect(await readNotice(page)).toMatchObject({ acknowledged: false, notice_version: 2 }); await start.click(); await expect(dialog).toBeVisible(); diff --git a/frontend/src/features/answer-assessment/ui/answer-form.test.tsx b/frontend/src/features/answer-assessment/ui/answer-form.test.tsx new file mode 100644 index 0000000..7bd2e8a --- /dev/null +++ b/frontend/src/features/answer-assessment/ui/answer-form.test.tsx @@ -0,0 +1,69 @@ +import { renderToStaticMarkup } from "react-dom/server"; +import { describe, expect, it } from "vitest"; +import type { AssessmentItem } from "../../../shared/api/schemas"; +import { AnswerForm } from "./answer-form"; + +const item = { + id: "01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d02", + sequence: 1, + prompt: "Выберите вариант", + content: { + format: "choice", + multiple: false, + options: [ + { id: "a", text: "Первый вариант" }, + { id: "b", text: "Второй вариант" }, + ], + }, +} satisfies AssessmentItem; + +const numberItem = { + id: "01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d03", + sequence: 2, + prompt: "Сколько", + content: { format: "number", unit: null }, +} satisfies AssessmentItem; + +const practiceItem = { + id: "01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d04", + sequence: 3, + prompt: "Решите", + content: { + format: "practice", + languages: ["python"], + public_examples: [], + max_source_length: 4096, + }, +} satisfies AssessmentItem; + +function render(concealed: boolean, answered: AssessmentItem = item): string { + return renderToStaticMarkup( + undefined} + onRetry={() => undefined} + />, + ); +} + +describe("answer form", () => { + it("shows the options and the submit button", () => { + const markup = render(false); + expect(markup).toContain("Первый вариант"); + expect(markup).toContain("Отправить ответ"); + }); + + it("renders nothing while concealed, so no option text stays in the page", () => { + expect(render(true)).toBe(""); + }); + + it("marks only the code editor as a field where pasting is allowed", () => { + expect(render(false, practiceItem)).toContain('data-paste="allowed"'); + expect(render(false, numberItem)).not.toContain("data-paste"); + }); +}); diff --git a/frontend/src/features/answer-assessment/ui/answer-form.tsx b/frontend/src/features/answer-assessment/ui/answer-form.tsx index 1c6cd61..c56e3d8 100644 --- a/frontend/src/features/answer-assessment/ui/answer-form.tsx +++ b/frontend/src/features/answer-assessment/ui/answer-form.tsx @@ -11,6 +11,11 @@ type AnswerFormProps = { isSaving: boolean; retryable: boolean; errorMessage: string | null; + /** + * Renders nothing while the task is hidden. The form stays mounted, so the + * draft in its state survives and the task content is not in the page. + */ + concealed?: boolean; onSubmit: (draft: AnswerDraft) => void; onRetry: () => void; }; @@ -21,6 +26,7 @@ export function AnswerForm({ isSaving, retryable, errorMessage, + concealed = false, onSubmit, onRetry, }: AnswerFormProps) { @@ -67,6 +73,8 @@ export function AnswerForm({ option.click(); } + if (concealed) return null; + return (
{ + it("shows the task while the candidate is in fullscreen, visible and focused", () => { + expect(coverReason({ page: inside, mode: "fullscreen", fullscreenPending: false })).toBeNull(); + }); + + it("covers when fullscreen is left", () => { + expect( + coverReason({ + page: { ...inside, fullscreen: false }, + mode: "fullscreen", + fullscreenPending: false, + }), + ).toBe("fullscreen"); + }); + + it("covers when the tab is hidden or the window loses focus", () => { + for (const page of [ + { ...inside, visible: false }, + { ...inside, focused: false }, + ]) { + expect(coverReason({ page, mode: "fullscreen", fullscreenPending: false })).toBe("away"); + } + }); + + it("keeps the fullscreen cover when both are lost, because it has the way back", () => { + expect( + coverReason({ + page: { visible: false, focused: false, fullscreen: false }, + mode: "fullscreen", + fullscreenPending: false, + }), + ).toBe("fullscreen"); + }); + + it("does not treat a pending fullscreen request as an exit", () => { + expect( + coverReason({ + page: { ...inside, fullscreen: false }, + mode: "fullscreen", + fullscreenPending: true, + }), + ).toBeNull(); + }); + + it("without fullscreen the task is covered only while the tab or window is left", () => { + const outside: PageState = { visible: true, focused: true, fullscreen: false }; + expect(coverReason({ page: outside, mode: "overlay", fullscreenPending: false })).toBeNull(); + expect( + coverReason({ + page: { ...outside, visible: false }, + mode: "overlay", + fullscreenPending: false, + }), + ).toBe("away"); + }); + + it("requires fullscreen unless a fallback applies", () => { + expect(lockdownMode(null)).toBe("fullscreen"); + expect(lockdownMode("unsupported")).toBe("overlay"); + expect(lockdownMode("denied")).toBe("overlay"); + }); +}); diff --git a/frontend/src/features/assessment-lockdown/model/cover.ts b/frontend/src/features/assessment-lockdown/model/cover.ts new file mode 100644 index 0000000..1cfe2e0 --- /dev/null +++ b/frontend/src/features/assessment-lockdown/model/cover.ts @@ -0,0 +1,41 @@ +/** How the attempt is protected: fullscreen is required, or only the tab is watched. */ +export type LockdownMode = "fullscreen" | "overlay"; + +/** Why fullscreen is not required for this attempt, or null when it is required. */ +export type FullscreenFallback = "unsupported" | "denied" | null; + +/** What the browser reports about the page right now. */ +export type PageState = { + /** The tab is visible (document.visibilityState). */ + visible: boolean; + /** The window has the keyboard focus (document.hasFocus()). */ + focused: boolean; + /** The page is in fullscreen. */ + fullscreen: boolean; +}; + +export type CoverReason = "away" | "fullscreen"; + +export type CoverInputs = { + page: PageState; + mode: LockdownMode; + /** A fullscreen request is in flight, so the missing fullscreen is not yet an exit. */ + fullscreenPending: boolean; +}; + +/** + * Decides whether the task is covered and why. + * + * Leaving the tab or the window always covers. In fullscreen mode, being out of + * fullscreen covers as well, and it wins over "away" because only the + * fullscreen cover has a way back (a click that is a user gesture). + */ +export function coverReason({ page, mode, fullscreenPending }: CoverInputs): CoverReason | null { + if (mode === "fullscreen" && !page.fullscreen && !fullscreenPending) return "fullscreen"; + if (!page.visible || !page.focused) return "away"; + return null; +} + +export function lockdownMode(fallback: FullscreenFallback): LockdownMode { + return fallback === null ? "fullscreen" : "overlay"; +} diff --git a/frontend/src/features/assessment-lockdown/model/fullscreen.test.ts b/frontend/src/features/assessment-lockdown/model/fullscreen.test.ts new file mode 100644 index 0000000..cb31b35 --- /dev/null +++ b/frontend/src/features/assessment-lockdown/model/fullscreen.test.ts @@ -0,0 +1,81 @@ +import { describe, expect, it, vi } from "vitest"; +import { + isFullscreenSupported, + leaveFullscreen, + requestFullscreen, + type FullscreenDocument, +} from "./fullscreen"; + +function fakeDocument(overrides: Partial = {}): FullscreenDocument { + return { + fullscreenEnabled: true, + fullscreenElement: null, + documentElement: { requestFullscreen: () => Promise.resolve() }, + exitFullscreen: () => Promise.resolve(), + ...overrides, + }; +} + +describe("fullscreen support", () => { + it("is supported only when the browser enables it and the element can request it", () => { + expect(isFullscreenSupported(fakeDocument())).toBe(true); + expect(isFullscreenSupported(fakeDocument({ fullscreenEnabled: false }))).toBe(false); + // iPhone Safari: no fullscreenEnabled and no element request. + expect(isFullscreenSupported(fakeDocument({ documentElement: {} }))).toBe(false); + const withoutEnabled = fakeDocument(); + delete (withoutEnabled as { fullscreenEnabled?: boolean }).fullscreenEnabled; + expect(isFullscreenSupported(withoutEnabled)).toBe(false); + }); +}); + +describe("requesting fullscreen", () => { + it("issues the request synchronously and hides the browser navigation", async () => { + const request = vi.fn(() => Promise.resolve()); + const doc = fakeDocument({ documentElement: { requestFullscreen: request } }); + const pending = requestFullscreen(doc); + // The request is already made before the promise settles: it stays in the gesture. + expect(request).toHaveBeenCalledWith({ navigationUI: "hide" }); + await expect(pending).resolves.toBe("entered"); + }); + + it("reports a refusal instead of throwing", async () => { + const doc = fakeDocument({ + documentElement: { requestFullscreen: () => Promise.reject(new TypeError("denied")) }, + }); + await expect(requestFullscreen(doc)).resolves.toBe("failed"); + }); + + it("does not ask again when the page is already fullscreen", async () => { + const request = vi.fn(() => Promise.resolve()); + const doc = fakeDocument({ + fullscreenElement: {}, + documentElement: { requestFullscreen: request }, + }); + await expect(requestFullscreen(doc)).resolves.toBe("already"); + expect(request).not.toHaveBeenCalled(); + }); + + it("fails without an element request", async () => { + await expect(requestFullscreen(fakeDocument({ documentElement: {} }))).resolves.toBe("failed"); + }); +}); + +describe("leaving fullscreen", () => { + it("exits only from fullscreen and ignores a refusal", async () => { + const exit = vi.fn(() => Promise.resolve()); + await leaveFullscreen(fakeDocument({ exitFullscreen: exit })); + expect(exit).not.toHaveBeenCalled(); + + await leaveFullscreen(fakeDocument({ fullscreenElement: {}, exitFullscreen: exit })); + expect(exit).toHaveBeenCalledTimes(1); + + await expect( + leaveFullscreen( + fakeDocument({ + fullscreenElement: {}, + exitFullscreen: () => Promise.reject(new Error("x")), + }), + ), + ).resolves.toBeUndefined(); + }); +}); diff --git a/frontend/src/features/assessment-lockdown/model/fullscreen.ts b/frontend/src/features/assessment-lockdown/model/fullscreen.ts new file mode 100644 index 0000000..b0f033f --- /dev/null +++ b/frontend/src/features/assessment-lockdown/model/fullscreen.ts @@ -0,0 +1,55 @@ +/** The part of an element the lockdown asks to go fullscreen. */ +export type FullscreenTarget = { + requestFullscreen?: (options?: { navigationUI?: "hide" | "show" | "auto" }) => Promise; +}; + +/** The part of `document` the lockdown reads and drives; tests pass small fakes. */ +export type FullscreenDocument = { + readonly fullscreenEnabled?: boolean; + readonly fullscreenElement: unknown; + readonly documentElement: FullscreenTarget; + exitFullscreen?: () => Promise; +}; + +/** + * True when the browser can put the page into fullscreen. iPhone Safari has no + * element fullscreen, so both checks guard against a half-present API. + */ +export function isFullscreenSupported(doc: FullscreenDocument): boolean { + return ( + doc.fullscreenEnabled === true && typeof doc.documentElement.requestFullscreen === "function" + ); +} + +export function isFullscreenActive(doc: FullscreenDocument): boolean { + return doc.fullscreenElement != null; +} + +export type FullscreenRequestResult = "entered" | "already" | "failed"; + +/** + * Asks the browser for fullscreen. The request is issued synchronously, so the + * caller must run it inside a click or key handler: browsers refuse the request + * without a user gesture. A refusal is reported as "failed", never thrown. + */ +export async function requestFullscreen(doc: FullscreenDocument): Promise { + if (isFullscreenActive(doc)) return "already"; + const request = doc.documentElement.requestFullscreen; + if (typeof request !== "function") return "failed"; + try { + await request.call(doc.documentElement, { navigationUI: "hide" }); + return "entered"; + } catch { + return "failed"; + } +} + +/** Leaves fullscreen when the page is in it; a refusal is ignored. */ +export async function leaveFullscreen(doc: FullscreenDocument): Promise { + if (!isFullscreenActive(doc) || typeof doc.exitFullscreen !== "function") return; + try { + await doc.exitFullscreen(); + } catch { + // The browser may already have left fullscreen. + } +} diff --git a/frontend/src/features/assessment-lockdown/model/task-guard.test.ts b/frontend/src/features/assessment-lockdown/model/task-guard.test.ts new file mode 100644 index 0000000..b7d35f6 --- /dev/null +++ b/frontend/src/features/assessment-lockdown/model/task-guard.test.ts @@ -0,0 +1,175 @@ +import { describe, expect, it, vi } from "vitest"; +import { + createTaskGuard, + describeField, + inputIsBlocked, + type ElementLike, + type GuardEvent, + type SelectionLike, +} from "./task-guard"; + +// A tiny element: `matches` lists the selectors that find it from itself, and +// `parent` is the element a text node or a child belongs to. +function element( + tagName: string, + options: { type?: string; paste?: boolean; parent?: ElementLike } = {}, +): ElementLike { + const self: ElementLike = { + tagName: tagName.toUpperCase(), + ...(options.type !== undefined ? { type: options.type } : {}), + closest(selector: string) { + if (selector === "input, textarea" && (tagName === "input" || tagName === "textarea")) { + return self; + } + if (selector === '[data-paste="allowed"]' && options.paste) return self; + return options.parent?.closest(selector) ?? null; + }, + }; + return self; +} + +const taskText = element("p"); +const numberField = element("input", { type: "text" }); +const configField = element("textarea"); +const editor = element("textarea", { paste: true }); +const checkbox = element("input", { type: "checkbox" }); +const textNodeOfTask = { parentElement: taskText }; + +describe("describeField", () => { + it("tells text fields from task content and finds the paste exception", () => { + expect(describeField(numberField)).toEqual({ textField: true, pasteAllowed: false }); + expect(describeField(configField)).toEqual({ textField: true, pasteAllowed: false }); + expect(describeField(editor)).toEqual({ textField: true, pasteAllowed: true }); + expect(describeField(taskText)).toEqual({ textField: false, pasteAllowed: false }); + expect(describeField(textNodeOfTask)).toEqual({ textField: false, pasteAllowed: false }); + // An option is task content: it holds no text of the candidate. + expect(describeField(checkbox)).toEqual({ textField: false, pasteAllowed: false }); + expect(describeField(null)).toEqual({ textField: false, pasteAllowed: false }); + }); +}); + +function guardWith(options: { selection?: SelectionLike | null; insideRegion?: unknown[] } = {}) { + const pasteBlocked = vi.fn(); + const inside = new Set(options.insideRegion ?? [taskText, numberField, editor]); + const guard = createTaskGuard({ + region: { contains: (node) => inside.has(node) }, + selection: () => options.selection ?? null, + onPasteBlocked: pasteBlocked, + }); + return { guard, pasteBlocked }; +} + +function event(target: unknown, extra: Partial = {}) { + const preventDefault = vi.fn(); + const setData = vi.fn(); + const value = { + target, + preventDefault, + clipboardData: { setData }, + ...extra, + } satisfies GuardEvent; + return { event: value, preventDefault, setData }; +} + +describe("task guard", () => { + it("blocks selection, the context menu, and drag on the task text only", () => { + const { guard } = guardWith(); + for (const handler of [guard.onSelectStart, guard.onContextMenu, guard.onDragStart]) { + const onTask = event(taskText); + handler(onTask.event); + expect(onTask.preventDefault).toHaveBeenCalledTimes(1); + + const onField = event(numberField); + handler(onField.event); + expect(onField.preventDefault).not.toHaveBeenCalled(); + } + }); + + it("never lets a drop fill an answer field", () => { + const { guard } = guardWith(); + const dropped = event(editor); + guard.onDrop(dropped.event); + expect(dropped.preventDefault).toHaveBeenCalledTimes(1); + }); + + it("refuses paste in answer fields, says so, and allows it in the code editor", () => { + const { guard, pasteBlocked } = guardWith(); + const intoNumber = event(numberField); + guard.onPaste(intoNumber.event); + expect(intoNumber.preventDefault).toHaveBeenCalledTimes(1); + expect(pasteBlocked).toHaveBeenCalledTimes(1); + + const intoEditor = event(editor); + guard.onPaste(intoEditor.event); + expect(intoEditor.preventDefault).not.toHaveBeenCalled(); + expect(pasteBlocked).toHaveBeenCalledTimes(1); + }); + + it("closes the beforeinput routes that bypass the paste event", () => { + const numberInfo = describeField(numberField); + const editorInfo = describeField(editor); + expect(inputIsBlocked(numberInfo, "insertFromPaste")).toBe(true); + expect(inputIsBlocked(numberInfo, "insertFromDrop")).toBe(true); + expect(inputIsBlocked(editorInfo, "insertFromPaste")).toBe(false); + expect(inputIsBlocked(editorInfo, "insertFromDrop")).toBe(true); + // Typing, deleting, and composing are never touched. + for (const inputType of ["insertText", "deleteContentBackward", "insertCompositionText"]) { + expect(inputIsBlocked(numberInfo, inputType)).toBe(false); + } + + const { guard, pasteBlocked } = guardWith(); + const typing = event(numberField, { inputType: "insertText" }); + guard.onBeforeInput(typing.event); + expect(typing.preventDefault).not.toHaveBeenCalled(); + const pasted = event(numberField, { inputType: "insertFromPaste" }); + guard.onBeforeInput(pasted.event); + expect(pasted.preventDefault).toHaveBeenCalledTimes(1); + expect(pasteBlocked).toHaveBeenCalledTimes(1); + }); + + it("copies nothing from the task text and leaves an empty clipboard text", () => { + const { guard } = guardWith(); + const copy = event(taskText); + guard.onClipboardRead(copy.event); + expect(copy.preventDefault).toHaveBeenCalledTimes(1); + expect(copy.setData).toHaveBeenCalledWith("text/plain", ""); + }); + + it("lets a field copy and cut its own text", () => { + const { guard } = guardWith(); + for (const field of [numberField, editor]) { + const copy = event(field); + guard.onClipboardRead(copy.event); + expect(copy.preventDefault).not.toHaveBeenCalled(); + expect(copy.setData).not.toHaveBeenCalled(); + } + }); + + it("blocks a select-all copy that starts outside the region but reaches into it", () => { + const body = element("body"); + const selection: SelectionLike = { + rangeCount: 1, + anchorNode: body, + focusNode: body, + containsNode: (node, partial) => node !== null && partial === true, + }; + const { guard } = guardWith({ selection }); + const copy = event(body); + guard.onClipboardRead(copy.event); + expect(copy.preventDefault).toHaveBeenCalledTimes(1); + }); + + it("leaves a copy alone when neither the target nor the selection touches the region", () => { + const header = element("h1"); + const selection: SelectionLike = { + rangeCount: 1, + anchorNode: header, + focusNode: header, + containsNode: () => false, + }; + const { guard } = guardWith({ selection }); + const copy = event(header); + guard.onClipboardRead(copy.event); + expect(copy.preventDefault).not.toHaveBeenCalled(); + }); +}); diff --git a/frontend/src/features/assessment-lockdown/model/task-guard.ts b/frontend/src/features/assessment-lockdown/model/task-guard.ts new file mode 100644 index 0000000..243d76c --- /dev/null +++ b/frontend/src/features/assessment-lockdown/model/task-guard.ts @@ -0,0 +1,180 @@ +/** + * Rules that keep the task text from being copied out of an attempt and keep + * foreign text out of the answer fields. + * + * Nothing here touches keyboard input or assistive technology: the text stays + * in the page for screen readers, typing is never intercepted, and a field's own + * text can still be selected, copied, and cut. The decisions are plain + * functions of small structural types so they run without a DOM in tests. + */ + +/** The part of an element the rules read. */ +export type ElementLike = { + closest(selector: string): ElementLike | null; + readonly tagName?: string; + readonly type?: string; +}; + +/** What a target is for the rules: a text field (and whether paste may go in) or anything else. */ +export type FieldInfo = { textField: boolean; pasteAllowed: boolean }; + +const textInputTypes = new Set(["", "text", "search", "number", "email", "url", "tel", "password"]); + +function isElementLike(value: unknown): value is ElementLike { + return ( + typeof value === "object" && + value !== null && + typeof (value as { closest?: unknown }).closest === "function" + ); +} + +/** The element of an event target; a text node stands for its parent element. */ +export function targetElement(target: unknown): ElementLike | null { + if (isElementLike(target)) return target; + const parent = (target as { parentElement?: unknown } | null)?.parentElement; + return isElementLike(parent) ? parent : null; +} + +/** + * Classifies a target. A text field is a textarea or a text-like input: checkboxes + * and radio buttons hold no text of the candidate, so they count as task content. + * Paste is allowed in a field that sits in an element marked `data-paste="allowed"` + * (the practice code editor). + */ +export function describeField(target: unknown): FieldInfo { + const element = targetElement(target); + const field = element?.closest("input, textarea") ?? null; + const tag = field?.tagName?.toLowerCase(); + const textField = + tag === "textarea" || + (tag === "input" && textInputTypes.has((field?.type ?? "").toLowerCase())); + const pasteAllowed = textField && field?.closest('[data-paste="allowed"]') != null; + return { textField, pasteAllowed }; +} + +/** The task text is not selectable; the candidate's own text is. */ +export function selectionStartIsBlocked(info: FieldInfo): boolean { + return !info.textField; +} + +/** The context menu offers copy and "search for selection" on the task text; fields keep theirs. */ +export function contextMenuIsBlocked(info: FieldInfo): boolean { + return !info.textField; +} + +/** Task text cannot be dragged out; a selection inside a field can still be moved. */ +export function dragStartIsBlocked(info: FieldInfo): boolean { + return !info.textField; +} + +/** Foreign text is refused by every answer field except the code editor. */ +export function pasteIsBlocked(info: FieldInfo): boolean { + return info.textField && !info.pasteAllowed; +} + +/** + * Copy and cut are refused when they would read the task: the target is not a + * field and it, or the selection, reaches into the protected region. + */ +export function clipboardReadIsBlocked( + info: FieldInfo, + reach: { targetInRegion: boolean; selectionInRegion: boolean }, +): boolean { + return !info.textField && (reach.targetInRegion || reach.selectionInRegion); +} + +const pasteInputTypes = new Set(["insertFromPaste", "insertFromPasteAsQuotation"]); +const dropInputTypes = new Set(["insertFromDrop"]); + +/** What a `beforeinput` event does to a field, judged by its input type. */ +export function inputIsBlocked(info: FieldInfo, inputType: string): boolean { + if (!info.textField) return false; + if (dropInputTypes.has(inputType)) return true; + return pasteInputTypes.has(inputType) && !info.pasteAllowed; +} + +// DOM glue: the handlers below turn events into the decisions above. + +/** The part of an event the handlers read and change. */ +export type GuardEvent = { + readonly target: unknown; + readonly inputType?: string; + readonly clipboardData?: { setData(format: string, data: string): void } | null; + preventDefault(): void; +}; + +/** The part of `Selection` the copy rule reads. */ +export type SelectionLike = { + readonly rangeCount: number; + readonly anchorNode: unknown; + readonly focusNode: unknown; + containsNode(node: unknown, allowPartialContainment?: boolean): boolean; +}; + +export type TaskGuardOptions = { + region: { contains(node: unknown): boolean }; + selection: () => SelectionLike | null; + /** Called when a paste into an answer field was refused, so the screen can say so. */ + onPasteBlocked?: () => void; +}; + +export type TaskGuard = { + onSelectStart(event: GuardEvent): void; + onContextMenu(event: GuardEvent): void; + onDragStart(event: GuardEvent): void; + onDrop(event: GuardEvent): void; + onPaste(event: GuardEvent): void; + onBeforeInput(event: GuardEvent): void; + onClipboardRead(event: GuardEvent): void; +}; + +export function createTaskGuard(options: TaskGuardOptions): TaskGuard { + function selectionInRegion(): boolean { + const selection = options.selection(); + if (!selection || selection.rangeCount === 0) return false; + return ( + options.region.contains(selection.anchorNode) || + options.region.contains(selection.focusNode) || + selection.containsNode(options.region, true) + ); + } + + return { + onSelectStart(event) { + if (selectionStartIsBlocked(describeField(event.target))) event.preventDefault(); + }, + onContextMenu(event) { + if (contextMenuIsBlocked(describeField(event.target))) event.preventDefault(); + }, + onDragStart(event) { + if (dragStartIsBlocked(describeField(event.target))) event.preventDefault(); + }, + onDrop(event) { + // Dropped text is foreign text too, and the drop is never recorded as a paste. + event.preventDefault(); + }, + onPaste(event) { + if (!pasteIsBlocked(describeField(event.target))) return; + event.preventDefault(); + options.onPasteBlocked?.(); + }, + onBeforeInput(event) { + const info = describeField(event.target); + if (!inputIsBlocked(info, event.inputType ?? "")) return; + event.preventDefault(); + if (pasteInputTypes.has(event.inputType ?? "")) options.onPasteBlocked?.(); + }, + onClipboardRead(event) { + const info = describeField(event.target); + const targetInRegion = options.region.contains(event.target); + if ( + !clipboardReadIsBlocked(info, { targetInRegion, selectionInRegion: selectionInRegion() }) + ) { + return; + } + event.preventDefault(); + // An empty text overwrites nothing useful and leaves no task text in the clipboard. + event.clipboardData?.setData("text/plain", ""); + }, + }; +} diff --git a/frontend/src/features/assessment-lockdown/model/use-attempt-lockdown.ts b/frontend/src/features/assessment-lockdown/model/use-attempt-lockdown.ts new file mode 100644 index 0000000..3c2041d --- /dev/null +++ b/frontend/src/features/assessment-lockdown/model/use-attempt-lockdown.ts @@ -0,0 +1,126 @@ +import { useCallback, useEffect, useState, useSyncExternalStore } from "react"; +import { + coverReason, + lockdownMode, + type CoverReason, + type FullscreenFallback, + type LockdownMode, + type PageState, +} from "./cover"; +import { + isFullscreenActive, + isFullscreenSupported, + leaveFullscreen, + requestFullscreen, +} from "./fullscreen"; + +export type AttemptLockdown = { + /** Fullscreen is required, or only leaving the tab covers the task. */ + mode: LockdownMode; + /** Why fullscreen is not required, or null when it is. */ + fallback: FullscreenFallback; + /** The task is hidden right now. */ + covered: boolean; + reason: CoverReason | null; + /** + * Asks for fullscreen. Call it from the click that starts or resumes the work: + * the browser accepts the request only inside a user gesture. + */ + enter: () => Promise; + /** Leaves fullscreen, for example when the candidate declines to start. */ + leave: () => void; +}; + +type Options = { + /** A real attempt that is not finished: fullscreen and the cover apply. */ + applies: boolean; + /** The candidate started or resumed the work, so a task is on the screen. */ + running: boolean; +}; + +// The page state is packed in one number so that the store snapshot is a +// primitive and React compares it without extra bookkeeping. +const visibleBit = 1; +const focusedBit = 2; +const fullscreenBit = 4; + +function readPage(): number { + return ( + (document.visibilityState === "visible" ? visibleBit : 0) | + (document.hasFocus() ? focusedBit : 0) | + (isFullscreenActive(document) ? fullscreenBit : 0) + ); +} + +// Rendered without a browser (server markup in tests), nothing is left, so nothing is covered. +function readServerPage(): number { + return visibleBit | focusedBit | fullscreenBit; +} + +function subscribePage(onChange: () => void): () => void { + document.addEventListener("visibilitychange", onChange); + document.addEventListener("fullscreenchange", onChange); + window.addEventListener("focus", onChange); + window.addEventListener("blur", onChange); + return () => { + document.removeEventListener("visibilitychange", onChange); + document.removeEventListener("fullscreenchange", onChange); + window.removeEventListener("focus", onChange); + window.removeEventListener("blur", onChange); + }; +} + +function pageFromBits(bits: number): PageState { + return { + visible: (bits & visibleBit) !== 0, + focused: (bits & focusedBit) !== 0, + fullscreen: (bits & fullscreenBit) !== 0, + }; +} + +/** + * Keeps a real attempt in fullscreen and hides the task whenever the candidate + * leaves the tab, the window, or fullscreen. It only decides what is shown: the + * attempt timer and the answer state stay on the server and in the form, and + * the passive signal collector records the same exits on its own. + * + * A browser without element fullscreen (iPhone Safari) or one that refuses the + * request keeps the candidate in the test with the tab watch alone; `fallback` + * says which case it is so the screen can explain it. + */ +export function useAttemptLockdown({ applies, running }: Options): AttemptLockdown { + const supported = useState( + () => typeof document !== "undefined" && isFullscreenSupported(document), + )[0]; + const [denied, setDenied] = useState(false); + const [pending, setPending] = useState(false); + const page = pageFromBits(useSyncExternalStore(subscribePage, readPage, readServerPage)); + + const fallback: FullscreenFallback = !supported ? "unsupported" : denied ? "denied" : null; + const mode = lockdownMode(fallback); + const reason = + applies && running ? coverReason({ page, mode, fullscreenPending: pending }) : null; + + const enter = useCallback(async () => { + if (!applies || fallback !== null) return; + setPending(true); + // The request is issued synchronously inside this call, still within the gesture. + const result = await requestFullscreen(document); + setPending(false); + if (result === "failed") setDenied(true); + }, [applies, fallback]); + + const leave = useCallback(() => { + void leaveFullscreen(document); + }, []); + + useEffect(() => { + if (!applies) return undefined; + // A finished attempt, or a page that is left, must not stay fullscreen. + return () => { + void leaveFullscreen(document); + }; + }, [applies]); + + return { mode, fallback, covered: reason !== null, reason, enter, leave }; +} diff --git a/frontend/src/features/assessment-lockdown/model/use-task-guard.ts b/frontend/src/features/assessment-lockdown/model/use-task-guard.ts new file mode 100644 index 0000000..bc3a54c --- /dev/null +++ b/frontend/src/features/assessment-lockdown/model/use-task-guard.ts @@ -0,0 +1,51 @@ +import { useEffect, type RefObject } from "react"; +import { createTaskGuard, type GuardEvent, type TaskGuard } from "./task-guard"; + +/** + * Registers the guard on a region and on its document. Copy and cut are heard + * on the document because a select-all copy starts outside the region. Nothing + * stops propagation, so the passive signal collector still sees every paste, + * copy, and cut, including the ones refused here. + */ +export function attachTaskGuard(region: HTMLElement, guard: TaskGuard): () => void { + const doc = region.ownerDocument; + const registered: Array<[EventTarget, string, EventListener]> = []; + + function listen(target: EventTarget, type: string, handler: (event: GuardEvent) => void): void { + const listener: EventListener = (event) => handler(event as unknown as GuardEvent); + target.addEventListener(type, listener); + registered.push([target, type, listener]); + } + + listen(region, "selectstart", guard.onSelectStart); + listen(region, "contextmenu", guard.onContextMenu); + listen(region, "dragstart", guard.onDragStart); + listen(region, "drop", guard.onDrop); + listen(region, "paste", guard.onPaste); + listen(region, "beforeinput", guard.onBeforeInput); + listen(doc, "copy", guard.onClipboardRead); + listen(doc, "cut", guard.onClipboardRead); + + return () => { + for (const [target, type, listener] of registered) target.removeEventListener(type, listener); + registered.length = 0; + }; +} + +/** Applies the task guard to the region while `enabled`. */ +export function useTaskGuard( + regionRef: RefObject, + enabled: boolean, + onPasteBlocked: () => void, +): void { + useEffect(() => { + const region = regionRef.current; + if (!enabled || !region) return undefined; + const guard = createTaskGuard({ + region, + selection: () => region.ownerDocument.getSelection(), + onPasteBlocked, + }); + return attachTaskGuard(region, guard); + }, [regionRef, enabled, onPasteBlocked]); +} diff --git a/frontend/src/features/assessment-lockdown/ui/attempt-cover.module.css b/frontend/src/features/assessment-lockdown/ui/attempt-cover.module.css new file mode 100644 index 0000000..bf99fe0 --- /dev/null +++ b/frontend/src/features/assessment-lockdown/ui/attempt-cover.module.css @@ -0,0 +1,31 @@ +.cover { + display: grid; + gap: var(--space-3); + min-width: 0; +} + +.cover:focus { + outline: none; +} + +.cover:focus-visible { + outline: var(--focus-ring-width) solid var(--color-focus-ring); + outline-offset: var(--focus-ring-offset); +} + +.title { + margin: 0; + color: var(--color-text-strong); + font-size: var(--font-size-l); +} + +.text { + margin: 0; + color: var(--color-text-secondary); +} + +.actions { + display: flex; + flex-wrap: wrap; + gap: var(--space-3); +} diff --git a/frontend/src/features/assessment-lockdown/ui/attempt-cover.tsx b/frontend/src/features/assessment-lockdown/ui/attempt-cover.tsx new file mode 100644 index 0000000..ff87c7d --- /dev/null +++ b/frontend/src/features/assessment-lockdown/ui/attempt-cover.tsx @@ -0,0 +1,39 @@ +import { forwardRef } from "react"; +import { Button } from "../../../shared/ui"; +import type { CoverReason } from "../model/cover"; +import styles from "./attempt-cover.module.css"; + +type AttemptCoverProps = { + reason: CoverReason; + headingId: string; + onContinue: () => void; +}; + +const bodies: Readonly> = { + fullscreen: "Тест идет в полноэкранном режиме. Вернитесь в него, чтобы продолжить.", + away: "Вы вышли из вкладки или окна. Вернитесь, чтобы продолжить.", +}; + +/** + * Stands in for the task while the candidate is away. The task is not rendered + * under it: it is replaced, so nothing of the task stays in the page, in a + * screenshot, or for a reader that ignores styles. + */ +export const AttemptCover = forwardRef(function AttemptCover( + { reason, headingId, onContinue }, + ref, +) { + return ( +
+

+ Задание скрыто +

+

{bodies[reason]} Введенный ответ сохранен.

+ {reason === "fullscreen" ? ( +
+ +
+ ) : null} +
+ ); +}); diff --git a/frontend/src/features/assessment-lockdown/ui/fullscreen-fallback-notice.tsx b/frontend/src/features/assessment-lockdown/ui/fullscreen-fallback-notice.tsx new file mode 100644 index 0000000..fda2172 --- /dev/null +++ b/frontend/src/features/assessment-lockdown/ui/fullscreen-fallback-notice.tsx @@ -0,0 +1,21 @@ +import { Notice } from "../../../shared/ui"; +import type { FullscreenFallback } from "../model/cover"; + +const messages: Readonly, string>> = { + unsupported: + "Этот браузер не поддерживает полноэкранный режим. Тест можно пройти и без него: при выходе из вкладки или окна задание скрывается.", + denied: + "Браузер не включил полноэкранный режим. Тест продолжается без него: при выходе из вкладки или окна задание скрывается.", +}; + +/** Explains why fullscreen is not asked for. It is information, not an error. */ +export function FullscreenFallbackNotice({ fallback }: { fallback: FullscreenFallback }) { + if (fallback === null) return null; + return ( +
+ +

{messages[fallback]}

+
+
+ ); +} diff --git a/frontend/src/features/assessment-lockdown/ui/protected-region.module.css b/frontend/src/features/assessment-lockdown/ui/protected-region.module.css new file mode 100644 index 0000000..92ad07c --- /dev/null +++ b/frontend/src/features/assessment-lockdown/ui/protected-region.module.css @@ -0,0 +1,32 @@ +/* The task text cannot be selected or dragged out. Fields keep their own + * selection, and the text stays in the page for screen readers. + * Safari still needs the -webkit- forms of user-select (the lint exception is + * for those lines only); without the explicit rule on fields, Safari refuses + * to edit them inside a non-selectable region. */ +.region { + /* stylelint-disable-next-line property-no-vendor-prefix */ + -webkit-user-select: none; + user-select: none; + -webkit-touch-callout: none; +} + +.region :is(input:not([type="checkbox"], [type="radio"]), textarea) { + /* stylelint-disable-next-line property-no-vendor-prefix */ + -webkit-user-select: text; + user-select: text; +} + +.refused { + margin: 0; + color: var(--color-text-secondary); + font-size: var(--font-size-s); +} + +/* Printing leaves the task, its options, and the answer fields out. The + * element selector keeps this rule above the page's own display rule for the + * panel, whichever stylesheet loads last. */ +@media print { + article.region { + display: none; + } +} diff --git a/frontend/src/features/assessment-lockdown/ui/protected-region.test.tsx b/frontend/src/features/assessment-lockdown/ui/protected-region.test.tsx new file mode 100644 index 0000000..0bd001a --- /dev/null +++ b/frontend/src/features/assessment-lockdown/ui/protected-region.test.tsx @@ -0,0 +1,93 @@ +import { renderToStaticMarkup } from "react-dom/server"; +import { describe, expect, it } from "vitest"; +import type { AttemptLockdown } from "../model/use-attempt-lockdown"; +import { FullscreenFallbackNotice } from "./fullscreen-fallback-notice"; +import { ProtectedRegion } from "./protected-region"; + +const prompt = "SECRET-PROMPT-TEXT"; + +function lockdown(overrides: Partial): AttemptLockdown { + return { + mode: "fullscreen", + fallback: null, + covered: false, + reason: null, + enter: () => Promise.resolve(), + leave: () => undefined, + ...overrides, + }; +} + +// Stands in for the answer form, which hides its own options while concealed. +function AnswerStub({ concealed }: { concealed: boolean }) { + return concealed ? null : SECRET-OPTION-ONE; +} + +function render(state: AttemptLockdown | null): string { + return renderToStaticMarkup( + +

Задание 1

+

{prompt}

+ + } + > + +
, + ); +} + +describe("protected region", () => { + it("shows the task and the answer form while the candidate is in fullscreen", () => { + const markup = render(lockdown({})); + expect(markup).toContain("SECRET-PROMPT-TEXT"); + expect(markup).toContain("SECRET-OPTION-ONE"); + expect(markup).not.toContain("Задание скрыто"); + }); + + it("replaces the task and the options with the cover, leaving none of their text in the page", () => { + const markup = render(lockdown({ covered: true, reason: "fullscreen" })); + expect(markup).toContain("Задание скрыто"); + expect(markup).toContain("Продолжить в полном экране"); + expect(markup).not.toContain("SECRET-PROMPT-TEXT"); + expect(markup).not.toContain("SECRET-OPTION"); + }); + + it("covers a left tab without a fullscreen button", () => { + const markup = render(lockdown({ covered: true, reason: "away" })); + expect(markup).toContain("Вы вышли из вкладки или окна"); + expect(markup).not.toContain("Продолжить в полном экране"); + expect(markup).not.toContain("SECRET-PROMPT-TEXT"); + }); + + it("marks a protected region for the selection and print rules, and no other", () => { + expect(render(lockdown({}))).toContain("region"); + expect(render(null)).not.toContain("region"); + // The paste notice appears only after a paste was refused. + expect(render(lockdown({}))).not.toContain("Вставка в поля ответа отключена"); + }); + + it("leaves an unprotected attempt as it is", () => { + const markup = render(null); + expect(markup).toContain("SECRET-PROMPT-TEXT"); + expect(markup).not.toContain("Задание скрыто"); + }); +}); + +describe("fullscreen fallback notice", () => { + it("explains an unsupported browser and a refused request, and stays silent otherwise", () => { + expect(renderToStaticMarkup()).toContain( + "не поддерживает полноэкранный режим", + ); + expect(renderToStaticMarkup()).toContain( + "Тест можно пройти и без него", + ); + expect(renderToStaticMarkup()).toContain( + "не включил полноэкранный режим", + ); + expect(renderToStaticMarkup()).toBe(""); + }); +}); diff --git a/frontend/src/features/assessment-lockdown/ui/protected-region.tsx b/frontend/src/features/assessment-lockdown/ui/protected-region.tsx new file mode 100644 index 0000000..08a6590 --- /dev/null +++ b/frontend/src/features/assessment-lockdown/ui/protected-region.tsx @@ -0,0 +1,77 @@ +import { useCallback, useEffect, useRef, useState, type ReactNode } from "react"; +import type { AttemptLockdown } from "../model/use-attempt-lockdown"; +import { useTaskGuard } from "../model/use-task-guard"; +import { AttemptCover } from "./attempt-cover"; +import styles from "./protected-region.module.css"; + +type ProtectedRegionProps = { + /** The lockdown of a real attempt, or null for an attempt that is not protected. */ + lockdown: AttemptLockdown | null; + className?: string | undefined; + headingId: string; + /** The task text. It is replaced by the cover while the candidate is away. */ + task: ReactNode; + /** The answer controls. They hide their own task content while `lockdown.covered`. */ + children: ReactNode; +}; + +/** + * The panel of the current item. It shows the task, or the cover in its place, + * and puts the keyboard focus where the candidate can continue: on the cover + * while the task is hidden, on the panel when the task comes back. + */ +export function ProtectedRegion({ + lockdown, + className, + headingId, + task, + children, +}: ProtectedRegionProps) { + const regionRef = useRef(null); + const coverRef = useRef(null); + const wasCovered = useRef(false); + const covered = lockdown?.covered ?? false; + const protectedText = lockdown !== null; + const [pasteRefused, setPasteRefused] = useState(false); + const refusePaste = useCallback(() => setPasteRefused(true), []); + useTaskGuard(regionRef, protectedText, refusePaste); + + useEffect(() => { + if (covered) { + wasCovered.current = true; + const action = coverRef.current?.querySelector("button"); + (action ?? coverRef.current)?.focus(); + } else if (wasCovered.current) { + wasCovered.current = false; + regionRef.current?.focus(); + } + }, [covered]); + + return ( +
setPasteRefused(false)} + > + {lockdown && lockdown.reason ? ( + void lockdown.enter()} + /> + ) : ( + task + )} + {children} + {pasteRefused && !covered ? ( +

+ Вставка в поля ответа отключена. Введите ответ вручную. +

+ ) : null} +
+ ); +} diff --git a/frontend/src/features/assessment-signals/model/notice-content.ts b/frontend/src/features/assessment-signals/model/notice-content.ts index d3877a1..fa1e739 100644 --- a/frontend/src/features/assessment-signals/model/notice-content.ts +++ b/frontend/src/features/assessment-signals/model/notice-content.ts @@ -3,7 +3,7 @@ * candidate acknowledged; change this number together with the text and with * the version the server requires, so that everyone acknowledges the new text. */ -export const knownSignalNoticeVersion = 1; +export const knownSignalNoticeVersion = 2; export type DisclosedSignal = { code: string; title: string; detail: string }; @@ -22,7 +22,42 @@ export const browserSignals: readonly DisclosedSignal[] = [ { code: "fullscreen", title: "Выход из полноэкранного режима", - detail: "Только факт выхода. Полноэкранный режим включать не нужно.", + detail: "Только факт выхода.", + }, +]; + +/** + * What the page does itself during a real attempt. These measures record + * nothing on their own: the browser signals above are the only record. + */ +export const attemptMeasures: readonly DisclosedSignal[] = [ + { + code: "fullscreen", + title: "Полноэкранный режим", + detail: + "Попытка идет на весь экран. Если браузер его не поддерживает, тест идет без него, и вы увидите это на экране.", + }, + { + code: "cover", + title: "Скрытие задания", + detail: + "При выходе из полноэкранного режима, вкладки или окна задание скрывается, пока вы не вернетесь. Введенный ответ сохраняется.", + }, + { + code: "task_text", + title: "Защита текста задания", + detail: + "Копирование, вырезание, выделение, контекстное меню, перетаскивание и печать текста задания отключены.", + }, + { + code: "paste", + title: "Вставка в поля ответа", + detail: "Отключена. В редакторе кода вставка разрешена, фиксируется только ее размер.", + }, + { + code: "watermark", + title: "Водяной знак на странице задания", + detail: "Планируется. Пока не используется.", }, ]; diff --git a/frontend/src/features/assessment-signals/model/use-signal-notice-gate.ts b/frontend/src/features/assessment-signals/model/use-signal-notice-gate.ts index e556431..1123bf2 100644 --- a/frontend/src/features/assessment-signals/model/use-signal-notice-gate.ts +++ b/frontend/src/features/assessment-signals/model/use-signal-notice-gate.ts @@ -13,9 +13,11 @@ export type SignalNoticeGate = { /** * Runs the action at once when the notice is acknowledged on the server. * Otherwise the notice dialog opens, and the action runs only after the - * candidate confirms and the server stores the confirmation. + * candidate confirms and the server stores the confirmation. `onDeclined` + * runs when the action will not run: the notice state could not be read or + * is outdated, or the candidate closed the notice without confirming. */ - guard: (action: () => void) => Promise; + guard: (action: () => void, onDeclined?: () => void) => Promise; /** A message when the notice state could not be read or is outdated. */ checkError: string | null; dialog: { @@ -40,13 +42,15 @@ export function useSignalNoticeGate({ actor, queryClient, enabled }: Options): S const [dialog, dispatch] = useReducer(noticeDialogReducer, closedNoticeDialog); const [checkError, setCheckError] = useState(null); const pendingAction = useRef<(() => void) | null>(null); + const pendingDeclined = useRef<(() => void) | null>(null); - async function guard(action: () => void): Promise { + async function guard(action: () => void, onDeclined?: () => void): Promise { setCheckError(null); const current = notice.data ?? (await notice.refetch()).data; const decision = decideNotice(current); if (decision.kind === "unavailable" || decision.kind === "outdated") { setCheckError(decision.message); + onDeclined?.(); return; } if (decision.kind === "proceed") { @@ -54,6 +58,7 @@ export function useSignalNoticeGate({ actor, queryClient, enabled }: Options): S return; } pendingAction.current = action; + pendingDeclined.current = onDeclined ?? null; dispatch({ type: "open" }); } @@ -70,13 +75,17 @@ export function useSignalNoticeGate({ actor, queryClient, enabled }: Options): S dispatch({ type: "confirmed" }); const action = pendingAction.current; pendingAction.current = null; + pendingDeclined.current = null; action?.(); } function close(): void { if (dialog.busy) return; pendingAction.current = null; + const declined = pendingDeclined.current; + pendingDeclined.current = null; dispatch({ type: "close" }); + declined?.(); } return { diff --git a/frontend/src/features/assessment-signals/ui/signal-notice.test.tsx b/frontend/src/features/assessment-signals/ui/signal-notice.test.tsx index 054d258..f2c15c7 100644 --- a/frontend/src/features/assessment-signals/ui/signal-notice.test.tsx +++ b/frontend/src/features/assessment-signals/ui/signal-notice.test.tsx @@ -1,8 +1,32 @@ import { renderToStaticMarkup } from "react-dom/server"; import { describe, expect, it } from "vitest"; +import { knownSignalNoticeVersion } from "../model/notice-content"; import { SignalNoticeContent, SignalNoticeDialog, SignalNoticeSummary } from "./signal-notice"; describe("signal notice", () => { + it("is version 2, the text that added the attempt measures", () => { + expect(knownSignalNoticeVersion).toBe(2); + }); + + it("lists every measure the page applies during a real attempt", () => { + const markup = renderToStaticMarkup(); + expect(markup).toContain("Что ограничено во время теста"); + expect(markup).toContain("Полноэкранный режим"); + expect(markup).toContain("Скрытие задания"); + expect(markup).toContain("Защита текста задания"); + expect(markup).toContain("Копирование, вырезание, выделение, контекстное меню"); + expect(markup).toContain("печать текста задания отключены"); + expect(markup).toContain("Вставка в поля ответа"); + expect(markup).toContain("В редакторе кода вставка разрешена"); + expect(markup).toContain("Водяной знак на странице задания"); + expect(markup).toContain("Планируется"); + }); + + it("says that keyboard input and screen readers keep working", () => { + const markup = renderToStaticMarkup(); + expect(markup).toContain("Ввод с клавиатуры, чтение с экрана"); + }); + it("lists the browser signals and the server signals", () => { const markup = renderToStaticMarkup(); expect(markup).toContain("Смена вкладки или окна"); diff --git a/frontend/src/features/assessment-signals/ui/signal-notice.tsx b/frontend/src/features/assessment-signals/ui/signal-notice.tsx index 69b94ff..62c1c78 100644 --- a/frontend/src/features/assessment-signals/ui/signal-notice.tsx +++ b/frontend/src/features/assessment-signals/ui/signal-notice.tsx @@ -1,6 +1,7 @@ import { useEffect, useRef } from "react"; import { Button } from "../../../shared/ui"; import { + attemptMeasures, browserSignals, notCollected, serverSignals, @@ -37,6 +38,8 @@ export function SignalNoticeContent({ headingLevel }: ContentProps) { Что фиксирует браузер

События сохраняются, только пока действует согласие C3.

+ Что ограничено во время теста + Что измеряет сервер Что не собирается @@ -46,11 +49,11 @@ export function SignalNoticeContent({ headingLevel }: ContentProps) { ))}

- Адреса и токены сессий не хранятся: для них есть только односторонние отпечатки. Во время - теста сбор ничего не показывает и не блокирует: ввод, вставка и отправка ответов работают - как обычно. Браузерные сигналы легко исказить, а ложные срабатывания возможны, например при - случайном переключении окна, поэтому это только подсказка. Экспресс-тест сигналы не - собирает. + Адреса и токены сессий не хранятся: для них есть только односторонние отпечатки. Сбор + сигналов ничего не показывает. Ввод с клавиатуры, чтение с экрана и отправка ответов + работают как обычно. Браузерные сигналы легко исказить, а ложные срабатывания возможны, + например при случайном переключении окна, поэтому это только подсказка. Экспресс-тест + сигналы не собирает и не ограничивает.

Подтверждение хранится на сервере. Оно не заменяет согласие C3, которое управляется отдельно @@ -126,7 +129,7 @@ export function SignalNoticeDialog({ {open ? ( <>

- Перед началом: какие сигналы собираются + Перед началом: какие сигналы собираются и что ограничено

{errorMessage ? ( diff --git a/frontend/src/pages/assessment/ui/assessment-attempt-page.module.css b/frontend/src/pages/assessment/ui/assessment-attempt-page.module.css index 773a3a9..f68379d 100644 --- a/frontend/src/pages/assessment/ui/assessment-attempt-page.module.css +++ b/frontend/src/pages/assessment/ui/assessment-attempt-page.module.css @@ -199,6 +199,15 @@ background: var(--color-surface); } +.item:focus { + outline: none; +} + +.item:focus-visible { + outline: var(--focus-ring-width) solid var(--color-focus-ring); + outline-offset: var(--focus-ring-offset); +} + .item-heading { display: flex; flex-wrap: wrap; diff --git a/frontend/src/pages/assessment/ui/assessment-attempt-page.tsx b/frontend/src/pages/assessment/ui/assessment-attempt-page.tsx index cf09e74..9ff6875 100644 --- a/frontend/src/pages/assessment/ui/assessment-attempt-page.tsx +++ b/frontend/src/pages/assessment/ui/assessment-attempt-page.tsx @@ -53,6 +53,11 @@ import { submitPendingAnswerCommand, } from "../../../features/answer-assessment"; import type { AnswerDraft, PendingAnswerCommand } from "../../../features/answer-assessment"; +import { + FullscreenFallbackNotice, + ProtectedRegion, + useAttemptLockdown, +} from "../../../features/assessment-lockdown"; import { SignalNoticeDialog, shouldCollectSignals, @@ -153,6 +158,12 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) { }), ), }); + // A real attempt runs in fullscreen and hides the task when the candidate + // leaves the tab, the window, or fullscreen. The express run is not protected. + const lockdown = useAttemptLockdown({ + applies: Boolean(attempt && collectsSignals && !isTerminal(attempt)), + running: workReady, + }); const [resumeBusy, setResumeBusy] = useState(false); const [pendingResume, setPendingResume] = useState<{ key: string; version: number } | null>(null); const [pendingAnswer, setPendingAnswer] = useState(null); @@ -598,6 +609,10 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) { /> ) : null} + {collectsSignals && !terminal ? ( + + ) : null} + {resumedExpress && attempt.kind === "demo_express" && !terminal ? (

@@ -630,11 +645,16 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {