diff --git a/astrbot/dashboard/plugin_page_bridge.js b/astrbot/dashboard/plugin_page_bridge.js
index 15774e74c0f..19e261b410e 100644
--- a/astrbot/dashboard/plugin_page_bridge.js
+++ b/astrbot/dashboard/plugin_page_bridge.js
@@ -1,5 +1,6 @@
(function attachAstrBotPluginPageBridge() {
const CHANNEL = "astrbot-plugin-page";
+ const CONTROL_CHAR_RE = /[\u0000-\u001F\u007F]/;
const SELF_ORIGIN = window.location.origin;
const pendingRequests = new Map();
const sseHandlers = new Map();
@@ -61,7 +62,8 @@
return new Promise((resolve, reject) => {
if (
(context?.target === "chat_message" || (["chat_workbench", "chat_workbench_with_launcher"].includes(context?.target) && context?.view)) &&
- action !== "view:action"
+ action !== "view:action" &&
+ action !== "external:open"
) {
reject(
Object.assign(
@@ -288,6 +290,112 @@
}
});
+ function openExternal(url) {
+ if (typeof url !== "string" || !url.trim()) {
+ return Promise.reject(
+ Object.assign(
+ new Error("External URL must be a non-empty http(s) URL."),
+ { code: "INVALID_EXTERNAL_URL" },
+ ),
+ );
+ }
+ if (!context) {
+ return readyPromise.then(() => makeRequest("external:open", { url }));
+ }
+ return makeRequest("external:open", { url });
+ }
+
+ function findLinkFromClickEvent(event) {
+ if (typeof event.composedPath === "function") {
+ for (const node of event.composedPath()) {
+ if (
+ node &&
+ node.nodeType === 1 &&
+ String(node.tagName || "").toUpperCase() === "A" &&
+ typeof node.getAttribute === "function" &&
+ node.getAttribute("href")
+ ) {
+ return node;
+ }
+ }
+ }
+ const target = event.target;
+ if (target && typeof target.closest === "function") {
+ return target.closest("a[href]");
+ }
+ return null;
+ }
+
+ function handleExternalLinkClick(event) {
+ if (
+ !event ||
+ event.defaultPrevented ||
+ !event.isTrusted ||
+ event.button !== 0 ||
+ event.altKey ||
+ window.parent === window
+ ) {
+ return;
+ }
+ const anchor = findLinkFromClickEvent(event);
+ if (
+ !anchor ||
+ (typeof anchor.hasAttribute === "function" &&
+ anchor.hasAttribute("download"))
+ ) {
+ return;
+ }
+ const baseTarget =
+ typeof document !== "undefined" &&
+ typeof document.querySelector === "function"
+ ? document.querySelector("base[target]")?.getAttribute("target") || ""
+ : "";
+ const rawAnchorTarget = String(anchor.getAttribute("target") || "").trim();
+ const targetAttr = (
+ rawAnchorTarget || String(baseTarget || "").trim()
+ ).toLowerCase();
+ const opensNewTab =
+ Boolean(
+ targetAttr &&
+ targetAttr !== "_self" &&
+ targetAttr !== "_parent" &&
+ targetAttr !== "_top",
+ ) || Boolean(event.ctrlKey || event.metaKey || event.shiftKey);
+ if (!opensNewTab) {
+ return;
+ }
+ const rawHref = String(anchor.getAttribute("href") || "").trim();
+ if (
+ !rawHref ||
+ rawHref.startsWith("#") ||
+ CONTROL_CHAR_RE.test(rawHref) ||
+ typeof URL !== "function"
+ ) {
+ return;
+ }
+ let parsed;
+ try {
+ parsed = new URL(rawHref);
+ } catch {
+ return;
+ }
+ if (
+ (parsed.protocol !== "http:" && parsed.protocol !== "https:") ||
+ parsed.username ||
+ parsed.password
+ ) {
+ return;
+ }
+ if (
+ (SELF_ORIGIN !== "null" && parsed.origin === SELF_ORIGIN) ||
+ (parentOrigin && parentOrigin !== "null" && parsed.origin === parentOrigin)
+ ) {
+ return;
+ }
+ event.preventDefault();
+ void openExternal(parsed.href).catch(() => {});
+ }
+
window.AstrBotPluginView = {
async ready() {
await readyPromise;
@@ -462,10 +570,20 @@
sseHandlers.delete(subscriptionId);
return makeRequest("sse:unsubscribe", { subscriptionId });
},
+ openExternal(url) {
+ return openExternal(url);
+ },
};
// "Views" is the preferred naming; AstrBotPluginPage stays as an alias.
window.AstrBotPluginPage = window.AstrBotPluginView;
+ if (
+ typeof document !== "undefined" &&
+ typeof document.addEventListener === "function"
+ ) {
+ document.addEventListener("click", handleExternalLinkClick);
+ }
+
send("ready");
})();
diff --git a/dashboard/src/components/chat/message_list_comps/PluginViewCard.vue b/dashboard/src/components/chat/message_list_comps/PluginViewCard.vue
index 142c07aa8a7..a26e70c870f 100644
--- a/dashboard/src/components/chat/message_list_comps/PluginViewCard.vue
+++ b/dashboard/src/components/chat/message_list_comps/PluginViewCard.vue
@@ -22,6 +22,7 @@ import { useTheme } from "vuetify";
import { fetchWithAuth } from "@/api/http";
import { useI18n, useModuleI18n } from "@/i18n/composables";
import { viewActionKey, type ViewActionHandler } from "@/utils/chatViews";
+import { openExternalPluginUrl } from "@/utils/pluginExternalUrl";
import { resolvePluginViewText } from "@/utils/pluginI18n";
import type { MessagePart } from "@/composables/useMessages";
@@ -92,6 +93,16 @@ async function receive(event: MessageEvent) {
height.value = Math.max(80, Math.min(1000, message.height));
} else if (message.kind === "request" && message.session === session) {
try {
+ if (message.action === "external:open") {
+ const result = openExternalPluginUrl(message.url);
+ send({
+ kind: "response",
+ requestId: message.requestId,
+ ok: true,
+ data: result,
+ });
+ return;
+ }
if (message.action !== "view:action")
throw Object.assign(
new Error("This capability is unavailable in chat views."),
diff --git a/dashboard/src/components/plugins/PluginViewFrame.vue b/dashboard/src/components/plugins/PluginViewFrame.vue
index 423f31eb2b7..ddd96e6a677 100644
--- a/dashboard/src/components/plugins/PluginViewFrame.vue
+++ b/dashboard/src/components/plugins/PluginViewFrame.vue
@@ -8,6 +8,7 @@ import { useModuleI18n } from "@/i18n/composables";
import { usePluginI18n } from "@/utils/pluginI18n";
import { workbenchChatKey } from "@/utils/chatViews";
+import { openExternalPluginUrl } from "@/utils/pluginExternalUrl";
const workbenchChat = inject(workbenchChatKey, undefined);
const BRIDGE_CHANNEL = "astrbot-plugin-page";
@@ -395,6 +396,19 @@ const handleBridgeRequest = async (message) => {
throw new Error("Missing plugin bridge request id.");
}
+ if (action === "external:open") {
+ try {
+ const result = openExternalPluginUrl(message.url);
+ sendBridgeResponse(requestId, true, result);
+ } catch (error) {
+ sendBridgeResponse(requestId, false, {
+ code: error?.code || "INVALID_EXTERNAL_URL",
+ message: getBridgeErrorMessage(error, "Failed to open external URL."),
+ });
+ }
+ return;
+ }
+
if (action === "chat:fill" || action === "chat:send") {
if (props.target !== "chat_workbench_with_launcher" || !workbenchChat) throw new Error("Chat control is only available to workbench launcher views.");
if (message.sessionId !== (props.sessionId || null)) throw new Error("The active session has changed.");
diff --git a/dashboard/src/utils/pluginExternalUrl.ts b/dashboard/src/utils/pluginExternalUrl.ts
new file mode 100644
index 00000000000..95d76d3b7d2
--- /dev/null
+++ b/dashboard/src/utils/pluginExternalUrl.ts
@@ -0,0 +1,149 @@
+const CONTROL_CHAR_RE = /[\u0000-\u001F\u007F]/;
+
+export type PluginExternalUrlErrorCode =
+ | "INVALID_EXTERNAL_URL"
+ | "USER_ACTIVATION_REQUIRED";
+
+export interface PluginExternalUrlError extends Error {
+ code: PluginExternalUrlErrorCode;
+}
+
+export interface OpenExternalResult {
+ url: string;
+}
+
+export interface OpenExternalOptions {
+ hostOrigin?: string;
+ userActivation?: { isActive?: boolean } | null;
+ openWindow?: (
+ url?: string | URL,
+ target?: string,
+ features?: string,
+ ) => Window | null;
+}
+
+function createExternalUrlError(
+ code: PluginExternalUrlErrorCode,
+ message: string,
+): PluginExternalUrlError {
+ return Object.assign(new Error(message), { code });
+}
+
+function normalizeHostOrigin(rawOrigin: string): string {
+ if (!rawOrigin || rawOrigin === "null") {
+ return "";
+ }
+ try {
+ const parsed = new URL(rawOrigin);
+ return parsed.origin !== "null" ? parsed.origin : "";
+ } catch {
+ return "";
+ }
+}
+
+export function validateExternalPluginUrl(
+ rawUrl: unknown,
+ hostOrigin: string = typeof window !== "undefined"
+ ? window.location.origin
+ : "",
+): string {
+ if (typeof rawUrl !== "string") {
+ throw createExternalUrlError(
+ "INVALID_EXTERNAL_URL",
+ "External URL must be a string.",
+ );
+ }
+
+ const trimmed = rawUrl.trim();
+ if (!trimmed || CONTROL_CHAR_RE.test(trimmed)) {
+ throw createExternalUrlError(
+ "INVALID_EXTERNAL_URL",
+ "External URL is invalid.",
+ );
+ }
+
+ let parsed: URL;
+ try {
+ parsed = new URL(trimmed);
+ } catch {
+ throw createExternalUrlError(
+ "INVALID_EXTERNAL_URL",
+ "External URL must be an absolute http(s) URL.",
+ );
+ }
+
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
+ throw createExternalUrlError(
+ "INVALID_EXTERNAL_URL",
+ "Only http(s) external URLs are allowed.",
+ );
+ }
+
+ if (parsed.username || parsed.password) {
+ throw createExternalUrlError(
+ "INVALID_EXTERNAL_URL",
+ "External URL must not contain embedded credentials.",
+ );
+ }
+
+ const normalizedHostOrigin = normalizeHostOrigin(hostOrigin);
+ if (!normalizedHostOrigin || parsed.origin === "null") {
+ throw createExternalUrlError(
+ "INVALID_EXTERNAL_URL",
+ "Cannot verify external URL origin.",
+ );
+ }
+
+ if (parsed.origin === normalizedHostOrigin) {
+ throw createExternalUrlError(
+ "INVALID_EXTERNAL_URL",
+ "Opening same-origin URLs from plugin views is not allowed.",
+ );
+ }
+
+ return parsed.href;
+}
+
+export function openExternalPluginUrl(
+ rawUrl: unknown,
+ options?: OpenExternalOptions,
+): OpenExternalResult {
+ const safeUrl = validateExternalPluginUrl(rawUrl, options?.hostOrigin);
+ const activation =
+ options && "userActivation" in options
+ ? options.userActivation
+ : typeof navigator !== "undefined"
+ ? navigator.userActivation
+ : undefined;
+
+ if (activation && activation.isActive === false) {
+ throw createExternalUrlError(
+ "USER_ACTIVATION_REQUIRED",
+ "Opening external URLs requires a user gesture.",
+ );
+ }
+
+ const openWindow =
+ options?.openWindow ??
+ (typeof window !== "undefined" && typeof window.open === "function"
+ ? window.open.bind(window)
+ : null);
+
+ if (!openWindow) {
+ throw createExternalUrlError(
+ "INVALID_EXTERNAL_URL",
+ "Unable to open external URL in this environment.",
+ );
+ }
+
+ const opened = openWindow(safeUrl, "_blank", "noopener,noreferrer");
+ if (opened) {
+ try {
+ opened.opener = null;
+ } catch {
+ // Cross-origin opener assignment may throw in some environments.
+ }
+ }
+
+ return { url: safeUrl };
+}
diff --git a/dashboard/tests/pluginViewBridge.test.mjs b/dashboard/tests/pluginViewBridge.test.mjs
index 82730c2858e..2e86ece63ec 100644
--- a/dashboard/tests/pluginViewBridge.test.mjs
+++ b/dashboard/tests/pluginViewBridge.test.mjs
@@ -13,14 +13,23 @@ function setupBridge(target = "chat_message") {
const styles = new Map();
const attributes = new Map();
let receive;
+ let clickHandler;
let resize;
let bodyHeight = 410;
let uuid = 0;
+ let baseTarget = "";
const parent = { postMessage: (message) => sent.push(message) };
const body = { getBoundingClientRect: () => ({ height: bodyHeight }) };
const document = {
readyState: "complete",
body,
+ addEventListener: (name, handler) => {
+ if (name === "click") clickHandler = handler;
+ },
+ querySelector: (selector) =>
+ selector === "base[target]" && baseTarget
+ ? { getAttribute: (attr) => (attr === "target" ? baseTarget : null) }
+ : null,
documentElement: {
setAttribute: (key, value) => attributes.set(key, value),
style: { setProperty: (key, value) => styles.set(key, value) },
@@ -46,6 +55,7 @@ function setupBridge(target = "chat_message") {
vm.runInNewContext(source, {
window,
document,
+ URL,
structuredClone,
console,
crypto: { randomUUID: () => `click-${++uuid}` },
@@ -86,6 +96,38 @@ function setupBridge(target = "chat_message") {
bodyHeight = height;
resize();
},
+ setBaseTarget(value) {
+ baseTarget = value;
+ },
+ clickLink(attrs, eventOverrides = {}) {
+ let prevented = false;
+ const anchor = {
+ nodeType: 1,
+ tagName: "A",
+ getAttribute: (name) => (name in attrs ? attrs[name] : null),
+ hasAttribute: (name) => name in attrs && attrs[name] !== null,
+ closest: (selector) => (selector === "a[href]" && attrs.href ? anchor : null),
+ };
+ const event = {
+ isTrusted: true,
+ button: 0,
+ altKey: false,
+ ctrlKey: false,
+ metaKey: false,
+ shiftKey: false,
+ target: anchor,
+ composedPath: () => [anchor],
+ get defaultPrevented() {
+ return prevented;
+ },
+ preventDefault() {
+ prevented = true;
+ },
+ ...eventOverrides,
+ };
+ clickHandler(event);
+ return { prevented };
+ },
};
}
@@ -320,3 +362,123 @@ test("with-launcher views use actions only when opened with a message snapshot",
assert.equal((await result).sessionId, "session-one");
}
});
+
+test("openExternal works across all plugin view targets and delegates trusted external anchor clicks", async () => {
+ for (const target of [
+ "plugin_page",
+ "chat_message",
+ "chat_workbench",
+ "chat_workbench_with_launcher",
+ ]) {
+ const env = setupBridge(target);
+ env.deliver({ kind: "context", context: env.context });
+ await env.bridge.ready();
+
+ await assert.rejects(env.bridge.openExternal(""), {
+ code: "INVALID_EXTERNAL_URL",
+ });
+ await assert.rejects(env.bridge.openExternal(null), {
+ code: "INVALID_EXTERNAL_URL",
+ });
+
+ const pending = env.bridge.openExternal("https://docs.astrbot.app/");
+ const request = env.sent.at(-1);
+ assert.equal(request.action, "external:open");
+ assert.equal(request.url, "https://docs.astrbot.app/");
+ env.deliver({
+ kind: "response",
+ requestId: request.requestId,
+ ok: true,
+ data: { url: "https://docs.astrbot.app/" },
+ });
+ assert.deepEqual(await pending, { url: "https://docs.astrbot.app/" });
+
+ const countBefore = env.sent.length;
+ const wiki = env.clickLink({
+ href: "https://en.wikipedia.org/wiki/Tokyo",
+ target: "_blank",
+ });
+ assert.equal(wiki.prevented, true);
+ assert.equal(env.sent.length, countBefore + 1);
+ assert.equal(env.sent.at(-1).action, "external:open");
+ assert.equal(env.sent.at(-1).url, "https://en.wikipedia.org/wiki/Tokyo");
+ env.deliver({
+ kind: "response",
+ requestId: env.sent.at(-1).requestId,
+ ok: true,
+ data: { url: "https://en.wikipedia.org/wiki/Tokyo" },
+ });
+
+ // Cross-origin standalone plugin server (different port) is also allowed.
+ const standalone = env.clickLink({
+ href: "http://127.0.0.1:18765/",
+ target: "_blank",
+ });
+ assert.equal(standalone.prevented, true);
+ assert.equal(env.sent.at(-1).url, "http://127.0.0.1:18765/");
+ env.deliver({
+ kind: "response",
+ requestId: env.sent.at(-1).requestId,
+ ok: true,
+ data: { url: "http://127.0.0.1:18765/" },
+ });
+
+ // Ctrl+Click on an external link without target="_blank" opens externally.
+ const ctrlOpen = env.clickLink(
+ { href: "https://www.openstreetmap.org/copyright" },
+ { ctrlKey: true },
+ );
+ assert.equal(ctrlOpen.prevented, true);
+ assert.equal(
+ env.sent.at(-1).url,
+ "https://www.openstreetmap.org/copyright",
+ );
+ env.deliver({
+ kind: "response",
+ requestId: env.sent.at(-1).requestId,
+ ok: true,
+ data: { url: "https://www.openstreetmap.org/copyright" },
+ });
+
+ // inheritance works unless overridden by target="_self".
+ env.setBaseTarget("_blank");
+ const baseOpen = env.clickLink({ href: "https://example.org/guide" });
+ assert.equal(baseOpen.prevented, true);
+ assert.equal(env.sent.at(-1).url, "https://example.org/guide");
+ env.deliver({
+ kind: "response",
+ requestId: env.sent.at(-1).requestId,
+ ok: true,
+ data: { url: "https://example.org/guide" },
+ });
+ const sentAfterAllowed = env.sent.length;
+ assert.equal(
+ env.clickLink({ href: "https://example.org/self", target: "_self" })
+ .prevented,
+ false,
+ );
+ env.setBaseTarget("");
+
+ // Unsafe, same-origin, relative, untrusted, download, or defaultPrevented clicks are never intercepted.
+ for (const [attrs, overrides] of [
+ [{ href: "https://dashboard.test/api/v1/plugins/p/views/v/_t/t/", target: "_blank" }, {}],
+ [{ href: "./evil.html", target: "_blank" }, {}],
+ [{ href: "/api/v1/auth/login", target: "_blank" }, {}],
+ [{ href: "javascript:alert(1)", target: "_blank" }, {}],
+ [{ href: "data:text/html,", target: "_blank" }, {}],
+ [{ href: "https://user:pass@example.com/", target: "_blank" }, {}],
+ [{ href: "https://example.com/file.zip", target: "_blank", download: "" }, {}],
+ [{ href: "https://example.com/in-frame" }, {}],
+ [{ href: "https://example.com/spoofed", target: "_blank" }, { isTrusted: false }],
+ [{ href: "https://example.com/handled", target: "_blank" }, { defaultPrevented: true }],
+ ]) {
+ const result = env.clickLink(attrs, overrides);
+ assert.equal(
+ result.prevented,
+ false,
+ `expected click not to be intercepted for ${JSON.stringify(attrs)}`,
+ );
+ }
+ assert.equal(env.sent.length, sentAfterAllowed);
+ }
+});
diff --git a/dashboard/tests/pluginViewCard.test.mjs b/dashboard/tests/pluginViewCard.test.mjs
index 5f69bfc6633..0f2a86d237c 100644
--- a/dashboard/tests/pluginViewCard.test.mjs
+++ b/dashboard/tests/pluginViewCard.test.mjs
@@ -3,7 +3,7 @@ import { readFileSync } from "node:fs";
import test from "node:test";
import vm from "node:vm";
import ts from "typescript";
-import { ref } from "vue";
+import { computed, markRaw, ref, toRaw } from "vue";
for (const authorized of [true, false]) {
test(`card loads the shared SDK through host authentication: ${authorized}`, async () => {
@@ -78,6 +78,7 @@ for (const authorized of [true, false]) {
for (const path of [
"../src/api/http.ts",
"../src/utils/pluginI18n.js",
+ "../src/utils/pluginExternalUrl.ts",
"../src/components/chat/message_list_comps/PluginViewCard.vue",
]) {
let source = readFileSync(new URL(path, import.meta.url), "utf8");
@@ -135,3 +136,333 @@ for (const authorized of [true, false]) {
}
});
}
+
+test("plugin view iframes keep strict sandboxes and validate external:open requests on the host", async () => {
+ const frameSource = readFileSync(
+ new URL("../src/components/plugins/PluginViewFrame.vue", import.meta.url),
+ "utf8",
+ );
+ const cardSource = readFileSync(
+ new URL(
+ "../src/components/chat/message_list_comps/PluginViewCard.vue",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ assert.ok(
+ frameSource.includes('sandbox="allow-scripts allow-forms allow-downloads"'),
+ );
+ assert.ok(!frameSource.includes("allow-popups"));
+ assert.ok(!frameSource.includes("allow-popups-to-escape-sandbox"));
+ assert.ok(cardSource.includes('sandbox="allow-scripts"'));
+ assert.ok(!cardSource.includes("allow-popups"));
+ assert.ok(!cardSource.includes("allow-popups-to-escape-sandbox"));
+
+ let messageHandler;
+ const openedCalls = [];
+ const postedToIframe = [];
+ const userActivation = { isActive: true };
+ const iframeWindow = {
+ postMessage: (msg, origin) => postedToIframe.push({ msg, origin }),
+ };
+
+ const context = vm.createContext({
+ exports: {},
+ axios: { create: () => ({}) },
+ localStorage: { getItem: () => null },
+ navigator: { userActivation },
+ window: {
+ location: new URL("https://dashboard.test/"),
+ addEventListener: (name, handler) => {
+ if (name === "message") messageHandler = handler;
+ },
+ open: (url, target, features) => {
+ const handle = { opener: "parent" };
+ openedCalls.push({ url, target, features, handle });
+ return handle;
+ },
+ fetch: async () => new Response("{}", { status: 200 }),
+ },
+ DOMParser: class {},
+ URL,
+ Request,
+ Headers,
+ crypto: { randomUUID: () => "card-session" },
+ ref,
+ defineProps: () => ({ part: { id: "card-1", name: "map" } }),
+ inject() {},
+ watch() {},
+ onMounted: (callback) => callback(),
+ onBeforeUnmount() {},
+ useI18n: () => ({ locale: ref("zh-CN") }),
+ useModuleI18n: () => ({ tm: (key) => key }),
+ useTheme: () => ({
+ global: { current: ref({ dark: false, colors: {} }) },
+ }),
+ viewActionKey: Symbol(),
+ });
+
+ for (const path of [
+ "../src/api/http.ts",
+ "../src/utils/pluginI18n.js",
+ "../src/utils/pluginExternalUrl.ts",
+ "../src/components/chat/message_list_comps/PluginViewCard.vue",
+ ]) {
+ let source = readFileSync(new URL(path, import.meta.url), "utf8");
+ if (path.endsWith(".vue")) {
+ source = source.match(/",
+ "blob:https://dashboard.test/1234",
+ "file:///etc/passwd",
+ "about:blank",
+ "https://dashboard.test@evil.example/",
+ "https://example.com/\nheader",
+ "",
+ ];
+ for (const [index, badUrl] of rejectedUrls.entries()) {
+ await sendRequest(`bad-${index}`, badUrl);
+ const response = postedToIframe.at(-1).msg;
+ assert.equal(response.ok, false, `expected rejection for ${badUrl}`);
+ assert.equal(response.error.code, "INVALID_EXTERNAL_URL");
+ }
+ assert.equal(openedCalls.length, 2);
+
+ // Missing user activation rejects even valid cross-origin URLs.
+ userActivation.isActive = false;
+ await sendRequest("no-gesture", "https://en.wikipedia.org/wiki/Tokyo");
+ assert.equal(openedCalls.length, 2);
+ assert.equal(postedToIframe.at(-1).msg.ok, false);
+ assert.equal(postedToIframe.at(-1).msg.error.code, "USER_ACTIVATION_REQUIRED");
+
+ // Wrong session or wrong message source is ignored completely.
+ userActivation.isActive = true;
+ const responsesBeforeSpoof = postedToIframe.length;
+ await sendRequest("wrong-session", "https://example.org/", {
+ data: {
+ channel: "astrbot-plugin-page",
+ session: "forged",
+ kind: "request",
+ requestId: "wrong-session",
+ action: "external:open",
+ url: "https://example.org/",
+ },
+ });
+ await sendRequest("wrong-source", "https://example.org/", { source: {} });
+ assert.equal(openedCalls.length, 2);
+ assert.equal(postedToIframe.length, responsesBeforeSpoof);
+});
+
+test("PluginViewFrame handles external:open securely without relaxing iframe sandbox", async () => {
+ let messageHandler;
+ const openedCalls = [];
+ const postedToIframe = [];
+ const userActivation = { isActive: true };
+ const iframeWindow = {
+ postMessage: (msg, origin) => postedToIframe.push({ msg, origin }),
+ };
+
+ const context = vm.createContext({
+ exports: {},
+ axios: {
+ create: () => ({}),
+ get: async () => ({ data: {} }),
+ post: async () => ({ data: {} }),
+ },
+ localStorage: { getItem: () => null },
+ navigator: { userActivation },
+ window: {
+ location: new URL("http://127.0.0.1:6185/"),
+ addEventListener: (name, handler) => {
+ if (name === "message") messageHandler = handler;
+ },
+ removeEventListener() {},
+ open: (url, target, features) => {
+ openedCalls.push({ url, target, features });
+ return null;
+ },
+ fetch: async () => new Response("{}", { status: 200 }),
+ },
+ URL,
+ Request,
+ Headers,
+ computed,
+ inject: () => undefined,
+ onBeforeUnmount() {},
+ onMounted: (callback) => callback(),
+ ref,
+ toRaw,
+ watch() {},
+ useTheme: () => ({
+ global: { current: ref({ dark: false, colors: {} }) },
+ }),
+ pluginApi: {
+ get: async () => ({ data: { data: null } }),
+ page: async () => ({ data: { data: null } }),
+ },
+ useModuleI18n: () => ({ tm: (key) => key }),
+ usePluginI18n: () => ({
+ locale: ref("zh-CN"),
+ pluginName: () => "map_companion",
+ pluginViewTitle: () => "Map",
+ }),
+ workbenchChatKey: Symbol(),
+ defineProps: () => ({
+ pluginId: "map_companion",
+ viewName: "map",
+ target: "plugin_page",
+ sessionId: "",
+ }),
+ defineEmits: () => () => {},
+ });
+
+ for (const path of [
+ "../src/api/http.ts",
+ "../src/utils/pluginExternalUrl.ts",
+ "../src/components/plugins/PluginViewFrame.vue",
+ ]) {
+ let source = readFileSync(new URL(path, import.meta.url), "utf8");
+ if (path.endsWith(".vue")) {
+ source = source.match(/