Skip to content
12 changes: 12 additions & 0 deletions .changeset/page-request-and-payment-refusal.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
---
"@understudy/protocol": minor
"@understudy/connector": minor
---

Add the `page-request-v1` capability for declarative same-origin JSON requests
in unattended sessions. GET uses the read path. An explicitly permitted write
uses prepare and grant. Durable command and connector records retain the HTTP
status and omit the response body.

Report `payment_refused` for blocked payment input and `security_check` when the
browser encounters a CAPTCHA or verification-code prompt.
2 changes: 1 addition & 1 deletion apps/backend/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -477,7 +477,7 @@ function v2Outcome(
case "legacy_snapshot_required":
return c.json({ error: "legacy extension requires snapshot compatibility" }, 426);
case "unsupported":
return c.json({ error: "extension lacks safe-write-v3" }, 426);
return c.json({ error: `extension lacks ${outcome.capability ?? "safe-write-v3"}` }, 426);
case "terminal_session":
return c.json({ error: "session is terminal" }, 410);
}
Expand Down
90 changes: 74 additions & 16 deletions apps/backend/src/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import {
isCommandType,
isCommandResultEvent,
isWriteCommand,
pageRequestReceipt,
resolvePageRequestUrl,
safeParseEvent,
safeParseSessionClientFrame,
utf8ByteLength,
Expand All @@ -18,6 +20,7 @@ import type {
Command,
CommandState,
Event,
PageRequestResult,
SessionClientFrame,
SessionServerFrame,
TabInfo,
Expand Down Expand Up @@ -68,6 +71,8 @@ const RECENT_DIALOGS_CAP = 50;
const PREPARE_DEADLINE_MS = 5_000;
const EXECUTION_DEADLINE_MS = 25_000;
const SYNCHRONOUS_WAIT_MS = 20_000;
const PAGE_REQUEST_BODY_TTL_MS = 60_000;
const MAX_PAGE_REQUEST_BODIES = 16;
const LegacyDialogEventSchema = z
.object({
type: z.literal("dialog"),
Expand Down Expand Up @@ -122,6 +127,7 @@ export class SessionAgent extends Agent<Env, SessionState> {
private readonly coordinator: CfSessionCoordinator;
private readonly stateWaiters = new Map<string, Set<() => void>>();
private readonly connectionWaiters = new Set<(connected: boolean) => void>();
private readonly pageRequestBodies = new Map<string, { event: PageRequestResult; expiresAt: number }>();

constructor(ctx: AgentContext, env: Env) {
super(ctx, env);
Expand Down Expand Up @@ -491,18 +497,29 @@ export class SessionAgent extends Agent<Env, SessionState> {
isCommandResultEvent(row.command_type, frame.event.type) &&
this.frameMatchesCurrentLease(frame)
) {
const event =
row.dry_run === 1 && row.is_write === 1 && frame.event.type === "action_result"
? { ...frame.event, simulated: true }
: frame.event;
this.sql`
UPDATE command_journal
SET state = 'completed', result_json = ${JSON.stringify(event)},
updated_at = ${now}
WHERE attempt_id = ${frame.attemptId} AND state = 'granted'
AND execution_deadline_at > ${now}
`;
this.notifyAttempt(frame.attemptId);
if (
row.command_type === "page_request" && row.is_write === 1 && row.dry_run === 0 &&
frame.event.type === "action_result" && frame.event.reason === "outcome_unknown"
) {
this.terminalizeAttempt(row, "unknown");
} else {
const event =
row.dry_run === 1 && row.is_write === 1 && frame.event.type === "action_result"
? { ...frame.event, simulated: true }
: frame.event;
const recorded = event.type === "page_request_result" ? pageRequestReceipt(event) : event;
this.sql`
UPDATE command_journal
SET state = 'completed', result_json = ${JSON.stringify(recorded)},
updated_at = ${now}
WHERE attempt_id = ${frame.attemptId} AND state = 'granted'
AND execution_deadline_at > ${now}
`;
if (event.type === "page_request_result" && event.body !== undefined) {
this.rememberPageRequestBody(row.attempt_id, event);
}
this.notifyAttempt(frame.attemptId);
}
} else if (
row?.state === "granted" &&
row.execution_deadline_at !== null &&
Expand Down Expand Up @@ -617,6 +634,9 @@ export class SessionAgent extends Agent<Env, SessionState> {
async dispatch(command: Command, dryRun?: boolean): Promise<DispatchOutcome> {
try {
if (this.isTerminalSession()) return this.terminalDispatchOutcome();
if (command.type === "page_request") {
return { ok: true, event: { type: "action_result", commandId: command.commandId, ok: false, reason: "unsupported" } };
}
const fingerprint = await requestFingerprint(command, dryRun === true);
if (this.isTerminalSession()) return this.terminalDispatchOutcome();
const tombstone = legacyTombstone(command, fingerprint);
Expand Down Expand Up @@ -671,6 +691,28 @@ export class SessionAgent extends Agent<Env, SessionState> {
) {
return { kind: "not_connected", commandId: command.commandId };
}
if (command.type === "page_request") {
const lease = this.state.unattended;
if (
lease === undefined ||
this.state.protocolVersion !== PROTOCOL_VERSION ||
!(this.state.capabilities ?? []).includes("page-request-v1")
) {
return { kind: "unsupported", commandId: command.commandId, capability: "page-request-v1" };
}
const pageUrl = this.state.currentUrl ?? this.state.tabs[0]?.url;
const origin = pageUrl === undefined ? null : URL.parse(pageUrl)?.origin;
if (!origin || !lease.allowedOrigins.includes(origin) ||
(isWriteCommand(command) && command.origin !== origin) ||
resolvePageRequestUrl(origin, command.path, command.query) === null) {
return { kind: "terminal", event: {
type: "action_result",
commandId: command.commandId,
ok: false,
reason: "navigation_blocked",
} };
}
}
if (
isWriteCommand(command) &&
!dryRun &&
Expand Down Expand Up @@ -818,7 +860,7 @@ export class SessionAgent extends Agent<Env, SessionState> {
}
}

if (dryRun && isWriteCommand(command)) {
if (dryRun && (isWriteCommand(command) || command.type === "page_request")) {
const ref = this.commandRef(command);
if (ref === undefined) {
const event = this.simulatedResult(command.commandId, { ok: true });
Expand Down Expand Up @@ -951,7 +993,7 @@ export class SessionAgent extends Agent<Env, SessionState> {
return {
commandId,
status: row.state,
...(row.result_json === null ? {} : { event: JSON.parse(row.result_json) as Event }),
...(row.result_json === null ? {} : { event: this.completedEvent(row) }),
safeToRetry: row.state === "not_started" || row.state === "timed_out",
};
}
Expand Down Expand Up @@ -1295,8 +1337,7 @@ export class SessionAgent extends Agent<Env, SessionState> {
private outcomeForRow(row: CommandRow, statusUrl: string): V2DispatchOutcome {
switch (row.state) {
case "completed": {
if (row.result_json === null) throw new Error("completed command is missing its result");
return { kind: "terminal", event: JSON.parse(row.result_json) as Event };
return { kind: "terminal", event: this.completedEvent(row) };
}
case "not_started":
return { kind: "not_started", commandId: row.command_id, safeToRetry: true };
Expand All @@ -1311,6 +1352,23 @@ export class SessionAgent extends Agent<Env, SessionState> {
}
}

private completedEvent(row: CommandRow): Event {
if (row.result_json === null) throw new Error("completed command is missing its result");
const body = this.pageRequestBodies.get(row.attempt_id);
if (body !== undefined && body.expiresAt > Date.now()) return body.event;
this.pageRequestBodies.delete(row.attempt_id);
return JSON.parse(row.result_json) as Event;
}

private rememberPageRequestBody(attemptId: string, event: PageRequestResult): void {
if (this.pageRequestBodies.size >= MAX_PAGE_REQUEST_BODIES) {
const oldest = this.pageRequestBodies.keys().next().value;
if (oldest !== undefined) this.pageRequestBodies.delete(oldest);
}
this.pageRequestBodies.set(attemptId, { event, expiresAt: Date.now() + PAGE_REQUEST_BODY_TTL_MS });
setTimeout(() => this.pageRequestBodies.delete(attemptId), PAGE_REQUEST_BODY_TTL_MS);
}

private continuationOutcome(
attemptId: string,
expected: CommandState,
Expand Down
2 changes: 1 addition & 1 deletion apps/backend/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ export type V2DispatchOutcome =
| { kind: "busy"; commandId: string }
| { kind: "not_connected"; commandId: string }
| { kind: "legacy_snapshot_required"; commandId: string }
| { kind: "unsupported"; commandId: string }
| { kind: "unsupported"; commandId: string; capability?: "page-request-v1" }
| { kind: "terminal_session"; commandId: string };

export interface CommandStatusRecord {
Expand Down
148 changes: 148 additions & 0 deletions apps/backend/test/session.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -928,6 +928,154 @@ describe("hello resync", () => {
});

describe("protocol-v3 command result correlation", () => {
it("simulates a credentialed page request GET without sending it to the browser", async () => {
// #given
const sessionId = crypto.randomUUID();
const stub = await getSessionStub(sessionId);
await runInDurableObject(stub, async (instance: SessionAgent) => {
const lease = unattendedLease(sessionId);
const peer = fakeConnection({ authorized: true });
await instance.initializeUnattended("tenantA", lease);
setAuthoritative(instance, peer.connection);
instance.setState({
...instance.state, protocolVersion: 3, capabilities: ["page-request-v1"], currentUrl: lease.allowedOrigins[0]!,
});
Object.assign(instance, {
getConnections: () => [peer.connection],
tenantCoordinator: () => ({
authorizeCommand: async () => ({ ok: true, idleExpiresAt: lease.idleExpiresAt }),
}),
});

// #when
const result = await instance.dispatchV2(
{ type: "page_request", commandId: "preview", path: "/orders", method: "GET" },
true, "actor", "https://example.test/status",
);

// #then
expect(result).toEqual({ kind: "terminal", event: {
type: "action_result", commandId: "preview", ok: true, simulated: true,
} });
expect(peer.send).not.toHaveBeenCalled();
});
});

it("rejects a page request write whose approved origin differs from the current allowed origin", async () => {
// #given
const sessionId = crypto.randomUUID();
const stub = await getSessionStub(sessionId);
await runInDurableObject(stub, async (instance: SessionAgent) => {
const lease = unattendedLease(sessionId);
const currentOrigin = lease.allowedOrigins[0]!;
const origin = "https://previous.example";
await instance.initializeUnattended("tenantA", {
...lease, allowedOrigins: [currentOrigin, origin],
});
setAuthoritative(instance);
instance.setState({
...instance.state, protocolVersion: 3, capabilities: ["page-request-v1", "safe-write-v3"], currentUrl: currentOrigin,
});
Object.assign(instance, { getConnections: () => [FAKE_CONNECTION] });

// #when
const result = await instance.dispatchV2(
{ type: "page_request", commandId: "moved", path: "/orders", origin, method: "POST" },
false, "actor", "https://example.test/status",
);

// #then
expect(result).toEqual({ kind: "terminal", event: {
type: "action_result", commandId: "moved", ok: false, reason: "navigation_blocked",
} });
});
});

it("terminalizes an ambiguous page request write as unsafe to retry", async () => {
// #given
const sessionId = crypto.randomUUID();
const stub = await getSessionStub(sessionId);
await runInDurableObject(stub, async (instance: SessionAgent) => {
const lease = unattendedLease(sessionId);
const { leaseId, leaseEpoch, browserEpoch } = lease;
await instance.initializeUnattended("tenantA", lease);
setAuthoritative(instance);
const attempt = seedAttempt(instance, { state: "granted", commandType: "page_request", dryRun: false, isWrite: true });

// #when
await instance.onMessage(FAKE_CONNECTION, JSON.stringify({
type: "command_result",
attemptId: attempt.attemptId,
commandId: attempt.commandId,
leaseId, leaseEpoch, browserEpoch,
event: { type: "action_result", commandId: attempt.commandId, ok: false, reason: "outcome_unknown" },
}));

// #then
await expect(instance.getCommandStatus(attempt.commandId)).resolves.toEqual({
commandId: attempt.commandId, status: "unknown", safeToRetry: false,
});
});
});

it("requires the page-request capability before dispatching a request", async () => {
// #given
const sessionId = crypto.randomUUID();
const stub = await getSessionStub(sessionId);
await runInDurableObject(stub, async (instance: SessionAgent) => {
await instance.initializeUnattended("tenantA", unattendedLease(sessionId));
setAuthoritative(instance);
instance.setState({ ...instance.state, protocolVersion: 3, capabilities: ["safe-write-v3"] });
Object.assign(instance, { getConnections: () => [FAKE_CONNECTION] });

// #then
await expect(instance.dispatchV2(
{ type: "page_request", commandId: "page-request", path: "/orders" },
false,
"actor",
"https://example.test/status",
)).resolves.toEqual({ kind: "unsupported", commandId: "page-request", capability: "page-request-v1" });
});
});

it("returns page request JSON during polling and persists only the response receipt", async () => {
// #given
const sessionId = crypto.randomUUID();
const stub = await getSessionStub(sessionId);
await runInDurableObject(stub, async (instance: SessionAgent) => {
const lease = unattendedLease(sessionId);
const { leaseId, leaseEpoch, browserEpoch } = lease;
await instance.initializeUnattended("tenantA", lease);
setAuthoritative(instance);
const attempt = seedAttempt(instance, { state: "granted", commandType: "page_request", dryRun: false, isWrite: true });
const event = {
type: "page_request_result",
commandId: attempt.commandId,
status: 201,
body: { records: [1] },
};

// #when
await instance.onMessage(FAKE_CONNECTION, JSON.stringify({
type: "command_result",
attemptId: attempt.attemptId,
commandId: attempt.commandId,
leaseId, leaseEpoch, browserEpoch, event,
}));

// #then
await expect(instance.getCommandStatus(attempt.commandId)).resolves.toEqual({
commandId: attempt.commandId, status: "completed", safeToRetry: false, event,
});
const row = instance.sql<{ result_json: string }>`
SELECT result_json FROM command_journal WHERE command_id = ${attempt.commandId}
`[0];
expect(JSON.parse(row!.result_json)).toEqual({
type: "page_request_result", commandId: attempt.commandId, status: 201, bodyUnavailable: true,
});
});
});

it("permits legacy snapshot fallback only for a protocol-1/2 peer", async () => {
const stub = await getSessionStub(crypto.randomUUID());
await runInDurableObject(stub, async (instance: SessionAgent) => {
Expand Down
Loading