diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 49b95185..ead94741 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -56,7 +56,9 @@ jobs: with: node-version: ${{ matrix.node }} - - run: bun install --frozen-lockfile + # isolated-vm asks for Node 24. Under the floor its binary does not + # load, and its install script fails trying to build one. + - run: bun install --frozen-lockfile ${{ matrix.node == '20.19' && '--ignore-scripts' || '' }} # libuild's executable is a shell script, which npx can't start on # Windows. diff --git a/bun.lock b/bun.lock index 2b419093..e4ac7aca 100644 --- a/bun.lock +++ b/bun.lock @@ -30,13 +30,17 @@ "@webref/idl": "^3.84.0", "@xterm/headless": "^6", "codemirror": "^6.0.2", + "core-js-pure": "3.50.0", + "esbuild": "^0.28.1", "eslint": "^10", "eslint-plugin-acrocase": "^0.1.1", "eslint-plugin-crank": "^0.2.2", "eslint-plugin-esfold": "^0.1.14", "fast-check": "^4.10.2", + "fflate": "0.8.3", "ghostty-web": "0.4.0", "htm": "^3.1.1", + "isolated-vm": "^7.0.2", "katex": "^0.18.9", "marked": "^18.0.14", "marked-highlight": "^2.2.4", @@ -49,12 +53,15 @@ "tsx": "^4.23.15", "typescript": "~6.0.3", "vue": "^3.5.43", + "web-streams-polyfill": "4.3.0", "webidl2": "^24.5.0", }, "peerDependencies": { + "isolated-vm": "^7.0.2", "node-pty": "^1.1.0", }, "optionalPeers": [ + "isolated-vm", "node-pty", ], }, @@ -346,6 +353,8 @@ "convert-source-map": ["convert-source-map@2.0.0", "", {}, "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg=="], + "core-js-pure": ["core-js-pure@3.50.0", "", {}, "sha512-6GP3Pxz4IKyWjAfa747vIu/jilB5z29JWROLqH/b+pXVcpgh6tM06ZIBwSuglgVqzDYURhOK6oEzTrG0bCHitA=="], + "cpu-features": ["cpu-features@0.0.10", "", { "dependencies": { "buildcheck": "~0.0.6", "nan": "^2.19.0" } }, "sha512-9IkYqtX3YHPCzoVg1Py+o9057a3i0fp7S530UWokCSaFVTc7CwXPRiOjRjBQQ18ZCNafx78YfnG+HALxtVmOGA=="], "crelt": ["crelt@1.0.7", "", {}, "sha512-aK6BbWfhf4U/wCcLHKPJl/xa6VkVstRaPywWtMKGwuOLc/wZTyQYuoxgvZnNsBvv7Kg3YTBQYYBCggcviQczuA=="], @@ -412,6 +421,8 @@ "fdir": ["fdir@6.5.0", "", { "peerDependencies": { "picomatch": "^3 || ^4" }, "optionalPeers": ["picomatch"] }, "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg=="], + "fflate": ["fflate@0.8.3", "", {}, "sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA=="], + "file-entry-cache": ["file-entry-cache@11.1.5", "", { "dependencies": { "flat-cache": "^6.1.23" } }, "sha512-+PFTHITI08JIGhnNpGNI8T8inUpgZfk3GNEqfT9R2zZV2iFXg3CvqzSl/uEhs7TSGujYRELEANyDvS8Fj7+S7Q=="], "find-up": ["find-up@5.0.0", "", { "dependencies": { "locate-path": "^6.0.0", "path-exists": "^4.0.0" } }, "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng=="], @@ -458,6 +469,8 @@ "isexe": ["isexe@2.0.0", "", {}, "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw=="], + "isolated-vm": ["isolated-vm@7.0.2", "", { "dependencies": { "node-gyp-build": "^4.8.4" } }, "sha512-Z1sYxpptGyGiKblG16EJEdP5x9/68C6AuqFFsewnrxlwSlrTLHKqtRMogOjcYZ0f8/cijMaRi+XwiHVQ1+uG+g=="], + "istanbul-lib-coverage": ["istanbul-lib-coverage@3.2.2", "", {}, "sha512-O8dpsF+r0WV/8MNRKfnmrtCWhuKjxrq2w+jpzBL5UZKTi2LeVWnWOmWRxFlesJONmc+wLAGvKQZEOanko0LFTg=="], "istanbul-lib-report": ["istanbul-lib-report@3.0.1", "", { "dependencies": { "istanbul-lib-coverage": "^3.0.0", "make-dir": "^4.0.0", "supports-color": "^7.1.0" } }, "sha512-GCfE1mtsHGOELCU8e/Z7YWzpmybrx/+dSTfLrvY8qRmaY6zXTKWn6WQIjaAFw069icm6GVMNkgu0NzI4iPZUNw=="], @@ -516,6 +529,8 @@ "natural-compare": ["natural-compare@1.4.0", "", {}, "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw=="], + "node-gyp-build": ["node-gyp-build@4.8.4", "", { "bin": { "node-gyp-build": "bin.js", "node-gyp-build-optional": "optional.js", "node-gyp-build-test": "build-test.js" } }, "sha512-LA4ZjwlnUblHVgq0oBF3Jl/6h/Nvs5fzBLwdEF4nuxnFdsfajde4WfxtJr3CaiH+F6ewcIB/q4jQ4UzPyid+CQ=="], + "optionator": ["optionator@0.9.4", "", { "dependencies": { "deep-is": "^0.1.3", "fast-levenshtein": "^2.0.6", "levn": "^0.4.1", "prelude-ls": "^1.2.1", "type-check": "^0.4.0", "word-wrap": "^1.2.5" } }, "sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g=="], "p-limit": ["p-limit@3.1.0", "", { "dependencies": { "yocto-queue": "^0.1.0" } }, "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ=="], @@ -606,6 +621,8 @@ "w3c-keyname": ["w3c-keyname@2.2.8", "", {}, "sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ=="], + "web-streams-polyfill": ["web-streams-polyfill@4.3.0", "", {}, "sha512-/Gnggvj9oSrEvJbDyyPtAnxBt5fGQM2iWOKQNu7ie1OxDgK40iZpyV3TKaRiEzVj1oA1UxKnEy9XPXh6PW3eVw=="], + "webidl2": ["webidl2@24.5.0", "", {}, "sha512-fxOigKkIem1iAgQ9t4cFOP+kWEA8y6Be/uh50FpJh0FijoeeT/VMrOyJzNLUgjy0rGMEcHeReKDCqj0g9dIe9A=="], "which": ["which@2.0.2", "", { "dependencies": { "isexe": "^2.0.0" }, "bin": { "node-which": "./bin/node-which" } }, "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA=="], diff --git a/docs/guides/06-images-and-canvas.md b/docs/guides/06-images-and-canvas.md index 331d315a..34490785 100644 --- a/docs/guides/06-images-and-canvas.md +++ b/docs/guides/06-images-and-canvas.md @@ -1,6 +1,6 @@ --- title: Images and canvas -description: How and draw pixels, and how runs a program. +description: How and draw pixels, how '; +``` + +A frame lays its page out in the page's cell, so a page that shows web +pages wants a cell the size web pages expect, such as `cellSize: {width: +8, height: 16}` or `"auto"`. Under the default cell of one CSS pixel, a +page meant for a browser lays out 8 times as wide. + +TermDOM loads the frame's page the way it loads an image: under the +page's `csp`, where `frame-src` governs frames, and through its `fetch` +listeners. So do the frame's own stylesheets, images and scripts, +without the headers Fetch forbids a page to set, such as `Cookie`. The +frame lays out, runs its scripts and paints in its isolate, and the page +draws the cells it paints, checking each one, so a frame can't send the +terminal escape codes. + +Each frame's isolate has 256 MB of heap, and each call into it 30 +seconds. A frame that runs past either is stopped and shows nothing, and +the page goes on. A frame runs scripts where the page has `scripting: +"enabled"` and a `sandbox` attribute, if it has one, includes +`allow-scripts`. + +Click a frame, or focus it, and keys, the mouse and pastes go to the +document in it. To the page, the frame's window is one of another +origin, whatever its URL: `contentDocument` is null, and the two talk +through `postMessage()`. A frame that sets `parent.location.href` asks +the page to navigate, as above, and a link or form in the frame loads +the new page in a new isolate. + ## `` Experimental. It may change in a minor release. diff --git a/package.json b/package.json index ffd24df0..d680690c 100644 --- a/package.json +++ b/package.json @@ -35,7 +35,7 @@ ], "scripts": { "bench": "node bench/run.ts", - "build": "libuild build", + "build": "libuild build && node scripts/build-isolate-frame.ts", "lint": "eslint .", "prepublishOnly": "echo 'ERROR: Cannot publish from root directory. Use libuild to publish or stage the package.' && exit 1", "smoke": "node scripts/smoke.js", @@ -54,9 +54,13 @@ "parse5": "8.1.0" }, "peerDependencies": { + "isolated-vm": "^7.0.2", "node-pty": "^1.1.0" }, "peerDependenciesMeta": { + "isolated-vm": { + "optional": true + }, "node-pty": { "optional": true } @@ -83,13 +87,17 @@ "@webref/idl": "^3.84.0", "@xterm/headless": "^6", "codemirror": "^6.0.2", + "core-js-pure": "3.50.0", + "esbuild": "^0.28.1", "eslint": "^10", "eslint-plugin-acrocase": "^0.1.1", "eslint-plugin-crank": "^0.2.2", "eslint-plugin-esfold": "^0.1.14", "fast-check": "^4.10.2", + "fflate": "0.8.3", "ghostty-web": "0.4.0", "htm": "^3.1.1", + "isolated-vm": "^7.0.2", "katex": "^0.18.9", "marked": "^18.0.14", "marked-highlight": "^2.2.4", @@ -102,6 +110,7 @@ "tsx": "^4.23.15", "typescript": "~6.0.3", "vue": "^3.5.43", + "web-streams-polyfill": "4.3.0", "webidl2": "^24.5.0" }, "module": "./dist/index.js", diff --git a/scripts/build-isolate-frame.ts b/scripts/build-isolate-frame.ts new file mode 100644 index 00000000..a49f6e50 --- /dev/null +++ b/scripts/build-isolate-frame.ts @@ -0,0 +1,17 @@ +/** + * Writes the isolated frame runtime next to the built modules, so a + * package loads it without bundling anything at run time. + * + * bun run build + */ +import {writeFile} from "node:fs/promises"; + +import { + buildFrameScript, + FRAME_SCRIPT, +} from "../src/internal/isolate/bundle.ts"; + +await writeFile( + new URL(`../dist/${FRAME_SCRIPT}`, import.meta.url), + await buildFrameScript(), +); diff --git a/src/index.ts b/src/index.ts index 016669ed..6b9642ae 100644 --- a/src/index.ts +++ b/src/index.ts @@ -109,6 +109,7 @@ import { setDecodeWorkerURL, } from "./internal/images.ts"; import {Input, resolvePendingHover} from "./internal/input.ts"; +import {findFrameIsolator} from "./internal/isolatedframes.ts"; import { compressKittyUploads, forgetKittyImages, @@ -680,6 +681,7 @@ export class TermDOM extends EventTarget { const images = toGraphicsOption("images", options.images); const canvas = toGraphicsOption("canvas", options.canvas); const pty = toPTYSpawner(options.ptyEmbeds); + const isolateFrame = findFrameIsolator(); const slots = _(this); slots.colorDepth = toColorDepth(options.colorDepth); slots.graphicsProtocols = { @@ -774,6 +776,7 @@ export class TermDOM extends EventTarget { images: images.setting, canvas: canvas.setting, pty, + isolateFrame, load: (request, context) => answerRequest( slots.fetchTarget, diff --git a/src/internal/dom.ts b/src/internal/dom.ts index df0d80b5..f6a6a940 100644 --- a/src/internal/dom.ts +++ b/src/internal/dom.ts @@ -33,7 +33,7 @@ import { setElementStates, } from "./cssselectors.ts"; import * as CSSValues from "./cssvalues.ts"; -import type {Exchange} from "./exchange.ts"; +import type {Exchange, WireKey} from "./exchange.ts"; import {defineFlags} from "./flags.ts"; import { type Caret, @@ -57,6 +57,7 @@ import { decodeImageOffThread, getNaturalHeight, getNaturalWidth, + type GridImage, IMAGE_ACCEPT, loadImageCodecs, MAX_IMAGE_PIXELS, @@ -65,6 +66,7 @@ import { resolveImageURL, unregisterReplacedContent, } from "./images.ts"; +import type {FrameIsolator} from "./isolateprotocol.ts"; import type {Layout} from "./layout.ts"; import {PTYSession, type PTYSpawner} from "./pty.ts"; import {rehomeClone} from "./realms.ts"; @@ -15975,7 +15977,7 @@ function getURLAttribute(element: Element, attribute: string): string { // document's URL. Falls back to the document's URL when there is no such // element or its href does not parse. function getDocumentBaseURL(document: Document): string { - const fallback = _(document).extra.documentURL; + const fallback = getFallbackBaseURL(document); for (const node of descendants(document)) { if (getNodeType(node) !== ELEMENT_NODE) { continue; @@ -15996,6 +15998,17 @@ function getDocumentBaseURL(document: Document): string { return fallback; } +// HTML's fallback base URL: a frame's srcdoc or about:blank document +// resolves against the base URL of the document its iframe is in. +function getFallbackBaseURL(document: Document): string { + const url = _(document).extra.documentURL; + const window = _(document).extra.defaultView as Window | null; + const frame = window === null ? null : _(window).frameOwner; + return frame !== null && (url === "about:srcdoc" || url === "about:blank") + ? getDocumentBaseURL(_(frame).document) + : url; +} + function parseInteger(value: string): number | null { const match = /^[\t\n\f\r ]*([+-]?[0-9]+)/.exec(value); if (match === null) { @@ -17611,10 +17624,31 @@ class HTMLEmbedElement extends HTMLElement { declareExtraSlots(HTMLEmbedElement); -/** The program an embed runs, or null for an element that runs none. */ +/** + * What takes the input that reaches a box as a terminal's program would: + * an embed's program, or a frame drawn from another isolate. + */ +export interface ProgramInput { + readonly cols: number; + readonly rows: number; + sendKey(key: WireKey): boolean; + paste(text: string): void; + sendMouse(code: number, col: number, row: number, release: boolean): boolean; + scrollBy(lines: number): boolean; + sendFocus(focused: boolean): void; +} + +/** + * The program an embed runs, or the isolated frame an iframe shows, or + * null for an element that has neither. + */ export function getRunningProgram( element: globalThis.Element | Element | null, -): PTYSession | null { +): ProgramInput | null { + if (implementsInterface(element, HTMLIFrameElement)) { + const window = _(element).extra.contentWindow; + return implementsInterface(window, Window) ? _(window).isolatedFrame : null; + } if (element === null || !implementsInterface(element, HTMLEmbedElement)) { return null; } @@ -19239,15 +19273,16 @@ interface FrameWindowLike { } // A frame's document and the window that shows it, built in a realm of -// their own, or null where the runtime cannot make a realm. window.ts -// gives the factory, since a window is built above the DOM. +// their own where the runtime can make one, and in the engine's realm +// where it cannot. window.ts gives the factory, since a window is built +// above the DOM. type FrameWindowFactory = ( source: string, url: string, registry: CustomElementRegistry, parent: Window | null, frame: HTMLIFrameElement, -) => {document: Document; window: Window} | null; +) => {document: Document; window: Window}; let frameWindowFactory: FrameWindowFactory | null = null; @@ -19279,6 +19314,31 @@ type FrameEngineFactory = ( let frameEngineFactory: FrameEngineFactory | null = null; +/** A frame drawn from another isolate, as the iframe that shows it holds it. */ +export interface IsolatedFrameView extends BoxRenderer, ProgramInput { + // A message for the frame's window, from a window of `origin`. + postMessage(data: unknown, origin: string, targetOrigin: string): void; + // The images the cells the last fit returned show. + images(): GridImage[]; +} + +// Builds a frame whose document at `url` is in another isolate, standing +// in `window` for it, given the attached document the iframe is in. +type IsolatedFrameFactory = ( + frame: HTMLIFrameElement, + window: Window, + url: string, + parent: Document, + isolate: FrameIsolator, + changed: () => void, +) => IsolatedFrameView; + +let isolatedFrameFactory: IsolatedFrameFactory | null = null; + +export function setIsolatedFrameFactory(factory: IsolatedFrameFactory): void { + isolatedFrameFactory = factory; +} + export function setFrameEngineFactory(factory: FrameEngineFactory): void { frameEngineFactory = factory; } @@ -19296,6 +19356,438 @@ function getTopWindow(window: Window): Window { return current; } +// Whether `window` is `ancestor`, or a frame somewhere inside it. +function isWindowWithin(window: Window, ancestor: Window): boolean { + for ( + let current: Window | null = window; + current !== null; + current = _(current).parentWindow + ) { + if (current === ancestor) { + return true; + } + } + return false; +} + +/** + * An origin, as HTML has it: a tuple origin by its serialization, or an + * opaque origin, which is an object compared by identity. + */ +type Origin = string | object; + +// The origin of `url`, with `opaque` standing for one that is opaque. +function getURLOrigin(url: string, opaque: object): Origin { + const origin = parseURL(url)?.origin ?? "null"; + return origin === "null" ? opaque : origin; +} + +// A sandbox without allow-same-origin gives a window an opaque origin of +// its own. A frame showing srcdoc or about:blank has the origin of the +// document its iframe is in, which created it. Otherwise the URL says. +function getWindowOrigin(window: Window): Origin { + const slots = _(window); + if (slots.sandboxOrigin !== null) { + return slots.sandboxOrigin; + } + const url = _(window.document).extra.documentURL; + const frame = slots.frameOwner; + if (frame !== null && (url === "about:srcdoc" || url === "about:blank")) { + return getDocumentOrigin(_(frame).document); + } + return getURLOrigin(url, window); +} + +function getDocumentOrigin(document: Document): Origin { + const window = _(document).extra.defaultView as Window | null; + return window !== null + ? getWindowOrigin(window) + : getURLOrigin(_(document).extra.documentURL, document); +} + +function serializeOrigin(origin: Origin): string { + return typeof origin === "string" ? origin : "null"; +} + +/** + * HTML's iframe sandboxing flag set, as the allow- tokens that lift its + * flags: those of the iframe's sandbox attribute that the window it is in + * has too. Null where no sandbox applies. + */ +function getFrameSandbox( + frame: HTMLIFrameElement, + parent: Window | null, +): ReadonlySet | null { + const attribute = getAttributeValue(frame, "sandbox"); + const above = parent === null ? null : _(parent).sandbox; + if (attribute === null) { + return above; + } + const tokens = splitOnASCIIWhitespace(toASCIILowercase(attribute)); + return new Set( + above === null ? tokens : tokens.filter((token) => above.has(token)), + ); +} + +/** + * HTML's "allowed by sandboxing to navigate": a sandboxed window + * navigates itself and the frames inside it, and its top window where + * allow-top-navigation lets it, or allow-top-navigation-by-user-activation + * and the user's action. + */ +function isAllowedToNavigate(source: Window, target: Window): boolean { + const sandbox = _(source).sandbox; + if (sandbox === null || isWindowWithin(target, source)) { + return true; + } + if (target !== getTopWindow(source)) { + return false; + } + return sandbox.has("allow-top-navigation") || + (sandbox.has("allow-top-navigation-by-user-activation") && + hasTransientActivation(source.document)); +} + +/** + * The window whose code calls a member of `window`, HTML's incumbent, + * where a realm tells: the frame whose realm runs, or null for the + * engine's own. + */ +function getIncumbentWindow(window: Window): Window | null { + const realm = _(window).realm !== null + ? getCallerRealm() + : getIncumbentRealm(); + return realm === null ? null : realm.global as unknown as Window; +} + +// What code of another origin reaches on a window, HTML's +// CrossOriginProperties, and what it reads as undefined. +const CROSS_ORIGIN_WINDOW_KEYS = [ + "window", + "self", + "location", + "close", + "closed", + "focus", + "blur", + "frames", + "length", + "top", + "opener", + "parent", + "postMessage", +]; + +const CROSS_ORIGIN_FALLBACK_KEYS: ReadonlyArray = [ + "then", + Symbol.toStringTag, + Symbol.hasInstance, + Symbol.isConcatSpreadable, +]; + +/** + * A window or its location as code of another origin's window, the + * viewer, holds it: HTML's cross-origin WindowProxy and Location. The + * record is the proxy's target, which the traps read and never expose. + */ +interface CrossOriginWindowRecord { + kind: "window"; + viewer: Window; + target: Window; + proxy: Window | null; + location: CrossOriginLocationRecord; + postMessage: (...args: unknown[]) => void; + close: () => void; + focus: () => void; + blur: () => void; +} + +interface CrossOriginLocationRecord { + kind: "location"; + viewer: Window; + target: Window; + proxy: object | null; + replace: (...args: unknown[]) => void; + setHref: (...args: unknown[]) => void; +} + +type CrossOriginRecord = CrossOriginWindowRecord | CrossOriginLocationRecord; + +function crossOriginError( + record: CrossOriginRecord, + key: string | symbol, +): Error { + return domError( + "SecurityError", + `Blocked a frame with origin "${ + serializeOrigin(getWindowOrigin(record.viewer)) + }" from accessing '${String(key)}' on a cross-origin ${ + record.kind === "window" ? "window" : "location" + }.`, + ); +} + +// The window of the frame at index `key` of `window`'s frames, or of the +// first one `key` names whose origin is the window's. +function getChildFrameWindow(window: Window, key: string): Window | null { + const frames = getDocumentFrames(window.document); + const frame = isArrayIndex(key) + ? frames[Number(key)] + : frames.find((each) => getAttributeValue(each, "name") === key); + if (frame === undefined) { + return null; + } + ensureFrameDocument(frame); + const content = _(frame).extra.contentWindow; + return implementsInterface(content, Window) && + (isArrayIndex(key) || getWindowOrigin(content) === getWindowOrigin(window)) + ? content + : null; +} + +function describeData(value: unknown, enumerable = false): PropertyDescriptor { + return {value, writable: false, enumerable, configurable: true}; +} + +// HTML's CrossOriginGetOwnPropertyHelper, with the fallback: what code of +// the viewer's origin may find under `key`, or a SecurityError. +function describeCrossOrigin( + record: CrossOriginRecord, + key: string | symbol, +): PropertyDescriptor { + if (CROSS_ORIGIN_FALLBACK_KEYS.includes(key)) { + return describeData(undefined); + } + if (record.kind === "location") { + if (key === "href") { + return { + get: undefined, + set: record.setHref, + enumerable: false, + configurable: true, + }; + } + if (key === "replace") { + return describeData(record.replace); + } + throw crossOriginError(record, key); + } + const {viewer, target} = record; + switch (key) { + case "window": + case "self": + case "frames": + return describeData(record.proxy); + case "location": + return describeData(record.location.proxy); + case "closed": + return describeData(target.closed || _(target).discarded); + case "length": + return describeData(getDocumentFrames(target.document).length); + case "top": + return describeData(viewWindow(viewer, getTopWindow(target))); + case "parent": + return describeData(viewWindow(viewer, _(target).parentWindow ?? target)); + case "opener": + return describeData(null); + case "postMessage": + case "close": + case "focus": + case "blur": + return describeData(record[key]); + } + const child = typeof key === "string" + ? getChildFrameWindow(target, key) + : null; + if (child === null) { + throw crossOriginError(record, key); + } + return describeData(viewWindow(viewer, child), isArrayIndex(key as string)); +} + +const CROSS_ORIGIN_HANDLER: ProxyHandler = { + get(record, key) { + const descriptor = describeCrossOrigin(record, key); + if ("value" in descriptor) { + return descriptor.value as unknown; + } + throw crossOriginError(record, key); + }, + set(record, key, value) { + if (record.kind === "window" && key === "location") { + record.location.setHref(value); + return true; + } + const descriptor = describeCrossOrigin(record, key); + if (descriptor.set === undefined) { + throw crossOriginError(record, key); + } + descriptor.set(value); + return true; + }, + has(record, key) { + describeCrossOrigin(record, key); + return true; + }, + getOwnPropertyDescriptor(record, key) { + return describeCrossOrigin(record, key); + }, + ownKeys(record) { + if (record.kind === "location") { + return ["href", "replace", ...CROSS_ORIGIN_FALLBACK_KEYS]; + } + const length = getDocumentFrames(record.target.document).length; + return [ + ...Array.from({length}, (_value, index) => String(index)), + ...CROSS_ORIGIN_WINDOW_KEYS, + ...CROSS_ORIGIN_FALLBACK_KEYS, + ]; + }, + defineProperty(record, key) { + throw crossOriginError(record, key); + }, + deleteProperty(record, key) { + throw crossOriginError(record, key); + }, + getPrototypeOf() { + return null; + }, + setPrototypeOf(_record, prototype) { + return prototype === null; + }, + isExtensible() { + return true; + }, + preventExtensions() { + return false; + }, +}; + +function crossOriginPostMessage( + record: CrossOriginWindowRecord, + ...args: unknown[] +): void { + if (args.length < 1) { + throw new TypeError( + "Failed to execute 'postMessage' on 'Window': 1 argument required, but only 0 present.", + ); + } + postWindowMessage(record.target, record.viewer, args[0], args[1]); +} + +// A cross-origin close reaches a top window the viewer may navigate. +function crossOriginClose(record: CrossOriginWindowRecord): void { + const {viewer, target} = record; + if (_(target).parentWindow === null && isAllowedToNavigate(viewer, target)) { + target.close(); + } +} + +function crossOriginFocus(record: CrossOriginWindowRecord): void { + record.target.focus(); +} + +function crossOriginBlur(record: CrossOriginWindowRecord): void { + record.target.blur(); +} + +function crossOriginSetHref( + record: CrossOriginLocationRecord, + ...args: unknown[] +): void { + navigateWindow(record.viewer, record.target, String(args[0]), "auto"); +} + +function crossOriginReplace( + record: CrossOriginLocationRecord, + ...args: unknown[] +): void { + if (args.length < 1) { + throw new TypeError( + "Failed to execute 'replace' on 'Location': 1 argument required, but only 0 present.", + ); + } + navigateWindow(record.viewer, record.target, String(args[0]), "replace"); +} + +// A cross-origin function has its own identity for each viewer, and the +// name of the member it stands for. +function bindCrossOrigin( + implementation: (record: T, ...args: unknown[]) => void, + record: T, + name: string, +): (...args: unknown[]) => void { + const bound = implementation.bind(null, record); + Object.defineProperty(bound, "name", {value: name}); + return bound; +} + +function createCrossOriginWindow(viewer: Window, target: Window): Window { + const location = { + kind: "location", + viewer, + target, + proxy: null, + } as unknown as CrossOriginLocationRecord; + location.replace = bindCrossOrigin(crossOriginReplace, location, "replace"); + location.setHref = bindCrossOrigin(crossOriginSetHref, location, "set href"); + // A name HTML does not list throws, which only a proxy can do. + // eslint-disable-next-line no-restricted-globals + location.proxy = new Proxy(location, CROSS_ORIGIN_HANDLER); + const record = { + kind: "window", + viewer, + target, + proxy: null, + location, + } as unknown as CrossOriginWindowRecord; + record.postMessage = bindCrossOrigin( + crossOriginPostMessage, + record, + "postMessage", + ); + record.close = bindCrossOrigin(crossOriginClose, record, "close"); + record.focus = bindCrossOrigin(crossOriginFocus, record, "focus"); + record.blur = bindCrossOrigin(crossOriginBlur, record, "blur"); + // eslint-disable-next-line no-restricted-globals + record.proxy = new Proxy( + record, + CROSS_ORIGIN_HANDLER, + ) as unknown as Window; + return record.proxy; +} + +/** + * `target` as code of `viewer` holds it: the window itself where the two + * have one origin, and otherwise a cross-origin WindowProxy, the one + * `viewer` gets each time. + */ +function viewWindow(viewer: Window, target: Window): Window { + if (getWindowOrigin(viewer) === getWindowOrigin(target)) { + return target; + } + const slots = _(target); + const views = slots.crossOriginViews ??= new WeakMap(); + let view = views.get(viewer); + if (view === undefined) { + view = createCrossOriginWindow(viewer, target); + views.set(viewer, view); + } + return view; +} + +// The frame's window as code of the window its iframe is in holds it. +function getFrameView( + frame: HTMLIFrameElement, +): FrameWindowLike | Window | null { + ensureFrameDocument(frame); + const window = _(frame).extra.contentWindow; + const viewer = _(_(frame).document).extra.defaultView as Window | null; + return viewer !== null && implementsInterface(window, Window) + ? viewWindow(viewer, window) + : window; +} + // The iframes of `document`'s own tree, in tree order, which are its // window's frames. Those in shadow trees are not. function getDocumentFrames(document: Document): HTMLIFrameElement[] { @@ -19331,7 +19823,10 @@ function syncFrameIndexes(document: Document): void { } for (let index = slots.frameIndexes; index < count; index++) { Object.defineProperty(slots.namedProperties, String(index), { - get: () => getDocumentFrames(document)[index]?.contentWindow ?? undefined, + get: () => { + const frame = getDocumentFrames(document)[index]; + return frame === undefined ? undefined : getFrameView(frame); + }, configurable: true, }); } @@ -19345,12 +19840,13 @@ export function setFrameWindowFactory(factory: FrameWindowFactory): void { // A nested document. On insertion the iframe gets a content document (its // srcdoc parsed, or about:blank) with its own registry, and fires load. // Removal discards it, as removal discards a browsing context. The src -// attribute does nothing, because this engine performs no fetches, so a -// src iframe holds about:blank, the same document a browser shows before -// navigation. Where the runtime can make a realm, the document has a -// window of its own in one, with its own interfaces and intrinsics. -// Otherwise there is no second realm: the frame's constructors are this -// realm's, and its window is a stand-in. +// attribute loads nothing in the engine's heap, so a src iframe holds +// about:blank, the same document a browser shows before navigation, +// unless the TermDOM starts frames in isolates, where an http: or https: +// src loads there. The document has a window of its own. Where the runtime can +// make a realm, the window is in one, with its own interfaces and +// intrinsics; otherwise its constructors are this realm's. A window +// stands in for the frame's only where no factory builds windows. interface HTMLIFrameElementExtra extends NodeExtra { contentDocument: Document | null; contentWindow: FrameWindowLike | Window | null; @@ -19411,18 +19907,23 @@ class HTMLIFrameElement extends HTMLElement { getFocusedElement(slots.document) === this ? slots.extra.frameRenderer?.caret ?? null : null, + images: () => getFrameImages(this), })); } + // A document of another origin is not the iframe's document's to read. get contentDocument(): Document | null { ensureFrameDocument(this); - return _(this).extra.contentDocument; + const slots = _(this); + const window = slots.extra.contentWindow; + return implementsInterface(window, Window) && + getWindowOrigin(window) !== getDocumentOrigin(slots.document) + ? null + : slots.extra.contentDocument; } get contentWindow(): globalThis.WindowProxy | null { - ensureFrameDocument(this); - return _(this).extra.contentWindow as unknown as globalThis.WindowProxy | - null; + return getFrameView(this) as unknown as globalThis.WindowProxy | null; } getSVGDocument(): Document | null { @@ -19518,12 +20019,44 @@ function scheduleFrameLoad(frame: HTMLIFrameElement): void { const slots = _(frame); const run = (slots.extra.frameDocumentRun = {}); setTimeout(() => { - if (frame.isConnected && slots.extra.frameDocumentRun === run) { + if ( + frame.isConnected && + slots.extra.frameDocumentRun === run && + getIsolatedSource(frame) === null + ) { frame.dispatchEvent(constructInternal(() => new Event("load"))); } }, 0); } +/** + * The URL of the document an iframe shows from another isolate: its src, + * where the TermDOM showing the iframe isolates frames and src names an + * http: or https: URL of another origin than the iframe's document has. + * Null for a frame drawn in the engine's heap, which its page can reach + * into. An isolated frame fires load when its document has loaded there. + */ +function getIsolatedSource(frame: HTMLIFrameElement): string | null { + const attached = getAttachedDocument(frame); + if ( + attached === undefined || + _(attached).extra.isolateFrame === null || + isolatedFrameFactory === null || + getAttributeValue(frame, "srcdoc") !== null + ) { + return null; + } + const src = getAttributeValue(frame, "src"); + const url = src === null + ? null + : parseURL(src, getDocumentBaseURL(_(frame).document)); + return url !== null && + (url.protocol === "http:" || url.protocol === "https:") && + url.origin !== getDocumentOrigin(_(frame).document) + ? url.href + : null; +} + /** * The iframe `document` is the content document of, or null for one that * is no frame's. @@ -19543,7 +20076,8 @@ export function getDrawnFrameDocument( element: globalThis.Element | Element | null, ): Document | null { return implementsInterface(element, HTMLIFrameElement) && - _(element).extra.frameRenderer !== null + _(element).extra.frameRenderer !== null && + getRunningProgram(element) === null ? _(element).extra.contentDocument : null; } @@ -19687,6 +20221,15 @@ function ensureFrameRenderer(frame: HTMLIFrameElement): void { } } +// The images an isolated frame's cells show. A frame in the engine's heap +// paints its images into its cells. +function getFrameImages(frame: HTMLIFrameElement): GridImage[] { + const window = _(frame).extra.contentWindow; + return implementsInterface(window, Window) + ? _(window).isolatedFrame?.images() ?? [] + : []; +} + // The frame's document changed: its cells are painted again with the // next frame of the document the iframe is in. function frameChanged(frame: HTMLIFrameElement): void { @@ -19709,7 +20252,41 @@ function ensureFrameDocument(frame: HTMLIFrameElement): void { const parent = _(frameSlots.document).extra.defaultView as Window | null; const built = frameWindowFactory?.(srcdoc ?? "", url, registry, parent, frame) ?? null; + const isolated = getIsolatedSource(frame); + const attached = getAttachedDocument(frame); + if (built !== null && isolated !== null && attached !== undefined) { + // The window here stands in for the frame's, whose document is in + // the other isolate. Its origin is opaque to the page, so the page + // reaches it as a window of another origin, through messages. + const windowSlots = _(built.window); + windowSlots.sandbox = getFrameSandbox(frame, parent); + windowSlots.sandboxOrigin = {}; + windowSlots.windowName = getAttributeValue(frame, "name") ?? ""; + frameSlots.extra.contentDocument = built.document; + frameSlots.extra.contentWindow = built.window; + const view = isolatedFrameFactory!( + frame, + built.window, + isolated, + attached, + _(attached).extra.isolateFrame!, + () => frameChanged(frame), + ); + windowSlots.isolatedFrame = view; + frameSlots.extra.frameRenderer = view; + return; + } if (built !== null) { + const windowSlots = _(built.window); + const sandbox = getFrameSandbox(frame, parent); + windowSlots.sandbox = sandbox; + windowSlots.sandboxOrigin = + sandbox !== null && + !sandbox.has("allow-same-origin") + ? {} + : null; + // HTML names the frame's window after the iframe as it is made. + windowSlots.windowName = getAttributeValue(frame, "name") ?? ""; frameSlots.extra.contentDocument = built.document; frameSlots.extra.contentWindow = built.window; ensureFrameRenderer(frame); @@ -28697,6 +29274,9 @@ export interface DocumentExtra extends NodeExtra { // none may run: the ptyEmbeds option is "none", the runtime has no // pseudo-terminal, or the document is a frame's. pty: PTYSpawner | "none" | "unavailable" | "framed"; + // Starts a frame's document in an isolate of its own, or null where + // frames are drawn in the engine's heap. + isolateFrame: FrameIsolator | null; load: ResourceLoader; loadSignal: globalThis.AbortSignal; // Whether the document's policies let an element's inline handler run. @@ -30988,8 +31568,8 @@ function removeNameEntry( } // The elements whose name attribute names them on the Window, as the HTML -// Standard lists them. -const NAMED_BY_NAME = new Set(["embed", "form", "img", "object"]); +// Standard lists them, and the iframe, whose name names its frame. +const NAMED_BY_NAME = new Set(["embed", "form", "iframe", "img", "object"]); function isNamedByName(element: Element): boolean { const elementSlots = _(element); @@ -38431,6 +39011,7 @@ export interface DocumentEngine { images: GraphicsSetting; canvas: GraphicsSetting; pty: PTYSpawner | "none" | "unavailable" | "framed"; + isolateFrame?: FrameIsolator | null; // Answers the loads the document's markup asks for. load: ResourceLoader; allowsInlineHandler(element: globalThis.Element): boolean; @@ -38476,6 +39057,7 @@ export function attachDocument( attachedSlots.extra.allowsPlugin = (element, violations) => engine.allowsPlugin(element, violations); attachedSlots.extra.loadSignal = engine.loadSignal; + attachedSlots.extra.isolateFrame = engine.isolateFrame ?? null; attachedSlots.extra.visible = false; attachedSlots.extra.systemFocused = true; attachedSlots.extra.layout = layout; @@ -39628,25 +40210,65 @@ function getLocationURL(location: Location): URL | null { return parseURL(location.href); } -// HTML's Location-object navigate. The URL resolves against the -// document's base URL. function navigateLocation( location: Location, value: string | URL, historyHandling: globalThis.NavigationHistoryBehavior, ): void { - const document = _(location).locationWindow.document as unknown as Document; + const window = _(location).locationWindow; + navigateWindow(getIncumbentWindow(window), window, value, historyHandling); +} + +/** + * HTML's Location-object navigate of `target`, by code of `source`, or of + * a window the engine cannot tell where that is null. The URL resolves + * against the base URL of the source's document, and the source's sandbox + * may forbid it. + */ +function navigateWindow( + source: Window | null, + target: Window, + value: string | URL, + historyHandling: globalThis.NavigationHistoryBehavior, +): void { + const document = target.document as unknown as Document; const url = typeof value === "string" - ? parseURL(value, getDocumentBaseURL(document)) + ? parseURL(value, getDocumentBaseURL((source ?? target).document)) : value; if (url === null) { throw domError("SyntaxError", `"${value}" is not a URL`); } + if (source !== null && !isAllowedToNavigate(source, target)) { + throw domError( + "SecurityError", + "The frame's sandbox does not allow it to navigate this window", + ); + } if (!navigateDocument(document, url, {historyHandling})) { throw failNavigation(document); } } +/** + * An isolated frame's navigation of the window its iframe is in, which + * `window` stands in the page for, held to the frame's sandbox. What the + * parent or its navigate listeners refuse comes to nothing, as the frame + * that asked is in another isolate. + */ +export function navigateFrameParent(window: Window, url: string): void { + const parent = _(window).parentWindow; + if (parent === null || _(window).discarded) { + return; + } + try { + navigateWindow(window, parent, url, "auto"); + } catch (error) { + if (!(error instanceof DOMException)) { + throw error; + } + } +} + // A setter of one part of the URL: the location navigates to its URL with // that part changed. A URL with an opaque path has no host, port or path // to change, and a protocol other than http and https is not one to go to. @@ -41480,15 +42102,28 @@ function syncNamedProperty(document: Document, name: string): void { } } -// The one element a name picks out, or all of them, live, when several do. +// The window of the first frame a name names, in tree order, or else the +// one element it picks out, or a live collection when several share it. function getNamedPropertyValue( document: Document, name: string, -): Element | HTMLCollection | undefined { +): Element | HTMLCollection | FrameWindowLike | Window | undefined { const documentSlots = _(document); + const named = documentSlots.extra.nameMap.get(name) ?? []; + if ( + named.some((element) => implementsInterface(element, HTMLIFrameElement)) + ) { + const frame = getDocumentFrames(document).find((each) => + getAttributeValue(each, "name") === name); + const view = frame === undefined ? null : getFrameView(frame); + if (view !== null) { + return view; + } + } const elements = new Set([ ...documentSlots.extra.idMap.get(name) ?? [], - ...documentSlots.extra.nameMap.get(name) ?? [], + ...named.filter((element) => + !implementsInterface(element, HTMLIFrameElement)), ]); if (elements.size === 0) { return undefined; @@ -41505,7 +42140,8 @@ function getNamedPropertyValue( null, (element) => getAttributeValue(element, "id") === name || - getExposedName(element) === name, + (getExposedName(element) === name && + !implementsInterface(element, HTMLIFrameElement)), ); cache.set(key, collection); } @@ -41929,6 +42565,16 @@ export interface WindowSlots extends EventTargetSlots { parentWindow: Window | null; frameOwner: HTMLIFrameElement | null; realm: Realm | null; + // A sandboxed frame's: the sandbox it was made under, and the opaque + // origin it has where the sandbox lacks allow-same-origin. + sandbox: ReadonlySet | null; + sandboxOrigin: object | null; + // Where a frame's document is in another isolate, the frame there, + // which this window stands in for. + isolatedFrame: IsolatedFrameView | null; + // The cross-origin WindowProxy each window of another origin holds this + // one by. + crossOriginViews?: WeakMap; // A frame's window whose iframe left the page or showed another // document. discarded: boolean; @@ -42206,15 +42852,15 @@ export class Window extends EventTarget { // is defined on the object, and node:vm makes a field defined on a // realm's global read-only, which a frame's window is. declare readonly document: Document; - constructor(document: Document) { + constructor(document: Document, frame: HTMLIFrameElement | null = null) { super(); this.document = document; // Attaching a document gives it a defaultView, and the attached // document is the one bare node constructors use. const documentSlots = _(document); documentSlots.extra.defaultView = this; - // A frame's window is its realm's, and leaves the top window's be. - if (getActiveRealm() === null) { + // A frame's window leaves the top window's be. + if (frame === null && getActiveRealm() === null) { ambientDocument = document; } const slots = _(this); @@ -42223,8 +42869,11 @@ export class Window extends EventTarget { ) as Record; Object.setPrototypeOf(this, slots.namedProperties); slots.parentWindow = null; - slots.frameOwner = null; + slots.frameOwner = frame; slots.realm = null; + slots.sandbox = null; + slots.sandboxOrigin = null; + slots.isolatedFrame = null; slots.discarded = false; slots.frameIndexes = 0; for (const name of new Set([ @@ -42398,8 +43047,13 @@ export class Window extends EventTarget { return EXTERNAL; } + // An iframe in a document of another origin is not the frame's to see. get frameElement(): globalThis.Element | null { - return _(this).frameOwner; + const frame = _(this).frameOwner; + return frame !== null && + getDocumentOrigin(_(frame).document) === getWindowOrigin(this) + ? frame + : null; } get frames(): Window { @@ -42472,7 +43126,8 @@ export class Window extends EventTarget { } get parent(): Window { - return _(this).parentWindow ?? this; + const parent = _(this).parentWindow; + return parent === null ? this : viewWindow(this, parent); } get screen(): globalThis.Screen { @@ -42505,7 +43160,7 @@ export class Window extends EventTarget { } get top(): Window | null { - return getTopWindow(this); + return viewWindow(this, getTopWindow(this)); } get visualViewport(): globalThis.VisualViewport | null { @@ -42520,15 +43175,8 @@ export class Window extends EventTarget { return true; } - // A frame showing srcdoc or about:blank has the origin of the window it - // is in, as HTML gives such a document its creator's. get origin(): string { - const url = this.document.URL; - const parent = _(this).parentWindow; - if (parent !== null && (url === "about:srcdoc" || url === "about:blank")) { - return parent.origin; - } - return parseURL(url)?.origin ?? "null"; + return serializeOrigin(getWindowOrigin(this)); } get localStorage(): Storage { @@ -42775,11 +43423,9 @@ export class Window extends EventTarget { return null; } - // HTML's window post message steps: the message is a clone made in this - // window's realm, from the window whose code posted it, which is the + // The message is from the window whose code posted it, which is the // realm a frame's binding was called from, or the realm running when a - // top window's is. It lands only if this window's origin is the one - // the poster named. + // top window's is. postMessage( message: any, targetOrigin: string, @@ -42787,51 +43433,12 @@ export class Window extends EventTarget { ): void; postMessage(message: any, options?: globalThis.WindowPostMessageOptions): void; postMessage(message: any, settings?: unknown): void { - const slots = _(this); - const callerRealm = slots.realm !== null - ? getCallerRealm() - : getIncumbentRealm(); - const source = callerRealm !== null - ? callerRealm.global as unknown as Window - : getTopWindow(this); - const named = typeof settings === "object" && settings !== null - ? (settings as {targetOrigin?: unknown}).targetOrigin - : settings; - let targetOrigin = named === undefined ? "/" : String(named); - if (targetOrigin === "/") { - targetOrigin = source.origin; - } else if (targetOrigin !== "*") { - const parsed = parseURL(targetOrigin); - if (parsed === null) { - throw domError( - "SyntaxError", - `Failed to execute 'postMessage' on 'Window': Invalid target origin '${targetOrigin}'.`, - ); - } - targetOrigin = parsed.origin; - } - const realm = slots.realm; - const data = runInRealm(realm, () => { - const clone = cloneStructured( - message, - "execute 'postMessage' on 'Window'", - ); - return realm === null ? clone : rehomeClone(clone, realm); - }); - const origin = source.origin; - queueWindowTask(this, () => { - if (targetOrigin !== "*" && targetOrigin !== this.origin) { - return; - } - const event = runInRealm(realm, () => - constructInternal(() => - new MessageEvent("message", { - data, - origin, - source: source as unknown as globalThis.MessageEventSource, - }))); - dispatch(this, event); - }); + postWindowMessage( + this, + getIncumbentWindow(this) ?? getTopWindow(this), + message, + settings, + ); } print(): void {} @@ -43246,6 +43853,105 @@ export function getProcessTimers(window: Window): Record { return _(window).processTimers!; } +/** + * HTML's window post message steps, for a message `source` posts to + * `target`: a clone made in the target's realm, which lands as a task, + * and only where the target's origin is the one the poster named. Its + * source is the poster as the target's code holds it. + */ +function postWindowMessage( + target: Window, + source: Window, + message: unknown, + settings: unknown, +): void { + const named = typeof settings === "object" && settings !== null + ? (settings as {targetOrigin?: unknown}).targetOrigin + : settings; + const text = named === undefined ? "/" : String(named); + let targetOrigin: Origin | null = null; + if (text === "/") { + targetOrigin = getWindowOrigin(source); + } else if (text !== "*") { + const parsed = parseURL(text); + if (parsed === null) { + throw domError( + "SyntaxError", + `Failed to execute 'postMessage' on 'Window': Invalid target origin '${text}'.`, + ); + } + targetOrigin = getURLOrigin(parsed.href, {}); + } + const isolated = _(target).isolatedFrame; + if (isolated !== null) { + const origin = serializeOrigin(getWindowOrigin(source)); + isolated.postMessage( + cloneStructured(message, "execute 'postMessage' on 'Window'"), + origin, + targetOrigin === null ? "*" : serializeOrigin(targetOrigin), + ); + return; + } + const realm = _(target).realm; + const data = runInRealm(realm, () => { + const clone = cloneStructured(message, "execute 'postMessage' on 'Window'"); + return realm === null ? clone : rehomeClone(clone, realm); + }); + const origin = serializeOrigin(getWindowOrigin(source)); + const eventSource = viewWindow(target, source); + queueWindowTask(target, () => { + if (targetOrigin !== null && targetOrigin !== getWindowOrigin(target)) { + return; + } + const event = runInRealm(realm, () => + constructInternal(() => + new MessageEvent("message", { + data, + origin, + source: eventSource as unknown as globalThis.MessageEventSource, + }))); + dispatch(target, event); + }); +} + +/** + * A message the document of an isolated frame posted to its parent, which + * `window` stands in the page for. It lands as one from a window of + * `origin` would, and only where the parent's origin is `targetOrigin`. + */ +export function receiveFrameMessage( + window: Window, + data: unknown, + origin: string, + targetOrigin: string, +): void { + const parent = _(window).parentWindow; + if ( + parent === null || + _(window).discarded || + (targetOrigin !== "*" && + targetOrigin !== serializeOrigin(getWindowOrigin(parent))) + ) { + return; + } + const realm = _(parent).realm; + const cloned = runInRealm(realm, () => { + const clone = cloneStructured(data, "execute 'postMessage' on 'Window'"); + return realm === null ? clone : rehomeClone(clone, realm); + }); + const eventSource = viewWindow(parent, window); + queueWindowTask(parent, () => { + const event = runInRealm(realm, () => + constructInternal(() => + new MessageEvent("message", { + data: cloned, + origin, + source: eventSource as unknown as globalThis.MessageEventSource, + }))); + dispatch(parent, event); + }); +} + function queueWindowTask(window: Window, task: () => void): void { const tasks = _(window).tasks ??= new Set(); const handle = runtime.setTimeout(() => { diff --git a/src/internal/framebuffer.ts b/src/internal/framebuffer.ts index 977c9dde..2e6457db 100644 --- a/src/internal/framebuffer.ts +++ b/src/internal/framebuffer.ts @@ -841,6 +841,158 @@ export function clearGrid(grid: CellGrid): void { grid.border.fill(0); } +/** + * A grid's cells as another heap rebuilds them: its planes, and the text + * of each cluster its cells name in this heap's table, which the other + * heap does not share. + */ +export interface GridCells { + rows: number; + cols: number; + cluster: Uint32Array; + fg: Uint32Array; + bg: Uint32Array; + attrs: Uint16Array; + border: Uint32Array; + graphemes: Array<[number, string]>; +} + +export function exportGrid(grid: CellGrid): GridCells { + const graphemes = new Map(); + for (const char of grid.cluster) { + if (char >= CHAR_INTERNED && !graphemes.has(char)) { + graphemes.set(char, internedGraphemes[char - CHAR_INTERNED]); + } + } + return { + rows: grid.rows, + cols: grid.cols, + cluster: grid.cluster.slice(), + fg: grid.fg.slice(), + bg: grid.bg.slice(), + attrs: grid.attrs.slice(), + border: grid.border.slice(), + graphemes: [...graphemes], + }; +} + +// The longest cluster a cell from elsewhere may hold, in UTF-16 units. +const MAX_IMPORTED_CLUSTER = 64; + +const STYLE_BITS = (1 << ATTR.WidthShift) - 1; + +// The text a cell from elsewhere shows, or a space for what a terminal +// must never be sent: a control character, a lone surrogate, a code point +// past Unicode's, or a placeholder, which would name one of this heap's +// images. +function readImportedChar( + char: number, + border: number, + graphemes: Map, +): string { + if (border > 0) { + return getBorderChar(border); + } + if (char >= CHAR_INTERNED) { + const text = graphemes.get(char) ?? " "; + return text.length <= MAX_IMPORTED_CLUSTER && + /^\P{Cc}+$/u.test(text) && + !/\p{Cs}/u.test(text) + ? text + : " "; + } + if ( + char > 0x10ffff || + (char >= 0xd800 && char <= 0xdfff) || + isPlaceholderChar(char) + ) { + return " "; + } + const text = String.fromCodePoint(char); + return /\p{Cc}/u.test(text) ? " " : text; +} + +/** A placeholder cell of another heap's, at a cell of the grid. */ +export interface ImportedPlaceholder { + row: number; + col: number; + imageRow: number; + imageCol: number; + // The image's id in the other heap, from the cell's foreground. + id: number; + bg: number | null; +} + +/** + * Cells another heap painted, into `grid` from its top left corner, as + * much of them as fits. What they name is checked as untrusted: each + * cell's text and width are taken again here, so no cell can write a + * control sequence or claim columns its text does not take. A placeholder + * for one of the other heap's images is left blank, with its background, + * and handed to `placed`, which draws the image over it. + */ +export function importGrid( + cells: GridCells, + grid: CellGrid, + placed?: (placeholder: ImportedPlaceholder) => void, +): void { + clearGrid(grid); + const graphemes = new Map(cells.graphemes); + const rows = Math.min(cells.rows, grid.rows); + const cols = Math.min(cells.cols, grid.cols); + const size = cells.rows * cells.cols; + if ( + [cells.cluster, cells.fg, cells.bg, cells.attrs, cells.border].some( + (plane) => plane.length < size, + ) + ) { + return; + } + for (let row = 0; row < rows; row++) { + let col = 0; + while (col < cols) { + const from = row * cells.cols + col; + const to = row * grid.cols + col; + grid.fg[to] = cells.fg[from] & COLOR_MASK; + grid.bg[to] = cells.bg[from] & COLOR_MASK; + const char = cells.cluster[from]; + if (char === 0) { + col++; + continue; + } + if (placed !== undefined && isPlaceholderChar(char)) { + grid.cluster[to] = 0x20; + grid.attrs[to] = 1 << ATTR.WidthShift; + placed({ + row, + col, + imageRow: (char >>> 12) & 0xfff, + imageCol: char & 0xfff, + id: cells.fg[from] & 0xffffff, + bg: grid.bg[to] === 0 ? null : grid.bg[to], + }); + grid.fg[to] = 0; + col++; + continue; + } + let text = readImportedChar(char, cells.border[from], graphemes); + let width = getGraphemeColumns(text); + if (width < 1 || col + width > cols) { + text = " "; + width = 1; + } + grid.cluster[to] = encodeGrapheme(text); + grid.attrs[to] = + (cells.attrs[from] & STYLE_BITS) | + ((width < ATTR.WidthWide ? width : ATTR.WidthWide) << ATTR.WidthShift); + for (let covered = 1; covered < width; covered++) { + grid.bg[to + covered] = cells.bg[from + covered] & COLOR_MASK; + } + col += width; + } + } +} + export function clearRange(grid: CellGrid, start: number, end: number): void { if (end <= start) { return; diff --git a/src/internal/frames.ts b/src/internal/frames.ts index dd9a0150..4008a48d 100644 --- a/src/internal/frames.ts +++ b/src/internal/frames.ts @@ -10,10 +10,13 @@ import {Cascade, dispose} from "./cssom.ts"; import { applyMutations, attachDocument, + type BoxRenderer, clampScrollOffsets, constructInternal, dispatchAsUserAgent, + type Document, flushObservers, + type GraphicsSetting, revealPendingCaret, revealPendingEditingCaret, revealTextControlCaret, @@ -25,6 +28,7 @@ import { syncMediaQueries, type Window, } from "./dom.ts"; +import type {ColorDepth, Exchange} from "./exchange.ts"; import { adoptCellPixels, type Caret, @@ -35,20 +39,73 @@ import { resize, settleBorders, } from "./framebuffer.ts"; +import type {FrameIsolator} from "./isolateprotocol.ts"; import {framePainted, Layout} from "./layout.ts"; import {paint, Painter} from "./painter.ts"; -import {getDocumentLoader} from "./resources.ts"; +import {getDocumentLoader, type ResourceLoader} from "./resources.ts"; import {_} from "./slots.ts"; +import type {CellSizeSetting, PixelRatioSetting} from "./units.ts"; + +/** + * What a frame's engine takes from where it is shown: the terminal's + * colors and cell, and how its document loads and reports errors. + */ +export interface FrameSettings { + colorDepth: ColorDepth; + exchange: Exchange; + cellSize: CellSizeSetting; + devicePixelRatio: PixelRatioSetting; + images: GraphicsSetting; + canvas: GraphicsSetting; + // Where the frame's own frames start their documents, if anywhere. + isolateFrame: FrameIsolator | null; + load: ResourceLoader; + loadSignal: AbortSignal; + reportUncaught(error: unknown): void; + // The size of a cell in pixels and the pixel ratio, as they are now. + cellPixels(): {width: number; height: number}; + pixelRatio(): number | null; +} setFrameEngineFactory((document, window, parent, changed) => { const parentSlots = _(parent).extra; + const loader = getDocumentLoader(window); + return createFrameEngine( + document, + window, + { + colorDepth: parentSlots.framebuffer.writer.colorDepth, + exchange: parentSlots.exchange, + cellSize: parentSlots.cellSize, + devicePixelRatio: parentSlots.devicePixelRatio, + images: parentSlots.images, + canvas: parentSlots.canvas, + isolateFrame: parentSlots.isolateFrame, + load: loader === null + ? parentSlots.load + : (request, context) => loader(document, request, context), + loadSignal: parentSlots.loadSignal, + reportUncaught: (error) => parentSlots.reportUncaught(error), + cellPixels: () => parentSlots.framebuffer.cellPixels, + pixelRatio: () => parentSlots.framebuffer.pixelRatio, + }, + changed, + ); +}); + +/** + * The engine that paints `document` into cells at the size it is asked + * for, and calls `changed` when it has something new to paint. + */ +export function createFrameEngine( + document: Document, + window: Window, + settings: FrameSettings, + changed: () => void, +): BoxRenderer { const layout = new Layout(window, 0, 0); const cascade = new Cascade(window, layout); - const framebuffer = new Framebuffer( - 0, - 0, - parentSlots.framebuffer.writer.colorDepth, - ); + const framebuffer = new Framebuffer(0, 0, settings.colorDepth); // Painted again only once something in the frame asked for a frame: // its own mutations, an animation frame, a load, a resize. let stale = true; @@ -82,25 +139,23 @@ setFrameEngineFactory((document, window, parent, changed) => { changed(); } }; - const loader = getDocumentLoader(window); const unloaded = new AbortController(); attachDocument(document, { layout, cascade, - exchange: parentSlots.exchange, + exchange: settings.exchange, framebuffer, - cellSize: parentSlots.cellSize, - devicePixelRatio: parentSlots.devicePixelRatio, - images: parentSlots.images, - canvas: parentSlots.canvas, + cellSize: settings.cellSize, + devicePixelRatio: settings.devicePixelRatio, + images: settings.images, + canvas: settings.canvas, pty: "framed", - load: loader === null - ? parentSlots.load - : (request, context) => loader(document, request, context), + isolateFrame: settings.isolateFrame, + load: settings.load, // A frame's handler attributes stay inert. allowsInlineHandler: () => false, allowsPlugin: () => false, - loadSignal: AbortSignal.any([parentSlots.loadSignal, unloaded.signal]), + loadSignal: AbortSignal.any([settings.loadSignal, unloaded.signal]), render: () => { stale = true; if (fitting) { @@ -110,7 +165,7 @@ setFrameEngineFactory((document, window, parent, changed) => { } return Promise.resolve(); }, - reportUncaught: (error) => parentSlots.reportUncaught(error), + reportUncaught: (error) => settings.reportUncaught(error), // A frame's history is its own, and the embedder follows the top's. historyChanged: () => {}, historyTraversed: () => {}, @@ -142,7 +197,7 @@ setFrameEngineFactory((document, window, parent, changed) => { }; function fitFrame(cols: number, rows: number): CellGrid { - const cell = parentSlots.framebuffer.cellPixels; + const cell = settings.cellPixels(); if ( framebuffer.cellPixels.width !== cell.width || framebuffer.cellPixels.height !== cell.height @@ -150,7 +205,7 @@ setFrameEngineFactory((document, window, parent, changed) => { adoptCellPixels(framebuffer, cell.width, cell.height); stale = true; } - framebuffer.pixelRatio = parentSlots.framebuffer.pixelRatio; + framebuffer.pixelRatio = settings.pixelRatio(); if (cols !== grid.cols || rows !== grid.rows) { resizeFrame(framebuffer, layout, cascade, window, cols, rows); grid = new CellGrid(rows, cols); @@ -173,6 +228,10 @@ setFrameEngineFactory((document, window, parent, changed) => { revealTextControlCaret(page); clearGrid(grid); const context = new CellContext(grid, rows, cols, -framebuffer.scrollTop); + // A frame whose images are sent on by the page holds them in its + // framebuffer's table, and paints the placeholders that name them. + // The page draws them in kitty or in cells, as its terminal can. + context.graphics = framebuffer.graphics; context.layers = layers; paint(painter, context); // Joined here, since the layers do not leave with the grid. @@ -186,7 +245,7 @@ setFrameEngineFactory((document, window, parent, changed) => { : {...context.caret, row: context.caret.row + context.viewportOffset}; return grid; } -}); +} // A frame resized with its iframe's box, as the document a TermDOM shows // is with the terminal: a size can flip any @media result and every vw diff --git a/src/internal/isolate/blob.ts b/src/internal/isolate/blob.ts new file mode 100644 index 00000000..8c960ea0 --- /dev/null +++ b/src/internal/isolate/blob.ts @@ -0,0 +1,296 @@ +import {ReadableStream} from "web-streams-polyfill"; + +import {encodeUTF8, TextDecoder, toBytes} from "./encoding.ts"; +import {DOMException} from "./events.ts"; + +const contents = new WeakMap(); + +function blobState(blob: object): {bytes: Uint8Array; type: string} { + const state = contents.get(blob); + if (state === undefined) { + throw new TypeError("Illegal invocation"); + } + + return state; +} + +export function blobBytes(blob: Blob): Uint8Array { + return blobState(blob).bytes; +} + +export function isBlob(value: unknown): value is Blob { + return typeof value === "object" && value !== null && contents.has(value); +} + +const MAX_BLOB_URLS = 10000; +const blobURLs = new Map(); + +export function createObjectURL(object: unknown, origin: string): string { + if (!isBlob(object)) { + throw new TypeError("URL.createObjectURL needs a Blob"); + } + + if (blobURLs.size >= MAX_BLOB_URLS) { + throw new DOMException("Too many blob URLs", "QuotaExceededError"); + } + + const url = `blob:${origin}/${crypto.randomUUID()}`; + blobURLs.set(url, object); + return url; +} + +export function revokeObjectURL(url: unknown): void { + blobURLs.delete(String(url)); +} + +export function blobAt(url: string): Blob | undefined { + return blobURLs.get(url.replace(/#.*$/, "")); +} + +function normalizeType(type: unknown): string { + const text = type === undefined ? "" : String(type); + return /^[\x20-\x7e]*$/.test(text) ? text.toLowerCase() : ""; +} + +function concat(parts: Iterable): Uint8Array { + const chunks: Uint8Array[] = []; + let length = 0; + for (const part of parts) { + let chunk: Uint8Array; + if (isBlob(part)) { + chunk = blobBytes(part); + } else if (part instanceof ArrayBuffer || ArrayBuffer.isView(part)) { + chunk = toBytes(part).slice(); + } else { + chunk = encodeUTF8(String(part)); + } + + chunks.push(chunk); + length += chunk.length; + } + + const out = new Uint8Array(length); + let offset = 0; + for (const chunk of chunks) { + out.set(chunk, offset); + offset += chunk.length; + } + + return out; +} + +export class Blob { + constructor(parts: Iterable = [], options: {type?: string} = {}) { + contents.set(this, { + bytes: concat(parts), + type: normalizeType(options.type), + }); + } + + get size(): number { + return blobState(this).bytes.length; + } + + get type(): string { + return blobState(this).type; + } + + slice(start = 0, end?: number, type?: string): Blob { + const bytes = blobState(this).bytes; + const size = bytes.length; + const from = start < 0 ? Math.max(size + start, 0) : Math.min(start, size); + const to = end === undefined + ? size + : end < 0 ? Math.max(size + end, 0) : Math.min(end, size); + return new Blob([bytes.subarray(from, Math.max(from, to))], {type}); + } + + async arrayBuffer(): Promise { + return blobState(this).bytes.slice().buffer; + } + + async bytes(): Promise { + return blobState(this).bytes.slice(); + } + + async text(): Promise { + return new TextDecoder().decode(blobState(this).bytes); + } + + stream(): ReadableStream { + const bytes = blobState(this).bytes.slice(); + return new ReadableStream({ + start(controller) { + if (bytes.length > 0) { + controller.enqueue(bytes); + } + + controller.close(); + }, + }); + } +} + +Object.defineProperty(Blob.prototype, Symbol.toStringTag, { + value: "Blob", + configurable: true, +}); + +const files = new WeakMap(); + +export class File extends Blob { + constructor( + parts: Iterable, + name: string, + options: {type?: string; lastModified?: number} = {}, + ) { + if (arguments.length < 2) { + throw new TypeError("File requires a name"); + } + + super(parts, options); + files.set(this, { + name: String(name), + lastModified: options.lastModified ?? Date.now(), + }); + } + + get name(): string { + const state = files.get(this); + if (state === undefined) { + throw new TypeError("Illegal invocation"); + } + + return state.name; + } + + get lastModified(): number { + const state = files.get(this); + if (state === undefined) { + throw new TypeError("Illegal invocation"); + } + + return state.lastModified; + } +} + +Object.defineProperty(File.prototype, Symbol.toStringTag, { + value: "File", + configurable: true, +}); + +type Entry = [string, string | File]; + +const forms = new WeakMap(); + +function formEntries(form: object): Entry[] { + const entries = forms.get(form); + if (entries === undefined) { + throw new TypeError("Illegal invocation"); + } + + return entries; +} + +function toEntry(name: string, value: unknown, filename?: string): Entry { + if (isBlob(value)) { + const file = value instanceof File && filename === undefined + ? value + : new File( + [value], + filename ?? (value instanceof File ? value.name : "blob"), + {type: value.type}, + ); + return [String(name), file]; + } + + return [String(name), String(value)]; +} + +export class FormData { + constructor(form?: unknown) { + if (form !== undefined) { + throw new TypeError("FormData from a form element is not supported here"); + } + + forms.set(this, []); + } + + append(name: string, value: unknown, filename?: string): void { + formEntries(this).push(toEntry(name, value, filename)); + } + + set(name: string, value: unknown, filename?: string): void { + const entries = formEntries(this); + const entry = toEntry(name, value, filename); + const index = entries.findIndex(([key]) => key === entry[0]); + if (index === -1) { + entries.push(entry); + return; + } + + entries.splice(index, 1, entry); + for (let i = entries.length - 1; i > index; i--) { + if (entries[i][0] === entry[0]) { + entries.splice(i, 1); + } + } + } + + delete(name: string): void { + const key = String(name); + const entries = formEntries(this); + forms.set(this, entries.filter(([k]) => k !== key)); + } + + get(name: string): string | File | null { + const key = String(name); + return formEntries(this).find(([k]) => k === key)?.[1] ?? null; + } + + getAll(name: string): Array { + const key = String(name); + return formEntries(this).filter(([k]) => k === key).map(([, v]) => v); + } + + has(name: string): boolean { + const key = String(name); + return formEntries(this).some(([k]) => k === key); + } + + forEach( + callback: (value: string | File, key: string, form: FormData) => void, + thisArg?: unknown, + ): void { + for (const [key, value] of formEntries(this).slice()) { + callback.call(thisArg, value, key, this); + } + } + + *entries(): IterableIterator { + for (const [key, value] of formEntries(this).slice()) { + yield [key, value]; + } + } + + *keys(): IterableIterator { + for (const [key] of formEntries(this).slice()) { + yield key; + } + } + + *values(): IterableIterator { + for (const [, value] of formEntries(this).slice()) { + yield value; + } + } + + [Symbol.iterator](): IterableIterator { + return this.entries(); + } +} + +Object.defineProperty(FormData.prototype, Symbol.toStringTag, { + value: "FormData", + configurable: true, +}); diff --git a/src/internal/isolate/bundle.ts b/src/internal/isolate/bundle.ts new file mode 100644 index 00000000..6f84ba0f --- /dev/null +++ b/src/internal/isolate/bundle.ts @@ -0,0 +1,107 @@ +/** + * The frame runtime as one classic script for a bare isolate: the engine, + * its shims and the frame entry, bundled with nothing left to import. The + * script evaluates to a function of the host's callbacks, which returns a + * function of the frame's settings, which returns the frame's dispatcher. + * A built package carries the script next to its modules, and a checkout + * bundles it from source on first use. + */ +import type * as FS from "node:fs/promises"; +import type * as NodeModule from "node:module"; +import type * as NodeURL from "node:url"; + +import type * as ESBuild from "esbuild"; + +export const HOST_CALLBACKS = [ + "post", + "log", + "setTimer", + "clearTimer", + "random", + "scripts", +] as const; + +export const FRAME_SCRIPT = "isolate-frame.js"; + +interface NodeProcess { + getBuiltinModule?(id: string): unknown; +} + +// Node's own modules, and packages beside this one, are reached through +// the process at run time, so a bundle of TermDOM made for another +// platform imports none of them. +function getNodeBuiltin(id: string): T { + const {process} = globalThis as {process?: NodeProcess}; + if (typeof process?.getBuiltinModule !== "function") { + throw new Error(`This runtime has no ${id}`); + } + return process.getBuiltinModule(id) as T; +} + +export function requireNodePackage(id: string): T { + const {createRequire} = getNodeBuiltin("node:module"); + return createRequire(import.meta.url)(id) as T; +} + +const ENTRY = new URL("./frame.ts", import.meta.url); + +export async function buildFrameScript(): Promise { + const {build} = requireNodePackage("esbuild"); + // The file's path, which on Windows a URL's pathname is not. + const {fileURLToPath} = getNodeBuiltin("node:url"); + const result = await build({ + entryPoints: [fileURLToPath(ENTRY)], + bundle: true, + write: false, + format: "iife", + globalName: "__termdomFrame", + platform: "neutral", + mainFields: ["module", "main"], + target: "es2022", + legalComments: "none", + define: {"import.meta.url": "undefined", "import.meta.litest": "undefined"}, + logLevel: "silent", + }); + return `(function (${HOST_CALLBACKS.join(", ")}) { +"use strict"; +${result.outputFiles[0].text} +const frame = __termdomFrame; +return (init) => { + frame.start({${HOST_CALLBACKS.join(", ")}}, init); + return (kind, ...args) => { + switch (kind) { + case "receive": return frame.receive(args[0]); + case "timer": return frame.fireTimer(args[0]); + case "scriptBegin": return frame.scriptBegin(args[0]); + case "scriptEnd": return frame.scriptEnd(args[0]); + case "scriptFinished": return frame.scriptFinished(args[0], args[1]); + case "interactive": return frame.documentInteractive(); + case "loaded": return frame.documentLoaded(); + case "dispose": return frame.dispose(); + } + }; +}; +})`; +} + +let script: Promise | undefined; + +export function loadFrameScript(): Promise { + script ??= (async () => { + for (const url of [ + new URL(`./${FRAME_SCRIPT}`, import.meta.url), + new URL(`../${FRAME_SCRIPT}`, import.meta.url), + ]) { + try { + const fs = getNodeBuiltin("node:fs/promises"); + return await fs.readFile(url, "utf8"); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "ENOENT") { + throw error; + } + } + } + return buildFrameScript(); + })(); + return script; +} diff --git a/src/internal/isolate/compression.ts b/src/internal/isolate/compression.ts new file mode 100644 index 00000000..523122f6 --- /dev/null +++ b/src/internal/isolate/compression.ts @@ -0,0 +1,139 @@ +import {Gunzip, Inflate, Unzlib} from "fflate"; +import {ReadableStream, WritableStream} from "web-streams-polyfill"; + +import {toBytes} from "./encoding.ts"; + +const SLICE_BYTES = 4096; + +type Inflater = Gunzip | Inflate | Unzlib; + +function createInflater(format: string): Inflater { + switch (format) { + case "gzip": + return new Gunzip(); + case "deflate": + return new Unzlib(); + case "deflate-raw": + return new Inflate(); + default: + throw new TypeError(`Unsupported compression format: ${format}`); + } +} + +const streams = new WeakMap< + object, + {readable: ReadableStream; writable: WritableStream} +>(); + +export class DecompressionStream { + constructor(format: string) { + const inflater = createInflater(String(format)); + const input: Uint8Array[] = []; + const output: Uint8Array[] = []; + let inputDone = false; + let ended = false; + let wake: (() => void) | null = null; + const signal = (): void => { + const resume = wake; + wake = null; + resume?.(); + }; + inflater.ondata = (chunk, final) => { + if (chunk.length > 0) { + output.push(chunk); + } + + if (final) { + ended = true; + } + }; + const readable = new ReadableStream({ + async pull(controller) { + while (output.length === 0) { + if (input.length > 0) { + const chunk = input[0]; + const piece = chunk.subarray(0, SLICE_BYTES); + if (chunk.length > SLICE_BYTES) { + input[0] = chunk.subarray(SLICE_BYTES); + } else { + input.shift(); + } + + if (ended) { + controller.error(new TypeError("Junk after the compressed data")); + return; + } + + try { + inflater.push(piece, inputDone && input.length === 0); + } catch (error) { + controller.error( + new TypeError(`Decompression failed: ${String(error)}`), + ); + return; + } + } else if (inputDone) { + if (!ended) { + controller.error(new TypeError("The compressed data ends early")); + } else { + controller.close(); + } + + return; + } else { + await new Promise((resolve) => { + wake = resolve; + }); + } + } + + controller.enqueue(output.shift()!); + }, + cancel() { + input.length = 0; + output.length = 0; + inputDone = true; + signal(); + }, + }); + const writable = new WritableStream({ + write(chunk) { + input.push(toBytes(chunk)); + signal(); + }, + close() { + inputDone = true; + signal(); + }, + abort() { + input.length = 0; + inputDone = true; + signal(); + }, + }); + streams.set(this, {readable, writable}); + } + + get readable(): ReadableStream { + const pair = streams.get(this); + if (pair === undefined) { + throw new TypeError("Illegal invocation"); + } + + return pair.readable; + } + + get writable(): WritableStream { + const pair = streams.get(this); + if (pair === undefined) { + throw new TypeError("Illegal invocation"); + } + + return pair.writable; + } +} + +Object.defineProperty(DecompressionStream.prototype, Symbol.toStringTag, { + value: "DecompressionStream", + configurable: true, +}); diff --git a/src/internal/isolate/console.ts b/src/internal/isolate/console.ts new file mode 100644 index 00000000..4c61ce19 --- /dev/null +++ b/src/internal/isolate/console.ts @@ -0,0 +1,60 @@ +import {host} from "./host.ts"; + +function describe(value: unknown, depth: number): string { + if (typeof value === "string") { + return depth === 0 ? value : JSON.stringify(value); + } + + if (value instanceof Error) { + return value.stack ?? `${value.name}: ${value.message}`; + } + + if (typeof value === "function") { + return `[Function ${value.name || "(anonymous)"}]`; + } + + if (typeof value !== "object" || value === null) { + return String(value); + } + + if (depth > 2) { + return Array.isArray(value) ? "[Array]" : "[Object]"; + } + + try { + if (Array.isArray(value)) { + return `[${value.map((item) => describe(item, depth + 1)).join(", ")}]`; + } + + const entries = Object.keys(value) + .map((key) => + `${key}: ${describe((value as Record)[key], depth + 1)}`, + ); + return `{${entries.join(", ")}}`; + } catch (error) { + return `[object: ${error instanceof Error ? error.message : "unreadable"}]`; + } +} + +function format(args: unknown[]): string { + return args.map((arg) => describe(arg, 0)).join(" "); +} + +function method(level: string): (...args: unknown[]) => void { + return (...args: unknown[]): void => { + host.log(level, format(args)); + }; +} + +export const console = { + debug: method("debug"), + error: method("error"), + info: method("info"), + log: method("log"), + trace: method("debug"), + warn: method("warn"), +}; + +export function reportError(error: unknown): void { + host.log("error", format(["Uncaught", error])); +} diff --git a/src/internal/isolate/encoding.ts b/src/internal/isolate/encoding.ts new file mode 100644 index 00000000..eb0f81d6 --- /dev/null +++ b/src/internal/isolate/encoding.ts @@ -0,0 +1,252 @@ +export function toBytes(input: unknown): Uint8Array { + if (input === undefined) { + return new Uint8Array(0); + } + + if (input instanceof ArrayBuffer || input instanceof SharedArrayBuffer) { + return new Uint8Array(input); + } + + if (ArrayBuffer.isView(input)) { + return new Uint8Array(input.buffer, input.byteOffset, input.byteLength); + } + + throw new TypeError("The input must be an ArrayBuffer or a view of one"); +} + +export function encodeUTF8(input: string): Uint8Array { + const out = new Uint8Array(input.length * 3); + let length = 0; + for (let i = 0; i < input.length; i++) { + let code = input.charCodeAt(i); + if (code >= 0xd800 && code <= 0xdbff && i + 1 < input.length) { + const next = input.charCodeAt(i + 1); + if (next >= 0xdc00 && next <= 0xdfff) { + code = 0x10000 + ((code - 0xd800) << 10) + (next - 0xdc00); + i++; + } else { + code = 0xfffd; + } + } else if (code >= 0xd800 && code <= 0xdfff) { + code = 0xfffd; + } + + if (code < 0x80) { + out[length++] = code; + } else if (code < 0x800) { + out[length++] = 0xc0 | (code >> 6); + out[length++] = 0x80 | (code & 0x3f); + } else if (code < 0x10000) { + out[length++] = 0xe0 | (code >> 12); + out[length++] = 0x80 | ((code >> 6) & 0x3f); + out[length++] = 0x80 | (code & 0x3f); + } else { + out[length++] = 0xf0 | (code >> 18); + out[length++] = 0x80 | ((code >> 12) & 0x3f); + out[length++] = 0x80 | ((code >> 6) & 0x3f); + out[length++] = 0x80 | (code & 0x3f); + } + } + + return out.slice(0, length); +} + +export class TextEncoder { + get encoding(): string { + return "utf-8"; + } + + encode(input = ""): Uint8Array { + return encodeUTF8(String(input)); + } + + encodeInto( + input: string, + destination: Uint8Array, + ): {read: number; written: number} { + let read = 0; + let written = 0; + for (const char of String(input)) { + const bytes = encodeUTF8(char); + if (written + bytes.length > destination.length) { + break; + } + + destination.set(bytes, written); + written += bytes.length; + read += char.length; + } + + return {read, written}; + } +} + +Object.defineProperty(TextEncoder.prototype, Symbol.toStringTag, { + value: "TextEncoder", + configurable: true, +}); + +const LABELS = new Set(["utf-8", "utf8", "unicode-1-1-utf-8"]); + +interface DecoderState { + fatal: boolean; + ignoreBOM: boolean; + pending: number[]; + seenBOM: boolean; +} + +const decoders = new WeakMap(); + +function decoderState(decoder: object): DecoderState { + const state = decoders.get(decoder); + if (state === undefined) { + throw new TypeError("Illegal invocation"); + } + + return state; +} + +function stripBOM(state: DecoderState, text: string): string { + if (!state.seenBOM && text.length > 0) { + state.seenBOM = true; + if (!state.ignoreBOM && text.charCodeAt(0) === 0xfeff) { + return text.slice(1); + } + } + + return text; +} + +export class TextDecoder { + constructor( + label = "utf-8", + options: {fatal?: boolean; ignoreBOM?: boolean} = {}, + ) { + if (!LABELS.has(String(label).trim().toLowerCase())) { + throw new RangeError(`The encoding "${label}" is not supported`); + } + + decoders.set(this, { + fatal: !!options.fatal, + ignoreBOM: !!options.ignoreBOM, + pending: [], + seenBOM: false, + }); + } + + get encoding(): string { + return "utf-8"; + } + + get fatal(): boolean { + return decoderState(this).fatal; + } + + get ignoreBOM(): boolean { + return decoderState(this).ignoreBOM; + } + + decode(input?: unknown, options: {stream?: boolean} = {}): string { + const state = decoderState(this); + const fresh = toBytes(input); + const bytes = state.pending.length > 0 + ? Uint8Array.from([...state.pending, ...fresh]) + : fresh; + state.pending = []; + let out = ""; + let i = 0; + const fail = (): void => { + if (state.fatal) { + state.pending = []; + throw new TypeError("The encoded data was not valid UTF-8"); + } + + out += "�"; + }; + while (i < bytes.length) { + const byte = bytes[i]; + let need: number; + let code: number; + let lower = 0x80; + let upper = 0xbf; + if (byte < 0x80) { + out += String.fromCharCode(byte); + i++; + continue; + } else if (byte >= 0xc2 && byte <= 0xdf) { + need = 1; + code = byte & 0x1f; + } else if (byte >= 0xe0 && byte <= 0xef) { + need = 2; + code = byte & 0x0f; + if (byte === 0xe0) { + lower = 0xa0; + } else if (byte === 0xed) { + upper = 0x9f; + } + } else if (byte >= 0xf0 && byte <= 0xf4) { + need = 3; + code = byte & 0x07; + if (byte === 0xf0) { + lower = 0x90; + } else if (byte === 0xf4) { + upper = 0x8f; + } + } else { + fail(); + i++; + continue; + } + + let j = 1; + let valid = true; + for (; j <= need; j++) { + if (i + j >= bytes.length) { + break; + } + + const next = bytes[i + j]; + if (next < lower || next > upper) { + valid = false; + break; + } + + lower = 0x80; + upper = 0xbf; + code = (code << 6) | (next & 0x3f); + } + + if (valid && j <= need) { + if (options.stream) { + state.pending = Array.from(bytes.subarray(i)); + return stripBOM(state, out); + } + + fail(); + i += j; + continue; + } + + if (!valid) { + fail(); + i += j; + continue; + } + + out += String.fromCodePoint(code); + i += need + 1; + } + + const result = stripBOM(state, out); + if (!options.stream) { + state.seenBOM = false; + } + + return result; + } +} + +Object.defineProperty(TextDecoder.prototype, Symbol.toStringTag, { + value: "TextDecoder", + configurable: true, +}); diff --git a/src/internal/isolate/events.ts b/src/internal/isolate/events.ts new file mode 100644 index 00000000..fe522562 --- /dev/null +++ b/src/internal/isolate/events.ts @@ -0,0 +1,480 @@ +import {reportError} from "./console.ts"; +import {performance, setTimeout} from "./timers.ts"; + +const CODES: Record = { + IndexSizeError: 1, + HierarchyRequestError: 3, + WrongDocumentError: 4, + InvalidCharacterError: 5, + NoModificationAllowedError: 7, + NotFoundError: 8, + NotSupportedError: 9, + InvalidStateError: 11, + SyntaxError: 12, + InvalidModificationError: 13, + NamespaceError: 14, + InvalidAccessError: 15, + TypeMismatchError: 17, + SecurityError: 18, + NetworkError: 19, + AbortError: 20, + URLMismatchError: 21, + QuotaExceededError: 22, + TimeoutError: 23, + InvalidNodeTypeError: 24, + DataCloneError: 25, +}; + +export class DOMException extends Error { + declare readonly name: string; + declare readonly code: number; + + constructor(message = "", name = "Error") { + super(String(message)); + Object.defineProperty(this, "name", { + value: String(name), + configurable: true, + writable: true, + }); + Object.defineProperty(this, "code", { + value: CODES[String(name)] ?? 0, + configurable: true, + }); + } +} + +interface EventState { + type: string; + bubbles: boolean; + cancelable: boolean; + composed: boolean; + target: EventTarget | null; + currentTarget: EventTarget | null; + phase: number; + canceled: boolean; + stopped: boolean; + stoppedImmediately: boolean; + inPassiveListener: boolean; + timeStamp: number; +} + +const events = new WeakMap(); + +function eventState(event: object): EventState { + const state = events.get(event); + if (state === undefined) { + throw new TypeError("Illegal invocation"); + } + + return state; +} + +function isTrusted(): boolean { + return false; +} + +export class Event { + static readonly NONE = 0; + static readonly CAPTURING_PHASE = 1; + static readonly AT_TARGET = 2; + static readonly BUBBLING_PHASE = 3; + + constructor(type: string, init: EventInit = {}) { + if (arguments.length === 0) { + throw new TypeError("The event type is required"); + } + + events.set(this, { + type: String(type), + bubbles: !!init?.bubbles, + cancelable: !!init?.cancelable, + composed: !!init?.composed, + target: null, + currentTarget: null, + phase: 0, + canceled: false, + stopped: false, + stoppedImmediately: false, + inPassiveListener: false, + timeStamp: performance.now(), + }); + Object.defineProperty(this, "isTrusted", { + get: isTrusted, + enumerable: true, + configurable: false, + }); + } + + get type(): string { + return eventState(this).type; + } + + get bubbles(): boolean { + return eventState(this).bubbles; + } + + get cancelable(): boolean { + return eventState(this).cancelable; + } + + get composed(): boolean { + return eventState(this).composed; + } + + get target(): EventTarget | null { + return eventState(this).target; + } + + get srcElement(): EventTarget | null { + return eventState(this).target; + } + + get currentTarget(): EventTarget | null { + return eventState(this).currentTarget; + } + + get eventPhase(): number { + return eventState(this).phase; + } + + get defaultPrevented(): boolean { + return eventState(this).canceled; + } + + get returnValue(): boolean { + return !eventState(this).canceled; + } + + get cancelBubble(): boolean { + return eventState(this).stopped; + } + + set cancelBubble(value: boolean) { + if (value) { + eventState(this).stopped = true; + } + } + + get timeStamp(): number { + return eventState(this).timeStamp; + } + + composedPath(): EventTarget[] { + const state = eventState(this); + return state.currentTarget ? [state.currentTarget] : []; + } + + preventDefault(): void { + const state = eventState(this); + if (state.cancelable && !state.inPassiveListener) { + state.canceled = true; + } + } + + stopPropagation(): void { + eventState(this).stopped = true; + } + + stopImmediatePropagation(): void { + const state = eventState(this); + state.stopped = true; + state.stoppedImmediately = true; + } +} + +Object.defineProperty(Event.prototype, Symbol.toStringTag, { + value: "Event", + configurable: true, +}); + +interface Listener { + callback: EventListenerOrEventListenerObject; + capture: boolean; + once: boolean; + passive: boolean; + removed: boolean; +} + +const targets = new WeakMap>(); + +function listenersOf(target: object): Map { + let map = targets.get(target); + if (map === undefined) { + map = new Map(); + targets.set(target, map); + } + + return map; +} + +function flatten(options: boolean | EventListenerOptions | undefined): boolean { + return typeof options === "boolean" ? options : !!options?.capture; +} + +export class EventTarget { + constructor() { + listenersOf(this); + } + + addEventListener( + type: string, + callback: EventListenerOrEventListenerObject | null, + options?: boolean | AddEventListenerOptions, + ): void { + if (callback == null) { + return; + } + + const capture = flatten(options); + const object = typeof options === "object" ? options : undefined; + const signal = object?.signal; + if (signal?.aborted) { + return; + } + + const map = listenersOf(this); + const key = String(type); + const list = map.get(key) ?? []; + if (list.some((l) => l.callback === callback && l.capture === capture)) { + return; + } + + const listener: Listener = { + callback, + capture, + once: !!object?.once, + passive: !!object?.passive, + removed: false, + }; + list.push(listener); + map.set(key, list); + signal?.addEventListener("abort", () => { + this.removeEventListener(key, callback, {capture}); + }); + } + + removeEventListener( + type: string, + callback: EventListenerOrEventListenerObject | null, + options?: boolean | EventListenerOptions, + ): void { + const capture = flatten(options); + const map = listenersOf(this); + const list = map.get(String(type)); + if (list === undefined) { + return; + } + + const index = list.findIndex( + (l) => l.callback === callback && l.capture === capture, + ); + if (index !== -1) { + list[index].removed = true; + list.splice(index, 1); + } + } + + dispatchEvent(event: Event): boolean { + const state = eventState(event); + if (state.phase !== 0) { + throw new DOMException( + "The event is already being dispatched.", + "InvalidStateError", + ); + } + + state.target = this; + state.currentTarget = this; + state.phase = 2; + const list = listenersOf(this).get(state.type); + for (const listener of list ? list.slice() : []) { + if (listener.removed) { + continue; + } + + if (listener.once) { + this.removeEventListener(state.type, listener.callback, { + capture: listener.capture, + }); + } + + state.inPassiveListener = listener.passive; + try { + const callback = listener.callback; + if (typeof callback === "function") { + callback.call(this, event as never); + } else { + callback.handleEvent(event as never); + } + } catch (error) { + reportError(error); + } + + state.inPassiveListener = false; + if (state.stoppedImmediately) { + break; + } + } + + state.phase = 0; + state.currentTarget = null; + return !state.canceled; + } +} + +Object.defineProperty(EventTarget.prototype, Symbol.toStringTag, { + value: "EventTarget", + configurable: true, +}); + +interface SignalState { + aborted: boolean; + reason: unknown; + onabort: ((event: Event) => unknown) | null; +} + +const signals = new WeakMap(); +let constructingSignal = false; + +function signalState(signal: object): SignalState { + const state = signals.get(signal); + if (state === undefined) { + throw new TypeError("Illegal invocation"); + } + + return state; +} + +function createSignal(): AbortSignal { + constructingSignal = true; + try { + return new AbortSignal(); + } finally { + constructingSignal = false; + } +} + +function abortSignal(signal: AbortSignal, reason: unknown): void { + const state = signalState(signal); + if (state.aborted) { + return; + } + + state.aborted = true; + state.reason = reason === undefined + ? new DOMException("This operation was aborted", "AbortError") + : reason; + const event = new Event("abort"); + if (state.onabort) { + try { + state.onabort.call(signal, event); + } catch (error) { + reportError(error); + } + } + + signal.dispatchEvent(event); +} + +export class AbortSignal extends EventTarget { + constructor() { + if (!constructingSignal) { + throw new TypeError("Illegal constructor"); + } + + super(); + signals.set(this, {aborted: false, reason: undefined, onabort: null}); + } + + get aborted(): boolean { + return signalState(this).aborted; + } + + get reason(): unknown { + return signalState(this).reason; + } + + get onabort(): ((event: Event) => unknown) | null { + return signalState(this).onabort; + } + + set onabort(value: ((event: Event) => unknown) | null) { + signalState(this).onabort = typeof value === "function" ? value : null; + } + + static abort(reason?: unknown): AbortSignal { + const signal = createSignal(); + abortSignal(signal, reason); + return signal; + } + + static timeout(ms: number): AbortSignal { + const signal = createSignal(); + setTimeout(() => { + abortSignal( + signal, + new DOMException("The operation timed out.", "TimeoutError"), + ); + }, ms); + return signal; + } + + static any(sources: Iterable): AbortSignal { + const signal = createSignal(); + const list = Array.from(sources); + for (const source of list) { + if (source.aborted) { + abortSignal(signal, source.reason); + return signal; + } + } + + for (const source of list) { + source.addEventListener( + "abort", + () => abortSignal(signal, source.reason), + {once: true}, + ); + } + + return signal; + } + + throwIfAborted(): void { + const state = signalState(this); + if (state.aborted) { + throw state.reason; + } + } +} + +Object.defineProperty(AbortSignal.prototype, Symbol.toStringTag, { + value: "AbortSignal", + configurable: true, +}); + +const controllers = new WeakMap(); + +export class AbortController { + constructor() { + controllers.set(this, createSignal()); + } + + get signal(): AbortSignal { + const signal = controllers.get(this); + if (signal === undefined) { + throw new TypeError("Illegal invocation"); + } + + return signal; + } + + abort(reason?: unknown): void { + abortSignal(this.signal, reason); + } +} + +Object.defineProperty(AbortController.prototype, Symbol.toStringTag, { + value: "AbortController", + configurable: true, +}); diff --git a/src/internal/isolate/fetch.ts b/src/internal/isolate/fetch.ts new file mode 100644 index 00000000..f9a1a466 --- /dev/null +++ b/src/internal/isolate/fetch.ts @@ -0,0 +1,660 @@ +import URLSearchParamsConstructor from "core-js-pure/actual/url-search-params/index.js"; +import URLConstructor from "core-js-pure/actual/url/index.js"; +import {ReadableStream} from "web-streams-polyfill"; + +import {Blob, blobAt, blobBytes, FormData, isBlob} from "./blob.ts"; +import {encodeUTF8, TextDecoder, toBytes} from "./encoding.ts"; +import {AbortController, type AbortSignal} from "./events.ts"; + +type HeaderList = Array<[string, string]>; + +const headerLists = + new WeakMap(); + +function headerState(headers: object): {list: HeaderList; immutable: boolean} { + const state = headerLists.get(headers); + if (state === undefined) { + throw new TypeError("Illegal invocation"); + } + + return state; +} + +function headerName(name: unknown): string { + const text = String(name); + if (!/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(text)) { + throw new TypeError(`Invalid header name: ${text}`); + } + + return text.toLowerCase(); +} + +function headerValue(value: unknown): string { + const text = String(value).replace(/^[\t\n\r ]+|[\t\n\r ]+$/g, ""); + if (/[\0\r\n]/.test(text)) { + throw new TypeError("Invalid header value"); + } + + return text; +} + +function mutable(headers: object): HeaderList { + const state = headerState(headers); + if (state.immutable) { + throw new TypeError("Headers are immutable"); + } + + return state.list; +} + +export function freezeHeaders(headers: Headers): void { + headerState(headers).immutable = true; +} + +export class Headers { + constructor(init?: unknown) { + headerLists.set(this, {list: [], immutable: false}); + if (init == null) { + return; + } + + if (init instanceof Headers) { + for (const [name, value] of headerState(init).list) { + this.append(name, value); + } + } else if ( + typeof init === "object" && Symbol.iterator in (init as object) + ) { + for (const pair of init as Iterable>) { + const items = Array.from(pair); + if (items.length !== 2) { + throw new TypeError("Each header must be a name and a value"); + } + + this.append(String(items[0]), String(items[1])); + } + } else if (typeof init === "object") { + for (const key of Object.keys(init as object)) { + this.append(key, String((init as Record)[key])); + } + } else { + throw new TypeError("Invalid headers"); + } + } + + append(name: string, value: string): void { + mutable(this).push([headerName(name), headerValue(value)]); + } + + set(name: string, value: string): void { + const key = headerName(name); + const list = mutable(this); + const index = list.findIndex(([k]) => k === key); + const entry: [string, string] = [key, headerValue(value)]; + if (index === -1) { + list.push(entry); + return; + } + + list.splice(index, 1, entry); + for (let i = list.length - 1; i > index; i--) { + if (list[i][0] === key) { + list.splice(i, 1); + } + } + } + + delete(name: string): void { + const key = headerName(name); + const list = mutable(this); + for (let i = list.length - 1; i >= 0; i--) { + if (list[i][0] === key) { + list.splice(i, 1); + } + } + } + + get(name: string): string | null { + const key = headerName(name); + const values = headerState(this) + .list.filter(([k]) => k === key) + .map(([, v]) => v); + return values.length === 0 ? null : values.join(", "); + } + + getSetCookie(): string[] { + return headerState(this) + .list.filter(([k]) => k === "set-cookie") + .map(([, v]) => v); + } + + has(name: string): boolean { + const key = headerName(name); + return headerState(this).list.some(([k]) => k === key); + } + + *entries(): IterableIterator<[string, string]> { + const names = [...new Set(headerState(this).list.map(([k]) => k))].sort(); + for (const name of names) { + yield [name, this.get(name)!]; + } + } + + *keys(): IterableIterator { + for (const [name] of this.entries()) { + yield name; + } + } + + *values(): IterableIterator { + for (const [, value] of this.entries()) { + yield value; + } + } + + forEach( + callback: (value: string, name: string, headers: Headers) => void, + thisArg?: unknown, + ): void { + for (const [name, value] of this.entries()) { + callback.call(thisArg, value, name, this); + } + } + + [Symbol.iterator](): IterableIterator<[string, string]> { + return this.entries(); + } +} + +Object.defineProperty(Headers.prototype, Symbol.toStringTag, { + value: "Headers", + configurable: true, +}); + +interface BodyState { + stream: ReadableStream | null; + bytes: Uint8Array | null; + used: boolean; +} + +const bodies = new WeakMap(); + +function bodyState(owner: object): BodyState { + const state = bodies.get(owner); + if (state === undefined) { + throw new TypeError("Illegal invocation"); + } + + return state; +} + +function extractBody( + init: unknown, + headers: Headers, +): {stream: ReadableStream | null; bytes: Uint8Array | null} { + if (init == null) { + return {stream: null, bytes: null}; + } + + let bytes: Uint8Array; + let type: string | null = null; + if (init instanceof ReadableStream) { + return {stream: init as ReadableStream, bytes: null}; + } else if (isBlob(init)) { + bytes = blobBytes(init).slice(); + type = (init as Blob).type || null; + } else if (init instanceof ArrayBuffer || ArrayBuffer.isView(init)) { + bytes = toBytes(init).slice(); + } else if (init instanceof URLSearchParamsConstructor) { + bytes = encodeUTF8(String(init)); + type = "application/x-www-form-urlencoded;charset=UTF-8"; + } else if (init instanceof FormData) { + throw new TypeError("A FormData body is not supported yet"); + } else { + bytes = encodeUTF8(String(init)); + type = "text/plain;charset=UTF-8"; + } + + if (type !== null && !headers.has("content-type")) { + headers.set("content-type", type); + } + + return {stream: null, bytes}; +} + +function streamOf(bytes: Uint8Array): ReadableStream { + return new ReadableStream({ + start(controller) { + if (bytes.length > 0) { + controller.enqueue(bytes.slice()); + } + + controller.close(); + }, + }); +} + +function bodyStream(state: BodyState): ReadableStream | null { + if (state.stream === null && state.bytes !== null) { + state.stream = streamOf(state.bytes); + } + + return state.stream; +} + +async function consume(owner: object): Promise { + const state = bodyState(owner); + if (state.used) { + throw new TypeError("Body has already been consumed"); + } + + state.used = true; + if (state.stream === null) { + return state.bytes ? state.bytes.slice() : new Uint8Array(0); + } + + const reader = state.stream.getReader(); + const chunks: Uint8Array[] = []; + let length = 0; + for (;;) { + const {done, value} = await reader.read(); + if (done) { + break; + } + + const chunk = toBytes(value); + chunks.push(chunk); + length += chunk.length; + } + + const out = new Uint8Array(length); + let offset = 0; + for (const chunk of chunks) { + out.set(chunk, offset); + offset += chunk.length; + } + + return out; +} + +function teeBody(state: BodyState): BodyState { + if (state.used) { + throw new TypeError("Body has already been consumed"); + } + + if (state.stream === null) { + return {stream: null, bytes: state.bytes, used: false}; + } + + const [left, right] = state.stream.tee(); + state.stream = left; + return {stream: right, bytes: null, used: false}; +} + +class Body { + get body(): ReadableStream | null { + return bodyStream(bodyState(this)); + } + + get bodyUsed(): boolean { + const state = bodyState(this); + return state.used || (state.stream?.locked ?? false); + } + + async arrayBuffer(): Promise { + return (await consume(this)).buffer as ArrayBuffer; + } + + async bytes(): Promise { + return consume(this); + } + + async text(): Promise { + return new TextDecoder().decode(await consume(this)); + } + + async json(): Promise { + return JSON.parse(await this.text()); + } + + async blob(): Promise { + const type = + (this as unknown as {headers: Headers}).headers.get("content-type"); + return new Blob([await consume(this)], {type: type ?? ""}); + } +} + +interface RequestState { + url: string; + method: string; + headers: Headers; + signal: AbortSignal; + redirect: RequestRedirect; + mode: RequestMode; + credentials: RequestCredentials; + cache: RequestCache; + destination: string; + referrer: string; + referrerPolicy: string; + integrity: string; + keepalive: boolean; +} + +const requests = new WeakMap(); + +function requestState(request: object): RequestState { + const state = requests.get(request); + if (state === undefined) { + throw new TypeError("Illegal invocation"); + } + + return state; +} + +let baseURL = "about:blank"; + +export function setBaseURL(url: string): void { + baseURL = url; +} + +export function setDestination(request: Request, destination: string): void { + requestState(request).destination = destination; +} + +const METHODS = new Set([ + "DELETE", + "GET", + "HEAD", + "OPTIONS", + "POST", + "PUT", + "PATCH", +]); + +export class Request extends Body { + constructor(input: unknown, init: RequestInit = {}) { + super(); + let source: RequestState | null = null; + let url: string; + if (input instanceof Request) { + source = requestState(input); + url = source.url; + } else { + url = new URLConstructor(String(input), baseURL).href; + } + + let method = init.method ?? source?.method ?? "GET"; + if (METHODS.has(method.toUpperCase())) { + method = method.toUpperCase(); + } + + const headers = new Headers(init.headers ?? source?.headers); + const controller = new AbortController(); + const parent = init.signal ?? source?.signal; + if (parent) { + if (parent.aborted) { + controller.abort(parent.reason); + } else { + parent.addEventListener( + "abort", + () => controller.abort(parent.reason), + {once: true}, + ); + } + } + + requests.set(this, { + url, + method, + headers, + signal: controller.signal, + redirect: init.redirect ?? source?.redirect ?? "follow", + mode: init.mode ?? source?.mode ?? "cors", + credentials: init.credentials ?? source?.credentials ?? "same-origin", + cache: init.cache ?? source?.cache ?? "default", + // Read through the request, where the engine sets it as its own + // property. + destination: source === undefined ? "" : (input as Request).destination, + referrer: init.referrer ?? source?.referrer ?? "about:client", + referrerPolicy: init.referrerPolicy ?? source?.referrerPolicy ?? "", + integrity: init.integrity ?? source?.integrity ?? "", + keepalive: init.keepalive ?? source?.keepalive ?? false, + }); + + if (init.body != null && (method === "GET" || method === "HEAD")) { + throw new TypeError("A GET or HEAD request cannot have a body"); + } + + if (init.body !== undefined) { + bodies.set(this, {...extractBody(init.body, headers), used: false}); + } else if (input instanceof Request) { + bodies.set(this, teeBody(bodyState(input))); + } else { + bodies.set(this, {stream: null, bytes: null, used: false}); + } + } + + get url(): string { + return requestState(this).url; + } + + get method(): string { + return requestState(this).method; + } + + get headers(): Headers { + return requestState(this).headers; + } + + get signal(): AbortSignal { + return requestState(this).signal; + } + + get redirect(): RequestRedirect { + return requestState(this).redirect; + } + + get mode(): RequestMode { + return requestState(this).mode; + } + + get credentials(): RequestCredentials { + return requestState(this).credentials; + } + + get cache(): RequestCache { + return requestState(this).cache; + } + + get destination(): string { + return requestState(this).destination; + } + + get referrer(): string { + return requestState(this).referrer; + } + + get referrerPolicy(): string { + return requestState(this).referrerPolicy; + } + + get integrity(): string { + return requestState(this).integrity; + } + + get keepalive(): boolean { + return requestState(this).keepalive; + } + + clone(): Request { + return new Request(this); + } +} + +Object.defineProperty(Request.prototype, Symbol.toStringTag, { + value: "Request", + configurable: true, +}); + +interface ResponseState { + status: number; + statusText: string; + headers: Headers; + url: string; + redirected: boolean; + type: ResponseType; +} + +const responses = new WeakMap(); + +function responseState(response: object): ResponseState { + const state = responses.get(response); + if (state === undefined) { + throw new TypeError("Illegal invocation"); + } + + return state; +} + +export function setResponseURL( + response: Response, + url: string, + redirected: boolean, +): void { + const state = responseState(response); + state.url = url; + state.redirected = redirected; + state.type = "basic"; +} + +export class Response extends Body { + constructor(body?: unknown, init: ResponseInit = {}) { + super(); + const status = init.status ?? 200; + if (status !== 0 && (status < 200 || status > 599)) { + throw new RangeError(`Invalid status ${status}`); + } + + const headers = new Headers(init.headers); + responses.set(this, { + status, + statusText: init.statusText ?? "", + headers, + url: "", + redirected: false, + type: status === 0 ? "error" : "default", + }); + bodies.set(this, {...extractBody(body, headers), used: false}); + } + + get status(): number { + return responseState(this).status; + } + + get statusText(): string { + return responseState(this).statusText; + } + + get ok(): boolean { + const status = responseState(this).status; + return status >= 200 && status < 300; + } + + get headers(): Headers { + return responseState(this).headers; + } + + get url(): string { + return responseState(this).url; + } + + get redirected(): boolean { + return responseState(this).redirected; + } + + get type(): ResponseType { + return responseState(this).type; + } + + static error(): Response { + const response = new Response(null, {status: 0}); + freezeHeaders(response.headers); + return response; + } + + static redirect(url: string, status = 302): Response { + if (![301, 302, 303, 307, 308].includes(status)) { + throw new RangeError(`Invalid redirect status ${status}`); + } + + return new Response(null, { + status, + headers: {location: new URLConstructor(String(url), baseURL).href}, + }); + } + + static json(data: unknown, init: ResponseInit = {}): Response { + const headers = new Headers(init.headers); + if (!headers.has("content-type")) { + headers.set("content-type", "application/json"); + } + + return new Response(JSON.stringify(data), { + ...init, + headers: headers as never, + }); + } + + clone(): Response { + const state = responseState(this); + const copy = new Response(null, { + status: state.status || 200, + statusText: state.statusText, + headers: state.headers as never, + }); + const copyState = responseState(copy); + copyState.status = state.status; + copyState.url = state.url; + copyState.redirected = state.redirected; + copyState.type = state.type; + bodies.set(copy, teeBody(bodyState(this))); + return copy; + } +} + +Object.defineProperty(Response.prototype, Symbol.toStringTag, { + value: "Response", + configurable: true, +}); + +export type Fetcher = (request: Request) => Promise; + +async function noNetwork(): Promise { + throw new TypeError("Failed to fetch: no network in this frame"); +} + +let fetcher: Fetcher = noNetwork; + +export function setFetcher(next: Fetcher): void { + fetcher = next; +} + +export async function fetch( + input: unknown, + init?: RequestInit, +): Promise { + const request = new Request(input, init); + request.signal.throwIfAborted(); + if (request.url.startsWith("blob:")) { + const blob = request.method === "GET" ? blobAt(request.url) : undefined; + if (blob === undefined) { + throw new TypeError("Failed to fetch"); + } + + return new Response(blob, { + headers: {"content-type": blob.type, "content-length": String(blob.size)}, + }); + } + + return fetcher(request); +} diff --git a/src/internal/isolate/frame.ts b/src/internal/isolate/frame.ts new file mode 100644 index 00000000..78f64bc2 --- /dev/null +++ b/src/internal/isolate/frame.ts @@ -0,0 +1,424 @@ +/** + * A frame's document shown from an isolate of its own. The page that + * holds the iframe lives in another heap, so the frame paints into cells + * and posts them, and everything it hears, from keys to messages and + * responses, arrives through receive(). + */ +import "./install.ts"; +import "../frames.ts"; + +import {Cascade, setReducedMotion} from "../cssom.ts"; +import { + type Document, + findRuntimeFetchClasses, + findRuntimeGlobals, + focusInitialAutofocus, + type Window, +} from "../dom.ts"; +import {installEditing} from "../editing.ts"; +import {Exchange, type TerminalTransport} from "../exchange.ts"; +import {exportGrid, Framebuffer} from "../framebuffer.ts"; +import {createFrameEngine} from "../frames.ts"; +import {dispatchInput, Input, resolvePendingHover} from "../input.ts"; +import {KittyImages, takeFrameImages} from "../kitty.ts"; +import {Layout} from "../layout.ts"; +import {_} from "../slots.ts"; +import {createWindow} from "../window.ts"; +import { + type FrameInit, + host, + type HostMessage, + type IsolateHost, + setHost, +} from "./host.ts"; +import {deliverError, deliverResponse} from "./network.ts"; +import {installPage} from "./page.ts"; +import {ScriptRunner} from "./scripts.ts"; +import {loadStylesheets} from "./stylesheets.ts"; +import {clearTimeout, fireTimer, queueTask, setTimeout} from "./timers.ts"; + +// How long the first paint waits for the document's stylesheets, so it +// does not flash the page unstyled. +const STYLESHEET_WAIT = 5000; + +export {fireTimer}; + +type WireInput = Parameters[1]; + +function nullTransport(cols: number, rows: number): TerminalTransport { + return { + cols, + rows, + readable: new ReadableStream(), + writable: new WritableStream(), + resizes: new ReadableStream(), + sharesScreen: false, + interactive: false, + ready: Promise.resolve(), + closed: new Promise(() => {}), + close() {}, + }; +} + +interface Frame { + receive(message: HostMessage): void; + scripts: ScriptRunner | null; + loaded(): void; + dispose(): void; +} + +let frame: Frame | null = null; + +export function start(callbacks: IsolateHost, init: FrameInit): void { + if (frame !== null) { + throw new Error("This isolate already shows a frame."); + } + setHost(callbacks); + frame = createFrame(init); +} + +export function receive(message: HostMessage): void { + frame?.receive(message); +} + +// The backend runs the scripts the frame reports, and tells it where each +// one starts and ends and how the document's loading goes. +export function scriptBegin(id: number): void { + if (frame !== null) { + frame.scripts?.begin(id); + } +} + +export function scriptEnd(id: number): void { + if (frame !== null) { + frame.scripts?.end(id); + } +} + +export function scriptFinished(id: number, ok: boolean): void { + if (frame !== null) { + frame.scripts?.finished(id, ok); + } +} + +export function documentInteractive(): void { + if (frame !== null) { + frame.scripts?.interactive(); + } +} + +export function documentLoaded(): void { + if (frame !== null) { + frame.scripts?.loaded(); + frame.loaded(); + } +} + +export function dispose(): void { + frame?.dispose(); + frame = null; +} + +function createFrame(init: FrameInit): Frame { + let {cols, rows, cellWidth, cellHeight, pixelRatio} = init; + findRuntimeGlobals(); + findRuntimeFetchClasses(); + const window = createWindow( + init.html, + init.url, + "text/html", + init.scripting, + ) as unknown as Window; + const document = window.document as unknown as Document; + const parent = createWindow( + "", + `${init.parentOrigin}/`, + ) as unknown as Window; + _(window).parentWindow = parent; + + let queued = false; + let styled = false; + let disposed = false; + let title = ""; + let loaded = false; + const schedule = (): void => { + if (queued || disposed) { + return; + } + queued = true; + queueTask(paint); + }; + + const exchange = createExchange(parent, init); + const loads = new AbortController(); + const engine = createFrameEngine( + document, + window, + { + colorDepth: init.colorDepth, + exchange, + cellSize: {width: cellWidth, height: cellHeight}, + devicePixelRatio: pixelRatio, + images: "cells", + canvas: "cells", + isolateFrame: null, + load: (request) => fetch(request), + loadSignal: loads.signal, + reportUncaught: (error) => { + host.log("error", `Uncaught ${describe(error)}`); + }, + cellPixels: () => ({ + width: Math.round(cellWidth * pixelRatio), + height: Math.round(cellHeight * pixelRatio), + }), + pixelRatio: () => pixelRatio, + }, + schedule, + ); + const extra = _(document).extra; + extra.framebuffer.measurer = exchange; + const graphics = init.images === "kitty" + ? new KittyImages(() => extra.framebuffer.cellPixels) + : null; + if (graphics !== null) { + graphics.images = true; + graphics.canvas = true; + extra.framebuffer.graphics = graphics; + } + installEditing(exchange); + setReducedMotion( + document as unknown as globalThis.Document, + init.reducedMotion, + ); + focusInitialAutofocus(document as unknown as globalThis.Document); + const input = new Input( + document as unknown as globalThis.Document, + extra.layout, + extra.cascade, + extra.framebuffer, + () => {}, + ); + + for (const [ + target, + view, + ] of [["self", window], ["parent", parent]] as const) { + view.navigation.addEventListener("navigate", (event) => { + const navigate = event as NavigateEvent; + if ( + navigate.hashChange || + navigate.destination.sameDocument || + !navigate.cancelable + ) { + return; + } + navigate.preventDefault(); + host.post({ + type: "navigate", + target, + url: navigate.destination.url, + ...encodeForm(navigate.formData, navigate.sourceElement), + }); + }); + } + window.navigation.addEventListener("currententrychange", (event) => { + const type = (event as NavigationCurrentEntryChangeEvent).navigationType; + const url = window.navigation.currentEntry?.url; + if ((type === "push" || type === "replace") && url) { + host.post({type: "history", url, replace: type === "replace"}); + } + }); + // The frame's postMessage to its parent lands on the stand-in, past the + // targetOrigin check, and goes on to the page. + parent.addEventListener("message", (event) => { + host.post({ + type: "message", + data: (event as MessageEvent).data, + targetOrigin: init.parentOrigin, + }); + }); + + let scripts: ScriptRunner | null = null; + if (init.scripting) { + installPage(window); + scripts = new ScriptRunner(document as unknown as globalThis.Document); + scripts.start(); + } + let wait: number | undefined; + void Promise.race([ + loadStylesheets(document as unknown as globalThis.Document), + new Promise((resolve) => { + wait = setTimeout(resolve, STYLESHEET_WAIT); + }), + ]).finally(() => { + clearTimeout(wait); + styled = true; + schedule(); + }); + + // Without scripts, the document is loaded once its first paint is out. + // With them, once the backend has run them all. + function announceLoad(): void { + if (!loaded) { + loaded = true; + host.post({type: "load"}); + } + } + + function paint(): void { + queued = false; + if (disposed || !styled) { + return; + } + resolvePendingHover(input); + const grid = engine.fit(cols, rows); + if (graphics !== null) { + const {added, dropped} = takeFrameImages(graphics, grid); + if (added.length > 0 || dropped.length > 0) { + host.post({type: "images", added, dropped}); + } + } + host.post({type: "paint", cells: exportGrid(grid), caret: engine.caret}); + if (document.title !== title) { + title = document.title; + host.post({type: "title", title}); + } + if (scripts === null) { + announceLoad(); + } + } + + return { + scripts, + loaded: announceLoad, + receive(message) { + if (disposed) { + return; + } + switch (message.type) { + case "resize": + cols = message.cols; + rows = message.rows; + cellWidth = message.cellWidth; + cellHeight = message.cellHeight; + pixelRatio = message.pixelRatio; + schedule(); + return; + case "input": + dispatchInput(input, toWireInput(message.item)); + schedule(); + return; + case "message": { + const target = message.targetOrigin; + if ( + target !== "*" && + target !== window.origin && + !(target === "/" && message.origin === window.origin) + ) { + return; + } + const view = window as unknown as typeof globalThis; + view.dispatchEvent( + new view.MessageEvent("message", { + data: message.data, + origin: message.origin, + source: view.parent, + }), + ); + return; + } + case "response": + deliverResponse(message.id, message.response); + return; + case "fetchError": + deliverError(message.id, message.message); + return; + } + }, + dispose() { + disposed = true; + loads.abort(); + engine.dispose(); + }, + }; +} + +// The terminal a frame's engine is told about. In a page, a frame shares +// the exchange of the document its iframe is in. Here that document is +// the blank one standing in for the page, on a transport that writes +// nowhere and asks the terminal nothing. +function createExchange(window: Window, init: FrameInit): Exchange { + const layout = new Layout(window, init.cols, init.rows); + const cascade = new Cascade(window, layout); + const framebuffer = new Framebuffer(init.rows, init.cols, init.colorDepth); + return new Exchange( + nullTransport(init.cols, init.rows), + window, + layout, + cascade, + framebuffer, + init.colorScheme, + ); +} + +// A form submitted with POST, in the encoding its enctype names. A file +// field sends its name only, since its bytes are not read here. +function encodeForm( + data: FormData | null, + source: Element | null, +): {method?: string; body?: Uint8Array; contentType?: string} { + if (data === null) { + return {}; + } + const control = source as HTMLButtonElement | HTMLInputElement | null; + const form = control?.form ?? (source as HTMLFormElement | null); + const enctype = ( + control?.getAttribute("formenctype") ?? form?.getAttribute("enctype") ?? "" + ).toLowerCase(); + const entries = [...data].map(([name, value]): [string, string] => [ + name, + typeof value === "string" ? value : value.name, + ]); + const encoder = new TextEncoder(); + if (enctype === "multipart/form-data") { + const boundary = `----termdom${Math.random().toString(16).slice(2)}`; + const parts = entries.map(([name, value]) => + `--${boundary}\r\nContent-Disposition: form-data; name="${ + name.replace(/"/g, "%22") + }"\r\n\r\n${value}\r\n`, + ); + return { + method: "POST", + body: encoder.encode(`${parts.join("")}--${boundary}--\r\n`), + contentType: `multipart/form-data; boundary=${boundary}`, + }; + } + if (enctype === "text/plain") { + return { + method: "POST", + body: encoder.encode( + entries.map(([name, value]) => `${name}=${value}\r\n`).join(""), + ), + contentType: "text/plain", + }; + } + return { + method: "POST", + body: encoder.encode(new URLSearchParams(entries).toString()), + contentType: "application/x-www-form-urlencoded", + }; +} + +// The page reports a click in the frame's own cells, counted from zero. +// The engine reads mouse reports as the terminal sends them, from one. +function toWireInput(item: WireInput): WireInput { + return !Array.isArray(item) && item.kind === "mouse" + ? {...item, col: item.col + 1, row: item.row + 1} + : item; +} + +function describe(error: unknown): string { + return error instanceof Error + ? error.stack ?? `${error.name}: ${error.message}` + : String(error); +} diff --git a/src/internal/isolate/host.ts b/src/internal/isolate/host.ts new file mode 100644 index 00000000..1fccc496 --- /dev/null +++ b/src/internal/isolate/host.ts @@ -0,0 +1,50 @@ +/** + * What an isolated frame asks of the process that hosts it. The isolate + * has no timers, randomness, network or output of its own, so each of + * these is a plain callback the backend provides when it loads the + * runtime. Messages are plain values and typed arrays, so any backend + * that copies structured data can carry them. + */ +import type {FrameMessage} from "../isolateprotocol.ts"; +import type {ScriptItem} from "./scripts.ts"; + +export type { + FrameInit, + FrameMessage, + FrameRequest, + FrameResponse, + HostMessage, +} from "../isolateprotocol.ts"; + +export interface IsolateHost { + post(message: FrameMessage): void; + log(level: string, text: string): void; + setTimer(id: number, ms: number): void; + clearTimer(id: number): void; + random(length: number): Uint8Array; + // The scripts the document holds, or that were added to it, for the + // backend to fetch, compile and run in order. + scripts(initial: boolean, items: ScriptItem[]): void; +} + +function missing(): never { + throw new Error("The isolate runtime has no host yet."); +} + +export const host: IsolateHost = { + post: missing, + log: missing, + setTimer: missing, + clearTimer: missing, + random: missing, + scripts: missing, +}; + +export function setHost(next: IsolateHost): void { + host.post = (message) => next.post(message); + host.log = (level, text) => next.log(level, text); + host.setTimer = (id, ms) => next.setTimer(id, ms); + host.clearTimer = (id) => next.clearTimer(id); + host.random = (length) => next.random(length); + host.scripts = (initial, items) => next.scripts(initial, items); +} diff --git a/src/internal/isolate/install.ts b/src/internal/isolate/install.ts new file mode 100644 index 00000000..87d6e393 --- /dev/null +++ b/src/internal/isolate/install.ts @@ -0,0 +1,128 @@ +import atob from "core-js-pure/actual/atob.js"; +import btoa from "core-js-pure/actual/btoa.js"; +import structuredClone from "core-js-pure/actual/structured-clone.js"; +import URLSearchParams from "core-js-pure/actual/url-search-params/index.js"; +import URL from "core-js-pure/actual/url/index.js"; +import { + ReadableStream, + TransformStream, + WritableStream, +} from "web-streams-polyfill"; + +import {Blob, File, FormData} from "./blob.ts"; +import {DecompressionStream} from "./compression.ts"; +import {console} from "./console.ts"; +import {TextDecoder, TextEncoder} from "./encoding.ts"; +import { + AbortController, + AbortSignal, + DOMException, + Event, + EventTarget, +} from "./events.ts"; +import {fetch, Headers, Request, Response} from "./fetch.ts"; +import {host} from "./host.ts"; +import {installNetwork} from "./network.ts"; +import { + clearInterval, + clearTimeout, + performance, + queueMicrotask, + setInterval, + setTimeout, +} from "./timers.ts"; + +const MAX_RANDOM_BYTES = 65536; + +function getRandomValues(view: T): T { + if ( + !(view instanceof Int8Array) && + !(view instanceof Uint8Array) && + !(view instanceof Uint8ClampedArray) && + !(view instanceof Int16Array) && + !(view instanceof Uint16Array) && + !(view instanceof Int32Array) && + !(view instanceof Uint32Array) && + !(view instanceof BigInt64Array) && + !(view instanceof BigUint64Array) + ) { + throw new DOMException( + "The data is not an integer typed array", + "TypeMismatchError", + ); + } + + if (view.byteLength > MAX_RANDOM_BYTES) { + throw new DOMException( + `The length exceeds ${MAX_RANDOM_BYTES} bytes`, + "QuotaExceededError", + ); + } + + const bytes = host.random(view.byteLength); + new Uint8Array(view.buffer, view.byteOffset, view.byteLength).set(bytes); + return view; +} + +// eslint-disable-next-line acrocase/acrocase -- the Web Crypto name +function randomUUID(): string { + const bytes = getRandomValues(new Uint8Array(16)); + bytes[6] = (bytes[6] & 0x0f) | 0x40; + bytes[8] = (bytes[8] & 0x3f) | 0x80; + const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")); + return [ + hex.slice(0, 4).join(""), + hex.slice(4, 6).join(""), + hex.slice(6, 8).join(""), + hex.slice(8, 10).join(""), + hex.slice(10).join(""), + ].join("-"); +} + +const crypto = {getRandomValues, randomUUID}; + +const globals: Record = { + AbortController, + AbortSignal, + Blob, + DOMException, + DecompressionStream, + Event, + EventTarget, + File, + FormData, + Headers, + ReadableStream, + Request, + Response, + TextDecoder, + TextEncoder, + TransformStream, + URL, + URLSearchParams, + WritableStream, + atob, + btoa, + clearInterval, + clearTimeout, + console, + crypto, + fetch, + performance, + queueMicrotask, + setInterval, + setTimeout, + structuredClone, +}; + +for (const name of Object.keys(globals)) { + Object.defineProperty(globalThis, name, { + value: globals[name], + writable: true, + configurable: true, + enumerable: false, + }); +} + +Reflect.deleteProperty(globalThis, "__core-js_shared__"); +installNetwork(); diff --git a/src/internal/isolate/messaging.ts b/src/internal/isolate/messaging.ts new file mode 100644 index 00000000..0fcda1fe --- /dev/null +++ b/src/internal/isolate/messaging.ts @@ -0,0 +1,125 @@ +import {queueTask} from "./timers.ts"; + +interface Win { + EventTarget: new () => EventTarget; + MessageEvent: new (type: string, init?: MessageEventInit) => Event; +} + +interface PortState { + other: PortState | null; + port: EventTarget; + queue: unknown[]; + started: boolean; + closed: boolean; + handler: ((event: Event) => void) | null; +} + +export function createMessageChannel(win: Win): { + MessageChannel: new () => {port1: EventTarget; port2: EventTarget}; + MessagePort: new () => EventTarget; +} { + const states = new WeakMap(); + const state = (port: object): PortState => { + const found = states.get(port); + if (found === undefined) { + throw new TypeError("Illegal invocation"); + } + + return found; + }; + + const deliver = (target: PortState): void => { + if (!target.started || target.closed) { + return; + } + + for (const data of target.queue.splice(0)) { + queueTask(() => { + if (!target.closed) { + target.port.dispatchEvent(new win.MessageEvent("message", {data})); + } + }); + } + }; + + let constructing = false; + + class MessagePort extends win.EventTarget { + constructor() { + if (!constructing) { + throw new TypeError("Illegal constructor"); + } + + super(); + states.set(this, { + other: null, + port: this, + queue: [], + started: false, + closed: false, + handler: null, + }); + } + + get onmessage(): ((event: Event) => void) | null { + return state(this).handler; + } + + set onmessage(handler: ((event: Event) => void) | null) { + const own = state(this); + if (own.handler !== null) { + this.removeEventListener("message", own.handler); + } + + own.handler = typeof handler === "function" ? handler : null; + if (own.handler !== null) { + this.addEventListener("message", own.handler); + this.start(); + } + } + + postMessage(message: unknown): void { + const own = state(this); + if (own.closed || own.other === null || own.other.closed) { + return; + } + + own.other.queue.push(structuredClone(message)); + deliver(own.other); + } + + start(): void { + const own = state(this); + own.started = true; + deliver(own); + } + + close(): void { + const own = state(this); + own.closed = true; + own.queue.length = 0; + } + } + + class MessageChannel { + readonly port1: MessagePort; + readonly port2: MessagePort; + + constructor() { + constructing = true; + try { + this.port1 = new MessagePort(); + this.port2 = new MessagePort(); + } finally { + constructing = false; + } + + const one = state(this.port1); + const two = state(this.port2); + one.other = two; + two.other = one; + } + } + + return {MessageChannel, MessagePort}; +} diff --git a/src/internal/isolate/network.ts b/src/internal/isolate/network.ts new file mode 100644 index 00000000..356cd1b0 --- /dev/null +++ b/src/internal/isolate/network.ts @@ -0,0 +1,88 @@ +import {Response, setFetcher, setResponseURL} from "./fetch.ts"; +import {type FrameResponse, host} from "./host.ts"; + +interface Pending { + resolve(response: Response): void; + reject(error: unknown): void; + release(): void; +} + +const NULL_BODY_STATUSES = new Set([101, 103, 204, 205, 304]); + +const pending = new Map(); +let nextId = 1; + +export function installNetwork(): void { + setFetcher(async (request) => { + const body = request.method === "GET" || request.method === "HEAD" + ? null + : new Uint8Array(await request.arrayBuffer()); + request.signal.throwIfAborted(); + return new Promise((resolve, reject) => { + const id = nextId++; + const signal = request.signal; + const onAbort = (): void => { + if (pending.delete(id)) { + host.post({type: "abortFetch", id}); + reject(signal.reason); + } + }; + pending.set(id, { + resolve, + reject, + release() { + signal.removeEventListener("abort", onAbort); + }, + }); + signal.addEventListener("abort", onAbort, {once: true}); + host.post({ + type: "fetch", + id, + request: { + url: request.url, + method: request.method, + headers: [...request.headers], + body, + redirect: request.redirect, + destination: request.destination, + referrer: request.referrer, + }, + }); + }); + }); +} + +export function deliverResponse(id: number, response: FrameResponse): void { + const entry = pending.get(id); + if (entry === undefined) { + return; + } + + pending.delete(id); + entry.release(); + try { + const result = new Response( + NULL_BODY_STATUSES.has(response.status) ? null : response.body, + { + status: response.status, + statusText: response.statusText, + headers: response.headers, + }, + ); + setResponseURL(result, response.url, response.redirected); + entry.resolve(result); + } catch (error) { + entry.reject(new TypeError(`Failed to fetch: ${String(error)}`)); + } +} + +export function deliverError(id: number, message: string): void { + const entry = pending.get(id); + if (entry === undefined) { + return; + } + + pending.delete(id); + entry.release(); + entry.reject(new TypeError(`Failed to fetch: ${message}`)); +} diff --git a/src/internal/isolate/page.ts b/src/internal/isolate/page.ts new file mode 100644 index 00000000..989ad0d7 --- /dev/null +++ b/src/internal/isolate/page.ts @@ -0,0 +1,132 @@ +/** + * A page's scripts run with the isolate's global object as theirs, and a + * global object cannot be swapped for the frame's window. So the window's + * members are copied onto it, its methods bound to the window, and its + * attributes read through to it, and window, self and frames name the + * global, as they would in a browser. + */ +import {createObjectURL, revokeObjectURL} from "./blob.ts"; +import {createMessageChannel} from "./messaging.ts"; + +type Win = + Record & + {location: {href: string}; parent: unknown; top: unknown}; + +const KEPT_GLOBALS = new Set([ + "constructor", + "globalThis", + "window", + "self", + "top", + "parent", + "frames", + "fetch", + "location", +]); + +export function installPage(window: object): void { + const win = window as Win; + const names = new Set(); + for ( + let object: object | null = win; + object !== null && object !== Object.prototype; + object = Object.getPrototypeOf(object) as object | null + ) { + for (const name of Object.getOwnPropertyNames(object)) { + names.add(name); + } + } + + for (const name of names) { + if (KEPT_GLOBALS.has(name)) { + continue; + } + + const existing = Object.getOwnPropertyDescriptor(globalThis, name); + if (existing !== undefined && !existing.configurable) { + continue; + } + + let value: unknown; + try { + value = win[name]; + } catch (error) { + if (!(error instanceof Error)) { + throw error; + } + + continue; + } + + if (typeof value === "function" && /^[a-z]/.test(name)) { + Object.defineProperty(globalThis, name, { + value: (value as (...args: unknown[]) => unknown).bind(win), + writable: true, + configurable: true, + }); + } else if (typeof value === "function") { + Object.defineProperty(globalThis, name, { + value, + writable: true, + configurable: true, + }); + } else { + Object.defineProperty(globalThis, name, { + get: () => win[name], + set: (next: unknown) => { + win[name] = next; + }, + configurable: true, + }); + } + } + + for (const name of ["window", "self", "frames"]) { + Object.defineProperty(globalThis, name, { + value: globalThis, + writable: false, + configurable: false, + }); + } + + for (const name of ["parent", "top"] as const) { + Object.defineProperty(globalThis, name, { + get: () => win[name], + configurable: false, + }); + } + + Object.defineProperty(globalThis, "location", { + get: () => win.location, + set: (value: unknown) => { + win.location.href = String(value); + }, + configurable: false, + }); + const {MessageChannel, MessagePort} = createMessageChannel( + win as unknown as Parameters[0], + ); + for (const [name, value] of [ + ["MessageChannel", MessageChannel], + ["MessagePort", MessagePort], + ] as const) { + Object.defineProperty(globalThis, name, { + value, + writable: true, + configurable: true, + }); + } + + const PageURL = (globalThis as unknown as {URL: object}).URL; + Object.defineProperty(PageURL, "createObjectURL", { + value: (object: unknown) => + createObjectURL(object, new URL(win.location.href).origin), + writable: true, + configurable: true, + }); + Object.defineProperty(PageURL, "revokeObjectURL", { + value: revokeObjectURL, + writable: true, + configurable: true, + }); +} diff --git a/src/internal/isolate/scripts.ts b/src/internal/isolate/scripts.ts new file mode 100644 index 00000000..4d4c4384 --- /dev/null +++ b/src/internal/isolate/scripts.ts @@ -0,0 +1,158 @@ +import {host} from "./host.ts"; + +const CLASSIC_TYPES = new Set([ + "", + "text/javascript", + "application/javascript", + "application/ecmascript", + "text/ecmascript", + "application/x-javascript", + "text/jscript", +]); + +export interface ScriptItem { + id: number; + kind: "classic" | "module" | "importmap"; + src: string | null; + text: string | null; + async: boolean; +} + +interface WindowLike { + Event: new (type: string, init?: EventInit) => Event; + dispatchEvent(event: Event): boolean; + MutationObserver: typeof MutationObserver; +} + +export class ScriptRunner { + readonly document: Document; + readonly elements: Map; + readonly seen: WeakSet; + nextId: number; + current: HTMLScriptElement | null; + readyState: DocumentReadyState; + + constructor(document: Document) { + this.document = document; + this.elements = new Map(); + this.seen = new WeakSet(); + this.nextId = 1; + this.current = null; + this.readyState = "loading"; + Object.defineProperty(document, "currentScript", { + get: () => this.current, + configurable: true, + enumerable: true, + }); + Object.defineProperty(document, "readyState", { + get: () => this.readyState, + configurable: true, + enumerable: true, + }); + } + + collect(root: ParentNode | Element): ScriptItem[] { + const found: HTMLScriptElement[] = []; + if ((root as Element).localName === "script") { + found.push(root as HTMLScriptElement); + } + + for (const script of root.querySelectorAll("script")) { + found.push(script); + } + + const items: ScriptItem[] = []; + for (const script of found) { + if (this.seen.has(script) || !script.isConnected) { + continue; + } + + this.seen.add(script); + const type = (script.getAttribute("type") ?? "").trim().toLowerCase(); + const kind = type === "module" + ? "module" + : type === "importmap" + ? "importmap" + : CLASSIC_TYPES.has(type) && !script.hasAttribute("nomodule") + ? "classic" + : null; + if (kind === null) { + continue; + } + + const id = this.nextId++; + const src = script.hasAttribute("src") && kind !== "importmap" + ? script.src + : null; + if (src !== null || kind === "classic") { + this.elements.set(id, script); + } + + items.push({ + id, + kind, + src, + text: src === null ? script.text : null, + async: + kind !== "importmap" && + (src !== null || kind === "module") && + script.hasAttribute("async"), + }); + } + + return items; + } + + start(): void { + const view = this.document.defaultView as unknown as WindowLike; + host.scripts(true, this.collect(this.document)); + new view.MutationObserver((records) => { + const items: ScriptItem[] = []; + for (const record of records) { + for (const node of record.addedNodes) { + if (node.nodeType === 1) { + items.push(...this.collect(node as Element)); + } + } + } + + if (items.length > 0) { + host.scripts(false, items); + } + }).observe(this.document, {childList: true, subtree: true}); + } + + begin(id: number): void { + this.current = this.elements.get(id) ?? null; + } + + end(id: number): void { + this.current = null; + if (this.elements.get(id)?.hasAttribute("src") === false) { + this.elements.delete(id); + } + } + + finished(id: number, ok: boolean): void { + const script = this.elements.get(id); + this.elements.delete(id); + const view = this.document.defaultView as unknown as WindowLike; + script?.dispatchEvent(new view.Event(ok ? "load" : "error")); + } + + interactive(): void { + const view = this.document.defaultView as unknown as WindowLike; + this.readyState = "interactive"; + this.document.dispatchEvent(new view.Event("readystatechange")); + this.document.dispatchEvent( + new view.Event("DOMContentLoaded", {bubbles: true}), + ); + } + + loaded(): void { + const view = this.document.defaultView as unknown as WindowLike; + this.readyState = "complete"; + this.document.dispatchEvent(new view.Event("readystatechange")); + view.dispatchEvent(new view.Event("load")); + } +} diff --git a/src/internal/isolate/stylesheets.ts b/src/internal/isolate/stylesheets.ts new file mode 100644 index 00000000..2e48bc8b --- /dev/null +++ b/src/internal/isolate/stylesheets.ts @@ -0,0 +1,114 @@ +import {reportError} from "./console.ts"; +import {fetch, Request, setDestination} from "./fetch.ts"; + +const URL_TOKEN = /url\(\s*(['"]?)([^'")]+)\1\s*\)/g; +const IMPORT_STRING = /@import\s+(['"])([^'"]+)\1/g; + +function absolutize(css: string, base: string): string { + const resolve = (url: string): string => { + if (/^(data:|#)/i.test(url)) { + return url; + } + + try { + return new URL(url, base).href; + } catch (error) { + if (!(error instanceof TypeError)) { + throw error; + } + + return url; + } + }; + return css + .replace(URL_TOKEN, (_, quote: string, url: string) => + `url(${quote}${resolve(url)}${quote})`) + .replace(IMPORT_STRING, (_, quote: string, url: string) => + `@import ${quote}${resolve(url)}${quote}`); +} + +function isStylesheetLink(element: Element): boolean { + if (element.localName !== "link" || element.hasAttribute("disabled")) { + return false; + } + + const rel = (element.getAttribute("rel") ?? "").toLowerCase().split(/\s+/); + return rel.includes("stylesheet") && !rel.includes("alternate"); +} + +export function loadStylesheets(document: Document): Promise { + const seen = new WeakSet(); + const fetchSheet = + async (link: Element): Promise => { + seen.add(link); + const href = (link as HTMLLinkElement).href; + if (!href) { + return null; + } + + const request = new Request(href); + setDestination(request, "style"); + const response = await fetch(request); + if (!response.ok) { + throw new Error(`${href} answered ${response.status}`); + } + + const style = document.createElement("style"); + const media = link.getAttribute("media"); + if (media) { + style.setAttribute("media", media); + } + + style.textContent = absolutize( + await response.text(), + response.url || href, + ); + return style; + }; + const place = (link: Element, style: HTMLStyleElement | null): void => { + if (style !== null && link.isConnected) { + link.after(style); + } + }; + const load = (link: Element): void => { + fetchSheet(link).then((style) => place(link, style), reportError); + }; + const scan = (root: ParentNode): void => { + for (const link of root.querySelectorAll("link")) { + if (!seen.has(link) && isStylesheetLink(link)) { + load(link); + } + } + }; + + const initial = [...document.querySelectorAll("link")] + .filter(isStylesheetLink); + const sheets = initial.map((link) => + fetchSheet(link).catch((error: unknown) => { + reportError(error); + return null; + }), + ); + const view = document.defaultView as unknown as { + MutationObserver: typeof MutationObserver; + }; + new view.MutationObserver((records) => { + for (const record of records) { + for (const node of record.addedNodes) { + if (node.nodeType !== 1) { + continue; + } + + const element = node as Element; + if (!seen.has(element) && isStylesheetLink(element)) { + load(element); + } else { + scan(element); + } + } + } + }).observe(document, {childList: true, subtree: true}); + return Promise.all(sheets).then((styles) => { + styles.forEach((style, i) => place(initial[i], style)); + }); +} diff --git a/src/internal/isolate/timers.ts b/src/internal/isolate/timers.ts new file mode 100644 index 00000000..eb98401a --- /dev/null +++ b/src/internal/isolate/timers.ts @@ -0,0 +1,132 @@ +import {reportError} from "./console.ts"; +import {host} from "./host.ts"; + +interface Timer { + callback: (...args: unknown[]) => unknown; + args: unknown[]; + ms: number; + repeat: boolean; + nesting: number; +} + +const timers = new Map(); +let nextId = 1; +let currentNesting = 0; + +const NESTING_LIMIT = 5; +const NESTED_MINIMUM = 4; + +function normalizeDelay(ms: unknown): number { + const delay = Number(ms); + return delay > 0 && delay < 2 ** 31 ? delay : 0; +} + +function schedule( + callback: unknown, + ms: unknown, + args: unknown[], + repeat: boolean, + task = false, +): number { + const id = nextId++; + if (typeof callback !== "function") { + return id; + } + + const nesting = task ? 0 : currentNesting + 1; + let delay = normalizeDelay(ms); + if (nesting > NESTING_LIMIT && delay < NESTED_MINIMUM) { + delay = NESTED_MINIMUM; + } + + timers.set(id, { + callback: callback as Timer["callback"], + args, + ms: delay, + repeat, + nesting, + }); + host.setTimer(id, delay); + return id; +} + +function cancel(id: unknown): void { + const key = Number(id); + if (timers.delete(key)) { + host.clearTimer(key); + } +} + +export function setTimeout( + callback: unknown, + ms?: unknown, + ...args: unknown[] +): number { + return schedule(callback, ms, args, false); +} + +export function setInterval( + callback: unknown, + ms?: unknown, + ...args: unknown[] +): number { + return schedule(callback, ms, args, true); +} + +export function queueTask(callback: () => void): void { + schedule(callback, 0, [], false, true); +} + +export const clearTimeout = cancel; +export const clearInterval = cancel; + +export function queueMicrotask(callback: unknown): void { + if (typeof callback !== "function") { + throw new TypeError("queueMicrotask expects a function"); + } + + void Promise.resolve().then(() => { + try { + (callback as () => void)(); + } catch (error) { + reportError(error); + } + }); +} + +export function fireTimer(id: number): void { + const timer = timers.get(id); + if (timer === undefined) { + return; + } + + if (timer.repeat) { + timer.nesting++; + if (timer.nesting > NESTING_LIMIT && timer.ms < NESTED_MINIMUM) { + timer.ms = NESTED_MINIMUM; + } + + host.setTimer(id, timer.ms); + } else { + timers.delete(id); + } + + const outer = currentNesting; + currentNesting = timer.nesting; + try { + timer.callback(...timer.args); + } catch (error) { + reportError(error); + } finally { + currentNesting = outer; + } +} + +const origin = Date.now(); + +export const performance = { + timeOrigin: origin, + now(): number { + return Date.now() - origin; + }, +}; diff --git a/src/internal/isolate/vendor.d.ts b/src/internal/isolate/vendor.d.ts new file mode 100644 index 00000000..d5ecb6e8 --- /dev/null +++ b/src/internal/isolate/vendor.d.ts @@ -0,0 +1,27 @@ +declare module "core-js-pure/actual/atob.js" { + const atob: (data: string) => string; + export default atob; +} + +declare module "core-js-pure/actual/btoa.js" { + const btoa: (data: string) => string; + export default btoa; +} + +declare module "core-js-pure/actual/structured-clone.js" { + const structuredClone: ( + value: T, + options?: StructuredSerializeOptions, + ) => T; + export default structuredClone; +} + +declare module "core-js-pure/actual/url/index.js" { + const URL: typeof globalThis.URL; + export default URL; +} + +declare module "core-js-pure/actual/url-search-params/index.js" { + const URLSearchParams: typeof globalThis.URLSearchParams; + export default URLSearchParams; +} diff --git a/src/internal/isolatedframes.ts b/src/internal/isolatedframes.ts new file mode 100644 index 00000000..af427114 --- /dev/null +++ b/src/internal/isolatedframes.ts @@ -0,0 +1,686 @@ +/** + * Frames whose document is in another isolate. The iframe loads its + * document under the page's policy and fetch listeners, starts it in an + * isolate the TermDOM's isolator makes, and draws the cells it paints + * there. Keys, the mouse, pastes and focus reach it as a program in an + * embed takes them, and messages cross as a window of another origin + * sends them. What comes back is the other isolate's word, so the cells + * are checked as they are drawn and nothing else of it is run here. + */ +import { + constructInternal, + type Document, + Event, + type HTMLIFrameElement, + type IsolatedFrameView, + navigateFrameParent, + receiveFrameMessage, + setIsolatedFrameFactory, + setRequestDestination, + type Window, +} from "./dom.ts"; +import type {WireKey} from "./exchange.ts"; +import { + type Caret, + CellGrid, + type GridCells, + type ImportedPlaceholder, + importGrid, +} from "./framebuffer.ts"; +import type {Bitmap, GridImage} from "./images.ts"; +import {requireNodePackage} from "./isolate/bundle.ts"; +import type { + FrameImage, + FrameInit, + FrameIsolator, + FrameMessage, + FrameRequest, + HostMessage, + IsolatedFrame, +} from "./isolateprotocol.ts"; +import {MAX_KITTY_PIXELS, MAX_PLACEHOLDER_CELLS} from "./kitty.ts"; +import {_} from "./slots.ts"; +import {getCellSize} from "./units.ts"; + +// The loads a frame may have in flight at once. +const MAX_FETCHES = 64; + +// The images a frame may hold at once. +const MAX_IMAGES = 256; + +// Tells each frame's images from another's among those the page shows. +let nextFrameToken = 1; + +// Request headers a frame may not set, as Fetch forbids a page to. +const FORBIDDEN_HEADER = + /^(?:accept-charset|accept-encoding|access-control-request-headers|access-control-request-method|connection|content-length|cookie|cookie2|date|dnt|expect|host|keep-alive|origin|referer|set-cookie|te|trailer|transfer-encoding|upgrade|via|proxy-.*|sec-.*)$/i; + +const DESTINATIONS = new Set([ + "", + "audio", + "document", + "embed", + "font", + "iframe", + "image", + "manifest", + "object", + "script", + "style", + "track", + "video", + "worker", +]); + +function isWebURL(url: URL): boolean { + return url.protocol === "http:" || url.protocol === "https:"; +} + +// A form's POST, as the frame encoded it. +interface Submission { + body: Uint8Array; + contentType: string; +} + +function readSubmission( + message: Extract, +): Submission | undefined { + if ( + typeof message.method !== "string" || + message.method.toUpperCase() !== "POST" + ) { + return undefined; + } + return { + body: message.body instanceof Uint8Array + ? Uint8Array.from(message.body) + : new Uint8Array(0), + contentType: typeof message.contentType === "string" + ? message.contentType.replace(/[\r\n]/g, "") + : "", + }; +} + +function describeError(error: unknown): string { + return error instanceof Error ? error.message : "Failed to fetch"; +} + +function escapeText(text: string): string { + return text.replace(/[&<]/g, (char) => (char === "&" ? "&" : "<")); +} + +function readHeaders(headers: Headers): Array<[string, string]> { + const entries: Array<[string, string]> = []; + headers.forEach((value, name) => { + entries.push([name, value]); + }); + return entries; +} + +class RemoteFrame implements IsolatedFrameView { + frame: HTMLIFrameElement; + window: Window; + parent: Document; + isolate: FrameIsolator; + changed: () => void; + url: string; + cols: number; + rows: number; + caret: Caret | null; + grid: CellGrid; + // The cells the frame painted last, imported into the grid at the + // next fit. + cells: GridCells | null; + stale: boolean; + token: number; + // The images the frame posted, by its ids, and those the grid's + // placeholders show. + posted: Map< + number, + {bitmap: Bitmap; cols: number; rows: number; version: number} + >; + + shown: GridImage[]; + imageVersion: number; + focused: boolean; + running: IsolatedFrame | null; + // What is sent before the frame has started, sent once it has. + waiting: HostMessage[]; + fetches: Map; + // Ends the load of the frame's document and its fetches, at a + // navigation or once the frame goes. + unload: AbortController; + disposed: boolean; + + constructor( + frame: HTMLIFrameElement, + window: Window, + url: string, + parent: Document, + isolate: FrameIsolator, + changed: () => void, + ) { + this.frame = frame; + this.window = window; + this.parent = parent; + this.isolate = isolate; + this.changed = changed; + this.url = url; + this.cols = 0; + this.rows = 0; + this.caret = null; + this.grid = new CellGrid(0, 0); + this.cells = null; + this.stale = false; + this.token = nextFrameToken++; + this.posted = new Map(); + this.shown = []; + this.imageVersion = 0; + this.focused = false; + this.running = null; + this.waiting = []; + this.fetches = new Map(); + this.unload = new AbortController(); + this.disposed = false; + void this.start(url); + } + + async start(url: string, submission?: Submission): Promise { + const unload = this.unload; + const engine = _(this.parent).extra; + let html: string; + let documentURL = url; + try { + const request = new Request(url, { + method: submission === undefined ? "GET" : "POST", + headers: submission?.contentType + ? {"content-type": submission.contentType} + : undefined, + body: submission?.body, + signal: unload.signal, + }); + setRequestDestination(request, "iframe"); + const response = await engine.load(request, { + initiator: this.frame as unknown as globalThis.Element, + }); + html = await response.text(); + documentURL = response.url === "" ? url : response.url; + } catch (error) { + if (unload.signal.aborted) { + return; + } + // A browser shows its own page for a frame that failed to load. + html = `
${escapeText(describeError(error))}
`; + } + if (unload.signal.aborted) { + return; + } + this.url = documentURL; + const framebuffer = engine.framebuffer; + const cell = getCellSize(this.parent); + const view = engine.defaultView as globalThis.Window | null; + const media = (query: string) => view?.matchMedia(query).matches ?? false; + const sandbox = _(this.window).sandbox; + this.running = this.isolate( + { + url: documentURL, + html, + parentOrigin: view?.origin ?? "null", + cols: this.cols, + rows: this.rows, + cellWidth: cell.width, + cellHeight: cell.height, + pixelRatio: framebuffer.pixelRatio ?? 1, + colorDepth: framebuffer.writer.colorDepth, + colorScheme: media("(prefers-color-scheme: dark)") ? "dark" : "light", + reducedMotion: media("(prefers-reduced-motion: reduce)"), + scripting: + media("(scripting: enabled)") && + (sandbox === null || sandbox.has("allow-scripts")), + images: engine.images === "none" ? "cells" : "kitty", + }, + (message) => { + if (unload === this.unload) { + this.receive(message); + } + }, + ); + for (const message of this.waiting.splice(0)) { + this.running.send(message); + } + } + + send(message: HostMessage): void { + if (this.disposed) { + return; + } + if (this.running === null) { + this.waiting.push(message); + } else { + this.running.send(message); + } + } + + receive(message: FrameMessage): void { + if (this.disposed) { + return; + } + switch (message.type) { + case "paint": + this.cells = message.cells; + this.caret = this.readCaret(message.caret, message.cells); + this.stale = true; + this.changed(); + break; + case "navigate": + if (message.target === "parent") { + navigateFrameParent(this.window, String(message.url)); + } else { + this.navigate(message.url, readSubmission(message)); + } + break; + case "history": + this.receiveHistory(message.url); + break; + case "images": + this.receiveImages(message.added, message.dropped); + break; + case "crash": + this.stop(); + this.cells = null; + this.caret = null; + this.stale = true; + this.changed(); + break; + case "load": + this.frame.dispatchEvent(constructInternal(() => new Event("load"))); + break; + case "message": + receiveFrameMessage( + this.window, + message.data, + this.getOrigin(), + String(message.targetOrigin), + ); + break; + case "fetch": + void this.fetch(message.id, message.request); + break; + case "abortFetch": + this.fetches.get(message.id)?.abort(); + break; + } + } + + // The frame's document changed its URL in place, which keeps its + // origin. + receiveHistory(target: string): void { + const url = URL.parse(String(target), this.url); + if (url === null || url.origin !== URL.parse(this.url)?.origin) { + return; + } + this.url = url.href; + } + + // The origin the frame's messages come from: its document's, or an + // opaque one where a sandbox withholds allow-same-origin. + getOrigin(): string { + const sandbox = _(this.window).sandbox; + if (sandbox !== null && !sandbox.has("allow-same-origin")) { + return "null"; + } + return URL.parse(this.url)?.origin ?? "null"; + } + + // The images the frame's next cells show, each checked against its + // size before the page holds it. + receiveImages(added: FrameImage[], dropped: number[]): void { + for (const id of dropped) { + this.posted.delete(id); + } + for (const image of added) { + const {id, width, height, cols, rows, pixels} = image; + if ( + ![id, width, height, cols, rows].every(Number.isInteger) || + id < 1 || + id > 0xffffff || + width < 1 || + height < 1 || + width * height > MAX_KITTY_PIXELS || + !(pixels instanceof Uint8ClampedArray) || + pixels.length !== width * height * 4 || + cols < 1 || + rows < 1 || + cols > MAX_PLACEHOLDER_CELLS || + rows > MAX_PLACEHOLDER_CELLS || + (!this.posted.has(id) && this.posted.size >= MAX_IMAGES) + ) { + continue; + } + this.posted.set(id, { + bitmap: {width, height, data: pixels}, + cols, + rows, + version: ++this.imageVersion, + }); + } + this.stale = true; + } + + images(): GridImage[] { + return this.shown; + } + + // A caret the frame names is drawn only inside the cells it painted. + readCaret(caret: Caret | null, cells: GridCells): Caret | null { + if ( + caret === null || + !Number.isInteger(caret.col) || + !Number.isInteger(caret.row) || + caret.col < 0 || + caret.row < 0 || + caret.col >= cells.cols || + caret.row >= cells.rows + ) { + return null; + } + return { + col: caret.col, + row: caret.row, + shape: Number(caret.shape) | 0, + color: typeof caret.color === "number" ? caret.color & 0xffffff : null, + }; + } + + // The frame's document went to another URL: the isolate goes, and + // one for the new document starts. + navigate(target: string, submission?: Submission): void { + const url = URL.parse(String(target), this.url); + if (url === null || !isWebURL(url)) { + return; + } + this.stop(); + this.unload = new AbortController(); + this.posted.clear(); + this.cells = null; + this.caret = null; + this.stale = true; + this.changed(); + void this.start(url.href, submission); + } + + async fetch(id: number, request: FrameRequest): Promise { + const url = URL.parse(String(request.url)); + if ( + url === null || + (!isWebURL(url) && url.protocol !== "data:") || + this.fetches.has(id) || + this.fetches.size >= MAX_FETCHES + ) { + this.send({type: "fetchError", id, message: "Failed to fetch"}); + return; + } + const abort = new AbortController(); + this.fetches.set(id, abort); + const unload = this.unload; + const onUnload = () => abort.abort(); + unload.signal.addEventListener("abort", onUnload, {once: true}); + try { + const headers = new Headers(); + for (const [name, value] of request.headers) { + if (!FORBIDDEN_HEADER.test(String(name))) { + headers.append(String(name), String(value)); + } + } + const method = String(request.method).toUpperCase(); + const loaded = new Request(url.href, { + method, + headers, + body: method === "GET" || method === "HEAD" || request.body === null + ? null + : Uint8Array.from(request.body), + redirect: request.redirect, + signal: abort.signal, + }); + if (DESTINATIONS.has(request.destination)) { + setRequestDestination( + loaded, + request.destination as RequestDestination, + ); + } + const response = await _(this.parent).extra.load(loaded, { + initiator: this.frame as unknown as globalThis.Element, + }); + const body = new Uint8Array(await response.arrayBuffer()); + if (!abort.signal.aborted) { + this.send({ + type: "response", + id, + response: { + url: response.url, + status: response.status, + statusText: response.statusText, + headers: readHeaders(response.headers), + redirected: response.redirected, + body, + }, + }); + } + } catch (error) { + if (!unload.signal.aborted) { + this.send({type: "fetchError", id, message: describeError(error)}); + } + } finally { + unload.signal.removeEventListener("abort", onUnload); + this.fetches.delete(id); + } + } + + fit(cols: number, rows: number): CellGrid { + if (cols !== this.cols || rows !== this.rows) { + this.cols = cols; + this.rows = rows; + this.grid = new CellGrid(rows, cols); + this.stale = true; + const cell = getCellSize(this.parent); + if (this.running !== null) { + this.running.send({ + type: "resize", + cols, + rows, + cellWidth: cell.width, + cellHeight: cell.height, + pixelRatio: _(this.parent).extra.framebuffer.pixelRatio ?? 1, + }); + } + } + if (this.stale) { + this.stale = false; + const shown = new Map(); + if (this.cells !== null) { + importGrid(this.cells, this.grid, (place) => + this.showImage(shown, place)); + } + this.shown = [...shown.values()]; + } + return this.grid; + } + + // A placeholder cell shows its image only where the frame posted one + // with that id that has a cell there. + showImage(shown: Map, place: ImportedPlaceholder): void { + const image = this.posted.get(place.id); + if ( + image === undefined || + place.imageRow >= image.rows || + place.imageCol >= image.cols + ) { + return; + } + let entry = shown.get(place.id); + if (entry === undefined) { + entry = { + key: `frame:${this.token}:${place.id}`, + version: image.version, + bitmap: image.bitmap, + cols: image.cols, + rows: image.rows, + cells: [], + }; + shown.set(place.id, entry); + } + entry.cells.push({ + row: place.row, + col: place.col, + imageRow: place.imageRow, + imageCol: place.imageCol, + bg: place.bg, + }); + } + + sendKey(key: WireKey): boolean { + this.send({ + type: "input", + item: [ + { + kind: "key", + key: key.key, + char: key.char, + shiftKey: key.shiftKey, + ctrlKey: key.ctrlKey, + altKey: key.altKey, + metaKey: key.metaKey, + }, + ], + }); + return true; + } + + paste(text: string): void { + this.send({type: "input", item: {kind: "paste", text}}); + } + + sendMouse(code: number, col: number, row: number, release: boolean): boolean { + this.send({ + type: "input", + item: {kind: "mouse", button: code, col, row, release, ticks: 1}, + }); + return true; + } + + scrollBy(): boolean { + return false; + } + + sendFocus(focused: boolean): void { + if (focused !== this.focused) { + this.focused = focused; + this.send({type: "input", item: {kind: "focus", focused}}); + } + } + + postMessage(data: unknown, origin: string, targetOrigin: string): void { + this.send({type: "message", data, origin, targetOrigin}); + } + + stop(): void { + this.unload.abort(); + this.running?.dispose(); + this.running = null; + this.waiting = []; + } + + dispose(): void { + this.stop(); + this.disposed = true; + } +} + +// A frame started before its backend has loaded, which starts there and +// sends what it was given once the backend has. +class PendingFrame implements IsolatedFrame { + init: FrameInit; + receive: (message: FrameMessage) => void; + waiting: HostMessage[]; + frame: IsolatedFrame | null; + disposed: boolean; + + constructor( + init: FrameInit, + receive: (message: FrameMessage) => void, + backend: Promise, + ) { + this.init = init; + this.receive = receive; + this.waiting = []; + this.frame = null; + this.disposed = false; + void backend.then((isolate) => this.start(isolate)); + } + + start(isolate: FrameIsolator | string): void { + if (this.disposed) { + return; + } + if (typeof isolate === "string") { + this.receive({type: "crash", reason: isolate}); + return; + } + this.frame = isolate(this.init, this.receive); + for (const message of this.waiting.splice(0)) { + this.frame.send(message); + } + } + + send(message: HostMessage): void { + if (this.frame === null) { + this.waiting.push(message); + } else { + this.frame.send(message); + } + } + + dispose(): void { + this.disposed = true; + this.waiting = []; + this.frame?.dispose(); + } +} + +let isolatedVM: Promise | null = null; + +// isolated-vm's isolator, compiled with the first frame. +function startInIsolatedVM( + init: FrameInit, + receive: (message: FrameMessage) => void, +): IsolatedFrame { + isolatedVM ??= import("./isolatedvm.ts") + .then((backend) => backend.createIsolatedVMFrames()) + .catch((error: unknown) => + `isolated-vm could not load: ${describeError(error)}`, + ); + return new PendingFrame(init, receive, isolatedVM); +} + +let found: FrameIsolator | null | undefined; + +/** + * What starts a frame's document in an isolate of its own, where the + * isolated-vm package is installed and loads, as on Node. Null elsewhere, + * where an iframe's src shows nothing. + */ +export function findFrameIsolator(): FrameIsolator | null { + if (found === undefined) { + try { + requireNodePackage("isolated-vm"); + found = startInIsolatedVM; + } catch (_err) { + found = null; + } + } + return found; +} + +setIsolatedFrameFactory((frame, window, url, parent, isolate, changed) => + new RemoteFrame(frame, window, url, parent, isolate, changed), +); diff --git a/src/internal/isolatedvm.ts b/src/internal/isolatedvm.ts new file mode 100644 index 00000000..14bcc3c7 --- /dev/null +++ b/src/internal/isolatedvm.ts @@ -0,0 +1,452 @@ +/** + * Frames in isolates of their own, made with isolated-vm. Each frame + * gets an isolate with a memory limit and a context running the frame + * runtime, and every call into it is held to a time limit. The backend + * drives the frame's timers, randomness and logs, and fetches, compiles + * and runs its scripts and modules in document order. Anything the frame + * fetches, its scripts included, goes to the page, which loads it under + * its own policy. + */ +import type ivm from "isolated-vm"; + +import { + HOST_CALLBACKS, + loadFrameScript, + requireNodePackage, +} from "./isolate/bundle.ts"; +import type {ScriptItem} from "./isolate/scripts.ts"; +import {ModuleLoader} from "./isolatedvmmodules.ts"; +import type { + FrameInit, + FrameIsolator, + FrameMessage, + FrameRequest, + FrameResponse, + HostMessage, +} from "./isolateprotocol.ts"; + +export const DEFAULT_MEMORY_LIMIT = 256; +export const DEFAULT_TASK_TIMEOUT = 30000; +const BOOT_TIMEOUT = 10000; +const MAX_RANDOM_BYTES = 65536; +const MAX_TIMERS = 10000; +const MAX_SCRIPTS = 1000; +const MAX_LOG_LENGTH = 4096; + +export interface IsolatedVMOptions { + // Megabytes of heap each frame's isolate may use. + memoryLimit?: number; + // Milliseconds any one call into a frame may run. + taskTimeout?: number; + // Where a frame's console output and uncaught errors go. + log?(level: string, text: string): void; +} + +type Dispatch = ivm.Reference<(kind: string, ...args: unknown[]) => unknown>; + +/** + * Resolves to the isolator, once isolated-vm has loaded and the frame + * runtime is compiled. Rejects where isolated-vm is not installed. + */ +export async function createIsolatedVMFrames( + options: IsolatedVMOptions = {}, +): Promise { + const ivmModule = requireNodePackage("isolated-vm"); + const source = await loadFrameScript(); + const memoryLimit = options.memoryLimit ?? DEFAULT_MEMORY_LIMIT; + const taskTimeout = options.taskTimeout ?? DEFAULT_TASK_TIMEOUT; + const log = options.log ?? (() => {}); + let cachedData: ivm.ExternalCopy | undefined; + return (init, receive) => { + const frame = new IsolatedVMFrame( + ivmModule, + {memoryLimit, taskTimeout, log}, + init, + receive, + ); + void frame.boot(source, cachedData).then((data) => { + cachedData ??= data; + }); + return { + send: (message) => frame.send(message), + dispose: () => frame.dispose(), + }; + }; +} + +class IsolatedVMFrame { + readonly ivm: typeof ivm; + readonly isolate: ivm.Isolate; + readonly init: FrameInit; + readonly receive: (message: FrameMessage) => void; + readonly taskTimeout: number; + readonly log: (level: string, text: string) => void; + readonly modules: ModuleLoader; + readonly timers: Map>; + readonly ownLoads: Map< + number, + {resolve(response: FrameResponse): void; reject(error: Error): void} + >; + + context!: ivm.Context; + dispatch: Dispatch | null; + queued: Array<[string, ...unknown[]]> | null; + nextOwnLoad: number; + scriptQueue: Promise; + asyncScripts: Set>; + executing: Promise; + scriptCount: number; + disposed: boolean; + + constructor( + ivmModule: typeof ivm, + limits: { + memoryLimit: number; + taskTimeout: number; + log(level: string, text: string): void; + }, + init: FrameInit, + receive: (message: FrameMessage) => void, + ) { + this.ivm = ivmModule; + this.init = init; + this.receive = receive; + this.taskTimeout = limits.taskTimeout; + this.log = (level, text) => + limits.log(String(level), String(text).slice(0, MAX_LOG_LENGTH)); + this.timers = new Map(); + this.ownLoads = new Map(); + this.dispatch = null; + this.queued = []; + this.nextOwnLoad = -1; + this.scriptQueue = Promise.resolve(); + this.asyncScripts = new Set(); + this.executing = Promise.resolve(); + this.scriptCount = 0; + this.disposed = false; + this.isolate = new ivmModule.Isolate({ + memoryLimit: limits.memoryLimit, + importModuleDynamically: (specifier, referrer) => + this.modules.import(String(specifier), String(referrer)), + onUnhandledRejection: (error) => { + this.log("error", `Unhandled rejection: ${String(error)}`); + }, + }); + this.modules = new ModuleLoader({ + isolate: this.isolate, + context: () => this.context, + baseURL: () => init.url, + timeout: () => this.taskTimeout, + fetch: (request) => this.fetchThroughPage(request), + }); + } + + async boot( + source: string, + cachedData: ivm.ExternalCopy | undefined, + ): Promise | undefined> { + const ivmModule = this.ivm; + try { + const script: ivm.Script & ivm.CachedDataResult = + await this.isolate.compileScript( + source, + { + filename: "termdom:frame", + ...(cachedData ? {cachedData} : {produceCachedData: true}), + }, + ); + this.context = await this.isolate.createContext(); + const boot = (await script.run(this.context, { + reference: true, + })) as unknown as ivm.Reference< + (...args: unknown[]) => unknown + >; + const callbacks: Record<(typeof HOST_CALLBACKS)[number], unknown> = { + post: new ivmModule.Callback( + (message: FrameMessage) => this.onPost(message), + {ignored: true}, + ), + log: new ivmModule.Callback( + (level: string, text: string) => this.log(level, text), + {ignored: true}, + ), + setTimer: new ivmModule.Callback( + (id: number, ms: number) => this.setTimer(id, ms), + {ignored: true}, + ), + clearTimer: new ivmModule.Callback( + (id: number) => this.clearTimer(id), + {ignored: true}, + ), + random: new ivmModule.Callback((length: number) => this.random(length)), + scripts: new ivmModule.Callback( + (initial: boolean, items: ScriptItem[]) => + this.runScripts(items, initial), + {ignored: true}, + ), + }; + const starter = (await boot.apply( + undefined, + HOST_CALLBACKS.map((name) => callbacks[name]) as ivm.Transferable[], + {timeout: BOOT_TIMEOUT, result: {reference: true}}, + )) as ivm.Reference<(init: FrameInit) => unknown>; + boot.release(); + this.dispatch = (await starter.apply( + undefined, + [this.init], + { + arguments: {copy: true}, + timeout: this.taskTimeout, + result: {reference: true}, + }, + )) as Dispatch; + starter.release(); + const queued = this.queued ?? []; + this.queued = null; + for (const args of queued) { + void this.call(...args); + } + return script.cachedData; + } catch (error) { + this.fail(error); + return undefined; + } + } + + call(kind: string, ...args: unknown[]): Promise { + if (this.disposed) { + return Promise.resolve(); + } + if (this.queued !== null || this.dispatch === null) { + this.queued?.push([kind, ...args]); + return Promise.resolve(); + } + return this.dispatch + .apply( + undefined, + [kind, ...args], + {arguments: {copy: true}, timeout: this.taskTimeout}, + ) + .then(() => {}, (error: unknown) => this.fail(error)); + } + + send(message: HostMessage): void { + if ( + (message.type === "response" || message.type === "fetchError") && + message.id < 0 + ) { + const own = this.ownLoads.get(message.id); + this.ownLoads.delete(message.id); + if (message.type === "response") { + own?.resolve(message.response); + } else { + own?.reject(new TypeError(`Failed to fetch: ${message.message}`)); + } + return; + } + void this.call("receive", message); + } + + onPost(message: FrameMessage): void { + if (this.disposed) { + return; + } + if ( + (message.type === "fetch" || message.type === "abortFetch") && + !(message.id > 0) + ) { + return; + } + this.receive(message); + } + + fail(error: unknown): void { + if (this.disposed) { + return; + } + const text = error instanceof Error ? error.message : String(error); + this.log("error", `The frame stopped: ${text}`); + this.dispose(); + this.receive({ + type: "crash", + reason: /timed out/i.test(text) + ? "timeout" + : /memory limit/i.test(text) ? "memory" : "error", + }); + } + + dispose(): void { + if (this.disposed) { + return; + } + this.disposed = true; + for (const timer of this.timers.values()) { + clearTimeout(timer); + } + this.timers.clear(); + for (const own of this.ownLoads.values()) { + own.reject(new TypeError("The frame is closed")); + } + this.ownLoads.clear(); + if (!this.isolate.isDisposed) { + this.isolate.dispose(); + } + } + + setTimer(id: number, ms: number): void { + if (this.disposed) { + return; + } + this.clearTimer(id); + if (this.timers.size >= MAX_TIMERS) { + this.log("warn", "Too many timers; this one will not fire"); + return; + } + this.timers.set( + id, + setTimeout(() => { + this.timers.delete(id); + void this.call("timer", id); + }, ms), + ); + } + + clearTimer(id: number): void { + const timer = this.timers.get(id); + if (timer !== undefined) { + clearTimeout(timer); + this.timers.delete(id); + } + } + + random(length: number): Uint8Array { + const size = Math.max(0, Math.min(Number(length) | 0, MAX_RANDOM_BYTES)); + return crypto.getRandomValues(new Uint8Array(size)); + } + + // The backend's own loads, a script's or a module's source, go to the + // page with ids below zero, so the frame's own stay above it. + fetchThroughPage(request: FrameRequest): Promise { + if (this.disposed) { + return Promise.reject(new TypeError("The frame is closed")); + } + const id = this.nextOwnLoad--; + return new Promise((resolve, reject) => { + this.ownLoads.set(id, {resolve, reject}); + this.receive({type: "fetch", id, request}); + }); + } + + runScripts(items: ScriptItem[], initial: boolean): void { + for (const script of items.slice(0, MAX_SCRIPTS - this.scriptCount)) { + this.scriptCount++; + const source = script.kind === "classic" && script.src !== null + ? this.loadScript(script.src) + : null; + source?.catch(() => {}); + if (script.async) { + const run = this.runScript(script, source); + this.asyncScripts.add(run); + void run.then(() => this.asyncScripts.delete(run)); + } else { + this.scriptQueue = this.scriptQueue.then(() => + this.runScript(script, source), + ); + } + } + if (initial) { + this.scriptQueue = this.scriptQueue.then(() => this.call("interactive")); + void this.scriptQueue + .then(async () => { + while (this.asyncScripts.size > 0) { + await Promise.all(this.asyncScripts); + } + }) + .then(() => this.call("loaded")); + } + } + + async runScript( + script: ScriptItem, + source: Promise | null, + ): Promise { + if (this.disposed) { + return; + } + let ok = true; + try { + if (script.kind === "importmap") { + this.modules.addImportMap(script.text ?? "", this.init.url); + } else if (script.kind === "module") { + if (script.src !== null) { + await this.modules.import(script.src, this.init.url); + } else { + await this.modules.importSource( + script.text ?? "", + `${this.init.url}#module-${script.id}`, + this.init.url, + ); + } + } else { + const text = script.src === null + ? script.text ?? "" + : await (source ?? this.loadScript(script.src)); + await this.execute(script, text); + } + } catch (error) { + ok = false; + if (this.isFatal(error)) { + this.fail(error); + return; + } + this.log( + "error", + `Uncaught ${error instanceof Error ? error.stack ?? error.message : String(error)}`, + ); + } + if (script.src !== null) { + void this.call("scriptFinished", script.id, ok); + } + } + + execute(script: ScriptItem, source: string): Promise { + const run = this.executing.then(async () => { + await this.call("scriptBegin", script.id); + try { + await this.context.eval(source, { + filename: script.src ?? this.init.url, + timeout: this.taskTimeout, + }); + } finally { + if (!this.disposed) { + await this.call("scriptEnd", script.id); + } + } + }); + this.executing = run.catch(() => {}); + return run; + } + + isFatal(error: unknown): boolean { + return this.isolate.isDisposed || + /timed out|memory limit|disposed/i.test(String(error)); + } + + async loadScript(url: string): Promise { + const response = await this.fetchThroughPage({ + url, + method: "GET", + headers: [["accept", "*/*"]], + body: null, + redirect: "follow", + destination: "script", + referrer: "", + }); + if (response.status < 200 || response.status > 299) { + throw new TypeError( + `Failed to load the script ${url}: ${response.status}`, + ); + } + return new TextDecoder().decode(response.body ?? new Uint8Array()); + } +} diff --git a/src/internal/isolatedvmmodules.ts b/src/internal/isolatedvmmodules.ts new file mode 100644 index 00000000..4e279362 --- /dev/null +++ b/src/internal/isolatedvmmodules.ts @@ -0,0 +1,280 @@ +/** + * Module scripts in an isolated frame: specifiers resolved through the + * page's import maps, sources loaded through the page, and each module + * compiled once in the frame's isolate and linked in order. + */ +import type ivm from "isolated-vm"; + +import type {FrameRequest, FrameResponse} from "./isolate/host.ts"; + +const JAVASCRIPT = /^(text|application)\/(x-)?(java|ecma)script$/; +const RELATIVE = /^(\.{0,2}\/)/; +const ISOLATE_REFERRER = ""; + +type SpecifierMap = Map; + +interface ImportMap { + imports: SpecifierMap; + scopes: Map; +} + +function parseURL(value: string, base?: string): string | null { + try { + return new URL(value, base).href; + } catch (error) { + if (!(error instanceof TypeError)) { + throw error; + } + + return null; + } +} + +function parseURLLike(specifier: string, base: string): string | null { + return RELATIVE.test(specifier) + ? parseURL(specifier, base) + : parseURL(specifier); +} + +function parseSpecifierMap(value: unknown, base: string): SpecifierMap { + const map: SpecifierMap = new Map(); + if (typeof value !== "object" || value === null || Array.isArray(value)) { + return map; + } + + for (const [key, address] of Object.entries(value)) { + if (key === "") { + continue; + } + + const url = typeof address === "string" + ? parseURLLike(address, base) + : null; + map.set( + parseURLLike(key, base) ?? key, + url !== null && key.endsWith("/") && !url.endsWith("/") ? null : url, + ); + } + + return map; +} + +function matchSpecifier( + specifier: string, + map: SpecifierMap, +): string | null | undefined { + if (map.has(specifier)) { + return map.get(specifier); + } + + let best: string | undefined; + for (const key of map.keys()) { + if ( + key.endsWith("/") && + specifier.startsWith(key) && + (best === undefined || key.length > best.length) + ) { + best = key; + } + } + + if (best === undefined) { + return undefined; + } + + const address = map.get(best); + return address == null + ? null + : parseURL(specifier.slice(best.length), address); +} + +export interface ModuleHost { + isolate: ivm.Isolate; + context(): ivm.Context; + baseURL(): string; + timeout(): number; + fetch(request: FrameRequest): Promise; +} + +export class ModuleLoader { + readonly host: ModuleHost; + readonly modules: Map>; + readonly ready: Map>; + readonly urls: WeakMap; + readonly importMap: ImportMap; + linking: Promise; + + constructor(host: ModuleHost) { + this.host = host; + this.modules = new Map(); + this.ready = new Map(); + this.urls = new WeakMap(); + this.importMap = {imports: new Map(), scopes: new Map()}; + this.linking = Promise.resolve(); + } + + addImportMap(text: string, base: string): void { + const value = JSON.parse(text) as unknown; + if (typeof value !== "object" || value === null || Array.isArray(value)) { + throw new TypeError("An import map must be a JSON object"); + } + + const {imports, scopes} = value as {imports?: unknown; scopes?: unknown}; + for (const [key, url] of parseSpecifierMap(imports, base)) { + if (!this.importMap.imports.has(key)) { + this.importMap.imports.set(key, url); + } + } + + if (typeof scopes !== "object" || scopes === null) { + return; + } + + for (const [prefix, map] of Object.entries(scopes)) { + const scope = parseURL(prefix, base); + if (scope === null) { + continue; + } + + const existing = this.importMap.scopes.get(scope) ?? new Map(); + for (const [key, url] of parseSpecifierMap(map, base)) { + if (!existing.has(key)) { + existing.set(key, url); + } + } + + this.importMap.scopes.set(scope, existing); + } + } + + resolve(specifier: string, referrer: string): string { + const base = referrer === ISOLATE_REFERRER || referrer === "" + ? this.host.baseURL() + : referrer; + const url = parseURLLike(specifier, base); + const key = url ?? specifier; + const scopes = [...this.importMap.scopes] + .filter(([scope]) => + scope === base || (scope.endsWith("/") && base.startsWith(scope))) + .sort(([a], [b]) => b.length - a.length); + for (const map of [ + ...scopes.map(([, map]) => map), + this.importMap.imports, + ]) { + const match = matchSpecifier(key, map); + if (match === null) { + throw new TypeError( + `Failed to resolve module specifier "${specifier}": the import map blocks it`, + ); + } + + if (match !== undefined) { + return match; + } + } + + if (url === null) { + throw new TypeError( + `Failed to resolve module specifier "${specifier}": a bare specifier must be in the page's import map`, + ); + } + + return url; + } + + fetchModule(url: string): Promise { + let module = this.modules.get(url); + if (module === undefined) { + module = this.compile(url); + this.modules.set(url, module); + } + + return module; + } + + async compile(url: string): Promise { + const response = await this.host.fetch({ + url, + method: "GET", + headers: [["accept", "*/*"]], + body: null, + redirect: "follow", + destination: "script", + referrer: "", + }); + if (response.status < 200 || response.status > 299) { + throw new TypeError(`Failed to load module ${url}: ${response.status}`); + } + + const type = + response.headers.find(([name]) => name === "content-type")?.[1]; + const essence = (type ?? "").split(";")[0].trim().toLowerCase(); + if (!JAVASCRIPT.test(essence)) { + throw new TypeError( + `Failed to load module ${url}: "${essence || "no type"}" is not a JavaScript MIME type`, + ); + } + + const final = response.url || url; + const module = await this.host.isolate.compileModule( + new TextDecoder().decode(response.body ?? new Uint8Array()), + { + filename: final, + meta: (meta: {url?: string}) => { + meta.url = final; + }, + }, + ); + this.urls.set(module, response.url || url); + return module; + } + + import(specifier: string, referrer: string): Promise { + const url = this.resolve(specifier, referrer); + let module = this.ready.get(url); + if (module === undefined) { + module = this.link(url); + this.ready.set(url, module); + } + + return module; + } + + async importSource( + source: string, + url: string, + base: string, + ): Promise { + const module = await this.host.isolate.compileModule(source, { + filename: url, + meta: (meta: {url?: string}) => { + meta.url = base; + }, + }); + this.urls.set(module, url); + this.modules.set(url, Promise.resolve(module)); + return this.link(url); + } + + async link(url: string): Promise { + const module = await this.fetchModule(url); + const previous = this.linking; + let done!: () => void; + this.linking = new Promise((resolve) => (done = resolve)); + try { + await previous; + await module.instantiate(this.host.context(), (specifier, referrer) => + this.fetchModule( + this.resolve(specifier, this.urls.get(referrer) ?? ""), + ), + ); + } finally { + done(); + } + + await module.evaluate( + {timeout: this.host.timeout(), promise: true} as ivm.ScriptRunOptions, + ); + return module; + } +} diff --git a/src/internal/isolateprotocol.ts b/src/internal/isolateprotocol.ts new file mode 100644 index 00000000..09297e6c --- /dev/null +++ b/src/internal/isolateprotocol.ts @@ -0,0 +1,120 @@ +/** + * What passes between a page and a frame whose document is in another + * isolate. The page draws the frame's box with the cells the frame + * paints, and hands it input, its size and messages. Each message is + * plain data and typed arrays, so any isolate a backend makes can carry + * it: isolated-vm's, a Worker's, or QuickJS's. + */ +import type { + ColorDepth, + WireFocus, + WireKey, + WireMouse, + WirePaste, +} from "./exchange.ts"; +import type {Caret, GridCells} from "./framebuffer.ts"; + +/** A frame's document and the terminal it is drawn for. */ +export interface FrameInit { + url: string; + html: string; + // The origin of the window the frame's iframe is in, which the frame's + // parent and top have. + parentOrigin: string; + cols: number; + rows: number; + cellWidth: number; + cellHeight: number; + pixelRatio: number; + colorDepth: ColorDepth; + colorScheme: "light" | "dark"; + reducedMotion: boolean; + scripting: boolean; + // "kitty" where the page sends images in the kitty graphics protocol, + // so the frame paints placeholders and posts the images' pixels. + images?: "kitty" | "cells"; +} + +export interface FrameRequest { + url: string; + method: string; + headers: Array<[string, string]>; + body: Uint8Array | null; + redirect: RequestRedirect; + destination: string; + referrer: string; +} + +export interface FrameResponse { + url: string; + status: number; + statusText: string; + headers: Array<[string, string]>; + redirected: boolean; + body: Uint8Array | null; +} + +export type FrameMessage = + {type: "paint"; cells: GridCells; caret: Caret | null} | + {type: "title"; title: string} | + // The frame went to another document, or sent its parent to one. + // A form's POST carries its method, its encoded fields and their type. + { + type: "navigate"; + target: "self" | "parent"; + url: string; + method?: string; + body?: Uint8Array | null; + contentType?: string; + } | + // The frame's document changed its URL in place: pushState, + // replaceState or a fragment. + {type: "history"; url: string; replace: boolean} | + {type: "load"} | + // The images the frame's placeholder cells name: those placed since its + // last paint, as RGBA pixels, and the ids it no longer shows. + {type: "images"; added: FrameImage[]; dropped: number[]} | + {type: "message"; data: unknown; targetOrigin: string} | + {type: "fetch"; id: number; request: FrameRequest} | + {type: "abortFetch"; id: number} | + // The frame ran past its time or memory, or failed to start, and its + // isolate is gone. + {type: "crash"; reason: string}; + +export type HostMessage = + { + type: "resize"; + cols: number; + rows: number; + cellWidth: number; + cellHeight: number; + pixelRatio: number; + } | + {type: "input"; item: WireKey[] | WireMouse | WirePaste | WireFocus} | + {type: "message"; data: unknown; origin: string; targetOrigin: string} | + {type: "response"; id: number; response: FrameResponse} | + {type: "fetchError"; id: number; message: string}; + +export interface FrameImage { + id: number; + width: number; + height: number; + cols: number; + rows: number; + pixels: Uint8ClampedArray; +} + +/** A frame running in an isolate, as its page holds it. */ +export interface IsolatedFrame { + send(message: HostMessage): void; + dispose(): void; +} + +/** + * Starts a frame in an isolate of its own. What the frame sends arrives + * through `receive`, never during the call that made the frame. + */ +export type FrameIsolator = ( + init: FrameInit, + receive: (message: FrameMessage) => void, +) => IsolatedFrame; diff --git a/src/internal/kitty.ts b/src/internal/kitty.ts index 3678b89c..f935c215 100644 --- a/src/internal/kitty.ts +++ b/src/internal/kitty.ts @@ -389,6 +389,63 @@ export function takeKittyOutput( return images.passthrough ? wrapForTmux(out) : out; } +/** An image a frame placed, for the page that draws the frame to send. */ +export interface FrameImage { + id: number; + width: number; + height: number; + cols: number; + rows: number; + pixels: Uint8ClampedArray; +} + +/** + * A frame's images after a paint, where the page that draws the frame + * sends them on: those placed since the last paint, with their pixels, + * and the ids of those `screen` no longer shows, which are forgotten. A + * frame keeps no scrollback, so an image goes once it is off screen. + */ +export function takeFrameImages( + images: KittyImages, + screen: CellGrid, +): {added: FrameImage[]; dropped: number[]} { + const frame = images.frame++; + const added: FrameImage[] = []; + const dropped: number[] = []; + const {cluster, fg} = screen; + for (let index = 0; index < cluster.length; index++) { + if (isPlaceholderChar(cluster[index])) { + const image = images.byId.get(fg[index] & MAX_ID); + if (image !== undefined) { + image.seen = frame; + } + } + } + for (const [key, image] of images.byKey) { + if (image.seen < frame) { + images.byKey.delete(key); + images.byId.delete(image.id); + dropped.push(image.id); + } else if (image.pixels !== null) { + const {id, width, height, cols, rows, pixels} = image; + added.push({id, width, height, cols, rows, pixels}); + image.pixels = null; + image.encoded = null; + } + } + images.retired = images.retired.filter(({image, frame: retiredAt}) => { + if (retiredAt === frame) { + return true; + } + if (images.byId.get(image.id) === image) { + images.byId.delete(image.id); + dropped.push(image.id); + } + return false; + }); + return {added, dropped}; +} + /** * `escapes` as tmux passes them on to the terminal it runs in: each one * in a DCS of its own, with the ESCs inside doubled. diff --git a/src/internal/resources.ts b/src/internal/resources.ts index 03a071d2..2724d396 100644 --- a/src/internal/resources.ts +++ b/src/internal/resources.ts @@ -519,6 +519,7 @@ const FETCH_DIRECTIVES: Partial> = { audio: "media-src", video: "media-src", track: "media-src", + iframe: "frame-src", }; /** The directive a policy enforces for a load, or null when none applies. */ @@ -531,6 +532,10 @@ function getEffectiveDirective( if (directive !== undefined && policy.directives.has(directive)) { return directive; } + // A frame falls back to child-src before default-src. + if (directive === "frame-src" && policy.directives.has("child-src")) { + return "child-src"; + } return policy.directives.has("default-src") ? "default-src" : null; } diff --git a/src/internal/window.ts b/src/internal/window.ts index 176d16c2..bc61d287 100644 --- a/src/internal/window.ts +++ b/src/internal/window.ts @@ -51,23 +51,24 @@ import { // A window starts with its interfaces and the timers any script expects // to find. The display fills in the rest (sizing, scrolling, animation -// frames, the clipboard) as it mounts the document. A frame's window is -// its realm's global object, with the realm's interfaces, and its timers -// run with the realm active. +// frames, the clipboard) as it mounts the document. A frame's window in a +// realm is the realm's global object, with the realm's interfaces, and +// its timers run with the realm active. export function buildWindow( document: Document, realm: Realm | null = null, + frame: ConstructorParameters[1] = null, ): Window { let window: Record; if (realm === null) { - window = new Window(document) as unknown as Record; + window = new Window(document, frame) as unknown as Record; } else { // The window keeps the prototype it is built with under its named // properties, so it takes the realm's first. Object.setPrototypeOf(realm.global, realm.prototypes.get(Window)!); window = runInRealm(realm, () => - constructOnto(realm.global, () => new Window(document))) as unknown as - Record; + constructOnto(realm.global, () => new Window(document, frame))) as + unknown as Record; } // HTML reports an exception a timer or a microtask lets escape, as it // does a listener's, and the page goes on. The runtime's own would end @@ -251,21 +252,20 @@ export function getInterfaceObjects(): ReadonlyMap { } // A frame's document and window, built in a realm of their own where the -// runtime can make one. Its handler attributes stay inert, as a frame's -// did before it had a realm, and its requests are the window's it is in: -// held to the same policy, and offered to the same fetch listeners. +// runtime can make one, and where it cannot, in the engine's, sharing its +// interfaces and intrinsics. Its handler attributes stay inert, and its +// requests are those of the window it is in: held to its policy, and +// offered to its fetch listeners. setFrameWindowFactory((source, url, registry, parent, frame) => { const realm = createRealm(); - if (realm === null) { - return null; - } return runInRealm(realm, () => { const document = parseHTMLDocument(source, url, true, registry); - realm.document = document; - const window = buildWindow(document, realm); + if (realm !== null) { + realm.document = document; + } + const window = buildWindow(document, realm, frame); const windowSlots = _(window); windowSlots.parentWindow = parent; - windowSlots.frameOwner = frame; windowSlots.realm = realm; const loader = parent === null ? null : getDocumentLoader(parent); if (loader !== null) { diff --git a/tests/frame-origins.test.ts b/tests/frame-origins.test.ts new file mode 100644 index 00000000..f7a38d74 --- /dev/null +++ b/tests/frame-origins.test.ts @@ -0,0 +1,315 @@ +/** + * Frames and their origins. + * + * A frame showing srcdoc or about:blank has the origin of the document + * that made it. A sandbox without allow-same-origin gives the frame an + * opaque origin of its own, and windows of two origins hold each other + * by HTML's cross-origin WindowProxy, which lets through only what HTML + * lists. postMessage carries messages between them, and a frame may send + * its parent to another page through the parent's location. + */ +import {spawn} from "node:child_process"; +import {fileURLToPath} from "node:url"; + +import {expect, test} from "@b9g/libuild/test"; + +import {TermDOM} from "../src/index.ts"; +import {getDrawnFrameDocument} from "../src/internal/dom.ts"; +import {MockProcess, until} from "./test-utils.ts"; + +function created(): TermDOM { + return new TermDOM({ + transport: new MockProcess().transport, + url: "https://example.com/inbox", + }); +} + +function addFrame( + dom: TermDOM, + attributes: Record = {}, +): HTMLIFrameElement { + const iframe = dom.document.createElement("iframe"); + iframe.setAttribute("srcdoc", "

hi

"); + for (const [name, value] of Object.entries(attributes)) { + iframe.setAttribute(name, value); + } + dom.document.body.append(iframe); + return iframe; +} + +// The frame's own window, as its own code holds it, which a frame of +// another origin does not hand to its parent. +function inside(iframe: HTMLIFrameElement): any { + void iframe.contentWindow; + return (getDrawnFrameDocument(iframe as any) as any).defaultView; +} + +function errorName(run: () => unknown): string | null { + try { + run(); + return null; + } catch (error) { + return (error as Error).name; + } +} + +const tick = () => new Promise((resolve) => setTimeout(resolve, 0)); + +test("a srcdoc frame and an about:blank one have their parent's origin", () => { + const dom = created(); + const srcdoc = addFrame(dom); + const blank = dom.document.createElement("iframe"); + dom.document.body.append(blank); + for (const iframe of [srcdoc, blank]) { + const frame = iframe.contentWindow as any; + expect(frame.origin).toBe("https://example.com"); + expect(iframe.contentDocument).not.toBe(null); + expect(frame.document).toBe(iframe.contentDocument); + expect(frame.parent).toBe(dom.window); + expect(frame.frameElement).toBe(iframe); + } + dom.dispose(); +}); + +test("a sandbox with allow-same-origin keeps the parent's origin", () => { + const dom = created(); + const iframe = addFrame(dom, {sandbox: "allow-same-origin allow-scripts"}); + const frame = iframe.contentWindow as any; + expect(frame.origin).toBe("https://example.com"); + expect(iframe.contentDocument).not.toBe(null); + expect(frame.getSelection()).not.toBe(null); + expect(inside(iframe).parent).toBe(dom.window); + dom.dispose(); +}); + +test("a sandboxed frame has an opaque origin and no document to its parent", () => { + const dom = created(); + const iframe = addFrame(dom, {sandbox: "allow-scripts", name: "box"}); + const frame = iframe.contentWindow as any; + expect(iframe.contentDocument).toBe(null); + expect(iframe.getSVGDocument()).toBe(null); + expect(inside(iframe).origin).toBe("null"); + expect(frame).toBe(iframe.contentWindow); + expect(frame).not.toBe(inside(iframe)); + expect((dom.window as any)[0]).toBe(frame); + expect(dom.window.frames[0]).toBe(frame); + expect((dom.window as any).box).toBe(frame); + dom.dispose(); +}); + +test("a cross-origin window lets through only what HTML lists", () => { + const dom = created(); + const iframe = addFrame(dom, {sandbox: ""}); + const frame = iframe.contentWindow as any; + expect(frame.window).toBe(frame); + expect(frame.self).toBe(frame); + expect(frame.frames).toBe(frame); + expect(frame.parent).toBe(dom.window); + expect(frame.top).toBe(dom.window); + expect(frame.opener).toBe(null); + expect(frame.closed).toBe(false); + expect(frame.length).toBe(0); + expect(typeof frame.postMessage).toBe("function"); + expect(frame.postMessage).toBe(frame.postMessage); + expect(frame.location).toBe(frame.location); + expect(frame.then).toBe(undefined); + expect(Object.getPrototypeOf(frame)).toBe(null); + for (const read of [ + () => frame.document, + () => frame.getSelection(), + () => frame.origin, + () => frame.name, + () => frame[0], + () => "document" in frame, + () => frame.location.href, + () => frame.location.reload(), + ]) { + expect(errorName(read)).toBe("SecurityError"); + } + expect( + errorName(() => { + frame.name = "x"; + }), + ).toBe("SecurityError"); + expect(errorName(() => Object.defineProperty(frame, "x", {value: 1}))) + .toBe("SecurityError"); + expect(typeof frame.location.replace).toBe("function"); + dom.dispose(); +}); + +test("a sandboxed frame holds its parent as a window of another origin", () => { + const dom = created(); + const iframe = addFrame(dom, {sandbox: "allow-scripts"}); + const frame = inside(iframe); + expect(frame.parent).not.toBe(dom.window); + expect(frame.parent).toBe(frame.parent); + expect(frame.top).toBe(frame.parent); + expect(frame.frameElement).toBe(null); + expect(errorName(() => frame.parent.document)).toBe("SecurityError"); + expect(frame.parent.frames[0]).toBe(frame); + dom.dispose(); +}); + +test("a frame of a sandboxed frame is sandboxed too", () => { + const dom = created(); + const iframe = addFrame(dom, {sandbox: "allow-scripts"}); + const frame = inside(iframe); + const inner = frame.document.createElement("iframe"); + inner.setAttribute("sandbox", "allow-same-origin"); + frame.document.body.append(inner); + expect(inner.contentDocument).toBe(null); + expect(errorName(() => inner.contentWindow.origin)).toBe("SecurityError"); + const plain = frame.document.createElement("iframe"); + frame.document.body.append(plain); + expect(plain.contentDocument).toBe(null); + dom.dispose(); +}); + +test("messages cross between a page and its sandboxed frame", async () => { + const dom = created(); + const iframe = addFrame(dom, {sandbox: "allow-scripts"}); + const outer = iframe.contentWindow as any; + const frame = inside(iframe); + const heard: unknown[] = []; + dom.window.addEventListener("message", (event) => { + heard.push(["page", event.data, event.origin, event.source === outer]); + (event.source as any).postMessage("pong", "*"); + }); + frame.addEventListener("message", (event: MessageEvent) => { + heard.push([ + "frame", + event.data, + event.origin, + event.source === frame.parent, + ]); + }); + frame.parent.postMessage("ping", "*"); + expect(heard).toEqual([]); + await until(() => heard.length === 2); + expect(heard).toEqual([ + ["page", "ping", "null", true], + ["frame", "pong", "https://example.com", true], + ]); + dom.dispose(); +}); + +test("a message lands only at the origin its poster names", async () => { + const dom = created(); + const iframe = addFrame(dom, {sandbox: "allow-scripts"}); + const frame = inside(iframe); + const heard: string[] = []; + frame.addEventListener("message", (event: MessageEvent) => { + heard.push(`frame ${event.data}`); + }); + dom.window.addEventListener("message", (event) => { + heard.push(`page ${event.data}`); + }); + const outer = iframe.contentWindow as any; + outer.postMessage("named", "https://example.com"); + outer.postMessage("own", "/"); + outer.postMessage("any", "*"); + frame.parent.postMessage("to the page", "https://example.com"); + frame.parent.postMessage("to another", "https://elsewhere.example"); + frame.parent.postMessage("to its own", "/"); + expect(errorName(() => outer.postMessage("x", "not a url"))) + .toBe("SyntaxError"); + await tick(); + await tick(); + expect(heard.sort()).toEqual(["frame any", "page to the page"]); + dom.dispose(); +}); + +test("a frame sends its parent to another page through its location", async () => { + const dom = created(); + const iframe = dom.document.createElement("iframe"); + iframe.setAttribute("src", "/post3.html"); + dom.document.body.append(iframe); + const frame = iframe.contentWindow as any; + const destinations: string[] = []; + dom.window.navigation.addEventListener("navigate", (event) => { + destinations.push(event.destination.url); + event.preventDefault(); + }); + frame.addEventListener("message", (event: MessageEvent) => { + if (event.source === frame.parent) { + frame.parent.window.location.href = event.data.slice(4); + } + }); + frame.postMessage("ddg:https://example.org/result", dom.window.origin); + await until(() => destinations.length > 0); + expect(destinations).toEqual(["https://example.org/result"]); + dom.dispose(); +}); + +test("a navigation of the parent no listener takes still fails", () => { + const dom = created(); + const frame = addFrame(dom).contentWindow as any; + expect( + errorName(() => { + frame.parent.location.href = "https://example.org/"; + }), + ).toBe("NotSupportedError"); + dom.dispose(); +}); + +test("a sandbox lets a frame navigate its top window only where it says so", () => { + const dom = created(); + const destinations: string[] = []; + dom.window.navigation.addEventListener("navigate", (event) => { + destinations.push(event.destination.url); + event.preventDefault(); + }); + const barred = inside(addFrame(dom, {sandbox: "allow-scripts"})); + expect( + errorName(() => { + barred.parent.location.href = "https://example.org/barred"; + }), + ).toBe("SecurityError"); + const allowed = inside(addFrame(dom, {sandbox: "allow-top-navigation"})); + allowed.parent.location.href = "https://example.org/href"; + allowed.parent.location = "https://example.org/location"; + allowed.top.location.replace("https://example.org/replace"); + expect(destinations).toEqual([ + "https://example.org/href", + "https://example.org/location", + "https://example.org/replace", + ]); + dom.dispose(); +}); + +const bun = (globalThis as {Bun?: unknown}).Bun === undefined + ? null + : process.execPath; + +// Where the runtime has no node:vm, as in isolated-vm, a frame's window +// is built in the engine's realm, and is a whole window still. +(bun === null ? test.skip : test)( + "without node:vm, a frame has a window that posts and navigates", + async () => { + const script = fileURLToPath( + new URL("./frames-without-vm.ts", import.meta.url), + ); + const output = await new Promise((resolve) => { + const child = spawn(bun!, [script], {stdio: ["ignore", "pipe", "pipe"]}); + let text = ""; + child.stdout.setEncoding("utf8"); + child.stdout.on("data", (chunk: string) => { + text += chunk; + }); + child.stderr.pipe(process.stderr); + child.on("close", () => resolve(text)); + }); + expect(JSON.parse(output)).toEqual({ + realms: false, + postMessage: "function", + parent: true, + top: true, + frameElement: true, + location: "about:blank", + origin: "https://duckduckgo.com", + sandboxedDocument: null, + heard: ["ddg:https://example.org/result", "https://duckduckgo.com", true], + navigated: "https://example.org/result", + }); + }, +); diff --git a/tests/frames-without-vm.ts b/tests/frames-without-vm.ts new file mode 100644 index 00000000..f5430259 --- /dev/null +++ b/tests/frames-without-vm.ts @@ -0,0 +1,63 @@ +/** + * Runs DuckDuckGo's result click, a message to a hidden frame that sends + * the page to the result, where the runtime has no node:vm, as in + * isolated-vm. Prints what the frame's window had and heard, as JSON. + * The engine looks for node:vm the first time a frame is made, so the + * runtime's has to be hidden before the engine loads. + * + * bun tests/frames-without-vm.ts + */ +const getBuiltinModule = process.getBuiltinModule.bind(process); +Object.defineProperty(process, "getBuiltinModule", { + value: (id: string) => + id === "node:vm" || id === "vm" ? undefined : getBuiltinModule(id), + configurable: true, +}); + +const {TermDOM} = await import("../src/index.ts"); +const {canCreateRealms} = await import("../src/internal/realms.ts"); +const {MockProcess, until} = await import("./test-utils.ts"); + +const dom = new TermDOM({ + transport: new MockProcess().transport, + url: "https://duckduckgo.com/?q=termdom", +}); +const iframe = dom.document.createElement("iframe"); +iframe.setAttribute("src", "/post3.html"); +iframe.style.display = "none"; +dom.document.body.append(iframe); +const frame = iframe.contentWindow as any; +const sandboxed = dom.document.createElement("iframe"); +sandboxed.setAttribute("sandbox", "allow-scripts"); +dom.document.body.append(sandboxed); + +let heard: unknown[] = []; +let navigated = ""; +dom.window.navigation.addEventListener("navigate", (event) => { + navigated = event.destination.url; + event.preventDefault(); +}); +frame.addEventListener("message", (event: MessageEvent) => { + heard = [event.data, event.origin, event.source === frame.parent]; + if (event.source === frame.parent) { + frame.parent.window.location.href = event.data.slice(4); + } +}); +frame.postMessage("ddg:https://example.org/result", dom.window.origin); +await until(() => navigated !== ""); + +process.stdout.write( + JSON.stringify({ + realms: canCreateRealms(), + postMessage: typeof frame.postMessage, + parent: frame.parent === dom.window, + top: frame.top === dom.window, + frameElement: frame.frameElement === iframe, + location: frame.location.href, + origin: frame.origin, + sandboxedDocument: sandboxed.contentDocument, + heard, + navigated, + }), +); +await dom.dispose(); diff --git a/tests/iframe-realms.test.ts b/tests/iframe-realms.test.ts index a8887600..d5b81b7a 100644 --- a/tests/iframe-realms.test.ts +++ b/tests/iframe-realms.test.ts @@ -12,6 +12,7 @@ import {expect, test} from "@b9g/libuild/test"; import {TermDOM} from "../src/index.ts"; +import {getDrawnFrameDocument} from "../src/internal/dom.ts"; import {canCreateRealms} from "../src/internal/realms.ts"; import {MockProcess, until} from "./test-utils.ts"; @@ -269,6 +270,33 @@ withRealms( }, ); +withRealms( + "a sandboxed frame's code holds its parent as a window of another origin", + async () => { + const dom = new TermDOM({ + transport: new MockProcess().transport, + url: "https://example.com/inbox", + }); + const iframe = dom.document.createElement("iframe"); + iframe.setAttribute("sandbox", "allow-scripts"); + dom.document.body.append(iframe); + const outer = iframe.contentWindow as any; + const frame = (getDrawnFrameDocument(iframe as any) as any).defaultView; + expect( + frame.eval("try { parent.document } catch (error) { error.name }"), + ).toBe("SecurityError"); + expect(frame.eval("parent === top && parent !== window")).toBe(true); + const heard: unknown[] = []; + dom.window.addEventListener("message", (event) => { + heard.push([event.data, event.origin, event.source === outer]); + }); + frame.eval("setTimeout(() => parent.postMessage('ping', '*'), 0)"); + await until(() => heard.length > 0); + expect(heard).toEqual([["ping", "null", true]]); + dom.dispose(); + }, +); + withRealms("a message for another origin does not land", async () => { const {dom, frame} = setup(); let heard = false; @@ -396,7 +424,7 @@ withRealms( frame.postMessage("from the parent", "*"); }); frame.eval("(async () => { await null; parent.document.body.click() })()"); - await new Promise((resolve) => setTimeout(resolve, 30)); + await until(() => heard.length > 0); expect(heard).toEqual(["top"]); dom.dispose(); }, diff --git a/tests/isolated-frames.test.ts b/tests/isolated-frames.test.ts new file mode 100644 index 00000000..1472ff37 --- /dev/null +++ b/tests/isolated-frames.test.ts @@ -0,0 +1,522 @@ +/** + * Frames whose document is in another isolate. + * + * Where frames are isolated, an iframe whose src is an http: or https: URL + * loads its document under the page's policy and fetch listeners and + * starts it through the isolator. The page draws the cells the frame + * sends, checked as untrusted, hands it keys and the mouse while it has + * them, and reaches it only through postMessage, as a window of another + * origin. The isolator here stands in for an isolate: it records what + * the page sends and plays what a frame would send. + */ +import {expect, test} from "@b9g/libuild/test"; + +import {TermDOM} from "../src/index.ts"; +import {toCellColor} from "../src/internal/cssvalues.ts"; +import {CellGrid, exportGrid} from "../src/internal/framebuffer.ts"; +import type { + FrameInit, + FrameIsolator, + FrameMessage, + HostMessage, +} from "../src/internal/isolateprotocol.ts"; +import {_} from "../src/internal/slots.ts"; +import { + captureRawOutput, + inputDispatched, + MockProcess, + nextFrame, + scriptReplies, + until, +} from "./test-utils.ts"; + +interface FakeFrame { + init: FrameInit; + sent: HostMessage[]; + post(message: FrameMessage): void; + disposed: boolean; +} + +function fakeIsolator(): { + frames: FakeFrame[]; + isolate: ( + init: FrameInit, + receive: (message: FrameMessage) => void, + ) => {send(message: HostMessage): void; dispose(): void}; +} { + const frames: FakeFrame[] = []; + return { + frames, + isolate: (init, receive) => { + const frame: FakeFrame = {init, sent: [], post: receive, disposed: false}; + frames.push(frame); + return { + send: (message) => { + frame.sent.push(message); + }, + dispose: () => { + frame.disposed = true; + }, + }; + }, + }; +} + +function useIsolator(dom: TermDOM, isolate: FrameIsolator): void { + (_(dom.document as never) as {extra: {isolateFrame: FrameIsolator}}) + .extra.isolateFrame = isolate; +} + +function paintText(lines: string[], cols: number): FrameMessage { + const grid = new CellGrid(lines.length, cols); + lines.forEach((line, row) => { + [...line].forEach((char, col) => grid.setCell(row * cols + col, char)); + }); + return {type: "paint", cells: exportGrid(grid), caret: null}; +} + +function rows(terminal: MockProcess, count: number): string[] { + const buffer = (terminal as any).terminal.buffer.active; + return Array.from( + {length: count}, + (_, row) => buffer.getLine(row).translateToString(true).trimEnd(), + ); +} + +async function settle(dom: TermDOM): Promise { + await nextFrame(dom); + await nextFrame(dom); +} + +function answerPages(dom: TermDOM, pages: Record): string[] { + const asked: string[] = []; + dom.addEventListener("fetch", (event: any) => { + asked.push(event.request.url); + const page = pages[event.request.url]; + if (page !== undefined) { + event.respondWith( + new Response(page, {headers: {"content-type": "text/html"}}), + ); + } + }); + return asked; +} + +const FRAME_STYLE = + "display: block; border: 1px solid; width: 14ch; height: 5px"; + +test("a frame's document loads through the page and starts in the isolator", async () => { + const {frames, isolate} = fakeIsolator(); + const terminal = new MockProcess({cols: 30, rows: 8}); + const dom = new TermDOM({ + transport: terminal.transport, + url: "https://page.example/", + }); + useIsolator(dom, isolate); + answerPages(dom, {"https://frame.example/a": "

framed

"}); + dom.document.body.innerHTML = + ``; + const frame = dom.document.querySelector("iframe")!; + let loads = 0; + frame.addEventListener("load", () => loads++); + await settle(dom); + await until(() => frames.length === 1); + expect(frames[0].init).toMatchObject({ + url: "https://frame.example/a", + html: "

framed

", + cols: 12, + rows: 3, + scripting: false, + }); + await new Promise((resolve) => setTimeout(resolve, 10)); + expect(loads).toBe(0); + frames[0].post({type: "load"}); + expect(loads).toBe(1); + dom.dispose(); +}); + +test("the cells a frame paints are drawn in its box, without control characters", async () => { + const {frames, isolate} = fakeIsolator(); + const terminal = new MockProcess({cols: 30, rows: 6}); + const dom = new TermDOM({transport: terminal.transport}); + useIsolator(dom, isolate); + answerPages(dom, {"https://frame.example/": ""}); + dom.document.body.innerHTML = + ``; + await settle(dom); + await until(() => frames.length === 1); + frames[0].post(paintText(["inside", "a\x1b[2Jb"], 12)); + await settle(dom); + expect(rows(terminal, 5)).toEqual([ + "┌────────────┐", + "│inside │", + "│a [2Jb │", + "│ │", + "└────────────┘", + ]); + dom.dispose(); +}); + +test("a frame's cells claim no columns their text does not take", async () => { + const {frames, isolate} = fakeIsolator(); + const terminal = new MockProcess({cols: 30, rows: 6}); + const dom = new TermDOM({transport: terminal.transport}); + useIsolator(dom, isolate); + answerPages(dom, {"https://frame.example/": ""}); + dom.document.body.innerHTML = + ``; + await settle(dom); + await until(() => frames.length === 1); + const message = paintText(["abc"], 12) as Extract< + FrameMessage, + {type: "paint"} + >; + message.cells.attrs[0] |= 0x1f << 9; + message.cells.cluster[1] = 0x110000; + message.cells.graphemes.push([0x8000_0001, "\x07"]); + message.cells.cluster[2] = 0x8000_0001; + frames[0].post(message); + await settle(dom); + expect(rows(terminal, 2)[1]).toBe("│a │"); + dom.dispose(); +}); + +test("a click focuses the frame, and its keys and mouse go there in its own cells", async () => { + const {frames, isolate} = fakeIsolator(); + const terminal = new MockProcess({cols: 30, rows: 8}); + const dom = new TermDOM({transport: terminal.transport}); + useIsolator(dom, isolate); + answerPages(dom, {"https://frame.example/": ""}); + dom.document.body.innerHTML = + ``; + await dom.attach(); + await settle(dom); + await until(() => frames.length === 1); + const frame = dom.document.querySelector("iframe")!; + let parentKeys = 0; + dom.document.addEventListener("keypress", () => parentKeys++); + // The frame's third column on its second row, inside the border. + terminal.stdin.simulateResponse("\x1b[<0;4;3M\x1b[<0;4;3m"); + await inputDispatched(); + await settle(dom); + expect(dom.document.activeElement).toBe(frame); + terminal.stdin.simulateResponse("x"); + await inputDispatched(); + const items = frames[0].sent + .filter((message) => message.type === "input") + .map((message) => message.item); + expect(items).toContainEqual({ + kind: "mouse", + button: 0, + col: 2, + row: 1, + release: false, + ticks: 1, + }); + expect(items).toContainEqual({kind: "focus", focused: true}); + expect(items).toContainEqual([ + expect.objectContaining({kind: "key", key: "x"}), + ]); + expect(parentKeys).toBe(0); + dom.dispose(); +}); + +test("the page and the frame reach each other only through messages", async () => { + const {frames, isolate} = fakeIsolator(); + const dom = new TermDOM({ + transport: new MockProcess({cols: 30, rows: 8}).transport, + url: "https://page.example/", + }); + useIsolator(dom, isolate); + answerPages(dom, {"https://frame.example/": ""}); + dom.document.body.innerHTML = + ``; + const frame = dom.document.querySelector("iframe")!; + await settle(dom); + await until(() => frames.length === 1); + expect(frame.contentDocument).toBe(null); + expect(() => (frame.contentWindow as any).document).toThrow(); + frame.contentWindow!.postMessage({hello: 1}, "https://frame.example"); + expect(frames[0].sent).toContainEqual({ + type: "message", + data: {hello: 1}, + origin: "https://page.example", + targetOrigin: "https://frame.example", + }); + const received: any[] = []; + dom.window.addEventListener("message", (event: MessageEvent) => { + received.push([ + event.data, + event.origin, + event.source === frame.contentWindow, + ]); + }); + frames[0].post({ + type: "message", + data: "elsewhere", + targetOrigin: "https://other.example", + }); + frames[0].post({type: "message", data: "back", targetOrigin: "*"}); + await until(() => received.length > 0); + await new Promise((resolve) => setTimeout(resolve, 10)); + expect(received).toEqual([["back", "https://frame.example", true]]); + dom.dispose(); +}); + +test("a frame's loads go through the page's fetch listeners, without forbidden headers", async () => { + const {frames, isolate} = fakeIsolator(); + const dom = new TermDOM({ + transport: new MockProcess({cols: 30, rows: 8}).transport, + }); + useIsolator(dom, isolate); + const headers: Array<[string, string]> = []; + dom.addEventListener("fetch", (event: any) => { + if (event.request.url === "https://frame.example/") { + event.respondWith(new Response("")); + } else if (event.request.url === "https://frame.example/data.json") { + event.request.headers.forEach((value: string, name: string) => { + headers.push([name, value]); + }); + event.respondWith(new Response("{}", {status: 201})); + } + }); + dom.document.body.innerHTML = + ``; + await settle(dom); + await until(() => frames.length === 1); + frames[0].post({ + type: "fetch", + id: 1, + request: { + url: "https://frame.example/data.json", + method: "GET", + headers: [["x-asked", "yes"], ["cookie", "stolen=1"]], + body: null, + redirect: "follow", + destination: "", + referrer: "", + }, + }); + frames[0].post({ + type: "fetch", + id: 2, + request: { + url: "file:///etc/passwd", + method: "GET", + headers: [], + body: null, + redirect: "follow", + destination: "", + referrer: "", + }, + }); + await until(() => frames[0].sent.length >= 2); + expect(headers).toEqual([["x-asked", "yes"]]); + const response = frames[0].sent.find( + (message) => message.type === "response", + ); + expect(response).toMatchObject({type: "response", id: 1}); + expect(new TextDecoder().decode((response as any).response.body)).toBe("{}"); + expect((response as any).response.status).toBe(201); + expect(frames[0].sent).toContainEqual({ + type: "fetchError", + id: 2, + message: "Failed to fetch", + }); + dom.dispose(); +}); + +test("a frame-src policy keeps a frame's document from loading", async () => { + const {frames, isolate} = fakeIsolator(); + const dom = new TermDOM({ + transport: new MockProcess({cols: 30, rows: 8}).transport, + csp: "frame-src https://allowed.example", + }); + useIsolator(dom, isolate); + const asked = answerPages(dom, { + "https://allowed.example/": "

allowed

", + "https://blocked.example/": "

blocked

", + }); + dom.document.body.innerHTML = + ``; + await settle(dom); + await until(() => frames.length === 2); + expect(asked).toEqual(["https://allowed.example/"]); + expect( + frames + .map((frame) => [frame.init.url, frame.init.html.includes("

")]) + .sort(), + ).toEqual([ + ["https://allowed.example/", true], + ["https://blocked.example/", false], + ]); + dom.dispose(); +}); + +test("a srcdoc frame stays in the page's heap, and a removed frame's isolate goes", async () => { + const {frames, isolate} = fakeIsolator(); + const dom = new TermDOM({ + transport: new MockProcess({cols: 30, rows: 8}).transport, + }); + useIsolator(dom, isolate); + answerPages(dom, {"https://frame.example/": ""}); + dom.document.body.innerHTML = + ``; + await settle(dom); + await until(() => frames.length === 1); + const [local, isolated] = dom.document.querySelectorAll("iframe"); + expect(local.contentDocument!.getElementById("here")).not.toBe(null); + isolated.remove(); + expect(frames[0].disposed).toBe(true); + dom.dispose(); +}); + +// A frame's red image, 2 by 1 cells, of 16 by 16 pixels, and the cells +// that show it under id 7 at the frame's top left. +function postRedImage(frame: FakeFrame, cols: number): void { + const pixels = new Uint8ClampedArray(16 * 16 * 4); + for (let index = 0; index < pixels.length; index += 4) { + pixels.set([255, 0, 0, 255], index); + } + frame.post({ + type: "images", + added: [{id: 7, width: 16, height: 16, cols: 2, rows: 1, pixels}], + dropped: [], + }); + const grid = new CellGrid(1, cols); + grid.setPlaceholder(0, 0, 0, {fg: toCellColor(7)}); + grid.setPlaceholder(1, 0, 1, {fg: toCellColor(7)}); + grid.setPlaceholder(2, 0, 0, {fg: toCellColor(8)}); + frame.post({type: "paint", cells: exportGrid(grid), caret: null}); +} + +test("a frame's images are drawn in half blocks where the terminal has no graphics", async () => { + const {frames, isolate} = fakeIsolator(); + const terminal = new MockProcess({cols: 30, rows: 6}); + const dom = new TermDOM({ + transport: terminal.transport, + colorDepth: "rgb", + images: "cells", + }); + useIsolator(dom, isolate); + answerPages(dom, {"https://frame.example/": ""}); + dom.document.body.innerHTML = + ``; + await settle(dom); + await until(() => frames.length === 1); + expect(frames[0].init.images).toBe("kitty"); + postRedImage(frames[0], 12); + await settle(dom); + const buffer = (terminal as any).terminal.buffer.active; + const line = buffer.getLine(1); + const backgrounds = [1, 2, 3].map((col) => { + const cell = line.getCell(col); + return cell.isBgRGB() ? cell.getBgColor() : null; + }); + expect(backgrounds).toEqual([0xff0000, 0xff0000, null]); + dom.dispose(); +}); + +test("a frame's images are sent in the kitty protocol where the terminal draws it", async () => { + const {frames, isolate} = fakeIsolator(); + const terminal = new MockProcess({cols: 30, rows: 6}); + scriptReplies(terminal, [{ask: "\x1b[16t", reply: "\x1b[6;16;8t"}]); + const output = captureRawOutput(terminal); + const dom = new TermDOM({ + transport: terminal.transport, + colorDepth: "rgb", + images: "kitty", + }); + useIsolator(dom, isolate); + answerPages(dom, {"https://frame.example/": ""}); + dom.document.body.innerHTML = + ``; + await settle(dom); + await until(() => frames.length === 1); + postRedImage(frames[0], 12); + await settle(dom); + const uploads = output().match(/\x1b_G[^;\x1b]*/g) ?? []; + expect(uploads.length).toBe(1); + expect(uploads[0]).toContain("c=2,r=1"); + dom.dispose(); +}); + +test("a frame goes to the document its own navigation names", async () => { + const {frames, isolate} = fakeIsolator(); + const terminal = new MockProcess({cols: 30, rows: 8}); + const dom = new TermDOM({transport: terminal.transport}); + useIsolator(dom, isolate); + const asked = answerPages(dom, { + "https://frame.example/": "", + "https://frame.example/b/next": "

next

", + }); + dom.document.body.innerHTML = + ``; + await settle(dom); + await until(() => frames.length === 1); + frames[0].post({type: "navigate", target: "self", url: "file:///etc/passwd"}); + frames[0].post({ + type: "history", + url: "https://bank.example/", + replace: false, + }); + frames[0].post({type: "history", url: "/b/here", replace: false}); + await new Promise((resolve) => setTimeout(resolve, 10)); + expect(frames[0].disposed).toBe(false); + frames[0].post({type: "navigate", target: "self", url: "next"}); + await until(() => frames.length === 2); + expect(frames[0].disposed).toBe(true); + expect(frames[1].init.html).toBe("

next

"); + expect(asked).toEqual([ + "https://frame.example/", + "https://frame.example/b/next", + ]); + dom.dispose(); +}); + +test("a form a frame posts loads its next document with a POST", async () => { + const {frames, isolate} = fakeIsolator(); + const terminal = new MockProcess({cols: 30, rows: 8}); + const dom = new TermDOM({transport: terminal.transport}); + useIsolator(dom, isolate); + const posted: Array<{method: string; type: string | null; body: string}> = []; + dom.addEventListener("fetch", (event: any) => { + const request: Request = event.request; + if (request.method === "POST") { + event.respondWith( + request.text().then((body) => { + posted.push({ + method: request.method, + type: request.headers.get("content-type"), + body, + }); + return new Response("

thanks

"); + }), + ); + } else { + event.respondWith(new Response("")); + } + }); + dom.document.body.innerHTML = + ``; + await settle(dom); + await until(() => frames.length === 1); + frames[0].post({ + type: "navigate", + target: "self", + url: "https://frame.example/send", + method: "post", + body: new TextEncoder().encode("q=tea"), + contentType: "application/x-www-form-urlencoded\r\nx-evil: 1", + }); + await until(() => frames.length === 2); + expect(posted).toEqual([ + { + method: "POST", + type: "application/x-www-form-urlencodedx-evil: 1", + body: "q=tea", + }, + ]); + expect(frames[1].init.html).toBe("

thanks

"); + dom.dispose(); +}); diff --git a/tests/isolated-vm-frames.test.ts b/tests/isolated-vm-frames.test.ts new file mode 100644 index 00000000..3a0253b6 --- /dev/null +++ b/tests/isolated-vm-frames.test.ts @@ -0,0 +1,243 @@ +/** + * Frames in isolated-vm's isolates, end to end: the page loads the + * frame's document, the frame lays it out, runs its scripts and paints it + * in an isolate of its own, and the page draws it, hands it keys and + * trades messages with it. A frame that runs forever is stopped alone. + * isolated-vm loads on Node only, from Node 24. + */ +import {expect, test} from "@b9g/libuild/test"; + +import {TermDOM} from "../src/index.ts"; +import {encodePNG} from "../src/internal/imagecodecs.ts"; +import {createIsolatedVMFrames} from "../src/internal/isolatedvm.ts"; +import type {FrameIsolator} from "../src/internal/isolateprotocol.ts"; +import {_} from "../src/internal/slots.ts"; +import { + captureRawOutput, + inputDispatched, + MockProcess, + nextFrame, + scriptReplies, + until, +} from "./test-utils.ts"; + +const onNode = + (globalThis as {Bun?: unknown}).Bun === undefined && + (globalThis as {Deno?: unknown}).Deno === undefined; +// isolated-vm 7 asks for Node 24, and neither loads nor builds under 20. +const loads = onNode && Number(process.versions.node.split(".")[0]) >= 24; +const nodeTest = loads ? test : test.skip; + +function rows(terminal: MockProcess, count: number): string[] { + const buffer = (terminal as any).terminal.buffer.active; + return Array.from( + {length: count}, + (_, row) => buffer.getLine(row).translateToString(true).trimEnd(), + ); +} + +function servePages(dom: TermDOM, pages: Record): void { + dom.addEventListener("fetch", (event: any) => { + const page = pages[event.request.url]; + if (page !== undefined) { + event.respondWith( + new Response(page, {headers: {"content-type": "text/html"}}), + ); + } + }); +} + +async function drawn( + dom: TermDOM, + terminal: MockProcess, + text: string, +): Promise { + const deadline = Date.now() + 20000; + while (Date.now() < deadline) { + await nextFrame(dom); + if (rows(terminal, 12).some((row) => row.includes(text))) { + break; + } + await new Promise((resolve) => setTimeout(resolve, 20)); + } + return rows(terminal, 12); +} + +const FRAME = "display: block; border: 1px solid; width: 30ch; height: 5px"; + +nodeTest( + "a frame's document is laid out and painted in its own isolate", + async () => { + const terminal = new MockProcess({cols: 40, rows: 12}); + const dom = new TermDOM({transport: terminal.transport, colorDepth: "rgb"}); + servePages(dom, { + "https://frame.example/": "

from the isolate

", + }); + dom.document.body.innerHTML = + `

page

`; + const screen = await drawn(dom, terminal, "from the isolate"); + expect(screen.slice(0, 3)).toEqual([ + "page", + "┌────────────────────────────┐", + "│from the isolate │", + ]); + await dom.dispose(); + }, + 60000, +); + +nodeTest( + "a frame's scripts run there, and it trades messages with the page", + async () => { + const terminal = new MockProcess({cols: 40, rows: 12}); + const dom = new TermDOM({ + transport: terminal.transport, + url: "https://page.example/", + scripting: "enabled", + }); + servePages(dom, { + "https://frame.example/": + "

waiting

", + }); + const received: string[] = []; + dom.window.addEventListener("message", (event: MessageEvent) => { + received.push(event.data); + }); + dom.document.body.innerHTML = + ``; + const frame = dom.document.querySelector("iframe")!; + await dom.attach(); + await until(() => received.includes("ready")); + expect(received).toEqual(["ready"]); + frame.contentWindow!.postMessage("ping", "https://frame.example"); + await until(() => received.includes("got ping")); + const screen = await drawn(dom, terminal, "ping from"); + expect(screen.slice(1, 3)).toEqual([ + "│ping from https:// │", + "│page.example │", + ]); + await dom.dispose(); + }, + 60000, +); + +nodeTest( + "keys typed into a focused frame reach its field", + async () => { + const terminal = new MockProcess({cols: 40, rows: 12}); + const dom = new TermDOM({transport: terminal.transport}); + servePages(dom, { + "https://frame.example/": + "", + }); + dom.document.body.innerHTML = + ``; + await dom.attach(); + await drawn(dom, terminal, "┌"); + dom.document.querySelector("iframe")!.focus(); + await nextFrame(dom); + terminal.stdin.simulateResponse("typed"); + await inputDispatched(); + const screen = await drawn(dom, terminal, "typed"); + expect(screen[1]).toMatch(/^│typed/); + await dom.dispose(); + }, + 60000, +); + +nodeTest( + "a frame that runs forever is stopped, and the page goes on", + async () => { + const terminal = new MockProcess({cols: 40, rows: 12}); + const dom = new TermDOM({ + transport: terminal.transport, + scripting: "enabled", + }); + // Long enough for the calm frame to start on a busy machine: the + // limit is on the clock, and holds a frame's first paint too. + (_(dom.document as never) as {extra: {isolateFrame: FrameIsolator}}) + .extra.isolateFrame = await createIsolatedVMFrames({taskTimeout: 2000}); + servePages(dom, { + "https://spin.example/": "

spin

", + "https://calm.example/": "

calm

", + }); + dom.document.body.innerHTML = + `` + + ``; + const screen = await drawn(dom, terminal, "calm"); + expect(screen).toContain("│calm │"); + dom.document.body.append("after"); + const later = await drawn(dom, terminal, "after"); + expect(later.some((row) => row.includes("after"))).toBe(true); + await dom.dispose(); + }, + 60000, +); + +nodeTest( + "an image in a frame goes to the terminal in the kitty protocol", + async () => { + const terminal = new MockProcess({cols: 40, rows: 12}); + scriptReplies(terminal, [{ask: "\x1b[16t", reply: "\x1b[6;16;8t"}]); + const output = captureRawOutput(terminal); + const dom = new TermDOM({ + transport: terminal.transport, + colorDepth: "rgb", + images: "kitty", + cellSize: {width: 8, height: 16}, + }); + const data = new Uint8ClampedArray(16 * 32 * 4).fill(255); + let binary = ""; + for (const byte of encodePNG({width: 16, height: 32, data})) { + binary += String.fromCharCode(byte); + } + servePages(dom, { + "https://frame.example/": + "" + + ``, + }); + dom.document.body.innerHTML = + ""; + await dom.attach(); + const deadline = Date.now() + 20000; + while (!/\x1b_G[^;]*c=2,r=2/.test(output()) && Date.now() < deadline) { + await nextFrame(dom); + await new Promise((resolve) => setTimeout(resolve, 20)); + } + expect(output()).toMatch(/\x1b_G[^;]*c=2,r=2/); + await dom.dispose(); + }, + 60000, +); + +nodeTest( + "a link clicked in a frame loads its next page there", + async () => { + const terminal = new MockProcess({cols: 40, rows: 12}); + const dom = new TermDOM({ + transport: terminal.transport, + scripting: "enabled", + }); + servePages(dom, { + "https://frame.example/": + "go", + "https://frame.example/next": "

next page

", + }); + dom.document.body.innerHTML = + ``; + await dom.attach(); + const screen = await drawn(dom, terminal, "next page"); + expect(screen[1]).toMatch(/^│next page/); + await dom.dispose(); + }, + 60000, +);