125 lines
7.6 KiB
TypeScript
125 lines
7.6 KiB
TypeScript
import type { JsonObject } from "../protocol";
|
|
import type { SurfaceInstance } from "./surface-instance-manager";
|
|
|
|
export type SurfaceHostCallbacks = Readonly<{
|
|
ready: (instanceID: string) => void;
|
|
event: (instanceID: string, event: "cancel") => void;
|
|
}>;
|
|
|
|
type HostedSurface = {
|
|
readonly instance: SurfaceInstance;
|
|
readonly frame: HTMLIFrameElement;
|
|
ready: boolean;
|
|
cancelSent: boolean;
|
|
};
|
|
|
|
const BRIDGE_VERSION = 1;
|
|
const READY_TYPE = "lineup.surface.v1.ready";
|
|
const STATE_TYPE = "lineup.surface.v1.state";
|
|
|
|
/**
|
|
* M2-03 Web Reference Host. The frame is deliberately an opaque sandbox
|
|
* origin: it receives no same-origin access to the chat page, its storage,
|
|
* the Tauri bridge, or browser network credentials. Its only connection to
|
|
* the parent is the narrow postMessage bridge below.
|
|
*/
|
|
export class IsolatedSurfaceHost {
|
|
private readonly surfaces = new Map<string, HostedSurface>();
|
|
|
|
public constructor(private readonly mountPoint: HTMLElement, private readonly callbacks: SurfaceHostCallbacks) {
|
|
window.addEventListener("message", this.receiveMessage);
|
|
}
|
|
|
|
public mount(instance: SurfaceInstance): void {
|
|
const current = this.surfaces.get(instance.instance_id);
|
|
if (current) {
|
|
current.frame.dataset.surfaceState = JSON.stringify(instance.state);
|
|
if (current.ready) this.sendState(current, instance.state);
|
|
return;
|
|
}
|
|
const frame = document.createElement("iframe");
|
|
frame.className = "isolated-surface-frame";
|
|
frame.title = `LineUp Surface ${instance.app_id}`;
|
|
frame.setAttribute("sandbox", "allow-scripts");
|
|
frame.setAttribute("referrerpolicy", "no-referrer");
|
|
frame.setAttribute("aria-label", "受限扩展界面");
|
|
// srcdoc comes only from this module's static source. No Envelope field,
|
|
// manifest field, Agent content or remote response can alter it.
|
|
frame.srcdoc = surfaceDocument(instance.instance_id);
|
|
const hosted: HostedSurface = { instance, frame, ready: false, cancelSent: false };
|
|
this.surfaces.set(instance.instance_id, hosted);
|
|
this.mountPoint.append(frame);
|
|
}
|
|
|
|
public update(instance: SurfaceInstance): void {
|
|
const hosted = this.surfaces.get(instance.instance_id);
|
|
if (!hosted || hosted.instance.app_id !== instance.app_id || hosted.instance.version !== instance.version) return;
|
|
if (hosted.ready) this.sendState(hosted, instance.state);
|
|
}
|
|
|
|
public unmount(instanceID: string): void {
|
|
const hosted = this.surfaces.get(instanceID);
|
|
if (!hosted) return;
|
|
this.surfaces.delete(instanceID);
|
|
hosted.frame.remove();
|
|
}
|
|
|
|
public destroy(): void {
|
|
window.removeEventListener("message", this.receiveMessage);
|
|
for (const instanceID of [...this.surfaces.keys()]) this.unmount(instanceID);
|
|
}
|
|
|
|
private readonly receiveMessage = (event: MessageEvent<unknown>): void => {
|
|
const message = parseBridgeMessage(event.data);
|
|
if (!message) return;
|
|
const hosted = this.surfaces.get(message.instance_id);
|
|
// An opaque sandbox needs targetOrigin="*" to receive a postMessage, so
|
|
// the source Window identity and instance id are mandatory checks here.
|
|
if (!hosted || event.source !== hosted.frame.contentWindow) return;
|
|
if (message.type === READY_TYPE) {
|
|
if (hosted.ready) return;
|
|
hosted.ready = true;
|
|
this.sendState(hosted, hosted.instance.state);
|
|
this.callbacks.ready(hosted.instance.instance_id);
|
|
return;
|
|
}
|
|
if (!hosted.ready || hosted.cancelSent) return;
|
|
hosted.cancelSent = true;
|
|
this.callbacks.event(hosted.instance.instance_id, "cancel");
|
|
};
|
|
|
|
private sendState(hosted: HostedSurface, state: JsonObject): void {
|
|
// The sandbox has an opaque origin; Window identity was captured at mount
|
|
// and all incoming traffic is checked above. No privileged data is sent.
|
|
hosted.frame.contentWindow?.postMessage({ v: BRIDGE_VERSION, type: STATE_TYPE, instance_id: hosted.instance.instance_id, state }, "*");
|
|
}
|
|
}
|
|
|
|
type SurfaceReadyMessage = Readonly<{ v: 1; type: typeof READY_TYPE; instance_id: string }>;
|
|
type SurfaceEventMessage = Readonly<{ v: 1; type: "lineup.surface.v1.event"; instance_id: string; event: "cancel" }>;
|
|
|
|
export function parseReadyMessage(value: unknown): SurfaceReadyMessage | undefined {
|
|
const parsed = parseBridgeMessage(value);
|
|
return parsed?.type === READY_TYPE ? parsed : undefined;
|
|
}
|
|
|
|
function parseBridgeMessage(value: unknown): SurfaceReadyMessage | SurfaceEventMessage | undefined {
|
|
if (!isPlainObject(value) || value.v !== BRIDGE_VERSION || (value.type !== READY_TYPE && value.type !== "lineup.surface.v1.event") || typeof value.instance_id !== "string"
|
|
|| !/^[A-Za-z0-9._:-]{1,128}$/.test(value.instance_id)) return undefined;
|
|
if (value.type === READY_TYPE && Object.keys(value).every(key => key === "v" || key === "type" || key === "instance_id")) return { v: 1, type: READY_TYPE, instance_id: value.instance_id };
|
|
if (value.type === "lineup.surface.v1.event" && value.event === "cancel" && Object.keys(value).every(key => key === "v" || key === "type" || key === "instance_id" || key === "event")) return { v: 1, type: "lineup.surface.v1.event", instance_id: value.instance_id, event: "cancel" };
|
|
return undefined;
|
|
}
|
|
|
|
/** A static boot document for the future host-local Task Dashboard bundle. */
|
|
export function surfaceDocument(instanceID: string): string {
|
|
const safeID = JSON.stringify(instanceID);
|
|
return `<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="referrer" content="no-referrer"><meta http-equiv="Content-Security-Policy" content="default-src 'none'; connect-src 'none'; img-src data:; style-src 'unsafe-inline'; script-src 'unsafe-inline'; base-uri 'none'; form-action 'none'; frame-src 'none'; object-src 'none'; navigate-to 'none'"><style>html,body{margin:0;background:#15231c;color:#e7f0eb;font:14px system-ui,sans-serif}main{padding:12px;display:grid;gap:10px}h2,p{margin:0}progress{width:100%}ul{margin:0;padding-left:20px}#logs{max-height:64px;overflow:auto;color:#b8cfc0;font-size:12px}button{justify-self:start;border:0;border-radius:7px;padding:8px 10px;background:#a9dfc4;color:#102018;font-weight:700}</style></head><body><main><h2 id="title">任务面板</h2><progress id="progress" max="100"></progress><p id="status">等待状态</p><ul id="steps"></ul><div id="logs" aria-label="日志摘要"></div><button id="cancel" type="button">请求取消</button></main><script>"use strict";const instanceId=${safeID},q=id=>document.getElementById(id),list=(id,items)=>q(id).replaceChildren(...(Array.isArray(items)?items.slice(0,12).map(x=>{const n=document.createElement(id==="logs"?"p":"li");n.textContent=typeof x==="string"?x:"";return n}):[]));q("cancel").onclick=()=>window.parent.postMessage({v:1,type:"lineup.surface.v1.event",instance_id:instanceId,event:"cancel"},"*");window.addEventListener("message",event=>{if(event.source!==window.parent)return;const d=event.data;if(!d||d.v!==1||d.type!=="lineup.surface.v1.state"||d.instance_id!==instanceId||!d.state||typeof d.state!=="object"||Array.isArray(d.state))return;const s=d.state;q("title").textContent=typeof s.title==="string"?s.title:"任务面板";q("progress").value=typeof s.percent==="number"?Math.max(0,Math.min(100,s.percent)):0;q("status").textContent=typeof s.status==="string"?s.status:"进行中";list("steps",s.steps);list("logs",s.logs);});window.parent.postMessage({v:1,type:"lineup.surface.v1.ready",instance_id:instanceId},"*");</script></body></html>`;
|
|
}
|
|
|
|
function isPlainObject(value: unknown): value is Record<string, unknown> {
|
|
if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
|
|
const prototype = Object.getPrototypeOf(value);
|
|
return prototype === Object.prototype || prototype === null;
|
|
}
|