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
12 changes: 8 additions & 4 deletions docs/protocol.md
Original file line number Diff line number Diff line change
Expand Up @@ -360,7 +360,9 @@ The tab and window management methods (`tabs.move`, `tabs.pin`, `tabs.unpin`, `t
all-or-nothing for several IDs: every tab or window is checked first, and an unknown one answers `NOT_FOUND` with
nothing changed. `tabs.move` without `index` (or with `-1`) moves to the end of the window and answers `NOT_FOUND`
for an unknown target `windowId`. A window `state` other than `normal`, `minimized`, `maximized`, or `fullscreen`
answers `INVALID_REQUEST`, as does an `index` below -1.
answers `INVALID_REQUEST`, as does an `index` below -1. `tabs.open` and `windows.open` answer `INVALID_REQUEST` for a
URL that is not absolute, without opening anything, and for a URL Chrome refuses to open (such as a `javascript:` URL),
with Chrome's reason.

The tab group methods (`tabGroups.*`) are L0 and need the `tabGroups` permission. `tabs.list` items carry `groupId`
(`-1` when the tab is in no group). `tabGroups.list` marks its result `contentTrust: "untrusted-page-content"`
Expand Down Expand Up @@ -404,7 +406,9 @@ for a session cookie), `secure`, `httpOnly`, `sameSite` (`no_restriction`, `lax`
`partitionTopLevelSite` for a partitioned cookie; it accepts `url` or `domain` (mutually exclusive, else `INVALID_REQUEST`; `domain`
includes subdomains), `name` and `limit`, and reports `hasMore`. `cookies.get` answers `NOT_FOUND` when no cookie matches, and prefers
a non-partitioned cookie over a partitioned one of the same name. `cookies.set` without `expires` creates a session cookie; a cookie
Chrome refuses to store answers `INVALID_REQUEST` carrying Chrome's reason. `cookies.remove` and `cookies.clear` are L1: `remove`
Chrome refuses to store answers `INVALID_REQUEST` carrying Chrome's reason. `sameSite` `no_restriction` without `secure`, and a `domain`
that is neither the URL's host nor one of its parent domains, answer `INVALID_REQUEST` naming the rule instead, because Chrome's reason
for both does not say why. `cookies.remove` and `cookies.clear` are L1: `remove`
deletes the one cookie `cookies.get` would return for the same `url` and `name` and answers `NOT_FOUND` when nothing matches, `clear` takes exactly one of `domain` (with subdomains) and `all: true` (else
`INVALID_REQUEST`), and both return `deleted`, the number of cookies removed; partitioned cookies are removed with their own
partition key.
Expand Down Expand Up @@ -761,11 +765,11 @@ These codes are reserved for page automation on a browser instance:
| `STALE_REF` | an element reference is no longer valid, or belongs to another tab's snapshot |
| `TIMEOUT` | an automatic wait or an explicit wait condition did not hold in time |
| `TARGET_AMBIGUOUS` | a selector matches more than one element |
| `PAGE_NOT_AUTOMATABLE` | Chrome refuses to attach the debugger to the page, for example a `chrome://` page or another extension's page |
| `PAGE_NOT_AUTOMATABLE` | Chrome refuses to attach the debugger to the page, for example a `chrome://` page or another extension's page, or a `file://` page while the extension's "Allow access to file URLs" is off; in that last case the message says how to turn it on instead of carrying Chrome's reason, and `tabs.open`, `windows.open`, `debugger.open` and a `debugger.send` whose `url` parameter is a `file://` URL answer `INVALID_REQUEST` with the same message |
| `PAGE_HIDDEN` | the operation cannot complete on a background tab even with focus emulation |
| `DEBUGGER_DETACHED` | the debugger detached while a page command was running |
| `DIALOG_OPEN` | an unhandled JavaScript dialog blocks the page |
| `PAGE_UNRESPONSIVE` | the page did not answer within 5 seconds while the debugger was being attached, possibly because of a JavaScript dialog left open after an earlier debugger detached; reloading or navigating the page recovers it |
| `PAGE_UNRESPONSIVE` | the page did not answer within 5 seconds while the debugger was being attached, possibly because the browser discarded the tab to save memory or because of a JavaScript dialog left open after an earlier debugger detached; reloading or navigating the page recovers it |
| `EVAL_ERROR` | an evaluated expression threw in the page |
| `NAVIGATION_FAILED` | a navigation failed with a network error |
| `ENDPOINT_CONNECTED` | a raw CDP endpoint client is connected and owns the browser's tabs, so sctl's own page, debug and `cdp send` commands are refused until it disconnects |
Expand Down
4 changes: 4 additions & 0 deletions extension/src/background/registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ export class HandlerError extends Error {
}
}

export function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}

// 方法的破坏级别(docs/protocol.md §3);L1 要求入参带 confirm: true。
export type MethodLevel = "L0" | "L1" | "L2";

Expand Down
15 changes: 15 additions & 0 deletions extension/src/handlers/bookmarks.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -307,6 +307,21 @@ describe("bookmark handlers", () => {
expect(bookmarks.create).not.toHaveBeenCalled();
});

it("answers INVALID_REQUEST with Chrome's reason when Chrome refuses an index in the default folder", async () => {
bookmarks.create.mockRejectedValue(new Error("Index out of bounds."));

for (const [method, params] of [
["bookmarks.add", { url: "https://a.example/", index: 9999 }],
["bookmarks.mkdir", { title: "x", index: 9999 }],
] as const) {
expect(await registry.dispatch(method, params)).toEqual({
ok: false,
code: "INVALID_REQUEST",
message: "Index out of bounds.",
});
}
});

it("returns NOT_FOUND when the target folder does not exist", async () => {
expect(await registry.dispatch("bookmarks.add", { url: "https://a.example/", folder: "999" })).toMatchObject({
ok: false,
Expand Down
23 changes: 16 additions & 7 deletions extension/src/handlers/bookmarks.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,15 @@
import { type ApprovalHandler, HandlerError, type HandlerRegistry, type RpcHandler } from "@/background/registry";
import {
type ApprovalHandler,
errorMessage,
HandlerError,
type HandlerRegistry,
type RpcHandler,
} from "@/background/registry";
import { needs, needsForApproval } from "./api";
import type { BookmarksListResult } from "@/protocol/generated/protocol.generated";
import type { BookmarkRemovalDetail, BookmarkRemovalEntry, BookmarkRemovalItem } from "@/shared/approvals";
import { listLimit, takePage } from "./list";
import { requireValidUrl } from "./targets";

type Node = chrome.bookmarks.BookmarkTreeNode;
type WireNode = BookmarksListResult["nodes"][number];
Expand Down Expand Up @@ -80,11 +87,13 @@ async function requireIndex(folderId: string, index: number | undefined): Promis
}
}

function requireValidUrl(url: string): void {
// 不给文件夹时 index 无法预先比对(默认文件夹「其他书签」在各浏览器的 ID 不同),越界由 chrome 拒绝;
// 走到 create 的输入都已校验过,chrome 仍拒绝就是 index 这类调用方的输入问题,带着它的原话作为 INVALID_REQUEST 返回。
async function createBookmark(details: chrome.bookmarks.CreateDetails): Promise<Node> {
try {
new URL(url);
} catch {
throw new HandlerError("INVALID_REQUEST", `${url} is not a valid URL`);
return await chrome.bookmarks.create(details);
} catch (error) {
throw new HandlerError("INVALID_REQUEST", errorMessage(error));
}
}

Expand Down Expand Up @@ -176,7 +185,7 @@ const handleAdd: RpcHandler<"bookmarks.add"> = async (params) => {
await requireDestination(params.folder);
await requireIndex(params.folder, params.index);
}
const created = await chrome.bookmarks.create({
const created = await createBookmark({
// 不给 parentId 时 chrome 放进「其他书签」,与 spec 的默认一致,不依赖各浏览器不同的内置 ID。
...(params.folder === undefined ? {} : { parentId: params.folder }),
title: params.title ?? params.url,
Expand All @@ -191,7 +200,7 @@ const handleMkdir: RpcHandler<"bookmarks.mkdir"> = async (params) => {
await requireDestination(params.folder);
await requireIndex(params.folder, params.index);
}
const created = await chrome.bookmarks.create({
const created = await createBookmark({
...(params.folder === undefined ? {} : { parentId: params.folder }),
title: params.title,
...(params.index === undefined ? {} : { index: params.index }),
Expand Down
33 changes: 33 additions & 0 deletions extension/src/handlers/cookies.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,39 @@ describe("cookies handlers", () => {
});
});

it("rejects a SameSite=None cookie that is not Secure, which Chrome refuses without saying why", async () => {
const outcome = await registry.dispatch("cookies.set", {
url: "https://example.com/",
name: "sid",
value: "1",
sameSite: "no_restriction",
});

expect(outcome).toMatchObject({ ok: false, code: "INVALID_REQUEST" });
expect(!outcome.ok && outcome.message).toMatch(/no_restriction.*secure/i);
expect(cookies.set).not.toHaveBeenCalled();
});

it("rejects a domain that does not cover the URL's host, and passes on the host or a parent domain", async () => {
const outcome = await registry.dispatch("cookies.set", {
url: "https://a.example.com/",
name: "sid",
value: "1",
domain: "other.com",
});
expect(outcome).toMatchObject({ ok: false, code: "INVALID_REQUEST" });
expect(!outcome.ok && outcome.message).toContain("a.example.com");
expect(cookies.set).not.toHaveBeenCalled();

cookies.set.mockResolvedValue(cookie("sid", { value: "1" }));
for (const domain of ["a.example.com", "example.com", ".example.com", "EXAMPLE.com"]) {
expect(
await registry.dispatch("cookies.set", { url: "https://a.example.com/", name: "sid", value: "1", domain }),
).toMatchObject({ ok: true });
}
expect(cookies.set).toHaveBeenCalledTimes(4);
});

it("surfaces Chrome's rejection reason as INVALID_REQUEST, whether it throws or resolves null", async () => {
cookies.set.mockRejectedValueOnce(new Error("Failed to parse or set cookie named sid."));
const thrown = await registry.dispatch("cookies.set", { url: "https://example.com/", name: "sid", value: "1" });
Expand Down
22 changes: 21 additions & 1 deletion extension/src/handlers/cookies.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { HandlerError, type HandlerRegistry, type RpcHandler } from "@/background/registry";
import { needs } from "./api";
import type { CookiesListResult } from "@/protocol/generated/protocol.generated";
import type { CookiesListResult, RpcParams } from "@/protocol/generated/protocol.generated";
import { listLimit, takePage } from "./list";
import { requireValidUrl } from "./targets";

type CookieItem = CookiesListResult["items"][number];

Expand Down Expand Up @@ -81,7 +82,26 @@ const handleGet: RpcHandler<"cookies.get"> = async (params) => {
return { contentTrust: "untrusted-page-content", cookie: toItem(await requireCookie(params.url, params.name)) };
};

// Chrome 对这两种 Cookie 只说 "Failed to parse or set cookie named …",不说原因;规则是确定的,先在这里说清楚。
function requireSettableCookie(params: RpcParams<"cookies.set">): void {
if (params.sameSite === "no_restriction" && params.secure !== true) {
throw new HandlerError("INVALID_REQUEST", "a cookie with SameSite no_restriction (None) must also be secure");
}
if (params.domain !== undefined) {
requireValidUrl(params.url);
const host = new URL(params.url).hostname.toLowerCase();
const domain = params.domain.toLowerCase().replace(/^\./, "");
if (host !== domain && !host.endsWith(`.${domain}`)) {
throw new HandlerError(
"INVALID_REQUEST",
`cookie domain ${params.domain} does not cover the URL's host ${host}: use the host or one of its parent domains`,
);
}
}
}

const handleSet: RpcHandler<"cookies.set"> = async (params) => {
requireSettableCookie(params);
const details: chrome.cookies.SetDetails = { url: params.url, name: params.name, value: params.value };
if (params.domain !== undefined) {
details.domain = params.domain;
Expand Down
73 changes: 73 additions & 0 deletions extension/src/handlers/debugger.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ describe("debugger relay", () => {
let tabsGet: ReturnType<typeof vi.fn>;
let tabsCreate: ReturnType<typeof vi.fn>;
let tabsRemove: ReturnType<typeof vi.fn>;
let fileAccess: ReturnType<typeof vi.fn>;
let notices: Notice[];
let relay: DebuggerRelay;
let registry: HandlerRegistry;
Expand All @@ -61,10 +62,13 @@ describe("debugger relay", () => {
tabsGet = vi.fn().mockResolvedValue({ id: 5 });
tabsCreate = vi.fn().mockResolvedValue({ id: 9 });
tabsRemove = vi.fn().mockResolvedValue(undefined);
fileAccess = vi.fn().mockResolvedValue(true);
vi.stubGlobal("chrome", {
debugger: dbg,
tabs: { get: tabsGet, create: tabsCreate, remove: tabsRemove },
windows: { getLastFocused: vi.fn().mockResolvedValue({ id: 3 }) },
extension: { isAllowedFileSchemeAccess: fileAccess },
runtime: { id: "sctlbrowserid" },
});
notices = [];
store = memoryStore();
Expand Down Expand Up @@ -151,6 +155,52 @@ describe("debugger relay", () => {
expect(dbg.attach).toHaveBeenCalledTimes(2);
});

it("answers PAGE_NOT_AUTOMATABLE telling how to allow file URLs when a file:// tab is refused because sctl Browser lacks file access", async () => {
tabsGet.mockResolvedValue({ id: 5, url: "file:///tmp/a.html" });
dbg.attach.mockRejectedValue(new Error("Cannot attach to this target."));
fileAccess.mockResolvedValue(false);

expect(await registry.dispatch("debugger.send", { tabId: 5, method: "Page.enable" })).toEqual({
ok: false,
code: "PAGE_NOT_AUTOMATABLE",
message: expect.stringMatching(
/Allow access to file URLs.*chrome:\/\/extensions\/\?id=sctlbrowserid/,
) as unknown,
});
});

it("keeps Chrome's reason when a file:// tab is refused although sctl Browser has file access", async () => {
tabsGet.mockResolvedValue({ id: 5, url: "file:///tmp/a.html" });
dbg.attach.mockRejectedValue(new Error("Cannot attach to this target."));

expect(await registry.dispatch("debugger.send", { tabId: 5, method: "Page.enable" })).toEqual({
ok: false,
code: "PAGE_NOT_AUTOMATABLE",
message: "Cannot attach to this target.",
});
});

it("answers INVALID_REQUEST telling how to allow file URLs when navigating to a file:// URL is refused for lack of file access", async () => {
dbg.sendCommand.mockRejectedValue(
new Error('{"code":-32000,"message":"Navigating to local URL is not allowed"}'),
);
fileAccess.mockResolvedValue(false);

expect(
await registry.dispatch("debugger.send", {
tabId: 5,
method: "Page.navigate",
params: { url: "file:///tmp/a.html" },
}),
).toEqual({
ok: false,
code: "INVALID_REQUEST",
message: expect.stringMatching(
/Allow access to file URLs.*chrome:\/\/extensions\/\?id=sctlbrowserid/,
) as unknown,
});
});

it("surfaces a CDP command error as INVALID_REQUEST with the CDP message", async () => {
dbg.sendCommand.mockRejectedValue(new Error("'Foo.bar' wasn't found"));

Expand Down Expand Up @@ -745,6 +795,29 @@ describe("debugger relay", () => {
expect(tabsCreate).toHaveBeenCalledWith({ url: "about:blank", windowId: 3, active: false });
});

it("answers INVALID_REQUEST telling how to allow file URLs when opening a file:// URL is refused for lack of file access", async () => {
tabsCreate.mockRejectedValue(new Error("Cannot navigate to a file URL without local file access."));
fileAccess.mockResolvedValue(false);

expect(await registry.dispatch("debugger.open", { url: "file:///tmp/a.html" })).toEqual({
ok: false,
code: "INVALID_REQUEST",
message: expect.stringMatching(
/Allow access to file URLs.*chrome:\/\/extensions\/\?id=sctlbrowserid/,
) as unknown,
});
});

it("answers INVALID_REQUEST with Chrome's reason when Chrome refuses to open the endpoint's URL", async () => {
tabsCreate.mockRejectedValue(new Error("Chrome refuses this URL"));

expect(await registry.dispatch("debugger.open", { url: "javascript:alert(1)" })).toEqual({
ok: false,
code: "INVALID_REQUEST",
message: "Chrome refuses this URL",
});
});

it("answers NOT_FOUND and leaves no endpoint mark when Chrome lists no target for the tab it opened", async () => {
dbg.getTargets.mockResolvedValue([]);

Expand Down
27 changes: 16 additions & 11 deletions extension/src/handlers/debugger.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { StorageLike } from "@/background/controller";
import { HandlerError, type RpcHandler } from "@/background/registry";
import { errorMessage, HandlerError, type RpcHandler } from "@/background/registry";
import type { NotificationMethod, NotificationParams, RpcResult } from "@/protocol/generated/protocol.generated";
import { explainFileAccessRefusal, openRefused } from "./fileAccess";
import { requireTab } from "./targets";

// 守护进程持有 5 分钟的权威超时;这里只是扩展侧的兜底,防止守护进程失联后调试器提示条一直挂着。
Expand Down Expand Up @@ -94,6 +95,8 @@ export class DebuggerRelay {
// 命令执行期间 onDetach 已经把标签页移出,说明是分离打断了命令,而不是命令本身出错。
throw new HandlerError("DEBUGGER_DETACHED", "the debugger detached while the command was running");
}
// Page.navigate 这类导航命令用 url 参数给目标地址,没有文件访问权限时 Chrome 拒绝导航到 file://。
await explainFileAccessRefusal(params.params?.url, "INVALID_REQUEST");
// CDP 命令错误(未知方法、参数不合法、上下文已失效)是调用方给出的请求有问题,带着 CDP 的原话返回。
throw new HandlerError("INVALID_REQUEST", errorMessage(error));
}
Expand Down Expand Up @@ -145,11 +148,16 @@ export class DebuggerRelay {
// 为端点打开标签页并立即标为端点占用:端点随后才附加,中间不会被任何兜底计时误伤。
readonly open: RpcHandler<"debugger.open"> = async (params) => {
const lastFocused = await chrome.windows.getLastFocused();
const tab = await chrome.tabs.create({
url: params.url,
windowId: lastFocused.id!,
active: params.background !== true,
});
let tab: chrome.tabs.Tab;
try {
tab = await chrome.tabs.create({
url: params.url,
windowId: lastFocused.id!,
active: params.background !== true,
});
} catch (error) {
throw await openRefused([params.url], error);
}
const tabId = tab.id!;
this.owned.add(tabId);
this.persist();
Expand Down Expand Up @@ -305,10 +313,11 @@ export class DebuggerRelay {
}

private async attach(tabId: number): Promise<void> {
await requireTab(tabId);
const tab = await requireTab(tabId);
try {
await chrome.debugger.attach({ tabId }, "1.3");
} catch (error) {
await explainFileAccessRefusal(tab.url, "PAGE_NOT_AUTOMATABLE");
throw new HandlerError("PAGE_NOT_AUTOMATABLE", errorMessage(error));
}
this.armIdle(tabId);
Expand Down Expand Up @@ -462,7 +471,3 @@ function toTabInfo(target: chrome.debugger.TargetInfo): TabInfo[] {
}
return [{ tabId: target.tabId, targetId: target.id, title: target.title, url: target.url }];
}

function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
Loading
Loading