mirror of
https://github.com/morluto/rea.git
synced 2026-11-18 20:53:00 +00:00
test(browser): consolidate navigation timeline coverage
Share observations across redirect response and fragment cases while retaining the wire checks for caller cancellation, final URL identity, and ordered lifecycle events.
This commit is contained in:
1 parent
085ef4cc3b
commit
005a61cf4c
5 files changed
+306
-435
No files matched your search
@@ -1,53 +1,50 @@
|
||||
import { getEventListeners } from "node:events";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { CdpBrowserProvider } from "../../../src/browser/CdpBrowserProvider.js";
|
||||
import { observeWebSessionInputSchema } from "../../../src/domain/browserSession.js";
|
||||
import { startFakeCdpBrowser } from "../../fixtures/fakeCdpBrowser.js";
|
||||
import { trackBrowser } from "./cdpBrowserProvider.support.js";
|
||||
import { frameNavigated, trackBrowser } from "./cdpBrowserProvider.support.js";
|
||||
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
|
||||
it.each([2_147_483_648, 3_000_000_000])(
|
||||
"keeps a long observation pending with a representable timer: %i",
|
||||
async (duration) => {
|
||||
const browser = await startFakeCdpBrowser();
|
||||
trackBrowser(browser);
|
||||
const controller = new AbortController();
|
||||
const reason = { stop: "long observation" };
|
||||
const provider = new CdpBrowserProvider();
|
||||
const nativeTimeout = globalThis.setTimeout;
|
||||
let scheduled!: (delay: number) => void;
|
||||
const scheduledDelay = new Promise<number>((resolve) => {
|
||||
scheduled = resolve;
|
||||
});
|
||||
vi.spyOn(globalThis, "setTimeout").mockImplementation(
|
||||
(callback, delay, ...args) => {
|
||||
if (delay === duration || delay === 2_147_483_647) scheduled(delay);
|
||||
return nativeTimeout(callback, delay, ...args);
|
||||
},
|
||||
);
|
||||
const pending = provider.observeSession(
|
||||
it("keeps a long observation pending until the caller cancels it", async () => {
|
||||
const browser = await startFakeCdpBrowser();
|
||||
trackBrowser(browser);
|
||||
const provider = new CdpBrowserProvider();
|
||||
const controller = new AbortController();
|
||||
const reason = { stop: "long observation" };
|
||||
let stop: ReturnType<typeof setTimeout> | undefined;
|
||||
try {
|
||||
const result = await provider.observeSession(
|
||||
observeWebSessionInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
observation_ms: duration,
|
||||
observation_ms: 3_000_000_000,
|
||||
}),
|
||||
{ signal: controller.signal },
|
||||
{
|
||||
signal: controller.signal,
|
||||
progress: {
|
||||
async report(update) {
|
||||
if (
|
||||
update.phase === "browser_observation" &&
|
||||
update.completed === 1
|
||||
)
|
||||
stop = setTimeout(() => controller.abort(reason), 150);
|
||||
},
|
||||
},
|
||||
},
|
||||
);
|
||||
const observedDelay = await scheduledDelay;
|
||||
controller.abort(reason);
|
||||
const result = await pending;
|
||||
await provider.close();
|
||||
expect(observedDelay).toBe(2_147_483_647);
|
||||
|
||||
if (result.ok) throw new Error("Long window completed before cancellation");
|
||||
expect(result.error).toMatchObject({ _tag: "AnalysisCancelledError" });
|
||||
expect(result.error.cause).toBe(reason);
|
||||
expect(getEventListeners(controller.signal, "abort")).toHaveLength(0);
|
||||
await expect.poll(() => browser.activeConnectionCount()).toBe(0);
|
||||
},
|
||||
);
|
||||
} finally {
|
||||
clearTimeout(stop);
|
||||
await provider.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("does not retain a caller listener when the target ends before the wait starts", async () => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
@@ -87,13 +84,12 @@ it("does not retain a caller listener when the target ends before the wait start
|
||||
await provider.close();
|
||||
});
|
||||
|
||||
it("preserves cancellation at the armed handshake without starting a window timer", async () => {
|
||||
it("preserves cancellation during the armed handshake", async () => {
|
||||
const browser = await startFakeCdpBrowser();
|
||||
trackBrowser(browser);
|
||||
const controller = new AbortController();
|
||||
const reason = { stop: "at armed handshake" };
|
||||
const provider = new CdpBrowserProvider();
|
||||
const timers = vi.spyOn(globalThis, "setTimeout");
|
||||
const result = await provider.observeSession(
|
||||
observeWebSessionInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
@@ -113,82 +109,46 @@ it("preserves cancellation at the armed handshake without starting a window time
|
||||
);
|
||||
if (result.ok) throw new Error("Expected armed cancellation");
|
||||
expect(result.error.cause).toBe(reason);
|
||||
expect(
|
||||
timers.mock.calls.filter(
|
||||
([, delay]) => delay === 3_000_000_000 || delay === 2_147_483_647,
|
||||
),
|
||||
).toHaveLength(0);
|
||||
expect(getEventListeners(controller.signal, "abort")).toHaveLength(0);
|
||||
await expect.poll(() => browser.activeConnectionCount()).toBe(0);
|
||||
await provider.close();
|
||||
});
|
||||
|
||||
it.each([
|
||||
"malformed-event",
|
||||
"missing-same-document",
|
||||
"missing-redirect",
|
||||
"foreign-event",
|
||||
"malformed-final",
|
||||
"normal",
|
||||
])("distinguishes protocol uncertainty in committed URLs: %s", async (kind) => {
|
||||
it("retains incomplete navigation facts without rejecting the target scope", async () => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
eventsBeforeReply: ["Page.setLifecycleEventsEnabled"],
|
||||
commandResult: ({ method }, origin, reads) =>
|
||||
method === "Page.getFrameTree" && kind === "malformed-final" && reads > 1
|
||||
? {
|
||||
frameTree: {
|
||||
frame: {
|
||||
id: "frame-main",
|
||||
url: `${origin}/app`,
|
||||
urlFragment: 7,
|
||||
},
|
||||
},
|
||||
}
|
||||
: undefined,
|
||||
commandEvents: ({ method, sessionId }, origin) => {
|
||||
if (method !== "Page.setLifecycleEventsEnabled") return undefined;
|
||||
const scope = sessionId === undefined ? {} : { sessionId };
|
||||
if (kind === "missing-same-document")
|
||||
return [
|
||||
{
|
||||
method: "Page.navigatedWithinDocument",
|
||||
...scope,
|
||||
params: { frameId: "frame-main" },
|
||||
commandEvents: (command, origin) => {
|
||||
if (command.method !== "Page.setLifecycleEventsEnabled") return undefined;
|
||||
return [
|
||||
frameNavigated(command, {
|
||||
id: "frame-main",
|
||||
loaderId: "numeric-fragment",
|
||||
url: `${origin}/first`,
|
||||
urlFragment: 7,
|
||||
}),
|
||||
frameNavigated(command, {
|
||||
id: "frame-main",
|
||||
loaderId: "unprefixed-fragment",
|
||||
url: `${origin}/second`,
|
||||
urlFragment: "bad-fragment",
|
||||
}),
|
||||
{
|
||||
method: "Page.navigatedWithinDocument",
|
||||
sessionId: command.sessionId,
|
||||
params: { frameId: "frame-main" },
|
||||
},
|
||||
{
|
||||
method: "Network.requestWillBeSent",
|
||||
sessionId: command.sessionId,
|
||||
params: {
|
||||
frameId: "frame-main",
|
||||
requestId: "missing-destination",
|
||||
type: "Document",
|
||||
redirectResponse: { url: `${origin}/prior`, status: 302 },
|
||||
request: {},
|
||||
},
|
||||
];
|
||||
if (kind === "missing-redirect")
|
||||
return [
|
||||
{
|
||||
method: "Network.requestWillBeSent",
|
||||
...scope,
|
||||
params: {
|
||||
frameId: "frame-main",
|
||||
requestId: "redirect",
|
||||
type: "Document",
|
||||
redirectResponse: { url: `${origin}/prior`, status: 302 },
|
||||
request: {},
|
||||
},
|
||||
},
|
||||
];
|
||||
return method === "Page.setLifecycleEventsEnabled"
|
||||
? [
|
||||
{
|
||||
method: "Page.frameNavigated",
|
||||
...(sessionId === undefined ? {} : { sessionId }),
|
||||
params: {
|
||||
frame: {
|
||||
id: "frame-main",
|
||||
loaderId: "loader-main",
|
||||
url:
|
||||
kind === "foreign-event"
|
||||
? "https://foreign.test/"
|
||||
: `${origin}/app`,
|
||||
...(kind === "malformed-event" ? { urlFragment: 7 } : {}),
|
||||
},
|
||||
},
|
||||
},
|
||||
]
|
||||
: undefined;
|
||||
},
|
||||
];
|
||||
},
|
||||
});
|
||||
trackBrowser(browser);
|
||||
@@ -201,123 +161,126 @@ it.each([
|
||||
}),
|
||||
);
|
||||
if (!result.ok) throw result.error;
|
||||
if (
|
||||
kind === "malformed-event" ||
|
||||
kind.startsWith("missing-") ||
|
||||
kind === "malformed-final"
|
||||
) {
|
||||
expect(result.value.completeness.excluded).toContainEqual({
|
||||
section: "timeline",
|
||||
reason: "invalid_protocol_value",
|
||||
count: 1,
|
||||
});
|
||||
expect(result.value.completeness.policy_filtered_sections).toEqual([]);
|
||||
}
|
||||
if (kind === "malformed-final")
|
||||
expect(result.value.target.final_url).toBeNull();
|
||||
if (
|
||||
kind === "malformed-event" ||
|
||||
kind === "malformed-final" ||
|
||||
kind.startsWith("missing-")
|
||||
)
|
||||
expect(result.value.window.end_reason).toBe("window_elapsed");
|
||||
if (kind === "foreign-event")
|
||||
expect(result.value.completeness.excluded).toContainEqual({
|
||||
section: "timeline",
|
||||
reason: "out_of_target_scope",
|
||||
count: 1,
|
||||
});
|
||||
if (kind === "normal")
|
||||
expect(result.value.window.end_reason).toBe("window_elapsed");
|
||||
});
|
||||
it.each(
|
||||
[false, true].flatMap((foreign) =>
|
||||
[7, "bad-fragment"].map((urlFragment) => ({ foreign, urlFragment })),
|
||||
),
|
||||
)(
|
||||
"retains malformed committed identity and known scope: $foreign/$urlFragment",
|
||||
async ({ foreign, urlFragment }) => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
eventsBeforeReply: ["Page.setLifecycleEventsEnabled"],
|
||||
commandEvents: ({ method, sessionId }, origin) =>
|
||||
method === "Page.setLifecycleEventsEnabled"
|
||||
? [
|
||||
{
|
||||
method: "Page.frameNavigated",
|
||||
...(sessionId === undefined ? {} : { sessionId }),
|
||||
params: {
|
||||
frame: {
|
||||
id: "frame-main",
|
||||
url: foreign ? "https://foreign.test/" : `${origin}/app`,
|
||||
urlFragment,
|
||||
},
|
||||
},
|
||||
},
|
||||
]
|
||||
: undefined,
|
||||
});
|
||||
trackBrowser(browser);
|
||||
const result = await new CdpBrowserProvider().observeSession(
|
||||
observeWebSessionInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
observation_ms: 1,
|
||||
}),
|
||||
);
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.completeness.excluded).toContainEqual({
|
||||
section: "timeline",
|
||||
reason: "invalid_protocol_value",
|
||||
count: 1,
|
||||
});
|
||||
expect(
|
||||
result.value.timeline.find(({ type }) => type === "navigation_committed"),
|
||||
).toMatchObject({
|
||||
expect(result.value.window.end_reason).toBe("window_elapsed");
|
||||
expect(result.value.timeline).toEqual([
|
||||
expect.objectContaining({
|
||||
type: "navigation_committed",
|
||||
loader_id: "numeric-fragment",
|
||||
url: null,
|
||||
destination_scope: foreign ? "outside_policy" : "approved",
|
||||
});
|
||||
expect(result.value.window.end_reason).toBe(
|
||||
foreign ? "target_left_scope" : "window_elapsed",
|
||||
);
|
||||
if (foreign) {
|
||||
expect(result.value.target.final_url).toBeNull();
|
||||
expect(result.value.completeness.excluded).toContainEqual({
|
||||
section: "timeline",
|
||||
reason: "out_of_target_scope",
|
||||
count: 1,
|
||||
});
|
||||
} else
|
||||
expect(result.value.completeness.policy_filtered_sections).toEqual([]);
|
||||
},
|
||||
);
|
||||
destination_scope: "approved",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
type: "navigation_committed",
|
||||
loader_id: "unprefixed-fragment",
|
||||
url: null,
|
||||
destination_scope: "approved",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
type: "same_document_navigation",
|
||||
url: null,
|
||||
}),
|
||||
expect.objectContaining({
|
||||
type: "redirect",
|
||||
request_id: "missing-destination",
|
||||
url: null,
|
||||
redirect_response: {
|
||||
url: `${browser.allowedOrigin}/prior`,
|
||||
scope: "approved",
|
||||
status: 302,
|
||||
},
|
||||
}),
|
||||
]);
|
||||
expect(result.value.completeness.excluded).toContainEqual({
|
||||
section: "timeline",
|
||||
reason: "invalid_protocol_value",
|
||||
count: 4,
|
||||
});
|
||||
expect(result.value.completeness.policy_filtered_sections).toEqual([]);
|
||||
});
|
||||
|
||||
it.each(
|
||||
[7, "bad-fragment"].flatMap((fragment) =>
|
||||
["allowed", "foreign", "missing"].map((scope) => ({ fragment, scope })),
|
||||
),
|
||||
)(
|
||||
"retains final-probe identity and scope without an event: $scope/$fragment",
|
||||
async ({ fragment, scope }) => {
|
||||
it("ends the window when a malformed commit still identifies a foreign origin", async () => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
eventsBeforeReply: ["Page.setLifecycleEventsEnabled"],
|
||||
commandEvents: (command) =>
|
||||
command.method === "Page.setLifecycleEventsEnabled"
|
||||
? [
|
||||
frameNavigated(command, {
|
||||
id: "frame-main",
|
||||
url: "https://foreign.test/",
|
||||
urlFragment: "bad-fragment",
|
||||
}),
|
||||
]
|
||||
: undefined,
|
||||
});
|
||||
trackBrowser(browser);
|
||||
const result = await new CdpBrowserProvider().observeSession(
|
||||
observeWebSessionInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
observation_ms: 1,
|
||||
}),
|
||||
);
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.window.end_reason).toBe("target_left_scope");
|
||||
expect(result.value.target.final_url).toBeNull();
|
||||
expect(result.value.timeline).toEqual([
|
||||
expect.objectContaining({
|
||||
type: "navigation_committed",
|
||||
url: null,
|
||||
destination_scope: "outside_policy",
|
||||
}),
|
||||
]);
|
||||
expect(result.value.completeness.excluded).toEqual(
|
||||
expect.arrayContaining([
|
||||
{ section: "timeline", reason: "invalid_protocol_value", count: 1 },
|
||||
{ section: "timeline", reason: "out_of_target_scope", count: 1 },
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{
|
||||
name: "approved URL",
|
||||
frame: (origin: string) => ({
|
||||
url: `${origin}/final?token=visible`,
|
||||
urlFragment: "#location",
|
||||
}),
|
||||
finalUrl: (origin: string) => `${origin}/final?token=visible#location`,
|
||||
endReason: "window_elapsed",
|
||||
exclusions: [],
|
||||
},
|
||||
{
|
||||
name: "approved origin with an invalid fragment",
|
||||
frame: (origin: string) => ({ url: `${origin}/final`, urlFragment: 7 }),
|
||||
finalUrl: () => null,
|
||||
endReason: "window_elapsed",
|
||||
exclusions: ["invalid_protocol_value"],
|
||||
},
|
||||
{
|
||||
name: "foreign origin with an invalid fragment",
|
||||
frame: () => ({
|
||||
url: "https://foreign.test/final",
|
||||
urlFragment: "bad-fragment",
|
||||
}),
|
||||
finalUrl: () => null,
|
||||
endReason: "target_left_scope",
|
||||
exclusions: ["invalid_protocol_value", "out_of_target_scope"],
|
||||
},
|
||||
{
|
||||
name: "missing URL",
|
||||
frame: () => ({ urlFragment: "#location" }),
|
||||
finalUrl: () => null,
|
||||
endReason: "window_elapsed",
|
||||
exclusions: ["invalid_protocol_value"],
|
||||
},
|
||||
])(
|
||||
"uses the final frame-tree evidence for $name",
|
||||
async ({ frame, finalUrl, endReason, exclusions }) => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
commandResult: ({ method }, origin, reads) =>
|
||||
method === "Page.getFrameTree" && reads > 1
|
||||
? {
|
||||
frameTree: {
|
||||
frame: {
|
||||
id: "frame-main",
|
||||
...(scope === "missing"
|
||||
? {}
|
||||
: {
|
||||
url:
|
||||
scope === "foreign"
|
||||
? "https://foreign.test/"
|
||||
: `${origin}/app`,
|
||||
}),
|
||||
urlFragment: fragment,
|
||||
},
|
||||
},
|
||||
}
|
||||
? { frameTree: { frame: { id: "frame-main", ...frame(origin) } } }
|
||||
: undefined,
|
||||
});
|
||||
trackBrowser(browser);
|
||||
@@ -330,24 +293,18 @@ it.each(
|
||||
}),
|
||||
);
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.target.final_url).toBeNull();
|
||||
expect(result.value.window.end_reason).toBe(
|
||||
scope === "foreign" ? "target_left_scope" : "window_elapsed",
|
||||
);
|
||||
expect(result.value.completeness.excluded).toContainEqual({
|
||||
section: "timeline",
|
||||
reason: "invalid_protocol_value",
|
||||
count: 1,
|
||||
});
|
||||
expect(result.value.target.final_url).toBe(finalUrl(browser.allowedOrigin));
|
||||
expect(result.value.window.end_reason).toBe(endReason);
|
||||
expect(
|
||||
result.value.completeness.policy_filtered_sections.includes("timeline"),
|
||||
).toBe(scope === "foreign");
|
||||
if (scope === "foreign")
|
||||
expect(result.value.completeness.excluded).toContainEqual({
|
||||
section: "timeline",
|
||||
reason: "out_of_target_scope",
|
||||
count: 1,
|
||||
});
|
||||
result.value.completeness.excluded.filter(
|
||||
({ section }) => section === "timeline",
|
||||
),
|
||||
).toEqual(
|
||||
exclusions.map((reason) => ({ section: "timeline", reason, count: 1 })),
|
||||
);
|
||||
expect(result.value.completeness.policy_filtered_sections).toEqual(
|
||||
endReason === "target_left_scope" ? ["timeline"] : [],
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
@@ -371,7 +328,17 @@ describe("CdpBrowserProvider navigation timeline", () => {
|
||||
? "target_left_scope"
|
||||
: "session_detached",
|
||||
);
|
||||
if (sessionTimeline === "target_detached") {
|
||||
if (sessionTimeline === "outside_policy") {
|
||||
expect(result.value.target.final_url).toBeNull();
|
||||
expect(result.value.timeline).toContainEqual(
|
||||
expect.objectContaining({
|
||||
type: "redirect",
|
||||
request_id: "document-request",
|
||||
url: null,
|
||||
destination_scope: "outside_policy",
|
||||
}),
|
||||
);
|
||||
} else {
|
||||
expect(result.value.timeline).toContainEqual(
|
||||
expect.objectContaining({ type: "session_detached" }),
|
||||
);
|
||||
@@ -381,55 +348,25 @@ describe("CdpBrowserProvider navigation timeline", () => {
|
||||
}
|
||||
},
|
||||
);
|
||||
it.each([2_147_483_648, 3_000_000_000])(
|
||||
"keeps a long observation pending until cancellation: %s",
|
||||
async (observation_ms) => {
|
||||
const browser = await startFakeCdpBrowser();
|
||||
trackBrowser(browser);
|
||||
const controller = new AbortController();
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
let armed = false;
|
||||
try {
|
||||
const result = await new CdpBrowserProvider().observeSession(
|
||||
observeWebSessionInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
observation_ms,
|
||||
}),
|
||||
{
|
||||
signal: controller.signal,
|
||||
progress: {
|
||||
report: async (update) => {
|
||||
if (
|
||||
update.phase === "browser_observation" &&
|
||||
update.completed === 1
|
||||
) {
|
||||
armed = true;
|
||||
timer = setTimeout(() => controller.abort(), 150);
|
||||
}
|
||||
},
|
||||
},
|
||||
},
|
||||
);
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisCancelledError" },
|
||||
});
|
||||
expect(armed).toBe(true);
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
},
|
||||
);
|
||||
// Event count has no ceiling; only a dropped event truncates the timeline.
|
||||
it("returns every event of a long session timeline without truncating it", async () => {
|
||||
const additionalEvents = 2_001;
|
||||
const timestamps = Array.from({ length: 2_001 }, (_, index) => index + 1);
|
||||
const browser = await startFakeCdpBrowser({
|
||||
pageScopedVersionWebSocket: true,
|
||||
omitTargetWebSocket: true,
|
||||
sessionTimeline: "same_origin",
|
||||
sessionTimelineEventCount: additionalEvents,
|
||||
eventsBeforeReply: ["Page.setLifecycleEventsEnabled"],
|
||||
commandEvents: (command) =>
|
||||
command.method === "Page.setLifecycleEventsEnabled"
|
||||
? timestamps.map((timestamp) => ({
|
||||
method: "Page.lifecycleEvent",
|
||||
sessionId: command.sessionId,
|
||||
params: {
|
||||
frameId: "frame-main",
|
||||
name: "networkIdle",
|
||||
timestamp,
|
||||
},
|
||||
}))
|
||||
: undefined,
|
||||
});
|
||||
trackBrowser(browser);
|
||||
|
||||
@@ -443,7 +380,11 @@ describe("CdpBrowserProvider navigation timeline", () => {
|
||||
);
|
||||
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.timeline).toHaveLength(additionalEvents + 6);
|
||||
expect(
|
||||
result.value.timeline
|
||||
.filter(({ type }) => type === "lifecycle")
|
||||
.map(({ timestamp }) => timestamp),
|
||||
).toEqual(timestamps);
|
||||
expect(result.value.completeness.truncated_sections).not.toContain(
|
||||
"timeline",
|
||||
);
|
||||
|
||||
@@ -4,58 +4,38 @@ import { CdpBrowserProvider } from "../../../src/browser/CdpBrowserProvider.js";
|
||||
import { observeWebSessionInputSchema } from "../../../src/domain/browserSession.js";
|
||||
import { startFakeCdpBrowser } from "../../fixtures/fakeCdpBrowser.js";
|
||||
|
||||
it.each(["Fetch", "Script"] as const)(
|
||||
"does not treat a %s redirect as leaving the observed page",
|
||||
async (type) => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
sessionTimeline: "outside_policy",
|
||||
sessionRedirectResourceType: type,
|
||||
});
|
||||
onTestFinished(async () => {
|
||||
await browser.close();
|
||||
});
|
||||
const result = await new CdpBrowserProvider().observeSession(
|
||||
observeWebSessionInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
observation_ms: 1,
|
||||
}),
|
||||
);
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.window.end_reason).toBe("window_elapsed");
|
||||
expect(result.value.timeline.some(({ type }) => type === "redirect")).toBe(
|
||||
false,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["Document", undefined] as const)(
|
||||
"retains outside-origin scope rejection for %s redirect metadata",
|
||||
async (type) => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
sessionTimeline: "outside_policy",
|
||||
...(type === undefined ? {} : { sessionRedirectResourceType: type }),
|
||||
});
|
||||
onTestFinished(async () => {
|
||||
await browser.close();
|
||||
});
|
||||
const result = await new CdpBrowserProvider().observeSession(
|
||||
observeWebSessionInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
observation_ms: 1,
|
||||
}),
|
||||
);
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.window.end_reason).toBe("target_left_scope");
|
||||
expect(result.value.target.final_url).toBeNull();
|
||||
expect(result.value.timeline.some(({ type }) => type === "redirect")).toBe(
|
||||
true,
|
||||
);
|
||||
},
|
||||
);
|
||||
it("ignores Fetch and Script redirects when observing page navigation", async () => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
eventsBeforeReply: ["Page.setLifecycleEventsEnabled"],
|
||||
commandEvents: (command, origin) =>
|
||||
command.method === "Page.setLifecycleEventsEnabled"
|
||||
? ["Fetch", "Script"].map((type) => ({
|
||||
method: "Network.requestWillBeSent",
|
||||
sessionId: command.sessionId,
|
||||
params: {
|
||||
requestId: type,
|
||||
frameId: "frame-main",
|
||||
type,
|
||||
request: { url: "https://private.example.test/redirected" },
|
||||
redirectResponse: { url: `${origin}/prior`, status: 302 },
|
||||
},
|
||||
}))
|
||||
: undefined,
|
||||
});
|
||||
onTestFinished(() => browser.close());
|
||||
const result = await new CdpBrowserProvider().observeSession(
|
||||
observeWebSessionInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
observation_ms: 1,
|
||||
}),
|
||||
);
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.window.end_reason).toBe("window_elapsed");
|
||||
expect(result.value.timeline).toEqual([]);
|
||||
expect(result.value.completeness.policy_filtered_sections).toEqual([]);
|
||||
});
|
||||
|
||||
it("keeps final URL unknown when a redirect races the final frame-tree read", async () => {
|
||||
let frameTreeReads = 0;
|
||||
@@ -101,29 +81,9 @@ it("keeps final URL unknown when a redirect races the final frame-tree read", as
|
||||
expect(result.value.target.final_url).toBeNull();
|
||||
expect(result.value.timeline.at(-1)).toMatchObject({
|
||||
type: "redirect",
|
||||
request_id: "late-main-document",
|
||||
url: null,
|
||||
destination_scope: "outside_policy",
|
||||
});
|
||||
expect(JSON.stringify(result.value)).not.toContain("private.example.test");
|
||||
});
|
||||
|
||||
it("retains the approved URL returned by the final frame-tree read", async () => {
|
||||
const browser = await startFakeCdpBrowser();
|
||||
onTestFinished(async () => {
|
||||
await browser.close();
|
||||
});
|
||||
const result = await new CdpBrowserProvider().observeSession(
|
||||
observeWebSessionInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
observation_ms: 1,
|
||||
}),
|
||||
);
|
||||
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.window.end_reason).toBe("window_elapsed");
|
||||
expect(result.value.target.final_url).toBe(
|
||||
`${browser.allowedOrigin}/app?token=frame-secret`,
|
||||
);
|
||||
});
|
||||
@@ -447,7 +447,6 @@ const redirectCases = [
|
||||
] as const
|
||||
).map(([name, status]) => ({
|
||||
name,
|
||||
invalidStatus: true,
|
||||
response: (origin: string) => ({ url: `${origin}/prior`, status }),
|
||||
expected: (origin: string) => ({
|
||||
url: `${origin}/prior`,
|
||||
@@ -529,73 +528,58 @@ const redirectCases = [
|
||||
},
|
||||
];
|
||||
|
||||
it.each(redirectCases)(
|
||||
"preserves scoped redirect response facts with $name",
|
||||
async (testCase) => {
|
||||
const { response, expected } = testCase;
|
||||
const { browser, observation } = await observeDuringClockSampling(
|
||||
(command, origin) => {
|
||||
if (command.method !== "Performance.getMetrics") return undefined;
|
||||
return [
|
||||
{
|
||||
method: "Network.requestWillBeSent",
|
||||
sessionId: command.sessionId,
|
||||
params: {
|
||||
requestId: "redirect-context",
|
||||
timestamp: 21,
|
||||
type: "Document",
|
||||
frameId: "frame-main",
|
||||
request: { url: `${origin}/next`, method: "GET" },
|
||||
redirectResponse: {
|
||||
...response(origin),
|
||||
headers: { Authorization: "discard-redirect-header" },
|
||||
},
|
||||
},
|
||||
it("retains scoped redirect response facts for each request", async () => {
|
||||
const { browser, observation } = await observeDuringClockSampling(
|
||||
(command, origin) => {
|
||||
if (command.method !== "Performance.getMetrics") return undefined;
|
||||
return redirectCases.map(({ name, response }, index) => ({
|
||||
method: "Network.requestWillBeSent",
|
||||
sessionId: command.sessionId,
|
||||
params: {
|
||||
requestId: name,
|
||||
timestamp: 21 + index,
|
||||
type: "Document",
|
||||
frameId: "frame-main",
|
||||
request: { url: `${origin}/next`, method: "GET" },
|
||||
redirectResponse: {
|
||||
...response(origin),
|
||||
headers: { Authorization: "discard-redirect-header" },
|
||||
},
|
||||
];
|
||||
},
|
||||
);
|
||||
expect(observation.timeline).toContainEqual(
|
||||
expect.objectContaining({
|
||||
type: "redirect",
|
||||
request_id: "redirect-context",
|
||||
redirect_response: expected(browser.allowedOrigin),
|
||||
}),
|
||||
);
|
||||
if (
|
||||
expected(browser.allowedOrigin).scope === null ||
|
||||
"invalidStatus" in testCase
|
||||
)
|
||||
expect(observation.completeness.excluded).toContainEqual(
|
||||
expect.objectContaining({
|
||||
section: "timeline",
|
||||
reason: "invalid_protocol_value",
|
||||
}),
|
||||
);
|
||||
else
|
||||
expect(observation.completeness.excluded).not.toContainEqual(
|
||||
expect.objectContaining({
|
||||
section: "timeline",
|
||||
reason: "invalid_protocol_value",
|
||||
}),
|
||||
);
|
||||
const scope = expected(browser.allowedOrigin).scope;
|
||||
if (scope === "outside_policy" || scope === "unsupported") {
|
||||
expect(observation.completeness.excluded).toContainEqual(
|
||||
expect.objectContaining({
|
||||
section: "timeline",
|
||||
reason:
|
||||
scope === "outside_policy"
|
||||
? "disallowed_origin"
|
||||
: "unsupported_url",
|
||||
}),
|
||||
);
|
||||
expect(observation.completeness.policy_filtered_sections).toContain(
|
||||
"timeline",
|
||||
);
|
||||
}
|
||||
const serialized = JSON.stringify(observation);
|
||||
expect(serialized).not.toContain("discard-redirect-");
|
||||
expect(serialized).not.toContain("outside.invalid");
|
||||
},
|
||||
);
|
||||
},
|
||||
}));
|
||||
},
|
||||
);
|
||||
|
||||
expect(observation.window.end_reason).toBe("window_elapsed");
|
||||
expect(
|
||||
observation.timeline
|
||||
.filter(({ type }) => type === "redirect")
|
||||
.map(({ request_id, redirect_response }) => ({
|
||||
request_id,
|
||||
redirect_response,
|
||||
})),
|
||||
).toEqual(
|
||||
redirectCases.map(({ name, expected }) => ({
|
||||
request_id: name,
|
||||
redirect_response: expected(browser.allowedOrigin),
|
||||
})),
|
||||
);
|
||||
|
||||
const timelineExclusions = observation.completeness.excluded.filter(
|
||||
({ section }) => section === "timeline",
|
||||
);
|
||||
expect(timelineExclusions).toHaveLength(3);
|
||||
expect(timelineExclusions).toEqual(
|
||||
expect.arrayContaining([
|
||||
{ section: "timeline", reason: "invalid_protocol_value", count: 7 },
|
||||
{ section: "timeline", reason: "disallowed_origin", count: 1 },
|
||||
{ section: "timeline", reason: "unsupported_url", count: 1 },
|
||||
]),
|
||||
);
|
||||
expect(observation.completeness.policy_filtered_sections).toContain(
|
||||
"timeline",
|
||||
);
|
||||
const serialized = JSON.stringify(observation);
|
||||
expect(serialized).not.toContain("discard-redirect-");
|
||||
expect(serialized).not.toContain("outside.invalid");
|
||||
});
|
||||
-12
@@ -271,7 +271,6 @@ const emitSessionTimeline = (
|
||||
: `http://127.0.0.1:${String(port)}/redirected?token=redirect-secret`;
|
||||
event(socket, "Network.requestWillBeSent", command.sessionId, {
|
||||
requestId: "document-request",
|
||||
type: options.sessionRedirectResourceType,
|
||||
frameId: "frame-main",
|
||||
loaderId: "loader-redirect",
|
||||
request: { url: redirectUrl, method: "GET" },
|
||||
@@ -300,17 +299,6 @@ const emitSessionTimeline = (
|
||||
name: "networkIdle",
|
||||
timestamp: 15,
|
||||
});
|
||||
for (
|
||||
let index = 0;
|
||||
index < (options.sessionTimelineEventCount ?? 0);
|
||||
index += 1
|
||||
)
|
||||
event(socket, "Page.lifecycleEvent", command.sessionId, {
|
||||
frameId: "frame-main",
|
||||
loaderId: "loader-reload",
|
||||
name: `lifecycle-${String(index)}`,
|
||||
timestamp: 16 + index,
|
||||
});
|
||||
if (options.sessionTimeline === "target_detached")
|
||||
event(socket, "Target.detachedFromTarget", undefined, {
|
||||
sessionId: command.sessionId,
|
||||
|
||||
-2
@@ -110,8 +110,6 @@ export interface FakeOptions {
|
||||
| "outside_policy"
|
||||
| "target_detached"
|
||||
| "target_crashed";
|
||||
readonly sessionTimelineEventCount?: number;
|
||||
readonly sessionRedirectResourceType?: "Document" | "Fetch" | "Script";
|
||||
readonly closeAfterMethod?: string;
|
||||
readonly sensitiveShapes?: boolean;
|
||||
/** Deliver a console argument the protocol spells as `{ type: "object", subtype: "null" }`. */
|
||||
|
||||
Reference in new issue
Block a user