Skip to content

armgit / Pake

Public Imported from GitHub
0

Turn any website into a lightweight desktop app with one command, on macOS, Windows and Linux.

fix: route iframe external links and avoid recursive find scans

Tw935cf394f9512c
diff --git a/src-tauri/src/app/window.rs b/src-tauri/src/app/window.rs
index 2a55c2bc..02ccc3df 100644
--- a/src-tauri/src/app/window.rs
+++ b/src-tauri/src/app/window.rs
@@ -497,7 +497,11 @@ fn build_window(
// any script that reads it (e.g. fullscreen polyfill checks for an opt-out
// flag), and toast must register `window.pakeToast` before Rust code
// calls show_toast().
- window_builder = window_builder.initialization_script(&config_script);
+ window_builder = window_builder
+ .initialization_script_for_all_frames(&config_script)
+ .initialization_script_for_all_frames(include_str!("../inject/link_policy.js"))
+ .initialization_script_for_all_frames(include_str!("../inject/auth.js"))
+ .initialization_script_for_all_frames(include_str!("../inject/frame_links.js"));
// find.js is opt-in via --enable-find and no-ops at runtime when disabled,
// so only inject its ~700 lines when the feature is on. Avoids parsing the
@@ -513,7 +517,6 @@ fn build_window(
.initialization_script(include_str!("../inject/event.js"))
.initialization_script(include_str!("../inject/style.js"))
.initialization_script(include_str!("../inject/theme_refresh.js"))
- .initialization_script(include_str!("../inject/auth.js"))
.initialization_script(include_str!("../inject/custom.js"));
#[cfg(target_os = "windows")]
diff --git a/src-tauri/src/inject/event.js b/src-tauri/src/inject/event.js
index c8b9ac44..6aa2c2b6 100644
--- a/src-tauri/src/inject/event.js
+++ b/src-tauri/src/inject/event.js
@@ -529,52 +529,6 @@ function isDownloadableFile(url) {
}
}
-// Public suffixes where the registrable domain needs more than two labels.
-// Not exhaustive; covers common packaging targets that last-two-label
-// matching would collapse incorrectly (e.g. amazon.co.uk vs evil.co.uk,
-// or every *.github.io site into one "domain").
-const MULTI_PART_PUBLIC_SUFFIXES = [
- "co.uk",
- "org.uk",
- "ac.uk",
- "gov.uk",
- "com.au",
- "net.au",
- "org.au",
- "co.jp",
- "ne.jp",
- "or.jp",
- "co.kr",
- "co.in",
- "com.br",
- "com.cn",
- "com.tw",
- "com.hk",
- "com.sg",
- "github.io",
- "gitlab.io",
- "pages.dev",
-];
-
-function getRootDomain(hostname) {
- const normalized = String(hostname || "").toLowerCase();
- if (!normalized) {
- return "";
- }
-
- const parts = normalized.split(".").filter(Boolean);
- if (parts.length <= 1) {
- return normalized;
- }
-
- const lastTwo = parts.slice(-2).join(".");
- if (MULTI_PART_PUBLIC_SUFFIXES.includes(lastTwo) && parts.length >= 3) {
- return parts.slice(-3).join(".");
- }
-
- return lastTwo;
-}
-
function normalizeAnchorHref(rawHref) {
return typeof rawHref === "string" ? rawHref.trim() : "";
}
@@ -642,21 +596,55 @@ function openAuthNavigation(originalWindowOpen, url, name, specs) {
return authWindow;
}
+// Install the receiver at document start: a subframe can open a link before
+// the main page's DOMContentLoaded routing setup has run.
+let openFrameLink = null;
+const pendingFrameLinks = [];
+function isDescendantFrame(source, parent = window) {
+ for (let index = 0; index < parent.frames.length; index++) {
+ const frame = parent.frames[index];
+ if (frame === source || isDescendantFrame(source, frame)) return true;
+ }
+ return false;
+}
+function routeFrameLink(source, href) {
+ try {
+ // Recheck on delivery because the frame may have been removed meanwhile.
+ if (!isDescendantFrame(source)) return;
+ const url = new URL(href);
+ if (!["http:", "https:", "mailto:", "tel:"].includes(url.protocol)) return;
+ if (openFrameLink) {
+ openFrameLink.call(window, url.href, "_blank");
+ } else {
+ pendingFrameLinks.push({ source, href: url.href });
+ }
+ } catch (error) {
+ console.error("[Pake] Failed to route frame link:", error);
+ }
+}
+window.addEventListener("message", (event) => {
+ if (
+ event.data?.type !== "pake:frame-external-link" ||
+ typeof event.data.url !== "string" ||
+ !event.source ||
+ event.source === window
+ )
+ return;
+ routeFrameLink(event.source, event.data.url);
+});
+window.addEventListener("pagehide", () => {
+ pendingFrameLinks.length = 0;
+});
+
document.addEventListener("DOMContentLoaded", () => {
const tauri = window.__TAURI__;
const appWindow = tauri.window.getCurrentWindow();
const invoke = tauri.core.invoke;
const pakeConfig = window["pakeConfig"] || {};
const forceInternalNavigation = pakeConfig.force_internal_navigation === true;
- const internalUrlRegex = pakeConfig.internal_url_regex || "";
- let internalUrlPattern = null;
- if (internalUrlRegex) {
- try {
- internalUrlPattern = new RegExp(internalUrlRegex);
- } catch (e) {
- console.error("[Pake] Invalid internal_url_regex pattern:", e);
- }
- }
+ const matchesInternalUrl = createInternalUrlMatcher(
+ pakeConfig.internal_url_regex,
+ );
if (!document.getElementById("pake-top-dom") && hasImmersiveHeader()) {
const topDom = document.createElement("div");
@@ -731,39 +719,7 @@ document.addEventListener("DOMContentLoaded", () => {
});
};
- // Check if URL belongs to the same domain (including subdomains)
- const isSameDomain = (url) => {
- try {
- const linkUrl = new URL(url);
- const currentUrl = new URL(window.location.href);
-
- if (linkUrl.hostname === currentUrl.hostname) return true;
-
- // e.g. www.bilibili.com and m.bilibili.com share bilibili.com;
- // amazon.co.uk must not share a root with evil.co.uk.
- return (
- getRootDomain(currentUrl.hostname) === getRootDomain(linkUrl.hostname)
- );
- } catch (e) {
- return false;
- }
- };
-
- // Check if URL should be treated as internal based on regex pattern or domain
- const isInternalUrl = (url) => {
- // If regex pattern is configured, use it as the primary check
- if (internalUrlPattern) {
- try {
- return internalUrlPattern.test(url);
- } catch (e) {
- console.error("[Pake] Error testing internal_url_regex:", e);
- // Fall back to domain check on error
- return isSameDomain(url);
- }
- }
- // Default to domain-based check
- return isSameDomain(url);
- };
+ const isInternalUrl = (url) => matchesInternalUrl(url, window.location.href);
const detectAnchorElementClick = (e) => {
// Safety check: ensure e.target exists and is an Element with closest method
@@ -947,6 +903,23 @@ document.addEventListener("DOMContentLoaded", () => {
}
};
+ // The sender is untrusted even when it belongs to this webview. This bridge
+ // may only open external links, never navigate the top page or create auth
+ // windows on a sandboxed frame's behalf.
+ openFrameLink = (url) => {
+ if (
+ forceInternalNavigation ||
+ isInternalUrl(url) ||
+ window.isAuthLink(url)
+ ) {
+ return;
+ }
+ handleExternalLink(url);
+ };
+ for (const { source, href } of pendingFrameLinks.splice(0)) {
+ routeFrameLink(source, href);
+ }
+
// Set the default zoom, There are problems with Loop without using try-catch.
try {
setDefaultZoom();
diff --git a/src-tauri/src/inject/find.js b/src-tauri/src/inject/find.js
index 6c09dd34..e171ec8e 100644
--- a/src-tauri/src/inject/find.js
+++ b/src-tauri/src/inject/find.js
@@ -522,29 +522,39 @@
}
function runSearch(query = state.query) {
+ clearTimeout(state.searchTimer);
state.query = query;
- clearHighlights();
+ // A full scan includes any pending page edits. Disconnect while replacing
+ // DOM marks so our own mutations cannot schedule another search.
+ stopObservingDocumentChanges();
+ try {
+ clearHighlights();
+
+ if (!query) {
+ state.matches = [];
+ state.activeIndex = -1;
+ state.truncated = false;
+ updateCounter();
+ return getState();
+ }
- if (!query) {
- state.matches = [];
- state.activeIndex = -1;
- state.truncated = false;
- updateCounter();
- return getState();
- }
+ const result = collectMatches(query);
+ state.matches = result.matches;
+ state.truncated = result.truncated;
+ state.activeIndex = state.matches.length > 0 ? 0 : -1;
- const result = collectMatches(query);
- state.matches = result.matches;
- state.truncated = result.truncated;
- state.activeIndex = state.matches.length > 0 ? 0 : -1;
+ if (!applyCustomHighlights()) {
+ applyDomHighlights();
+ }
- if (!applyCustomHighlights()) {
- applyDomHighlights();
+ updateCounter();
+ scrollActiveIntoView();
+ return getState();
+ } finally {
+ if (state.isOpen) {
+ observeDocumentChanges();
+ }
}
-
- updateCounter();
- scrollActiveIntoView();
- return getState();
}
function debounceSearch(query) {
diff --git a/src-tauri/src/inject/frame_links.js b/src-tauri/src/inject/frame_links.js
new file mode 100644
index 00000000..c781a4a4
--- /dev/null
+++ b/src-tauri/src/inject/frame_links.js
@@ -0,0 +1,62 @@
+// Subframes do not receive the main page's Tauri/event injection on WebKit.
+// Forward only known external destinations; native internal/auth/blank popup
+// behavior, including its WindowProxy return value, stays with the frame.
+(function () {
+ if (window === window.top) return;
+ const config = window.pakeConfig || {};
+ if (config.force_internal_navigation === true) return;
+ const isInternalUrl = createInternalUrlMatcher(config.internal_url_regex);
+ const originalOpen = window.open;
+
+ function externalDestination(rawUrl, name) {
+ if (
+ typeof rawUrl !== "string" ||
+ !rawUrl.trim() ||
+ rawUrl.trim().startsWith("#")
+ ) {
+ return null;
+ }
+ try {
+ const url = new URL(rawUrl, document.baseURI);
+ if (!["http:", "https:", "mailto:", "tel:"].includes(url.protocol))
+ return null;
+ if (window.isAuthPopup(url.href, name)) return null;
+ if (isInternalUrl(url.href, config.url)) return null;
+ return url.href;
+ } catch (error) {
+ return null;
+ }
+ }
+
+ function forward(url) {
+ window.top.postMessage({ type: "pake:frame-external-link", url }, "*");
+ }
+
+ window.open = function (url, name, specs) {
+ // Named targets can navigate an existing frame and must retain its proxy.
+ if (name && String(name).toLowerCase() !== "_blank") {
+ return originalOpen.call(window, url, name, specs);
+ }
+ const external = externalDestination(url, name);
+ if (!external) return originalOpen.call(window, url, name, specs);
+ forward(external);
+ return null;
+ };
+
+ document.addEventListener(
+ "click",
+ (event) => {
+ const anchor = event.target?.closest?.("a[href]");
+ if (!anchor || anchor.hasAttribute("download")) return;
+ // Named browsing contexts may be part of the page's own frame layout.
+ if (anchor.target && !["_blank", "_new", "_self"].includes(anchor.target))
+ return;
+ const external = externalDestination(anchor.getAttribute("href"), "");
+ if (!external) return;
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ forward(external);
+ },
+ true,
+ );
+})();
diff --git a/src-tauri/src/inject/link_policy.js b/src-tauri/src/inject/link_policy.js
new file mode 100644
index 00000000..0735752f
--- /dev/null
+++ b/src-tauri/src/inject/link_policy.js
@@ -0,0 +1,60 @@
+// Shared by the main page and the lightweight subframe bridge.
+// This list intentionally preserves Pake's existing domain routing policy.
+const MULTI_PART_PUBLIC_SUFFIXES = [
+ "co.uk",
+ "org.uk",
+ "ac.uk",
+ "gov.uk",
+ "com.au",
+ "net.au",
+ "org.au",
+ "co.jp",
+ "ne.jp",
+ "or.jp",
+ "co.kr",
+ "co.in",
+ "com.br",
+ "com.cn",
+ "com.tw",
+ "com.hk",
+ "com.sg",
+ "github.io",
+ "gitlab.io",
+ "pages.dev",
+];
+
+function getRootDomain(hostname) {
+ const normalized = String(hostname || "").toLowerCase();
+ if (!normalized) return "";
+ const parts = normalized.split(".").filter(Boolean);
+ if (parts.length <= 1) return normalized;
+ const lastTwo = parts.slice(-2).join(".");
+ if (MULTI_PART_PUBLIC_SUFFIXES.includes(lastTwo) && parts.length >= 3) {
+ return parts.slice(-3).join(".");
+ }
+ return lastTwo;
+}
+
+function createInternalUrlMatcher(pattern) {
+ let regex = null;
+ if (pattern) {
+ try {
+ regex = new RegExp(pattern);
+ } catch (error) {
+ console.error("[Pake] Invalid internal_url_regex pattern:", error);
+ }
+ }
+ return (url, baseUrl) => {
+ if (regex) return regex.test(url);
+ try {
+ const target = new URL(url);
+ const current = new URL(baseUrl);
+ return (
+ target.hostname === current.hostname ||
+ getRootDomain(target.hostname) === getRootDomain(current.hostname)
+ );
+ } catch (error) {
+ return false;
+ }
+ };
+}
diff --git a/tests/unit/event-clipboard-shortcuts.test.js b/tests/unit/event-clipboard-shortcuts.test.js
index cc509ccb..6eaf9645 100644
--- a/tests/unit/event-clipboard-shortcuts.test.js
+++ b/tests/unit/event-clipboard-shortcuts.test.js
@@ -33,10 +33,14 @@ function loadEventHelpers({
clipboardReadRejects = false,
userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64)",
} = {}) {
- const source = fs.readFileSync(
- path.join(process.cwd(), "src-tauri/src/inject/event.js"),
- "utf-8",
- );
+ const source = ["link_policy.js", "event.js"]
+ .map((file) =>
+ fs.readFileSync(
+ path.join(process.cwd(), "src-tauri/src/inject", file),
+ "utf-8",
+ ),
+ )
+ .join("\n");
const eventListeners = {};
const elementsById = new Map();
diff --git a/tests/unit/event-fullscreen-shortcuts.test.js b/tests/unit/event-fullscreen-shortcuts.test.js
index 5b68cb40..274ff532 100644
--- a/tests/unit/event-fullscreen-shortcuts.test.js
+++ b/tests/unit/event-fullscreen-shortcuts.test.js
@@ -34,10 +34,14 @@ function loadEventHelpers({
hideTitleBar = false,
hideWindowDecorations = false,
} = {}) {
- const source = fs.readFileSync(
- path.join(process.cwd(), "src-tauri/src/inject/event.js"),
- "utf-8",
- );
+ const source = ["link_policy.js", "event.js"]
+ .map((file) =>
+ fs.readFileSync(
+ path.join(process.cwd(), "src-tauri/src/inject", file),
+ "utf-8",
+ ),
+ )
+ .join("\n");
const eventListeners = {};
const elementsById = new Map();
diff --git a/tests/unit/event-link-guard.test.js b/tests/unit/event-link-guard.test.js
index 1ef5021f..f11f1921 100644
--- a/tests/unit/event-link-guard.test.js
+++ b/tests/unit/event-link-guard.test.js
@@ -8,10 +8,14 @@ function loadEventHelpers({
userAgent = "Mozilla/5.0",
initialZoom = null,
} = {}) {
- const source = fs.readFileSync(
- path.join(process.cwd(), "src-tauri/src/inject/event.js"),
- "utf-8",
- );
+ const source = ["link_policy.js", "event.js"]
+ .map((file) =>
+ fs.readFileSync(
+ path.join(process.cwd(), "src-tauri/src/inject", file),
+ "utf-8",
+ ),
+ )
+ .join("\n");
const invokeCalls = [];
const invoke = (command, payload) => {
@@ -66,6 +70,7 @@ function loadEventHelpers({
language: "en-US",
},
window: {
+ frames: [],
history: {
back: () => {},
forward: () => {},
@@ -146,6 +151,124 @@ function makeClickEvent(anchor) {
}
describe("event link guard", () => {
+ it.each([
+ ["internal", "https://example.com/forced", {}],
+ ["auth", "https://accounts.google.com/o/oauth2/auth", {}],
+ [
+ "forced internal",
+ "https://outside.example/forced",
+ { force_internal_navigation: true },
+ ],
+ [
+ "regex internal",
+ "https://outside.example/forced",
+ { internal_url_regex: "outside\\.example" },
+ ],
+ ])(
+ "rejects forged %s frame messages without navigating or opening windows",
+ (_kind, url, config) => {
+ const context = loadEventHelpers({
+ withTauri: true,
+ userAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 15_5)",
+ });
+ context.window.pakeConfig = config;
+ context.window.isAuthLink = context.window.isAuthPopup = (value) =>
+ value.includes("accounts.google.com");
+ const nativeOpen = vi.fn(() => ({}));
+ context.window.open = nativeOpen;
+ runDomReady(context);
+ const frame = { frames: [] };
+ context.window.frames.push(frame);
+ context.eventListeners.message[0].handler({
+ source: frame,
+ data: { type: "pake:frame-external-link", url },
+ });
+ expect(context.window.location.href).toBe("https://example.com/app");
+ expect(nativeOpen).not.toHaveBeenCalled();
+ expect(
+ context.invokeCalls.filter(
+ ([command]) => command === "plugin:shell|open",
+ ),
+ ).toEqual([]);
+ },
+ );
+
+ it("routes early frame messages once after readiness and rechecks live sources", () => {
+ const context = loadEventHelpers({ withTauri: true });
+ const live = { frames: [] };
+ const removed = { frames: [] };
+ context.window.frames.push(live, removed);
+ const listener = context.eventListeners.message?.[0]?.handler;
+ expect(listener).toBeTypeOf("function");
+ for (const [source, suffix] of [
+ [live, "first"],
+ [live, "second"],
+ [removed, "removed"],
+ ]) {
+ listener({
+ source,
+ data: {
+ type: "pake:frame-external-link",
+ url: `https://outside.example/${suffix}`,
+ },
+ });
+ }
+ expect(context.invokeCalls).toEqual([]);
+ context.window.frames.pop();
+ runDomReady(context);
+ expect(
+ context.invokeCalls.filter(
+ ([command]) => command === "plugin:shell|open",
+ ),
+ ).toEqual([
+ ["plugin:shell|open", { path: "https://outside.example/first" }],
+ ["plugin:shell|open", { path: "https://outside.example/second" }],
+ ]);
+ expect(context.eventListeners.DOMContentLoaded).toHaveLength(1);
+ });
+
+ it("discards a departing document's queued frame messages", () => {
+ const context = loadEventHelpers({ withTauri: true });
+ const frame = { frames: [] };
+ context.window.frames.push(frame);
+ const listener = context.eventListeners.message?.[0]?.handler;
+ expect(listener).toBeTypeOf("function");
+ listener({
+ source: frame,
+ data: {
+ type: "pake:frame-external-link",
+ url: "https://outside.example/old",
+ },
+ });
+ context.eventListeners.pagehide[0].handler();
+ runDomReady(context);
+ expect(
+ context.invokeCalls.filter(
+ ([command]) => command === "plugin:shell|open",
+ ),
+ ).toEqual([]);
+ });
+
+ it("routes only descendant-frame messages with supported URL protocols", () => {
+ const context = loadEventHelpers({ withTauri: true });
+ runDomReady(context);
+ const frame = { frames: [] };
+ context.window.frames.push(frame);
+ const listener = context.eventListeners.message[0].handler;
+ const send = (source, url) =>
+ listener({ source, data: { type: "pake:frame-external-link", url } });
+ send(frame, "https://outside.example/article");
+ expect(context.invokeCalls).toContainEqual([
+ "plugin:shell|open",
+ { path: "https://outside.example/article" },
+ ]);
+ const count = context.invokeCalls.length;
+ send({ frames: [] }, "https://outside.example/unrelated");
+ send(frame, "file:///tmp/example");
+ send(frame, "javascript:alert(1)");
+ send(null, "https://outside.example/opaque");
+ expect(context.invokeCalls).toHaveLength(count);
+ });
it("falls back from malformed saved zoom values", () => {
const context = loadEventHelpers({
withTauri: true,
diff --git a/tests/unit/find-shortcuts.test.js b/tests/unit/find-shortcuts.test.js
index c6de79c3..b14c1c5b 100644
--- a/tests/unit/find-shortcuts.test.js
+++ b/tests/unit/find-shortcuts.test.js
@@ -1,7 +1,7 @@
import fs from "fs";
import path from "path";
import { runInNewContext } from "node:vm";
-import { describe, expect, it } from "vitest";
+import { describe, expect, it, vi } from "vitest";
function createElement(tagName) {
const element = {
@@ -75,7 +75,7 @@ function createTextNode(value, parent) {
};
}
-function createDocument(textNodes) {
+function createDocument(textNodes, notifyMutation = () => {}) {
const listeners = {};
const body = createElement("body");
const head = createElement("head");
@@ -108,6 +108,10 @@ function createDocument(textNodes) {
this.start,
this.end,
);
+ notifyMutation({
+ type: "childList",
+ target: this.startContainer.parentNode,
+ });
},
};
},
@@ -164,11 +168,23 @@ function loadFindScript({
enabled = true,
userAgent = "Mozilla/5.0",
nodes = [],
+ observeMutations = false,
} = {}) {
const source = fs.readFileSync(
path.join(process.cwd(), "src-tauri/src/inject/find.js"),
"utf-8",
);
+ const observers = new Set();
+ const notifyMutation = (record) => {
+ for (const observer of observers) {
+ observer.records.push(record);
+ queueMicrotask(() => {
+ if (observer.records.length) {
+ observer.callback(observer.records.splice(0));
+ }
+ });
+ }
+ };
const context = {
console,
setTimeout,
@@ -183,13 +199,28 @@ function loadFindScript({
window: {
pakeConfig: { enable_find: enabled },
},
- document: createDocument(nodes),
+ document: createDocument(nodes, notifyMutation),
};
+ if (observeMutations) {
+ context.MutationObserver = class {
+ constructor(callback) {
+ this.callback = callback;
+ this.records = [];
+ }
+ observe() {
+ observers.add(this);
+ }
+ disconnect() {
+ observers.delete(this);
+ this.records = [];
+ }
+ };
+ }
context.window.NodeFilter = context.NodeFilter;
context.window.navigator = context.navigator;
runInNewContext(source, context);
- return context;
+ return { ...context, notifyMutation };
}
describe("Find injection", () => {
@@ -285,4 +316,45 @@ describe("Find injection", () => {
context.window.pakeFind.close();
expect(context.window.pakeFind.getState().matchCount).toBe(0);
});
+
+ it("ignores its own DOM highlights but searches real changes and stops on close", async () => {
+ vi.useFakeTimers();
+ try {
+ const paragraph = createElement("p");
+ const node = createTextNode("Alpha alpha", paragraph);
+ const context = loadFindScript({ nodes: [node], observeMutations: true });
+ const walk = vi.spyOn(context.document, "createTreeWalker");
+ const find = context.window.pakeFind;
+ find.open();
+ find.search("alpha");
+ await vi.advanceTimersByTimeAsync(650);
+ expect(walk).toHaveBeenCalledTimes(1);
+ expect(find.getState().matchCount).toBe(2);
+
+ node.nodeValue = "Alpha alpha alpha";
+ context.notifyMutation({ type: "characterData", target: node });
+ await vi.advanceTimersByTimeAsync(650);
+ expect(walk).toHaveBeenCalledTimes(2);
+ expect(find.getState().matchCount).toBe(3);
+
+ node.nodeValue = "Alpha alpha alpha alpha";
+ context.notifyMutation({ type: "characterData", target: node });
+ find.search("alpha");
+ await vi.advanceTimersByTimeAsync(650);
+ expect(walk).toHaveBeenCalledTimes(3);
+ expect(find.getState().matchCount).toBe(4);
+
+ context.notifyMutation({ type: "characterData", target: node });
+ await Promise.resolve();
+ find.close();
+ node.nodeValue = "Alpha";
+ context.notifyMutation({ type: "characterData", target: node });
+ await vi.advanceTimersByTimeAsync(650);
+ expect(walk).toHaveBeenCalledTimes(3);
+ expect(find.getState().isOpen).toBe(false);
+ expect(find.getState().matchCount).toBe(0);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
});
diff --git a/tests/unit/frame-links.test.js b/tests/unit/frame-links.test.js
new file mode 100644
index 00000000..65fc4419
--- /dev/null
+++ b/tests/unit/frame-links.test.js
@@ -0,0 +1,127 @@
+import fs from "node:fs";
+import path from "node:path";
+import { runInNewContext } from "node:vm";
+import { describe, expect, it, vi } from "vitest";
+
+function loadFrame(config = {}) {
+ const messages = [];
+ const nativeWindow = {};
+ const nativeOpen = vi.fn(() => nativeWindow);
+ const listeners = {};
+ const context = {
+ URL,
+ console,
+ window: {
+ location: { href: "https://mail.example.com/app" },
+ pakeConfig: { url: "https://mail.example.com/app", ...config },
+ top: { postMessage: (message) => messages.push(message) },
+ open: nativeOpen,
+ },
+ document: {
+ baseURI: "https://mail.example.com/app",
+ addEventListener: (name, fn) => {
+ listeners[name] = fn;
+ },
+ },
+ };
+ for (const file of ["link_policy.js", "auth.js", "frame_links.js"]) {
+ runInNewContext(
+ fs.readFileSync(
+ path.join(process.cwd(), "src-tauri/src/inject", file),
+ "utf8",
+ ),
+ context,
+ );
+ }
+ return { ...context, messages, nativeOpen, nativeWindow, listeners };
+}
+
+describe("subframe external links", () => {
+ it("injects only the shared policy and frame bridge into subframes", () => {
+ const source = fs.readFileSync(
+ path.join(process.cwd(), "src-tauri/src/app/window.rs"),
+ "utf8",
+ );
+ expect(source).toContain(
+ ".initialization_script_for_all_frames(&config_script)",
+ );
+ for (const file of ["link_policy.js", "auth.js", "frame_links.js"]) {
+ expect(source).toContain(
+ `.initialization_script_for_all_frames(include_str!("../inject/${file}"))`,
+ );
+ }
+ expect(source).toContain(
+ '.initialization_script(include_str!("../inject/event.js"))',
+ );
+ });
+ it.each([false, true])(
+ "forwards final external URLs with new_window=%s",
+ (new_window) => {
+ const frame = loadFrame({ new_window });
+ expect(
+ frame.window.open("https://outside.example/article", "_blank"),
+ ).toBeNull();
+ expect(frame.messages).toEqual([
+ {
+ type: "pake:frame-external-link",
+ url: "https://outside.example/article",
+ },
+ ]);
+ expect(frame.nativeOpen).not.toHaveBeenCalled();
+ },
+ );
+
+ it.each([
+ ["https://outside.example/article", "details", {}],
+ ["https://outside.example/article", "_self", {}],
+ ["https://outside.example/article", "_parent", {}],
+ ["https://outside.example/article", "_top", {}],
+ ["/message/42", "_blank", {}],
+ ["about:blank", "_blank", {}],
+ ["", "_blank", {}],
+ [" #message", "_blank", {}],
+ ["https://appleid.apple.com/auth/authorize", "AppleAuthentication", {}],
+ ["about:blank", "AppleAuthentication", {}],
+ ["https://accounts.google.com/o/oauth2/auth", "oauth", {}],
+ [
+ "https://outside.example/article",
+ "_blank",
+ { force_internal_navigation: true },
+ ],
+ [
+ "https://outside.example/article",
+ "_blank",
+ { internal_url_regex: "outside\\.example" },
+ ],
+ ["file:///tmp/article", "_blank", {}],
+ ["javascript:void(0)", "_blank", {}],
+ ])("preserves native semantics for %s (%s)", (url, name, config) => {
+ const frame = loadFrame(config);
+ expect(frame.window.open(url, name, "width=400")).toBe(frame.nativeWindow);
+ expect(frame.nativeOpen).toHaveBeenCalledWith(url, name, "width=400");
+ expect(frame.messages).toEqual([]);
+ });
+
+ it("forwards external anchors while preserving downloads and named frames", () => {
+ const frame = loadFrame();
+ const anchor = {
+ target: "_blank",
+ hasAttribute: () => false,
+ getAttribute: () => "https://outside.example/article",
+ };
+ const event = {
+ target: { closest: () => anchor },
+ preventDefault: vi.fn(),
+ stopImmediatePropagation: vi.fn(),
+ };
+ frame.listeners.click(event);
+ expect(event.preventDefault).toHaveBeenCalledOnce();
+ expect(frame.messages).toHaveLength(1);
+ anchor.hasAttribute = () => true;
+ frame.listeners.click(event);
+ anchor.hasAttribute = () => false;
+ anchor.target = "details-frame";
+ frame.listeners.click(event);
+ expect(frame.messages).toHaveLength(1);
+ });
+});