Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

feat(web): validate turn protocol boundaries

Bingxi Zhao (Frank)8bf74b9748aa
diff --git a/web/contracts/parse/turn-command.ts b/web/contracts/parse/turn-command.ts
new file mode 100644
index 000000000..f99a5368a
--- /dev/null
+++ b/web/contracts/parse/turn-command.ts
@@ -0,0 +1,139 @@
+import type {
+ CancelTurnCommand,
+ CheckActiveTurnCommand,
+ PingCommand,
+ RegenerateCommand,
+ ResumeTurnCommand,
+ StartTurnCommand,
+ SubmitUserReplyCommand,
+ SubscribeSessionCommand,
+ SubscribeTurnCommand,
+ UnsubscribeCommand,
+ UserAnswer,
+ UserInputCommand,
+} from "@/contracts/generated/turn-protocol";
+
+const PROTOCOL_VERSION = "2.0" as const;
+
+function id(value: string, field: string): string {
+ const normalized = value.trim();
+ if (!normalized) throw new TypeError(`${field} must not be empty`);
+ return normalized;
+}
+
+function sequence(value: number): number {
+ if (!Number.isInteger(value) || value < 0) {
+ throw new TypeError("after_seq must be a non-negative integer");
+ }
+ return value;
+}
+
+export function buildStartTurn(
+ input: Omit<StartTurnCommand, "type" | "protocol_version">,
+): StartTurnCommand {
+ return { ...input, type: "start_turn", protocol_version: PROTOCOL_VERSION };
+}
+
+export function buildSubscribeTurn(input: {
+ turnId: string;
+ afterSeq?: number;
+}): SubscribeTurnCommand {
+ return {
+ type: "subscribe_turn",
+ turn_id: id(input.turnId, "turn_id"),
+ after_seq: sequence(input.afterSeq ?? 0),
+ protocol_version: PROTOCOL_VERSION,
+ };
+}
+
+export function buildSubscribeSession(input: {
+ sessionId: string;
+ afterSeq?: number;
+}): SubscribeSessionCommand {
+ return {
+ type: "subscribe_session",
+ session_id: id(input.sessionId, "session_id"),
+ after_seq: sequence(input.afterSeq ?? 0),
+ protocol_version: PROTOCOL_VERSION,
+ };
+}
+
+export function buildResumeTurn(input: { turnId: string; afterSeq?: number }): ResumeTurnCommand {
+ return {
+ type: "resume_from",
+ turn_id: id(input.turnId, "turn_id"),
+ seq: sequence(input.afterSeq ?? 0),
+ protocol_version: PROTOCOL_VERSION,
+ };
+}
+
+export function buildCancelTurn(turnId: string): CancelTurnCommand {
+ return {
+ type: "cancel_turn",
+ turn_id: id(turnId, "turn_id"),
+ protocol_version: PROTOCOL_VERSION,
+ };
+}
+
+export function buildRegenerate(input: {
+ sessionId: string;
+ overrides?: Record<string, unknown>;
+}): RegenerateCommand {
+ return {
+ type: "regenerate",
+ session_id: id(input.sessionId, "session_id"),
+ overrides: input.overrides ?? {},
+ protocol_version: PROTOCOL_VERSION,
+ };
+}
+
+export function buildSubmitUserReply(input: {
+ turnId: string;
+ text?: string;
+ answers?: UserAnswer[];
+}): SubmitUserReplyCommand {
+ if (input.text === undefined && !input.answers?.length) {
+ throw new TypeError("submit_user_reply requires text or answers");
+ }
+ return {
+ type: "submit_user_reply",
+ turn_id: id(input.turnId, "turn_id"),
+ text: input.text,
+ answers: input.answers,
+ protocol_version: PROTOCOL_VERSION,
+ };
+}
+
+export function buildUserInput(input: { turnId: string; content: string }): UserInputCommand {
+ return {
+ type: "user_input",
+ turn_id: id(input.turnId, "turn_id"),
+ content: input.content,
+ protocol_version: PROTOCOL_VERSION,
+ };
+}
+
+export function buildCheckActiveTurn(sessionId: string): CheckActiveTurnCommand {
+ return {
+ type: "check_active_turn",
+ session_id: id(sessionId, "session_id"),
+ protocol_version: PROTOCOL_VERSION,
+ };
+}
+
+export function buildUnsubscribe(input: {
+ turnId?: string;
+ sessionId?: string;
+}): UnsubscribeCommand {
+ if (!input.turnId && !input.sessionId) throw new TypeError("unsubscribe requires a target");
+ return {
+ type: "unsubscribe",
+ turn_id: input.turnId ? id(input.turnId, "turn_id") : undefined,
+ session_id: input.sessionId ? id(input.sessionId, "session_id") : undefined,
+ protocol_version: PROTOCOL_VERSION,
+ };
+}
+
+export function buildPing(): PingCommand {
+ return { type: "ping", protocol_version: PROTOCOL_VERSION };
+}
diff --git a/web/contracts/parse/turn-event.ts b/web/contracts/parse/turn-event.ts
new file mode 100644
index 000000000..d79b34507
--- /dev/null
+++ b/web/contracts/parse/turn-event.ts
@@ -0,0 +1,153 @@
+import type {
+ ActiveTurnInfo,
+ ServerEvent,
+ StreamEvent,
+ StreamEventType,
+} from "@/contracts/generated/turn-protocol";
+
+export type ParseResult<T> =
+ | { ok: true; value: T }
+ | {
+ ok: false;
+ reason: "heartbeat" | "invalid" | "unsupported";
+ diagnostic: string;
+ };
+
+const STREAM_EVENT_TYPES = new Set<StreamEventType>([
+ "stage_start",
+ "stage_end",
+ "thinking",
+ "observation",
+ "content",
+ "tool_call",
+ "tool_result",
+ "progress",
+ "sources",
+ "result",
+ "error",
+ "session",
+ "session_meta",
+ "wait_for_input",
+ "done",
+]);
+
+function diagnostic(value: unknown, detail: string): string {
+ if (!value || typeof value !== "object") return detail;
+ const record = value as Record<string, unknown>;
+ const type = typeof record.type === "string" ? record.type.slice(0, 48) : typeof record.type;
+ const keys = Object.keys(record)
+ .filter((key) => !["content", "metadata", "token", "password", "secret"].includes(key))
+ .slice(0, 12)
+ .sort();
+ return `${detail}; type=${type}; keys=${keys.join(",")}`;
+}
+
+function parseRaw(raw: unknown): ParseResult<unknown> {
+ if (typeof raw !== "string") return { ok: true, value: raw };
+ if (!raw.trim() || raw.trim() === "heartbeat") {
+ return { ok: false, reason: "heartbeat", diagnostic: "heartbeat frame" };
+ }
+ try {
+ return { ok: true, value: JSON.parse(raw) as unknown };
+ } catch {
+ return {
+ ok: false,
+ reason: "invalid",
+ diagnostic: `invalid JSON frame; length=${raw.length}`,
+ };
+ }
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
+}
+
+function validProtocolVersion(value: unknown): boolean {
+ return value === undefined || value === "2.0";
+}
+
+export function parseTurnEvent(raw: unknown): ParseResult<ServerEvent> {
+ const decoded = parseRaw(raw);
+ if (!decoded.ok) return decoded;
+ if (!isRecord(decoded.value)) {
+ return { ok: false, reason: "invalid", diagnostic: "event is not an object" };
+ }
+
+ const event = decoded.value;
+ if (event.type === "ping" || event.type === "pong" || event.type === "heartbeat") {
+ return { ok: false, reason: "heartbeat", diagnostic: "heartbeat frame" };
+ }
+ if (typeof event.type !== "string") {
+ return { ok: false, reason: "invalid", diagnostic: diagnostic(event, "missing event type") };
+ }
+ if (!validProtocolVersion(event.protocol_version)) {
+ return {
+ ok: false,
+ reason: "unsupported",
+ diagnostic: diagnostic(event, "unsupported protocol version"),
+ };
+ }
+
+ if (event.type === "active_turn_info") {
+ const validStatus = new Set([
+ "none",
+ "queued",
+ "running",
+ "waiting_input",
+ "completed",
+ "failed",
+ "cancelled",
+ ]).has(String(event.status));
+ if (!validStatus || (event.turn_id !== undefined && typeof event.turn_id !== "string")) {
+ return {
+ ok: false,
+ reason: "invalid",
+ diagnostic: diagnostic(event, "invalid active-turn envelope"),
+ };
+ }
+ return { ok: true, value: event as unknown as ActiveTurnInfo };
+ }
+
+ if (!STREAM_EVENT_TYPES.has(event.type as StreamEventType)) {
+ return {
+ ok: false,
+ reason: "unsupported",
+ diagnostic: diagnostic(event, "unknown event type"),
+ };
+ }
+
+ const valid =
+ typeof event.turn_id === "string" &&
+ event.turn_id.trim().length > 0 &&
+ Number.isInteger(event.seq) &&
+ Number(event.seq) >= 0 &&
+ typeof event.timestamp === "number" &&
+ Number.isFinite(event.timestamp) &&
+ (event.content === undefined || typeof event.content === "string") &&
+ (event.source === undefined || typeof event.source === "string") &&
+ (event.stage === undefined || typeof event.stage === "string") &&
+ (event.session_id === undefined || typeof event.session_id === "string") &&
+ (event.metadata === undefined || isRecord(event.metadata));
+
+ if (!valid) {
+ return {
+ ok: false,
+ reason: "invalid",
+ diagnostic: diagnostic(event, "invalid stream envelope"),
+ };
+ }
+
+ return {
+ ok: true,
+ value: {
+ ...event,
+ content: event.content ?? "",
+ metadata: event.metadata ?? {},
+ protocol_version: "2.0",
+ seq: event.seq,
+ session_id: event.session_id ?? "",
+ source: event.source ?? "",
+ stage: event.stage ?? "",
+ } as StreamEvent,
+ };
+}
diff --git a/web/tests/turn-protocol-parser.test.ts b/web/tests/turn-protocol-parser.test.ts
new file mode 100644
index 000000000..65ed07793
--- /dev/null
+++ b/web/tests/turn-protocol-parser.test.ts
@@ -0,0 +1,118 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import {
+ buildCancelTurn,
+ buildResumeTurn,
+ buildSubmitUserReply,
+ buildSubscribeTurn,
+} from "../contracts/parse/turn-command";
+import { parseTurnEvent } from "../contracts/parse/turn-event";
+
+const eventTypes = [
+ "stage_start",
+ "stage_end",
+ "thinking",
+ "observation",
+ "content",
+ "tool_call",
+ "tool_result",
+ "progress",
+ "sources",
+ "result",
+ "error",
+ "session",
+ "session_meta",
+ "wait_for_input",
+ "done",
+] as const;
+
+test("every v2 stream event kind crosses the validated boundary", () => {
+ for (const [index, type] of eventTypes.entries()) {
+ const parsed = parseTurnEvent(
+ JSON.stringify({
+ type,
+ turn_id: "turn-1",
+ seq: index,
+ timestamp: 100 + index,
+ content: "safe",
+ metadata: { future_field: true },
+ }),
+ );
+ assert.equal(parsed.ok, true, type);
+ if (parsed.ok) assert.equal(parsed.value.type, type);
+ }
+});
+
+test("active turn information is validated and heartbeats are quarantined", () => {
+ const active = parseTurnEvent({
+ type: "active_turn_info",
+ turn_id: "turn-1",
+ status: "waiting_input",
+ protocol_version: "2.0",
+ });
+ assert.equal(active.ok, true);
+
+ for (const heartbeat of ["", "heartbeat", '{"type":"ping"}', '{"type":"pong"}']) {
+ const parsed = parseTurnEvent(heartbeat);
+ assert.deepEqual(parsed.ok ? null : parsed.reason, "heartbeat");
+ }
+});
+
+test("invalid, incomplete, future, and version-mismatched frames are rejected", () => {
+ const missing = parseTurnEvent({ type: "content", turn_id: "turn-1", timestamp: 1 });
+ assert.deepEqual(missing.ok ? null : missing.reason, "invalid");
+
+ const badSeq = parseTurnEvent({
+ type: "content",
+ turn_id: "turn-1",
+ seq: -1,
+ timestamp: 1,
+ });
+ assert.deepEqual(badSeq.ok ? null : badSeq.reason, "invalid");
+
+ const future = parseTurnEvent({
+ type: "telepathy",
+ turn_id: "turn-1",
+ seq: 1,
+ timestamp: 1,
+ });
+ assert.deepEqual(future.ok ? null : future.reason, "unsupported");
+
+ const version = parseTurnEvent({
+ type: "content",
+ protocol_version: "3.0",
+ turn_id: "turn-1",
+ seq: 1,
+ timestamp: 1,
+ });
+ assert.deepEqual(version.ok ? null : version.reason, "unsupported");
+});
+
+test("protocol diagnostics never echo content, metadata, or credentials", () => {
+ const parsed = parseTurnEvent({
+ type: "future_event",
+ content: "private prompt",
+ metadata: { token: "secret-token" },
+ password: "hunter2",
+ });
+ assert.equal(parsed.ok, false);
+ if (parsed.ok) return;
+ assert.doesNotMatch(parsed.diagnostic, /private prompt|secret-token|hunter2|content|metadata|password/);
+});
+
+test("command builders enforce IDs, sequence bounds, replies, and v2 versioning", () => {
+ assert.deepEqual(buildSubscribeTurn({ turnId: " turn-1 ", afterSeq: 7 }), {
+ type: "subscribe_turn",
+ turn_id: "turn-1",
+ after_seq: 7,
+ protocol_version: "2.0",
+ });
+ assert.equal(buildResumeTurn({ turnId: "turn-1", afterSeq: 9 }).seq, 9);
+ assert.equal(buildCancelTurn("turn-1").type, "cancel_turn");
+ assert.equal(buildSubmitUserReply({ turnId: "turn-1", text: "yes" }).text, "yes");
+
+ assert.throws(() => buildSubscribeTurn({ turnId: " ", afterSeq: 0 }), /turn_id/);
+ assert.throws(() => buildSubscribeTurn({ turnId: "turn-1", afterSeq: 1.5 }), /after_seq/);
+ assert.throws(() => buildSubmitUserReply({ turnId: "turn-1" }), /requires/);
+});