Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 40 additions & 1 deletion apps/server/src/preview/Manager.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
import { type PreviewEvent, ThreadId } from "@t3tools/contracts";
import { type PreviewEvent, type PreviewNavStatus, ThreadId } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as PubSub from "effect/PubSub";
Expand Down Expand Up @@ -37,6 +37,45 @@ const layer = PreviewManager.layer.pipe(
);

it.layer(layer)("PreviewManager", (it) => {
it.effect("redacts data page URLs in reported status, lists, and events", () =>
Effect.gen(function* () {
const manager = yield* PreviewManager.PreviewManager;
const url = 'data:text/html;charset="a,b",<p>PAYLOAD</p>';
const statuses: ReadonlyArray<PreviewNavStatus> = [
{ _tag: "Loading", url, title: "Page" },
{ _tag: "Success", url, title: "Page" },
{ _tag: "LoadFailed", url, title: "Page", code: -2, description: "Failed" },
{ _tag: "Idle" },
];
for (const runtime of ["desktop", "server"] as const) {
const threadId = freshThreadId();
const opened = yield* manager.open({ threadId, runtime });
const collector = yield* collectEvents;
for (const navStatus of statuses) {
yield* manager.reportStatus({
threadId,
tabId: opened.tabId,
serverControlled: runtime === "server",
navStatus,
canGoBack: false,
canGoForward: false,
});
const expected =
navStatus._tag === "Idle" ? navStatus : { ...navStatus, url: "data:text/html,…" };
expect((yield* manager.list({ threadId })).sessions[0]?.navStatus).toEqual(expected);
const events = yield* collector.drain;
expect(events).toHaveLength(1);
expect(events[0]).toMatchObject(
navStatus._tag === "LoadFailed"
? { type: "failed", url: "data:text/html,…" }
: { type: "navigated", snapshot: { navStatus: expected } },
);
expect(JSON.stringify(events)).not.toContain("PAYLOAD");
}
}
}),
);

it.effect("opens a session and emits opened with normalized URL", () =>
Effect.gen(function* () {
const threadId = freshThreadId();
Expand Down
21 changes: 12 additions & 9 deletions apps/server/src/preview/Manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import * as SynchronizedRef from "effect/SynchronizedRef";
import { PreviewControlRequiredError } from "@t3tools/contracts";
import { withoutDataPayload } from "./PreviewUrl.ts";

export class PreviewManager extends Context.Service<
PreviewManager,
Expand Down Expand Up @@ -231,28 +232,30 @@ export const make = Effect.gen(function* PreviewManagerMake() {
if (session.snapshot.runtime === "server" && !input.serverControlled)
return yield* new PreviewControlRequiredError({ tabId: input.tabId });
const updatedAt = yield* currentIsoTimestamp;
const navStatus =
input.navStatus._tag === "Idle"
? input.navStatus
: { ...input.navStatus, url: withoutDataPayload(input.navStatus.url) };
const snapshot: PreviewSessionSnapshot = {
...session.snapshot,
navStatus: input.navStatus,
navStatus,
canGoBack: input.canGoBack,
canGoForward: input.canGoForward,
viewport: session.snapshot.viewport ?? FILL_PREVIEW_VIEWPORT,
updatedAt,
};
const emit: PreviewEventDraft =
input.navStatus._tag === "LoadFailed"
navStatus._tag === "LoadFailed"
? {
type: "failed",
threadId: session.threadId,
tabId: session.tabId,
createdAt: snapshot.updatedAt,
url: input.navStatus.url,
title: input.navStatus.title,
code: input.navStatus.code,
description: input.navStatus.description,
...(input.navStatus.download === undefined
? {}
: { download: input.navStatus.download }),
url: navStatus.url,
title: navStatus.title,
code: navStatus.code,
description: navStatus.description,
...(navStatus.download === undefined ? {} : { download: navStatus.download }),
}
: {
type: "navigated",
Expand Down
24 changes: 24 additions & 0 deletions apps/server/src/preview/PreviewUrl.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/**
* A `data:` URL carries its content, which can be a whole file, and URLs and diagnostics
* reach tool results and provider logs. Keeps only the media type: the payload can hold any
* character and parameters are page-chosen too.
*/
export const withoutDataPayload = (url: string) => {
// Read the scheme as a browser would: it ignores leading controls and spaces, and tabs and
// newlines anywhere. A snapshot's YAML value may be quoted and escaped; an escape that isn't a
// tab or newline still decodes to something that can't start a scheme.
const value = url
.replace(/^["']/, "")
.replace(/\\(x[\da-f]{2}|u[\da-f]{4}|.)/gi, (_escape, code: string) =>
code.length > 1
? String.fromCharCode(Number.parseInt(code.slice(1), 16))
: ({ t: "\t", n: "\n", r: "\r", '"': '"', "\\": "\\" }[code] ?? "\u0001"),
)
.replace(/[\t\n\r]/g, "")
.replace(/^[\u0000-\u0020]+/, "");
const parsed = /^data:([^,;]*)/i.exec(value);
if (!parsed) return url;
const type = parsed[1]!.trim();
const mediaType = /^[\w.+-]{1,64}\/[\w.+-]{1,64}$/.test(type) ? type : "";
return `data:${mediaType},…`;
};
30 changes: 30 additions & 0 deletions apps/server/src/preview/ServerBrowser.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -398,6 +398,36 @@ beforeEach(() => {
desktopConnections.length = 0;
});

it.live.each([false, true])(
"redacts data page URLs in load reports and automation status (desktop: %s)",
(desktop) =>
Effect.scoped(
Effect.gen(function* () {
desktopRendersNext = desktop;
const { broker, tabId } = yield* ready;
const manager = yield* Manager.PreviewManager;
const events = yield* manager.subscribeEvents;
const page = desktop ? desktopConnections[0]!.context.page : contexts[0]!.page;
yield* Effect.promise(() =>
page.goto(`data:text/html;charset=${"x".repeat(2100)},<p>PAYLOAD</p>`),
);
const reported = yield* PubSub.take(events);
expect(reported).toMatchObject({
type: "navigated",
snapshot: { navStatus: { _tag: "Success", url: "data:text/html,…" } },
});
const status = yield* broker.invoke<PreviewAutomationStatus>({
scope,
tabId,
operation: "status",
input: {},
});
expect(status.url).toBe("data:text/html,…");
expect(status.tabs).toEqual([expect.objectContaining({ tabId, url: "data:text/html,…" })]);
}),
).pipe(Effect.provide(layer)),
);

it.live("tells the desktop once per thread when its agent turns start and end", () =>
Effect.gen(function* () {
yield* ServerBrowser.ServerBrowser;
Expand Down
22 changes: 13 additions & 9 deletions apps/server/src/preview/ServerBrowser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ import * as ServerBrowserPage from "./ServerBrowserPage.ts";
import * as PreviewBrowser from "./PreviewBrowser.ts";
import * as PreviewBrowserHost from "./PreviewBrowserHost.ts";
import { presentAsChrome, ServerBrowserContexts } from "./ServerBrowserContexts.ts";
import { withoutDataPayload } from "./PreviewUrl.ts";
import { BrowserControlInterrupted, SessionControl } from "./SessionControl.ts";
import { installPdfDocumentNavigation, isPdfAssetUrl } from "./PdfDocumentNavigation.ts";

Expand Down Expand Up @@ -571,7 +572,7 @@ const make = Effect.gen(function* () {
if (url === "about:blank" || url.startsWith("chrome-error://")) return;
const title = (await tab.page.title().catch(() => "")).slice(0, 512);
if (tab.loading || tab.page.url() !== url) return;
report(tab, { _tag: "Success", url: url.slice(0, 2048), title });
report(tab, { _tag: "Success", url: withoutDataPayload(url).slice(0, 2048), title });
};

const reportLiveTabs = () => {
Expand Down Expand Up @@ -809,7 +810,7 @@ const make = Effect.gen(function* () {
tab.loading = true;
report(tab, {
_tag: "Loading",
url: ServerBrowserPage.withoutDataPayload(request.url()).slice(0, 2048),
url: withoutDataPayload(request.url()).slice(0, 2048),
title: "",
});
});
Expand All @@ -833,7 +834,7 @@ const make = Effect.gen(function* () {
page.on("requestfailed", (request) => {
const errorText = request.failure()?.errorText ?? "";
pushBounded(tab.networkEntries, {
url: ServerBrowserPage.withoutDataPayload(request.url()),
url: withoutDataPayload(request.url()),
method: request.method(),
status: null,
failed: true,
Expand Down Expand Up @@ -864,15 +865,15 @@ const make = Effect.gen(function* () {
const { code, description } = ServerBrowserPage.parseNetError(errorText);
report(tab, {
_tag: "LoadFailed",
url: ServerBrowserPage.withoutDataPayload(request.url()).slice(0, 2048),
url: withoutDataPayload(request.url()).slice(0, 2048),
title: "",
code,
description,
});
});
page.on("response", (response) => {
pushBounded(tab.networkEntries, {
url: ServerBrowserPage.withoutDataPayload(response.url()),
url: withoutDataPayload(response.url()),
method: response.request().method(),
status: response.status(),
failed: false,
Expand Down Expand Up @@ -960,7 +961,7 @@ const make = Effect.gen(function* () {
}
report(tab, {
_tag: "LoadFailed",
url: ServerBrowserPage.withoutDataPayload(url).slice(0, 2048),
url: withoutDataPayload(url).slice(0, 2048),
title: "",
code: -3,
description: "ERR_ABORTED",
Expand Down Expand Up @@ -993,7 +994,7 @@ const make = Effect.gen(function* () {
fileName: download.suggestedFilename().slice(0, 255) || "download",
path,
sizeBytes: size,
url: ServerBrowserPage.withoutDataPayload(download.url()).slice(0, 2048),
url: withoutDataPayload(download.url()).slice(0, 2048),
completedAt: new Date().toISOString(),
};
tab.downloads.push(saved);
Expand Down Expand Up @@ -1488,7 +1489,7 @@ const make = Effect.gen(function* () {
available: true,
visible: tab.viewers.size > 0,
tabId: tab.tabId,
url: url === "about:blank" ? null : url,
url: url === "about:blank" ? null : withoutDataPayload(url),
title: null,
loading: tab.loading,
control: {
Expand All @@ -1506,7 +1507,10 @@ const make = Effect.gen(function* () {
.filter((candidate) => candidate.threadId === tab.threadId)
.map((candidate) => ({
tabId: candidate.tabId,
url: candidate.page.url() === "about:blank" ? null : candidate.page.url(),
url:
candidate.page.url() === "about:blank"
? null
: withoutDataPayload(candidate.page.url()),
...(candidate.openerTabId === undefined ? {} : { openerTabId: candidate.openerTabId }),
owner: tabOwner(candidate),
ownedByCaller: candidate.control.agentId === agentSessionId,
Expand Down
9 changes: 9 additions & 0 deletions apps/server/src/preview/ServerBrowserPage.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,15 @@ describe("server browser element refs", () => {
};
const repeatedRows = `<ul>${Array.from({ length: 5 }, (_, i) => `<li>row ${i + 1}<button data-testid="delete-row" onclick="this.parentElement.remove()">delete</button></li>`).join("")}</ul>`;

it("redacts a data page URL while preserving its visible text", async () => {
await page.goto(
'data:text/html;charset=utf-8,<p>PAYLOAD</p><input type="password" value="data">',
);
const result = await takeSnapshot();
expect(result.url).toBe("data:text/html,…");
expect(result.visibleText).toBe("PAYLOAD");
});

it("clicks the fifth repeated delete control without touching row one", async () => {
await page.setContent(repeatedRows);
const result = await takeSnapshot();
Expand Down
27 changes: 2 additions & 25 deletions apps/server/src/preview/ServerBrowserPage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import { constVoid } from "effect/Function";
import type { CDPSession, ConsoleMessage, Frame, Locator, Page } from "playwright-core";
import * as NodeCrypto from "node:crypto";
import { BrowserControlInterrupted } from "./SessionControl.ts";
import { withoutDataPayload } from "./PreviewUrl.ts";

const MAX_EVALUATION_BYTES = 64_000;
const MAX_VISIBLE_TEXT_LENGTH = 20_000;
Expand Down Expand Up @@ -157,31 +158,6 @@ const SNAPSHOT_SCRIPT = `(() => {

const MASKED_VALUE = "••••••••";

/**
* A `data:` URL carries its content, which can be a whole file, and URLs and diagnostics
* reach tool results and provider logs. Keeps only the media type: the payload can hold any
* character and parameters are page-chosen too.
*/
export const withoutDataPayload = (url: string) => {
// Read the scheme as a browser would: it ignores leading controls and spaces, and tabs and
// newlines anywhere. A snapshot's YAML value may be quoted and escaped; an escape that isn't a
// tab or newline still decodes to something that can't start a scheme.
const value = url
.replace(/^["']/, "")
.replace(/\\(x[\da-f]{2}|u[\da-f]{4}|.)/gi, (_escape, code: string) =>
code.length > 1
? String.fromCharCode(Number.parseInt(code.slice(1), 16))
: ({ t: "\t", n: "\n", r: "\r", '"': '"', "\\": "\\" }[code] ?? "\u0001"),
)
.replace(/[\t\n\r]/g, "")
.replace(/^[\u0000-\u0020]+/, "");
const parsed = /^data:([^,;]*)/i.exec(value);
if (!parsed) return url;
const type = parsed[1]!.trim();
const mediaType = /^[\w.+-]{1,64}\/[\w.+-]{1,64}$/.test(type) ? type : "";
return `data:${mediaType},…`;
};

/**
* Chromium's own console messages, which carry no arguments, quote `data:` URLs whole, as in a
* blocked navigation or a CSP violation. Everything after the first one goes, since Chromium
Expand Down Expand Up @@ -583,6 +559,7 @@ const capture = async (
});
return {
...page,
url: withoutDataPayload(page.url),
// Mask text before truncating so a value crossing the cut cannot leak its prefix.
visibleText: mask(page.visibleText).slice(0, MAX_VISIBLE_TEXT_LENGTH),
accessibilityTree,
Expand Down
Loading