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

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

No files matched your search

@@ -154,3 +154,37 @@ describe("assessment answer response validation", () => {
]);
});
});
describe("assessment answer command page identifier", () => {
it("sends the open page identifier so a second window is refused, and omits it when there is none", async () => {
const interceptedFetch = globalThis.fetch;
vi.stubGlobal("fetch", (input: string, init?: RequestInit) =>
interceptedFetch(new URL(input, "http://localhost"), init),
);
const clients: Array<string | null> = [];
server.use(
http.post(
`http://localhost/api/v1/me/assessment-attempts/${attemptId}/answers`,
({ request }) => {
clients.push(request.headers.get("X-Attempt-Client"));
return HttpResponse.json(validAttempt, { status: 200 });
},
),
);
const command: PendingAnswerCommand = {
key: "answer-command-key",
body: '{"expected_version":1,"item_id":"item-1","answer":{"format":"number","number":1}}',
itemId: "item-1",
};
const withClient = await submitPendingAnswerCommand(
command,
attemptId,
"csrf-token",
"7mK2pQx9Rt4vWc1Zb8NfYd3Ha6Js0LeG",
);
const withoutClient = await submitPendingAnswerCommand(command, attemptId, "csrf-token");
expect(withClient.kind).toBe("accepted");
expect(withoutClient.kind).toBe("accepted");
expect(clients).toEqual(["7mK2pQx9Rt4vWc1Zb8NfYd3Ha6Js0LeG", null]);
});
});
@@ -13,10 +13,15 @@ export type AnswerCommandOutcome =
| { kind: "retry"; command: PendingAnswerCommand; error: unknown }
| { kind: "rejected"; error: unknown };
/**
* Sends the answer. `client` names the open page, so that a second window of
* the same attempt is refused while another one holds its work session.
*/
export async function submitPendingAnswerCommand(
command: PendingAnswerCommand,
attemptId: string,
csrfToken: string,
client?: string,
): Promise<AnswerCommandOutcome> {
try {
const attempt = await apiRequest<AssessmentAttempt>(
@@ -27,6 +32,7 @@ export async function submitPendingAnswerCommand(
"Content-Type": "application/json",
"Idempotency-Key": command.key,
"X-CSRF-Token": csrfToken,
...(client ? { "X-Attempt-Client": client } : {}),
},
body: command.body,
},
@@ -0,0 +1,33 @@
import { describe, expect, it } from "vitest";
import { isScreenshotKey } from "./capture-keys";
describe("screenshot keys", () => {
it("recognizes PrintScreen alone and with Alt", () => {
expect(isScreenshotKey({ key: "PrintScreen", code: "PrintScreen" })).toBe(true);
expect(isScreenshotKey({ key: "PrintScreen", code: "PrintScreen", metaKey: false })).toBe(true);
expect(isScreenshotKey({ code: "PrintScreen" })).toBe(true);
});
it("recognizes the macOS shortcuts by the physical digit key, whatever Shift types", () => {
for (const code of ["Digit3", "Digit4", "Digit5"]) {
// With Shift the keys type #, $, and %, so the character is not what matters.
expect(isScreenshotKey({ key: "#", code, metaKey: true, shiftKey: true })).toBe(true);
}
});
it("recognizes the Windows snipping shortcut", () => {
expect(isScreenshotKey({ key: "S", code: "KeyS", metaKey: true, shiftKey: true })).toBe(true);
});
it("leaves ordinary typing and incomplete combinations alone", () => {
expect(isScreenshotKey({ key: "3", code: "Digit3" })).toBe(false);
expect(isScreenshotKey({ key: "3", code: "Digit3", shiftKey: true })).toBe(false);
expect(isScreenshotKey({ key: "3", code: "Digit3", metaKey: true })).toBe(false);
expect(isScreenshotKey({ key: "s", code: "KeyS", metaKey: true })).toBe(false);
expect(isScreenshotKey({ key: "s", code: "KeyS", shiftKey: true })).toBe(false);
expect(isScreenshotKey({ key: "6", code: "Digit6", metaKey: true, shiftKey: true })).toBe(
false,
);
expect(isScreenshotKey({})).toBe(false);
});
});
@@ -0,0 +1,26 @@
/** The parts of a keyboard event that the screenshot check reads. */
export type KeyLike = {
key?: string;
code?: string;
metaKey?: boolean;
shiftKey?: boolean;
};
/**
* Tells whether a key event is a screenshot shortcut that the browser can see:
* PrintScreen (also with Alt), Cmd+Shift+3, 4, or 5 on macOS, and Win+Shift+S on
* Windows. The operating system often takes these keys before the page, and a
* photo of the screen sends none, so a missed shortcut proves nothing and a seen
* one proves only that a key was pressed. Only the physical key (`code`) is used
* for the digits, because the produced character changes with Shift.
*/
export function isScreenshotKey(event: KeyLike): boolean {
if (event.code === "PrintScreen" || event.key === "PrintScreen") return true;
if (!event.metaKey || !event.shiftKey) return false;
return (
event.code === "Digit3" ||
event.code === "Digit4" ||
event.code === "Digit5" ||
event.code === "KeyS"
);
}
@@ -133,6 +133,55 @@ describe("signal collector", () => {
expect(events[0]).toMatchObject({ kind: "fullscreen_exit" });
});
it("records a screenshot key once for its press and release, and never prevents it", () => {
const { doc, events, advance } = setup();
const press = new Event("keydown", { cancelable: true });
Object.assign(press, { key: "PrintScreen", code: "PrintScreen" });
doc.dispatchEvent(press);
const release = new Event("keyup", { cancelable: true });
Object.assign(release, { key: "PrintScreen", code: "PrintScreen" });
doc.dispatchEvent(release);
expect(events).toHaveLength(1);
expect(events[0]).toMatchObject({ kind: "screenshot_key", item_instance_id: itemId });
expect(Object.keys(events[0] ?? {}).sort()).toEqual(
["item_instance_id", "kind", "occurred_at"].sort(),
);
expect(press.defaultPrevented).toBe(false);
expect(release.defaultPrevented).toBe(false);
// A later press is a new event.
advance(5_000);
doc.dispatchEvent(press);
expect(events).toHaveLength(2);
});
it("records the macOS and Windows screenshot shortcuts and no other key", () => {
const { doc, events, advance } = setup();
const press = (init: Record<string, unknown>) => {
const event = new Event("keydown");
Object.assign(event, init);
doc.dispatchEvent(event);
advance(2_000);
};
press({ key: "#", code: "Digit3", metaKey: true, shiftKey: true });
press({ key: "$", code: "Digit4", metaKey: true, shiftKey: true });
press({ key: "S", code: "KeyS", metaKey: true, shiftKey: true });
press({ key: "a", code: "KeyA" });
press({ key: "3", code: "Digit3", metaKey: true });
expect(events.map((event) => event.kind)).toEqual([
"screenshot_key",
"screenshot_key",
"screenshot_key",
]);
});
it("does not record a screenshot key while no item is shown", () => {
const { doc, events } = setup(null);
const press = new Event("keydown");
Object.assign(press, { key: "PrintScreen", code: "PrintScreen" });
doc.dispatchEvent(press);
expect(events).toHaveLength(0);
});
it("ignores events while no item is shown", () => {
const { doc, events } = setup(null);
doc.dispatchEvent(new Event("copy"));
@@ -1,6 +1,13 @@
import type { AssessmentSignalEvent } from "../../../shared/api/schemas";
import { pasteSizeBytes, selectionSize, type PasteSource, type SelectionSource } from "./measure";
import { clipboardEvent, focusLossEvent, fullscreenExitEvent } from "./signal-events";
import { isScreenshotKey, type KeyLike } from "./capture-keys";
import type { WindowSizes } from "./devtools-heuristic";
import {
clipboardEvent,
focusLossEvent,
fullscreenExitEvent,
screenshotKeyEvent,
} from "./signal-events";
/** The browser objects the collector listens to; tests pass small fakes. */
export type CollectorEnvironment = {
@@ -10,7 +17,7 @@ export type CollectorEnvironment = {
readonly fullscreenElement: unknown;
hasFocus(): boolean;
};
window: EventTarget;
window: EventTarget & Partial<WindowSizes>;
/** Device clock in milliseconds; only differences of it are used as durations. */
now: () => number;
/**
@@ -34,6 +41,13 @@ export type CollectorOptions = {
type ClipboardLike = Event & { clipboardData?: PasteSource | null };
/**
* A shortcut is reported once for its press and release, which both reach the
* page on some systems (Windows sends only the release of PrintScreen), and a
* held key repeats.
*/
const screenshotKeyCooldownMs = 1_000;
/**
* Observes the disclosed signals and reports them through onEvent.
*
@@ -47,6 +61,7 @@ export function attachSignalCollector(options: CollectorOptions): () => void {
const stamp = options.environment.toServerTime ?? ((deviceMs: number) => deviceMs);
let awaySince: number | null = null;
let wasFullscreen = doc.fullscreenElement != null;
let lastScreenshotKeyAt: number | null = null;
function emit(build: (itemId: string) => AssessmentSignalEvent): void {
const itemId = options.currentItemId();
@@ -102,6 +117,17 @@ export function attachSignalCollector(options: CollectorOptions): () => void {
const size = pasteSizeBytes((event as ClipboardLike).clipboardData);
emit((itemId) => clipboardEvent("paste", itemId, stamp(now()), size));
});
function onKey(event: Event): void {
if (!isScreenshotKey(event as unknown as KeyLike)) return;
const at = now();
if (lastScreenshotKeyAt !== null && at - lastScreenshotKeyAt < screenshotKeyCooldownMs) return;
lastScreenshotKeyAt = at;
emit((itemId) => screenshotKeyEvent(itemId, stamp(at)));
}
// The keys are only observed: nothing is prevented, so a screenshot is never
// blocked by the page, and typing is untouched.
listen(doc, "keydown", onKey);
listen(doc, "keyup", onKey);
listen(doc, "fullscreenchange", () => {
const isFullscreen = doc.fullscreenElement != null;
if (wasFullscreen && !isFullscreen) emit((itemId) => fullscreenExitEvent(itemId, stamp(now())));
@@ -0,0 +1,139 @@
import { describe, expect, it } from "vitest";
import { devtoolsDockedOpen, startDevtoolsWatcher, type WindowSizes } from "./devtools-heuristic";
const closed: WindowSizes = {
innerWidth: 1280,
innerHeight: 720,
outerWidth: 1280,
outerHeight: 820,
};
class FakeWindow extends EventTarget implements WindowSizes {
innerWidth = closed.innerWidth;
innerHeight = closed.innerHeight;
outerWidth = closed.outerWidth;
outerHeight = closed.outerHeight;
}
describe("developer tools heuristic", () => {
it("leaves a window with ordinary browser chrome alone", () => {
expect(devtoolsDockedOpen(closed)).toBe(false);
expect(devtoolsDockedOpen({ ...closed, outerHeight: 720 + 130 })).toBe(false);
// Fullscreen has no chrome at all.
expect(devtoolsDockedOpen({ ...closed, outerHeight: 720 })).toBe(false);
});
it("suspects a panel docked at the bottom or at the side", () => {
expect(devtoolsDockedOpen({ ...closed, innerHeight: 420 })).toBe(true);
expect(devtoolsDockedOpen({ ...closed, innerWidth: 900 })).toBe(true);
});
it("never suspects a window that reports no sizes", () => {
expect(devtoolsDockedOpen({})).toBe(false);
expect(devtoolsDockedOpen({ innerWidth: 100 })).toBe(false);
});
});
function watch(overrides: { cooldownMs?: number } = {}) {
const win = new FakeWindow();
let clock = 1_000_000;
const opens: number[] = [];
const timers: Array<() => void> = [];
const cancelled: unknown[] = [];
const stop = startDevtoolsWatcher({
window: win,
now: () => clock,
schedule: (callback) => {
timers.push(callback);
return timers.length;
},
cancel: (handle) => cancelled.push(handle),
onOpen: () => opens.push(clock),
...overrides,
});
return {
win,
opens,
timers,
cancelled,
stop,
advance: (ms: number) => {
clock += ms;
},
};
}
describe("developer tools watcher", () => {
it("reports the change from closed to open once, on a resize", () => {
const { win, opens } = watch();
expect(opens).toHaveLength(0);
win.innerHeight = 400;
win.dispatchEvent(new Event("resize"));
win.dispatchEvent(new Event("resize"));
expect(opens).toHaveLength(1);
});
it("notices a panel that is opened between resizes on its timer", () => {
const { win, opens, timers } = watch();
win.innerWidth = 800;
timers.at(-1)?.();
expect(opens).toHaveLength(1);
});
it("reports a panel that is already open when the watcher starts", () => {
const win = new FakeWindow();
win.innerHeight = 300;
const opens: number[] = [];
startDevtoolsWatcher({
window: win,
now: () => 1,
schedule: () => 1,
cancel: () => undefined,
onOpen: () => opens.push(1),
});
expect(opens).toHaveLength(1);
});
it("reports a panel that is closed and opened again only after the cooldown", () => {
const { win, opens, advance } = watch({ cooldownMs: 60_000 });
win.innerHeight = 400;
win.dispatchEvent(new Event("resize"));
win.innerHeight = closed.innerHeight;
win.dispatchEvent(new Event("resize"));
advance(10_000);
win.innerHeight = 400;
win.dispatchEvent(new Event("resize"));
expect(opens).toHaveLength(1);
win.innerHeight = closed.innerHeight;
win.dispatchEvent(new Event("resize"));
advance(60_000);
win.innerHeight = 400;
win.dispatchEvent(new Event("resize"));
expect(opens).toHaveLength(2);
});
it("stops listening and cancels its timer", () => {
const { win, opens, stop, cancelled } = watch();
stop();
expect(cancelled).toHaveLength(1);
win.innerHeight = 400;
win.dispatchEvent(new Event("resize"));
expect(opens).toHaveLength(0);
});
it("is not disturbed by a consumer that throws", () => {
const win = new FakeWindow();
win.innerHeight = 300;
expect(() =>
startDevtoolsWatcher({
window: win,
now: () => 1,
schedule: () => 1,
cancel: () => undefined,
onOpen: () => {
throw new Error("consumer failed");
},
}),
).not.toThrow();
});
});
@@ -0,0 +1,96 @@
/** The window sizes the heuristic reads. */
export type WindowSizes = {
innerWidth: number;
innerHeight: number;
outerWidth: number;
outerHeight: number;
};
/**
* How much larger the outer window may be than the page before the developer
* tools are suspected, in pixels. Window frames, tab strips, and address bars
* take up to about 130 px of height, and a docked panel takes at least 200.
*/
const sizeGapPx = 160;
/**
* Guesses that a docked developer tools panel is open, because it takes room
* from the page and leaves the outer window as it was. It is a heuristic with
* known false positives (a sidebar, a zoomed page, a window that is being
* resized) and false negatives (a detached panel), so a result is only a weak
* hint. A window that reports no sizes is never suspected.
*/
export function devtoolsDockedOpen(sizes: Partial<WindowSizes>): boolean {
const { innerWidth, innerHeight, outerWidth, outerHeight } = sizes;
if (
innerWidth === undefined ||
innerHeight === undefined ||
outerWidth === undefined ||
outerHeight === undefined
) {
return false;
}
return outerWidth - innerWidth > sizeGapPx || outerHeight - innerHeight > sizeGapPx;
}
export type DevtoolsWatcherOptions = {
window: EventTarget & Partial<WindowSizes>;
now: () => number;
schedule: (callback: () => void, delayMs: number) => unknown;
cancel: (handle: unknown) => void;
/** Called once when the panel looks opened, and again only after the cooldown. */
onOpen: () => void;
intervalMs?: number;
cooldownMs?: number;
};
const defaultIntervalMs = 2_000;
const defaultCooldownMs = 60_000;
/**
* Watches the window sizes on every resize and on a slow timer, and reports a
* change from closed to open. A panel that is closed and opened again reports
* again only after the cooldown, so a candidate who toggles it cannot flood the
* batch. Returns the function that stops the watcher.
*/
export function startDevtoolsWatcher(options: DevtoolsWatcherOptions): () => void {
const interval = options.intervalMs ?? defaultIntervalMs;
const cooldown = options.cooldownMs ?? defaultCooldownMs;
let open = false;
let lastReportAt: number | null = null;
let timer: unknown = null;
let stopped = false;
function check(): void {
const nowOpen = devtoolsDockedOpen(options.window);
if (nowOpen && !open) {
const at = options.now();
if (lastReportAt === null || at - lastReportAt >= cooldown) {
lastReportAt = at;
try {
options.onOpen();
} catch {
// A watcher must never disturb the test.
}
}
}
open = nowOpen;
}
function tick(): void {
if (stopped) return;
check();
timer = options.schedule(tick, interval);
}
const onResize = () => check();
options.window.addEventListener("resize", onResize, { passive: true });
check();
timer = options.schedule(tick, interval);
return () => {
stopped = true;
options.window.removeEventListener("resize", onResize);
if (timer !== null) options.cancel(timer);
};
}
@@ -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 = 3;
export const knownSignalNoticeVersion = 4;
export type DisclosedSignal = { code: string; title: string; detail: string };
@@ -24,6 +24,17 @@ export const browserSignals: readonly DisclosedSignal[] = [
title: "Выход из полноэкранного режима",
detail: "Только факт выхода.",
},
{
code: "screenshot_key",
title: "Клавиши снимка экрана",
detail:
"PrintScreen, Cmd+Shift+3, 4 или 5 и Win+Shift+S, если браузер их видит. Фиксируется только факт нажатия: сам снимок страница не видит и не блокирует.",
},
{
code: "devtools",
title: "Признаки открытых инструментов разработчика",
detail: "Это догадка по размерам окна, она может ошибаться. Фиксируется только факт.",
},
];
/**
@@ -54,6 +65,12 @@ export const attemptMeasures: readonly DisclosedSignal[] = [
title: "Вставка в поля ответа",
detail: "Отключена. В редакторе кода вставка разрешена, фиксируется только ее размер.",
},
{
code: "single_window",
title: "Одно окно",
detail:
"Попытку можно вести только в одном окне. Второе окно не сможет начать работу, пока первое открыто. После закрытия окна попытка освобождается сразу, а после потери связи - в течение двух минут.",
},
{
code: "watermark",
title: "Водяной знак на странице задания",
@@ -80,6 +97,12 @@ export const serverSignals: readonly DisclosedSignal[] = [
title: "Параллельные сессии",
detail: "Токен сессии не хранится, только односторонний ключевой отпечаток.",
},
{
code: "user_agent",
title: "Тип браузера (User-Agent)",
detail:
"Хранится только односторонний ключевой отпечаток, привязанный к попытке. Смена браузера или устройства во время попытки - слабый сигнал.",
},
{
code: "answer_match",
title: "Совпадение ответов с ответами других кандидатов",
@@ -94,3 +117,9 @@ export const notCollected: readonly string[] = [
"Звук: микрофон не используется.",
"Содержимое буфера обмена и вводимый текст: отправляется только размер вставки.",
];
/** What the measures and signals do not do, stated plainly. */
export const limits: readonly string[] = [
"Снимок экрана и фото экрана телефоном предотвратить нельзя: страница видит лишь часть клавиш и не знает о камере. Водяной знак нужен только затем, чтобы по утечке можно было найти попытку.",
"Сигналы ведут к ручной проверке и апелляции, но не к автоматическому снижению оценки. Работодатель их не видит.",
];
@@ -41,3 +41,17 @@ export function clipboardEvent(
export function fullscreenExitEvent(itemId: string, atMs: number): AssessmentSignalEvent {
return { kind: "fullscreen_exit", item_instance_id: itemId, occurred_at: timestamp(atMs) };
}
/**
* A key or key combination that usually takes a screenshot, as the browser saw
* it. It is a weak hint: the browser does not see every screenshot, and the
* event carries no measurement.
*/
export function screenshotKeyEvent(itemId: string, atMs: number): AssessmentSignalEvent {
return { kind: "screenshot_key", item_instance_id: itemId, occurred_at: timestamp(atMs) };
}
/** The developer tools were probably opened. A heuristic, so it is a weak hint. */
export function devtoolsOpenEvent(itemId: string, atMs: number): AssessmentSignalEvent {
return { kind: "devtools_open", item_instance_id: itemId, occurred_at: timestamp(atMs) };
}
@@ -37,6 +37,52 @@ function start(overrides: { itemId?: string | null; offsetMs?: number } = {}) {
return { doc, win, send, timers, stop, clock };
}
describe("signal session developer tools watcher", () => {
function startWatching() {
const win = Object.assign(new EventTarget(), {
innerWidth: 1280,
innerHeight: 720,
outerWidth: 1280,
outerHeight: 820,
});
const send = vi.fn<SignalSender>(async () => undefined);
const timers: Array<() => void> = [];
const stop = startSignalSession({
environment: {
document: new FakeDocument(),
window: win,
now: () => Date.UTC(2026, 9, 8, 12, 0, 0),
} as CollectorEnvironment,
send,
newKey: () => "key",
schedule: (callback) => timers.push(callback),
cancel: () => undefined,
currentItemId: () => itemId,
watchDevtools: true,
});
return { win, send, timers, stop };
}
it("batches a developer tools event bound to the current item", async () => {
const { win, send, timers } = startWatching();
win.innerHeight = 380;
win.dispatchEvent(new Event("resize"));
// The watcher's own timer comes first, the batch timer after the event.
for (const timer of [...timers]) timer();
await Promise.resolve();
expect(send).toHaveBeenCalled();
const events = send.mock.calls.flatMap((call) => call[0].events);
expect(events).toEqual([
expect.objectContaining({ kind: "devtools_open", item_instance_id: itemId }),
]);
});
it("does not watch the window unless asked to", () => {
const { timers } = start();
expect(timers).toHaveLength(0);
});
});
describe("signal session life cycle", () => {
it("batches an event and sends it when the timer fires", async () => {
const { doc, send, timers } = start();
@@ -1,5 +1,7 @@
import { createSignalBatcher, type SignalBatcher, type SignalSender } from "./batcher";
import { attachSignalCollector, type CollectorEnvironment } from "./collector";
import { startDevtoolsWatcher } from "./devtools-heuristic";
import { devtoolsOpenEvent } from "./signal-events";
export type SignalSessionOptions = {
environment: CollectorEnvironment;
@@ -8,6 +10,11 @@ export type SignalSessionOptions = {
schedule: (callback: () => void, delayMs: number) => unknown;
cancel: (handle: unknown) => void;
currentItemId: () => string | null;
/**
* Also watches the window size for open developer tools, on the timers above.
* Off by default: it needs a window that reports its sizes.
*/
watchDevtools?: boolean;
};
/**
@@ -30,8 +37,22 @@ export function startSignalSession(options: SignalSessionOptions): () => void {
onHidden: () => batcher.flush(),
onPageHide: () => batcher.flushOnExit(),
});
const stamp = options.environment.toServerTime ?? ((deviceMs: number) => deviceMs);
const stopDevtools = options.watchDevtools
? startDevtoolsWatcher({
window: options.environment.window,
now: options.environment.now,
schedule: options.schedule,
cancel: options.cancel,
onOpen: () => {
const itemId = options.currentItemId();
if (itemId) batcher.enqueue(devtoolsOpenEvent(itemId, stamp(options.environment.now())));
},
})
: () => undefined;
return () => {
detach();
stopDevtools();
batcher.dispose();
};
}
@@ -54,6 +54,7 @@ export function useAssessmentSignals({
schedule: (callback, delayMs) => window.setTimeout(callback, delayMs),
cancel: (handle) => window.clearTimeout(handle as number),
currentItemId: () => itemRef.current,
watchDevtools: true,
});
}, [attemptId, enabled]);
}
@@ -4,8 +4,25 @@ import { knownSignalNoticeVersion } from "../model/notice-content";
import { SignalNoticeContent, SignalNoticeDialog, SignalNoticeSummary } from "./signal-notice";
describe("signal notice", () => {
it("is version 3, the text that describes the watermark", () => {
expect(knownSignalNoticeVersion).toBe(3);
it("is version 4, the text that adds the capture hints and the one-window rule", () => {
expect(knownSignalNoticeVersion).toBe(4);
});
it("lists the screenshot keys, the developer tools hint, the User-Agent digest, and the single window", () => {
const markup = renderToStaticMarkup(<SignalNoticeContent headingLevel="h3" />);
expect(markup).toContain("Клавиши снимка экрана");
expect(markup).toContain("сам снимок страница не видит и не блокирует");
expect(markup).toContain("Признаки открытых инструментов разработчика");
expect(markup).toContain("Тип браузера (User-Agent)");
expect(markup).toContain("Одно окно");
});
it("says plainly that a screenshot or a photo cannot be prevented and that signals never lower a grade by themselves", () => {
const markup = renderToStaticMarkup(<SignalNoticeContent headingLevel="h3" />);
expect(markup).toContain("Чего эти меры не делают");
expect(markup).toContain("Снимок экрана и фото экрана телефоном предотвратить нельзя");
expect(markup).toContain("не к автоматическому снижению оценки");
expect(markup).toContain("Работодатель их не видит");
});
it("lists every measure the page applies during a real attempt", () => {
@@ -3,6 +3,7 @@ import { Button } from "../../../shared/ui";
import {
attemptMeasures,
browserSignals,
limits,
notCollected,
serverSignals,
type DisclosedSignal,
@@ -42,6 +43,12 @@ export function SignalNoticeContent({ headingLevel }: ContentProps) {
<SignalList signals={attemptMeasures} />
<Heading>Что измеряет сервер</Heading>
<SignalList signals={serverSignals} />
<Heading>Чего эти меры не делают</Heading>
<ul>
{limits.map((item) => (
<li key={item}>{item}</li>
))}
</ul>
<Heading>Что не собирается</Heading>
<ul>
{notCollected.map((item) => (
@@ -0,0 +1,5 @@
export { pageClientId } from "./model/page-client";
export { useWorkSession } from "./model/use-work-session";
export type { UseWorkSession } from "./model/use-work-session";
export { createWorkSession } from "./model/work-session";
export type { WorkSessionStatus } from "./model/work-session";
@@ -0,0 +1,7 @@
/**
* The identifier of this open page. A new one is made when the page loads and
* lives until it closes, so a reload is a new page and a second tab is another
* one. It is random, 36 characters of `A-Za-z0-9-`, and the server keeps only a
* keyed digest of it bound to the attempt.
*/
export const pageClientId: string = crypto.randomUUID();
@@ -0,0 +1,86 @@
import { useCallback, useEffect, useRef, useState } from "react";
import {
holdMyAssessmentWorkSession,
releaseMyAssessmentWorkSession,
} from "../../../shared/api/endpoints/assessment/assessment";
import { pageClientId } from "./page-client";
import {
createWorkSession,
type AcquireResult,
type WorkSession,
type WorkSessionStatus,
} from "./work-session";
export type UseWorkSessionOptions = {
attemptId: string;
csrfToken: string;
/** True for a real attempt, the only kind that has a protected work session. */
enabled: boolean;
};
export type UseWorkSession = {
status: WorkSessionStatus;
/** Holds the session for this page; `busy` means another page holds it. */
acquire: () => Promise<AcquireResult>;
release: () => void;
};
/**
* Keeps the work session of a real attempt for this page while it works, and
* gives it back when the page closes or leaves. A demonstration run has none.
*/
export function useWorkSession({
attemptId,
csrfToken,
enabled,
}: UseWorkSessionOptions): UseWorkSession {
const [status, setStatus] = useState<WorkSessionStatus>("idle");
const csrfRef = useRef(csrfToken);
const sessionRef = useRef<WorkSession | null>(null);
useEffect(() => {
csrfRef.current = csrfToken;
}, [csrfToken]);
useEffect(() => {
if (!enabled || !attemptId) return undefined;
const session = createWorkSession({
transport: {
hold: async () => {
const lease = await holdMyAssessmentWorkSession(
attemptId,
{ "X-Attempt-Client": pageClientId },
{ headers: { "X-CSRF-Token": csrfRef.current } },
);
return { renewAfterSeconds: lease.renew_after_seconds };
},
release: () =>
releaseMyAssessmentWorkSession(
attemptId,
{ "X-Attempt-Client": pageClientId },
{ headers: { "X-CSRF-Token": csrfRef.current }, keepalive: true },
),
},
schedule: (callback, delayMs) => window.setTimeout(callback, delayMs),
cancel: (handle) => window.clearTimeout(handle as number),
onStatus: setStatus,
});
sessionRef.current = session;
// A page that is closing or going to the back-forward cache frees the session
// at once, so the candidate can open the attempt in another window.
const onPageHide = () => session.release();
window.addEventListener("pagehide", onPageHide);
return () => {
window.removeEventListener("pagehide", onPageHide);
session.release();
sessionRef.current = null;
};
}, [attemptId, enabled]);
const acquire = useCallback(async (): Promise<AcquireResult> => {
const session = sessionRef.current;
return session ? session.acquire() : "held";
}, []);
const release = useCallback(() => sessionRef.current?.release(), []);
return { status, acquire, release };
}
@@ -0,0 +1,135 @@
import { describe, expect, it, vi } from "vitest";
import { ApiRequestError } from "../../../shared/api";
import {
createWorkSession,
type WorkSessionStatus,
type WorkSessionTransport,
} from "./work-session";
const conflict = () =>
new ApiRequestError({ status: 409, code: "state_conflict", title: "Conflict" });
const unavailable = () =>
new ApiRequestError({ status: 0, code: "network_error", title: "Offline" });
function setup(hold: WorkSessionTransport["hold"]) {
const statuses: WorkSessionStatus[] = [];
const timers: Array<{ callback: () => void; delayMs: number; id: number }> = [];
const cancelled: number[] = [];
const release = vi.fn<WorkSessionTransport["release"]>(async () => undefined);
const session = createWorkSession({
transport: { hold: vi.fn(hold), release },
schedule: (callback, delayMs) => {
const id = timers.length + 1;
timers.push({ callback, delayMs, id });
return id;
},
cancel: (handle) => cancelled.push(handle as number),
onStatus: (status) => statuses.push(status),
});
return { session, statuses, timers, cancelled, release };
}
const lease = { renewAfterSeconds: 15 };
describe("work session of a real attempt", () => {
it("holds the session, renews it on the server's cadence, and releases it on leaving", async () => {
const { session, statuses, timers, release } = setup(async () => lease);
await expect(session.acquire()).resolves.toBe("held");
expect(statuses).toEqual(["held"]);
expect(timers.at(-1)?.delayMs).toBe(15_000);
timers.at(-1)?.callback();
await Promise.resolve();
await Promise.resolve();
// A renewal arms the next one and changes no status.
expect(timers).toHaveLength(2);
expect(statuses).toEqual(["held"]);
session.release();
expect(release).toHaveBeenCalledTimes(1);
expect(statuses).toEqual(["held", "idle"]);
});
it("says busy when another page holds the session, and holds nothing", async () => {
const { session, statuses, timers, release } = setup(async () => {
throw conflict();
});
await expect(session.acquire()).resolves.toBe("busy");
expect(statuses).toEqual(["busy"]);
expect(timers).toHaveLength(0);
session.release();
// A page that never held the session has nothing to release.
expect(release).not.toHaveBeenCalled();
});
it("is lost when another page takes the session over at a renewal", async () => {
let refuse = false;
const { session, statuses, timers, cancelled } = setup(async () => {
if (refuse) throw conflict();
return lease;
});
await session.acquire();
refuse = true;
timers.at(-1)?.callback();
await Promise.resolve();
await Promise.resolve();
expect(statuses).toEqual(["held", "lost"]);
// It stops renewing a session it no longer has.
expect(timers).toHaveLength(1);
expect(cancelled).toHaveLength(1);
});
it("keeps trying through a network gap instead of giving the session up", async () => {
let offline = false;
const { session, statuses, timers } = setup(async () => {
if (offline) throw unavailable();
return lease;
});
await session.acquire();
offline = true;
timers.at(-1)?.callback();
await Promise.resolve();
await Promise.resolve();
expect(statuses).toEqual(["held"]);
expect(timers).toHaveLength(2);
expect(timers.at(-1)?.delayMs).toBe(5_000);
});
it("reports a failed start as an error without holding anything", async () => {
const { session, statuses, timers } = setup(async () => {
throw unavailable();
});
await expect(session.acquire()).resolves.toBe("error");
expect(statuses).toEqual([]);
expect(timers).toHaveLength(0);
});
it("keeps the renewal cadence within sane bounds", async () => {
const fast = setup(async () => ({ renewAfterSeconds: 1 }));
await fast.session.acquire();
expect(fast.timers.at(-1)?.delayMs).toBe(5_000);
const slow = setup(async () => ({ renewAfterSeconds: 3600 }));
await slow.session.acquire();
expect(slow.timers.at(-1)?.delayMs).toBe(60_000);
});
it("ignores a renewal that finishes after the page released the session", async () => {
const pending: { finish: (() => void) | null } = { finish: null };
let calls = 0;
const { session, statuses, timers } = setup(() => {
calls += 1;
if (calls === 1) return Promise.resolve(lease);
return new Promise((resolve) => {
pending.finish = () => resolve(lease);
});
});
await session.acquire();
timers.at(-1)?.callback();
session.release();
pending.finish?.();
await Promise.resolve();
await Promise.resolve();
expect(statuses).toEqual(["held", "idle"]);
expect(timers).toHaveLength(1);
});
});
@@ -0,0 +1,123 @@
import { ApiRequestError } from "../../../shared/api";
/** What the page knows about the single work session of the attempt. */
export type WorkSessionStatus =
/** Not holding it: before the work starts, and after a release. */
| "idle"
/** This page holds it. */
| "held"
/** Another open page holds it, so this page cannot work on the attempt. */
| "busy"
/** This page held it and another page took it over. */
| "lost";
export type AcquireResult = "held" | "busy" | "error";
export type WorkSessionTransport = {
/** Holds or renews the session and returns how often to renew it. */
hold: () => Promise<{ renewAfterSeconds: number }>;
/** Releases it. A page that closes uses a keepalive request. */
release: () => Promise<void>;
};
export type WorkSessionOptions = {
transport: WorkSessionTransport;
schedule: (callback: () => void, delayMs: number) => unknown;
cancel: (handle: unknown) => void;
onStatus: (status: WorkSessionStatus) => void;
};
export type WorkSession = {
/** Takes the session for this page and keeps it. Resolves `busy` when another page holds it. */
acquire: () => Promise<AcquireResult>;
/** Frees the session now, for a page that is closing or leaving the attempt. */
release: () => void;
};
const minRenewMs = 5_000;
const maxRenewMs = 60_000;
function isConflict(error: unknown): boolean {
return error instanceof ApiRequestError && error.status === 409;
}
/**
* Holds the one-page-at-a-time work session of a real attempt: the first call
* asks for it, a timer repeats the hold while this page works, and a release
* frees it when the page closes. A refusal at the start is `busy`; a refusal at a
* renewal means that another page took the session over, which is `lost`. A
* renewal that fails for any other reason is tried again at the next tick, so a
* short network gap does not end the work.
*/
export function createWorkSession(options: WorkSessionOptions): WorkSession {
let status: WorkSessionStatus = "idle";
let timer: unknown = null;
let generation = 0;
function setStatus(next: WorkSessionStatus): void {
if (status === next) return;
status = next;
options.onStatus(next);
}
function stopTimer(): void {
if (timer !== null) options.cancel(timer);
timer = null;
}
function renewDelay(renewAfterSeconds: number): number {
return Math.min(Math.max(renewAfterSeconds * 1000, minRenewMs), maxRenewMs);
}
function scheduleRenewal(delayMs: number, owner: number): void {
timer = options.schedule(() => void renew(owner), delayMs);
}
async function renew(owner: number): Promise<void> {
if (owner !== generation || status !== "held") return;
try {
const hold = await options.transport.hold();
if (owner !== generation) return;
scheduleRenewal(renewDelay(hold.renewAfterSeconds), owner);
} catch (error: unknown) {
if (owner !== generation) return;
if (isConflict(error)) {
stopTimer();
setStatus("lost");
return;
}
scheduleRenewal(minRenewMs, owner);
}
}
return {
async acquire(): Promise<AcquireResult> {
generation += 1;
const owner = generation;
stopTimer();
try {
const hold = await options.transport.hold();
if (owner !== generation) return "error";
setStatus("held");
scheduleRenewal(renewDelay(hold.renewAfterSeconds), owner);
return "held";
} catch (error: unknown) {
if (owner !== generation) return "error";
if (isConflict(error)) {
setStatus("busy");
return "busy";
}
setStatus("idle");
return "error";
}
},
release(): void {
generation += 1;
stopTimer();
if (status === "held") {
void options.transport.release().catch(() => undefined);
}
setStatus("idle");
},
};
}
@@ -64,6 +64,7 @@ import {
useAssessmentSignals,
useSignalNoticeGate,
} from "../../../features/assessment-signals";
import { pageClientId, useWorkSession } from "../../../features/assessment-work-session";
import { WatermarkedText, WatermarkTile } from "../../../features/assessment-watermark";
import { forgetExpressStart } from "../model/express-start";
import { AttemptFocusBar, type AnswerSaveState } from "./attempt-focus-bar";
@@ -165,6 +166,14 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
applies: Boolean(attempt && collectsSignals && !isTerminal(attempt)),
running: workReady,
});
// One open page per real attempt: this page asks for the work session before it
// starts, keeps it while it works, and learns when another window took it over.
const workSession = useWorkSession({
attemptId,
csrfToken: actor?.csrf_token ?? "",
enabled: actorReady && collectsSignals,
});
const [openElsewhere, setOpenElsewhere] = useState(false);
const [resumeBusy, setResumeBusy] = useState(false);
const [pendingResume, setPendingResume] = useState<{ key: string; version: number } | null>(null);
const [pendingAnswer, setPendingAnswer] = useState<PendingAnswerCommand | null>(null);
@@ -230,6 +239,18 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
resultQuery.isError,
]);
// Another window took the work session over: stop here and say why.
const workSessionLost = workSession.status === "lost";
const leaveFullscreen = lockdown.leave;
useEffect(() => {
if (!workSessionLost) return;
queueMicrotask(() => {
setWorkReady(false);
setOpenElsewhere(true);
leaveFullscreen();
});
}, [workSessionLost, leaveFullscreen]);
// A finished or expired express run cannot be resumed; its start key goes.
const expressFinishedId =
attempt && attempt.kind === "demo_express" && isTerminal(attempt) ? attempt.id : null;
@@ -278,11 +299,19 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
requestInFlight.current = true;
setResumeBusy(true);
setPageError(null);
setOpenElsewhere(false);
try {
if (collectsSignals && (await workSession.acquire()) === "busy") {
// The other window keeps the attempt: nothing was started here.
setPendingResume(null);
setOpenElsewhere(true);
lockdown.leave();
return;
}
const resumedResponse = await startMyAssessmentAttemptSession(
attempt.id,
{ expected_version: command.version },
{ "Idempotency-Key": command.key },
{ "Idempotency-Key": command.key, "X-Attempt-Client": pageClientId },
{ headers: { "X-CSRF-Token": actor.csrf_token } },
);
const resumed = parseAssessmentAttemptResponse(resumedResponse);
@@ -301,6 +330,11 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
} else if (isAccessLoss(error)) {
removeAssessmentQueries(queryClient);
setAccessDenied(true);
} else if (error instanceof ApiRequestError && error.status === 409) {
// Another window took the work session between the hold and the start.
setPendingResume(null);
setOpenElsewhere(true);
lockdown.leave();
} else if (isOutcomeAmbiguous(error)) {
setPageError("Не удалось подтвердить продолжение. Повторите запрос с тем же ключом.");
} else {
@@ -358,6 +392,7 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
command,
currentAttemptId,
currentActor.csrf_token,
pageClientId,
);
if (!isCurrentAssessmentSession(queryClient, currentActor)) return;
if (outcome.kind === "retry") {
@@ -630,6 +665,18 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
</div>
) : null}
{openElsewhere && !terminal ? (
<div role="alert">
<Notice tone="danger" title="Попытка открыта в другом окне">
<p className={attemptStyles["notice-text"]}>
Работать над попыткой можно только в одном окне. Закройте ее в другом окне или
вкладке и нажмите «Начать или продолжить» здесь. Если то окно уже закрыто или
браузер завершился, подождите до двух минут и повторите.
</p>
</Notice>
</div>
) : null}
{!workReady && !terminal ? (
<Card tone="raised" className={attemptStyles.resume}>
<p>
@@ -36,6 +36,7 @@ import type {
AssessmentSignalNotice,
AssessmentSignalReceipt,
AssessmentUncertainty,
AssessmentWorkSession,
BasicScore,
ChoiceItemContent,
ConfigurationItemContent,
@@ -150,6 +151,8 @@ export const getStartMyAssessmentAttemptSessionResponseMock = (): AssessmentAtte
export const getRecordMyAssessmentAttemptSignalsResponseMock = (overrideResponse: Partial<Extract<AssessmentSignalReceipt, object>> = {}): AssessmentSignalReceipt => ({status: faker.helpers.arrayElement(['accepted','saturated'] as const), accepted_events: faker.number.int({min: 0, max: 50}), received_at: faker.date.past().toISOString().slice(0, 19) + 'Z', ...overrideResponse})
export const getHoldMyAssessmentWorkSessionResponseMock = (overrideResponse: Partial<Extract<AssessmentWorkSession, object>> = {}): AssessmentWorkSession => ({held_until: faker.date.past().toISOString().slice(0, 19) + 'Z', renew_after_seconds: faker.number.int({min: 1, max: 3600}), ...overrideResponse})
export const getSubmitMyAssessmentAnswerResponseAssessmentSessionsMock = (overrideResponse: Partial<AssessmentSessions> = {}): AssessmentSessions => ({...{used: faker.number.int({min: 1, max: 10}), max: faker.number.int({min: 1, max: 10}), idle_timeout_seconds: faker.number.int({min: 60, max: 86400})}, ...overrideResponse});
export const getSubmitMyAssessmentAnswerResponseChoiceItemContentMock = (overrideResponse: Partial<ChoiceItemContent> = {}): ChoiceItemContent => ({...{format: faker.helpers.arrayElement(['choice'] as const), options: Array.from({ length: faker.number.int({min: 2, max: 10}) }, (_, i) => i + 1).map(() => ({id: fakeFromPattern("^[A-Za-z0-9_-]+$", {minLength: 1, maxLength: 32}), text: faker.string.alpha({length: {min: 1, max: 2000}})})), multiple: faker.datatype.boolean()}, ...overrideResponse});
@@ -315,6 +318,28 @@ export const getRecordMyAssessmentAttemptSignalsMockHandler = (overrideResponse?
}, options)
}
export const getHoldMyAssessmentWorkSessionMockHandler = (overrideResponse?: AssessmentWorkSession | ((info: Parameters<Parameters<typeof http.put>[1]>[0]) => Promise<AssessmentWorkSession> | AssessmentWorkSession), options?: RequestHandlerOptions) => {
return http.put('*/api/v1/me/assessment-attempts/:attemptId/work-session', async (info: Parameters<Parameters<typeof http.put>[1]>[0]) => {
return HttpResponse.json(overrideResponse !== undefined
? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse)
: getHoldMyAssessmentWorkSessionResponseMock(),
{ status: 200
})
}, options)
}
export const getReleaseMyAssessmentWorkSessionMockHandler = (overrideResponse?: void | ((info: Parameters<Parameters<typeof http.delete>[1]>[0]) => Promise<void> | void), options?: RequestHandlerOptions) => {
return http.delete('*/api/v1/me/assessment-attempts/:attemptId/work-session', async (info: Parameters<Parameters<typeof http.delete>[1]>[0]) => {
if (typeof overrideResponse === 'function') {await overrideResponse(info); }
return new HttpResponse(null,
{ status: 204
})
}, options)
}
export const getSubmitMyAssessmentAnswerMockHandler = (overrideResponse?: AssessmentAttempt | ((info: Parameters<Parameters<typeof http.post>[1]>[0]) => Promise<AssessmentAttempt> | AssessmentAttempt), options?: RequestHandlerOptions) => {
return http.post('*/api/v1/me/assessment-attempts/:attemptId/answers', async (info: Parameters<Parameters<typeof http.post>[1]>[0]) => {
@@ -359,6 +384,8 @@ export const getAssessmentMock = () => [
getGetMyAssessmentAttemptMockHandler(),
getStartMyAssessmentAttemptSessionMockHandler(),
getRecordMyAssessmentAttemptSignalsMockHandler(),
getHoldMyAssessmentWorkSessionMockHandler(),
getReleaseMyAssessmentWorkSessionMockHandler(),
getSubmitMyAssessmentAnswerMockHandler(),
getFinalizeMyAssessmentAttemptMockHandler(),
getGetMyAssessmentResultMockHandler()
@@ -37,11 +37,14 @@ import type {
AssessmentSignalNotice,
AssessmentSignalNoticeAcknowledgement,
AssessmentSignalReceipt,
AssessmentWorkSession,
CreateMyAssessmentAttemptHeaders,
FinalizeMyAssessmentAttemptHeaders,
HoldMyAssessmentWorkSessionHeaders,
ListMyAssessmentResultsParams,
Problem,
RecordMyAssessmentAttemptSignalsHeaders,
ReleaseMyAssessmentWorkSessionHeaders,
StartMyAssessmentAttemptSessionHeaders,
SubmitMyAssessmentAnswerHeaders
} from '../../schemas';
@@ -700,6 +703,8 @@ export const getStartMyAssessmentAttemptSessionUrl = (attemptId: string,) => {
*
* If the attempt deadline or session budget has passed, this command commits the due terminal transition and returns the resulting attempt. A pending practice submitted before the limit is graded first. `GetMyAssessmentAttempt` and `GetMyAssessmentResult` remain read-only: they never start a session or commit a due transition. A background transition may persist a due outcome independently; after that, this command returns the stored terminal attempt without changing it.
*
* One page at a time. While another page holds the work session of this attempt (HoldMyAssessmentWorkSession), a request from a different `X-Attempt-Client`, or from none, answers 409 `state_conflict` and changes nothing; the client tells the candidate that the attempt is open in another window. That refusal is not stored under the Idempotency-Key, because it lasts only until the other page closes or stops renewing. A real attempt that nobody holds is not refused.
*
* The attempt must belong to the candidate of the session. An attempt of another candidate answers 404 not_found, the same as an unknown identifier. An employer account answers 403 forbidden; no operation gives an employer answers, qualification evidence, or attempt history.
* @summary Start or resume a work session for the current candidate's attempt.
*/
@@ -875,6 +880,194 @@ export const useRecordMyAssessmentAttemptSignals = <TError = ErrorType<Problem>,
> => {
return useMutation(getRecordMyAssessmentAttemptSignalsMutationOptions(options), queryClient);
}
export const getHoldMyAssessmentWorkSessionUrl = (attemptId: string,) => {
return `/api/v1/me/assessment-attempts/${attemptId}/work-session`
}
/**
* Requires a candidate session, its CSRF token in X-CSRF-Token, an allowed Origin, and the `X-Attempt-Client` header of the page. A real attempt (`root` or `corrective`) allows one open page at a time. The page that works on the attempt calls this operation when the candidate starts or resumes work and then repeats it every `renew_after_seconds`; each call holds the work session until `held_until`.
*
* - If nobody holds the work session, the previous holder released it, or its hold expired, the page becomes the holder and the answer is 200.
* - If the same page holds it, the hold is renewed and the answer is 200.
* - If another page holds it, the answer is 409 `state_conflict` and nothing changes: the second page is refused until the first one releases the session (ReleaseMyAssessmentWorkSession) or stops renewing and its hold expires. The client tells the candidate that the attempt is open in another window and does not show the task.
*
* The same 409 answers a terminal or expired attempt and a `demo_express` attempt, which has no protected work session. The hold is a one-page-at-a-time rule, not a lock on the candidate: a candidate who closes a page, reloads, or opens the attempt on another device can continue when the hold is released or has expired (at most two minutes after the last renewal). It is not a security boundary: a client that never calls this operation is refused only while another page holds the session. The server stores one-way keyed digests of the page identifier and of the User-Agent, bound to the attempt; it never stores or returns either value. A change of the User-Agent digest during an attempt is a weak server signal for a manual review, never an automatic decision.
*
* Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden), the attempt (404 not_found for an unknown attempt or one of another candidate), then the hold (409 state_conflict).
* @summary Hold the single active work session of a real assessment attempt for this page.
*/
export const holdMyAssessmentWorkSession = async (attemptId: string,
headers: HoldMyAssessmentWorkSessionHeaders, options?: Parameters<typeof apiRequest>[1]): Promise<AssessmentWorkSession> => {
const getHeaders = (h?: NonNullable<RequestInit['headers']>): Record<string, string | readonly string[]> => {
if (!h) return {};
if (h instanceof Headers) return Object.fromEntries(h.entries());
if (Symbol.iterator in h) {
return Object.fromEntries(
Array.from(h as Iterable<Iterable<string>>, (entry) => Array.from(entry) as [string, string]),
);
}
const headers: Record<string, string | readonly string[]> = {};
for (const [name, value] of Object.entries<string | readonly string[] | undefined>(h)) {
if (value !== undefined) headers[name] = value;
}
return headers;
};
return apiRequest<AssessmentWorkSession>(getHoldMyAssessmentWorkSessionUrl(attemptId),
{
...options,
method: 'PUT',
headers: { ...headers, ...getHeaders(options?.headers) }
}
);}
export const getHoldMyAssessmentWorkSessionMutationKey = () => ['holdMyAssessmentWorkSession'] as const;
export const getHoldMyAssessmentWorkSessionMutationOptions = <TError = ErrorType<Problem>,
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof holdMyAssessmentWorkSession>>, TError,HoldMyAssessmentWorkSessionMutationVariables, TContext>, request?: SecondParameter<typeof apiRequest>}
): UseMutationOptions<Awaited<ReturnType<typeof holdMyAssessmentWorkSession>>, TError,HoldMyAssessmentWorkSessionMutationVariables, TContext> => {
const mutationKey = getHoldMyAssessmentWorkSessionMutationKey();
const {mutation: mutationOptions, request: requestOptions} = options ?
options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ?
options
: {...options, mutation: {...options.mutation, mutationKey}}
: {mutation: { mutationKey, }, request: undefined};
const mutationFn: MutationFunction<Awaited<ReturnType<typeof holdMyAssessmentWorkSession>>, HoldMyAssessmentWorkSessionMutationVariables> = (props) => {
const {attemptId,headers} = props ?? {};
return holdMyAssessmentWorkSession(attemptId,headers,requestOptions)
}
return { mutationFn, ...mutationOptions }}
export type HoldMyAssessmentWorkSessionMutationResult = NonNullable<Awaited<ReturnType<typeof holdMyAssessmentWorkSession>>>
export type HoldMyAssessmentWorkSessionMutationError = ErrorType<Problem>
export type HoldMyAssessmentWorkSessionMutationVariables = {attemptId: string;headers: HoldMyAssessmentWorkSessionHeaders}
/**
* @summary Hold the single active work session of a real assessment attempt for this page.
*/
export const useHoldMyAssessmentWorkSession = <TError = ErrorType<Problem>,
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof holdMyAssessmentWorkSession>>, TError,HoldMyAssessmentWorkSessionMutationVariables, TContext>, request?: SecondParameter<typeof apiRequest>}
, queryClient?: QueryClient): UseMutationResult<
Awaited<ReturnType<typeof holdMyAssessmentWorkSession>>,
TError,
HoldMyAssessmentWorkSessionMutationVariables,
TContext
> => {
return useMutation(getHoldMyAssessmentWorkSessionMutationOptions(options), queryClient);
}
export const getReleaseMyAssessmentWorkSessionUrl = (attemptId: string,) => {
return `/api/v1/me/assessment-attempts/${attemptId}/work-session`
}
/**
* Requires a candidate session, its CSRF token in X-CSRF-Token, an allowed Origin, and the `X-Attempt-Client` header of the page. The page calls it when it closes, so that the candidate can open the attempt in another window at once instead of waiting for the hold to expire. The request is idempotent and reveals nothing: it answers 204 whether this page held the session, another page holds it (which stays held), nobody held it, or the attempt is not held at all, and a repeat after a lost response succeeds. A page that is killed without calling it loses the hold within two minutes.
*
* Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden), the attempt (404 not_found for an unknown attempt or one of another candidate), then the release (204).
* @summary Release the work session that this page holds.
*/
export const releaseMyAssessmentWorkSession = async (attemptId: string,
headers: ReleaseMyAssessmentWorkSessionHeaders, options?: Parameters<typeof apiRequest>[1]): Promise<void> => {
const getHeaders = (h?: NonNullable<RequestInit['headers']>): Record<string, string | readonly string[]> => {
if (!h) return {};
if (h instanceof Headers) return Object.fromEntries(h.entries());
if (Symbol.iterator in h) {
return Object.fromEntries(
Array.from(h as Iterable<Iterable<string>>, (entry) => Array.from(entry) as [string, string]),
);
}
const headers: Record<string, string | readonly string[]> = {};
for (const [name, value] of Object.entries<string | readonly string[] | undefined>(h)) {
if (value !== undefined) headers[name] = value;
}
return headers;
};
return apiRequest<void>(getReleaseMyAssessmentWorkSessionUrl(attemptId),
{
...options,
method: 'DELETE',
headers: { ...headers, ...getHeaders(options?.headers) }
}
);}
export const getReleaseMyAssessmentWorkSessionMutationKey = () => ['releaseMyAssessmentWorkSession'] as const;
export const getReleaseMyAssessmentWorkSessionMutationOptions = <TError = ErrorType<Problem>,
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof releaseMyAssessmentWorkSession>>, TError,ReleaseMyAssessmentWorkSessionMutationVariables, TContext>, request?: SecondParameter<typeof apiRequest>}
): UseMutationOptions<Awaited<ReturnType<typeof releaseMyAssessmentWorkSession>>, TError,ReleaseMyAssessmentWorkSessionMutationVariables, TContext> => {
const mutationKey = getReleaseMyAssessmentWorkSessionMutationKey();
const {mutation: mutationOptions, request: requestOptions} = options ?
options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ?
options
: {...options, mutation: {...options.mutation, mutationKey}}
: {mutation: { mutationKey, }, request: undefined};
const mutationFn: MutationFunction<Awaited<ReturnType<typeof releaseMyAssessmentWorkSession>>, ReleaseMyAssessmentWorkSessionMutationVariables> = (props) => {
const {attemptId,headers} = props ?? {};
return releaseMyAssessmentWorkSession(attemptId,headers,requestOptions)
}
return { mutationFn, ...mutationOptions }}
export type ReleaseMyAssessmentWorkSessionMutationResult = NonNullable<Awaited<ReturnType<typeof releaseMyAssessmentWorkSession>>>
export type ReleaseMyAssessmentWorkSessionMutationError = ErrorType<Problem>
export type ReleaseMyAssessmentWorkSessionMutationVariables = {attemptId: string;headers: ReleaseMyAssessmentWorkSessionHeaders}
/**
* @summary Release the work session that this page holds.
*/
export const useReleaseMyAssessmentWorkSession = <TError = ErrorType<Problem>,
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof releaseMyAssessmentWorkSession>>, TError,ReleaseMyAssessmentWorkSessionMutationVariables, TContext>, request?: SecondParameter<typeof apiRequest>}
, queryClient?: QueryClient): UseMutationResult<
Awaited<ReturnType<typeof releaseMyAssessmentWorkSession>>,
TError,
ReleaseMyAssessmentWorkSessionMutationVariables,
TContext
> => {
return useMutation(getReleaseMyAssessmentWorkSessionMutationOptions(options), queryClient);
}
export const getSubmitMyAssessmentAnswerUrl = (attemptId: string,) => {
@@ -892,6 +1085,8 @@ export const useRecordMyAssessmentAttemptSignals = <TError = ErrorType<Problem>,
*
* Practice: an answer with format `practice` submits the solution of the main or the additional practice. It is stored, and the sandbox runs it asynchronously against the hidden check groups; the response shows the practice `pending`, and the client polls GetMyAssessmentAttempt for the verdict. Only the score 0-3 and the pass state of each group are shown, never the checks, error output, or seeds. Every outcome caused by the solution, such as a compilation error, a crash, or a time or memory limit, is a `finished` verdict. A `failed` verdict means only that the sandbox infrastructure could not run it; it consumes nothing. After `finished` the practice accepts no other solution, so hidden group results cannot be used to tune it. Debug runs of the candidate's own tests and the public examples are unlimited apart from the sandbox rate limit and never show hidden group results; they are planned as a separate operation.
*
* One page at a time. While another page holds the work session of this attempt (HoldMyAssessmentWorkSession), a request from a different `X-Attempt-Client`, or from none, answers 409 `state_conflict` and stores nothing, so a second window cannot answer. That refusal is not stored under the Idempotency-Key and is checked before the stored answer is replayed.
*
* Repeats and conflicts, per item:
* - A retry with the same Idempotency-Key and body within 24 hours replays the stored response.
* - Sending the answer already stored for the item again, even with a new key or an older `expected_version`, stores nothing, keeps the version, and answers 200 with the current attempt. Each answer format defines equality: sets for `option_ids` and `line_numbers`, the exact sequence for `element_ids`, numeric equality for `number`, identical text without normalization for `text` and `config`, and the same language with identical source for a practice.
@@ -0,0 +1,16 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const AssessmentCaptureSignal = zod.object({
"kind": zod.enum(['screenshot_key', 'devtools_open']),
"item_instance_id": zod.uuid().describe('Identifier of an item instance in one attempt. It identifies the fixed variant served to this candidate and reveals neither the task family, its version, nor the variant seed.'),
"occurred_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.')
}).describe('A hint that the screen may be captured or inspected. `screenshot_key` is a key or key combination that the browser saw and that usually takes a screenshot (PrintScreen, Cmd+Shift+3, 4, or 5 on macOS, Win+Shift+S); `devtools_open` is the result of a heuristic that guesses that the developer tools are open (a docked panel changes the window size, or the console reads an object). Both are weak: a browser does not see every screenshot, an operating system can take one without a key the page sees, a phone photo is invisible to the page, and the heuristic gives false positives. They lead to attention in a manual review at most, never to a score change, and they carry no measurement.')
export type AssessmentCaptureSignal = zod.input<typeof AssessmentCaptureSignal>;
export type AssessmentCaptureSignalOutput = zod.output<typeof AssessmentCaptureSignal>;
@@ -29,7 +29,11 @@ export const AssessmentSignalBatch = zod.object({
"kind": zod.enum(['fullscreen_exit']),
"item_instance_id": zod.uuid().describe('Identifier of an item instance in one attempt. It identifies the fixed variant served to this candidate and reveals neither the task family, its version, nor the variant seed.'),
"occurred_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.')
})]).describe('One client-reported event bound to an item instance of the attempt. The timestamp is untrusted input and is used only as event metadata; server receipt time is authoritative for limits and retention.')).min(1).max(assessmentSignalBatchEventsMax)
}),zod.object({
"kind": zod.enum(['screenshot_key', 'devtools_open']),
"item_instance_id": zod.uuid().describe('Identifier of an item instance in one attempt. It identifies the fixed variant served to this candidate and reveals neither the task family, its version, nor the variant seed.'),
"occurred_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.')
}).describe('A hint that the screen may be captured or inspected. `screenshot_key` is a key or key combination that the browser saw and that usually takes a screenshot (PrintScreen, Cmd+Shift+3, 4, or 5 on macOS, Win+Shift+S); `devtools_open` is the result of a heuristic that guesses that the developer tools are open (a docked panel changes the window size, or the console reads an object). Both are weak: a browser does not see every screenshot, an operating system can take one without a key the page sees, a phone photo is invisible to the page, and the heuristic gives false positives. They lead to attention in a manual review at most, never to a score change, and they carry no measurement.')]).describe('One client-reported event bound to an item instance of the attempt. The timestamp is untrusted input and is used only as event metadata; server receipt time is authoritative for limits and retention.')).min(1).max(assessmentSignalBatchEventsMax)
}).describe('A bounded batch of client event metadata. The raw request body is limited to 32 KiB before decoding and the batch contains at most 50 events.')
export type AssessmentSignalBatch = zod.input<typeof AssessmentSignalBatch>;
@@ -26,7 +26,11 @@ export const AssessmentSignalEvent = zod.union([zod.object({
"kind": zod.enum(['fullscreen_exit']),
"item_instance_id": zod.uuid().describe('Identifier of an item instance in one attempt. It identifies the fixed variant served to this candidate and reveals neither the task family, its version, nor the variant seed.'),
"occurred_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.')
})]).describe('One client-reported event bound to an item instance of the attempt. The timestamp is untrusted input and is used only as event metadata; server receipt time is authoritative for limits and retention.')
}),zod.object({
"kind": zod.enum(['screenshot_key', 'devtools_open']),
"item_instance_id": zod.uuid().describe('Identifier of an item instance in one attempt. It identifies the fixed variant served to this candidate and reveals neither the task family, its version, nor the variant seed.'),
"occurred_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.')
}).describe('A hint that the screen may be captured or inspected. `screenshot_key` is a key or key combination that the browser saw and that usually takes a screenshot (PrintScreen, Cmd+Shift+3, 4, or 5 on macOS, Win+Shift+S); `devtools_open` is the result of a heuristic that guesses that the developer tools are open (a docked panel changes the window size, or the console reads an object). Both are weak: a browser does not see every screenshot, an operating system can take one without a key the page sees, a phone photo is invisible to the page, and the heuristic gives false positives. They lead to attention in a manual review at most, never to a score change, and they carry no measurement.')]).describe('One client-reported event bound to an item instance of the attempt. The timestamp is untrusted input and is used only as event metadata; server receipt time is authoritative for limits and retention.')
export type AssessmentSignalEvent = zod.input<typeof AssessmentSignalEvent>;
export type AssessmentSignalEventOutput = zod.output<typeof AssessmentSignalEvent>;
@@ -0,0 +1,18 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const assessmentWorkSessionRenewAfterSecondsMax = 3600;
export const AssessmentWorkSession = zod.object({
"held_until": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),
"renew_after_seconds": zod.int().min(1).max(assessmentWorkSessionRenewAfterSecondsMax).describe('How often the page repeats the hold. It is well below the hold time, so a page whose timer is slowed down in the background still renews before its hold expires.')
}).describe('The work session of a real attempt that the calling page holds. It is a one-page-at-a-time rule for the attempt, not a score or a signal, and it changes no result.')
export type AssessmentWorkSession = zod.input<typeof AssessmentWorkSession>;
export type AssessmentWorkSessionOutput = zod.output<typeof AssessmentWorkSession>;
@@ -0,0 +1,20 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const holdMyAssessmentWorkSessionHeadersXAttemptClientMin = 16;
export const holdMyAssessmentWorkSessionHeadersXAttemptClientMax = 64;
export const holdMyAssessmentWorkSessionHeadersXAttemptClientRegExp = new RegExp('^[A-Za-z0-9_-]+$');
export const HoldMyAssessmentWorkSessionHeaders = zod.object({
"X-Attempt-Client": zod.string().min(holdMyAssessmentWorkSessionHeadersXAttemptClientMin).max(holdMyAssessmentWorkSessionHeadersXAttemptClientMax).regex(holdMyAssessmentWorkSessionHeadersXAttemptClientRegExp)
})
export type HoldMyAssessmentWorkSessionHeaders = zod.input<typeof HoldMyAssessmentWorkSessionHeaders>;
export type HoldMyAssessmentWorkSessionHeadersOutput = zod.output<typeof HoldMyAssessmentWorkSessionHeaders>;
@@ -16,6 +16,7 @@ export * from './assessmentAttemptSessionStart.zod';
export * from './assessmentAttemptState.zod';
export * from './assessmentAttemptVersion.zod';
export * from './assessmentAvailability.zod';
export * from './assessmentCaptureSignal.zod';
export * from './assessmentCategoryDecisionView.zod';
export * from './assessmentClipboardSignal.zod';
export * from './assessmentCorrectiveAttempt.zod';
@@ -67,6 +68,7 @@ export * from './assessmentUncertainty.zod';
export * from './assessmentVersionLabel.zod';
export * from './assessmentVersions.zod';
export * from './assessmentWatermark.zod';
export * from './assessmentWorkSession.zod';
export * from './basicScore.zod';
export * from './calibrationStatus.zod';
export * from './choiceAnswer.zod';
@@ -80,6 +82,7 @@ export * from './finalizeMyAssessmentAttemptBody.zod';
export * from './finalizeMyAssessmentAttemptHeaders.zod';
export * from './findErrorAnswer.zod';
export * from './findErrorItemContent.zod';
export * from './holdMyAssessmentWorkSessionHeaders.zod';
export * from './itemContent.zod';
export * from './listMyAssessmentResultsParams.zod';
export * from './numberAnswer.zod';
@@ -96,6 +99,7 @@ export * from './practiceStatus.zod';
export * from './practiceVerdict.zod';
export * from './recordMyAssessmentAttemptSignalsBody.zod';
export * from './recordMyAssessmentAttemptSignalsHeaders.zod';
export * from './releaseMyAssessmentWorkSessionHeaders.zod';
export * from './startMyAssessmentAttemptSessionBody.zod';
export * from './startMyAssessmentAttemptSessionHeaders.zod';
export * from './stringAnswer.zod';
@@ -29,7 +29,11 @@ export const RecordMyAssessmentAttemptSignalsBody = zod.object({
"kind": zod.enum(['fullscreen_exit']),
"item_instance_id": zod.uuid().describe('Identifier of an item instance in one attempt. It identifies the fixed variant served to this candidate and reveals neither the task family, its version, nor the variant seed.'),
"occurred_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.')
})]).describe('One client-reported event bound to an item instance of the attempt. The timestamp is untrusted input and is used only as event metadata; server receipt time is authoritative for limits and retention.')).min(1).max(recordMyAssessmentAttemptSignalsBodyEventsMax)
}),zod.object({
"kind": zod.enum(['screenshot_key', 'devtools_open']),
"item_instance_id": zod.uuid().describe('Identifier of an item instance in one attempt. It identifies the fixed variant served to this candidate and reveals neither the task family, its version, nor the variant seed.'),
"occurred_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.')
}).describe('A hint that the screen may be captured or inspected. `screenshot_key` is a key or key combination that the browser saw and that usually takes a screenshot (PrintScreen, Cmd+Shift+3, 4, or 5 on macOS, Win+Shift+S); `devtools_open` is the result of a heuristic that guesses that the developer tools are open (a docked panel changes the window size, or the console reads an object). Both are weak: a browser does not see every screenshot, an operating system can take one without a key the page sees, a phone photo is invisible to the page, and the heuristic gives false positives. They lead to attention in a manual review at most, never to a score change, and they carry no measurement.')]).describe('One client-reported event bound to an item instance of the attempt. The timestamp is untrusted input and is used only as event metadata; server receipt time is authoritative for limits and retention.')).min(1).max(recordMyAssessmentAttemptSignalsBodyEventsMax)
}).describe('A bounded batch of client event metadata. The raw request body is limited to 32 KiB before decoding and the batch contains at most 50 events.')
export type RecordMyAssessmentAttemptSignalsBody = zod.input<typeof RecordMyAssessmentAttemptSignalsBody>;
@@ -0,0 +1,20 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const releaseMyAssessmentWorkSessionHeadersXAttemptClientMin = 16;
export const releaseMyAssessmentWorkSessionHeadersXAttemptClientMax = 64;
export const releaseMyAssessmentWorkSessionHeadersXAttemptClientRegExp = new RegExp('^[A-Za-z0-9_-]+$');
export const ReleaseMyAssessmentWorkSessionHeaders = zod.object({
"X-Attempt-Client": zod.string().min(releaseMyAssessmentWorkSessionHeadersXAttemptClientMin).max(releaseMyAssessmentWorkSessionHeadersXAttemptClientMax).regex(releaseMyAssessmentWorkSessionHeadersXAttemptClientRegExp)
})
export type ReleaseMyAssessmentWorkSessionHeaders = zod.input<typeof ReleaseMyAssessmentWorkSessionHeaders>;
export type ReleaseMyAssessmentWorkSessionHeadersOutput = zod.output<typeof ReleaseMyAssessmentWorkSessionHeaders>;
@@ -10,9 +10,15 @@ export const startMyAssessmentAttemptSessionHeadersIdempotencyKeyMax = 255;
export const startMyAssessmentAttemptSessionHeadersIdempotencyKeyRegExp = new RegExp('^[A-Za-z0-9._:-]+$');
export const startMyAssessmentAttemptSessionHeadersXAttemptClientMin = 16;
export const startMyAssessmentAttemptSessionHeadersXAttemptClientMax = 64;
export const startMyAssessmentAttemptSessionHeadersXAttemptClientRegExp = new RegExp('^[A-Za-z0-9_-]+$');
export const StartMyAssessmentAttemptSessionHeaders = zod.object({
"Idempotency-Key": zod.string().min(1).max(startMyAssessmentAttemptSessionHeadersIdempotencyKeyMax).regex(startMyAssessmentAttemptSessionHeadersIdempotencyKeyRegExp)
"Idempotency-Key": zod.string().min(1).max(startMyAssessmentAttemptSessionHeadersIdempotencyKeyMax).regex(startMyAssessmentAttemptSessionHeadersIdempotencyKeyRegExp),
"X-Attempt-Client": zod.string().min(startMyAssessmentAttemptSessionHeadersXAttemptClientMin).max(startMyAssessmentAttemptSessionHeadersXAttemptClientMax).regex(startMyAssessmentAttemptSessionHeadersXAttemptClientRegExp).exactOptional()
})
export type StartMyAssessmentAttemptSessionHeaders = zod.input<typeof StartMyAssessmentAttemptSessionHeaders>;
@@ -10,9 +10,15 @@ export const submitMyAssessmentAnswerHeadersIdempotencyKeyMax = 255;
export const submitMyAssessmentAnswerHeadersIdempotencyKeyRegExp = new RegExp('^[A-Za-z0-9._:-]+$');
export const submitMyAssessmentAnswerHeadersXAttemptClientMin = 16;
export const submitMyAssessmentAnswerHeadersXAttemptClientMax = 64;
export const submitMyAssessmentAnswerHeadersXAttemptClientRegExp = new RegExp('^[A-Za-z0-9_-]+$');
export const SubmitMyAssessmentAnswerHeaders = zod.object({
"Idempotency-Key": zod.string().min(1).max(submitMyAssessmentAnswerHeadersIdempotencyKeyMax).regex(submitMyAssessmentAnswerHeadersIdempotencyKeyRegExp)
"Idempotency-Key": zod.string().min(1).max(submitMyAssessmentAnswerHeadersIdempotencyKeyMax).regex(submitMyAssessmentAnswerHeadersIdempotencyKeyRegExp),
"X-Attempt-Client": zod.string().min(submitMyAssessmentAnswerHeadersXAttemptClientMin).max(submitMyAssessmentAnswerHeadersXAttemptClientMax).regex(submitMyAssessmentAnswerHeadersXAttemptClientRegExp).exactOptional()
})
export type SubmitMyAssessmentAnswerHeaders = zod.input<typeof SubmitMyAssessmentAnswerHeaders>;