Skip to content

The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu

Check lens markup the way the real parser reads it

Claudeca849429a4d2
diff --git a/CLAUDE.md b/CLAUDE.md
index 5f817bdc..195489b5 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -15,7 +15,7 @@ Beacon Endpoint Agent is a local-only endpoint telemetry agent for AI runtimes.
- `plugins`: TypeScript sources for the managed runtime plugins/extensions (`opencode-beacon`, `cline-beacon`, `pi-beacon`, `omp-beacon`, `openclaw-beacon`, `prime-beacon`, `omo-beacon`), each mirrored into an embedded copy under `cli/beacon/internal/endpoint/hooks/assets/`.
- `agent-skills`: publishable Agent Skills plugin for the traces-to-memory workflow (`beacon-memory-recall`, `beacon-memory-distill`, `beacon-memory-promote`) for authoring dashboard lenses (`beacon-lens-create`), and for sharing the current session to beacon.sh (`beacon-trace-share`, which runs `beacon share --current --harness <runtime> --json`, keeps the default direct visibility and asks before public) with manifests for Claude Code, Agent Plugins (Codex, Copilot, VS Code, Kiro, Devin), Cursor, Kimi Code, and Gemini CLI. At the repo root, `.claude-plugin/marketplace.json` is read by most harnesses, `.cursor-plugin/marketplace.json` by Cursor, and `package.json` (`pi.skills` only) makes the repo a Pi/Prime Agent package; keep that root `package.json` free of dependencies and scripts. `cli/beacon/cmd/agent_skills_test.go` checks every `beacon` command and flag the skills name against the real command tree, so rename a command and update the skills together. The binary carries a copy of `agent-skills/skills` in `cli/beacon/internal/agentskills/skills` for onboarding and `beacon skills install`; a test keeps it identical, so copy it across whenever a skill changes.
- `rules` and `spec/threat-rules`: the open rule corpus and the Threat Rules format it conforms to. Every rule's `taxonomy.beacon_category` is its directory name, and the six embedded baseline rules in `pkg/asymptoteobserve/rulestore/baseline` are byte-identical copies of their corpus rules; conformance tests enforce both.
-- `spec/lenses`: the Lenses format — single-file HTML views of one trace that the local dashboard runs in a sandboxed, network-less frame and feeds once through `window.beacon.getTrace()`. The contract types (`LensManifestV1`, `LensDataV1`) live in `pkg/asymptoteobserve/lens.go`, and `lens_test.go` pins the spec's examples and manifest schema to them. The dashboard builds the data in `BuildLensData` (`/api/lens-data`), lists lenses at `/api/lenses`, and serves each lens at `/lenses/frame/<id>` under the spec's CSP with `lenses/prelude.js` (which defines `window.beacon`) injected ahead of it; that route is the only one that may be framed. Built-in lenses are `cli/beacon/internal/endpoint/dashboard/lenses/*.lens.html`, and `activity` is byte-identical to the spec example (a test enforces it). The session page (`static/session.html`, `initLensTabs` in `app.js`) shows lenses as tabs fed by `/api/lens-data?session=`, which projects exactly the events that page lists; it is the host half of the protocol and closes a lens that errors, stalls, or navigates its own frame. Trust model (SPEC "Trust model"): the opaque origin, sandbox and CSP keep a lens from touching Beacon or the dashboard and block ordinary network APIs, but cannot fully prevent a lens from sending trace data out through browser features no CSP governs (WebRTC, resource hints, speculative loading), so an installed lens is code the person trusts with the trace data it is shown; never describe the sandbox as making exfiltration impossible. `prelude.js` removes the `RTC*` globals and guards the document (refuses creating, inserting or parsing in nested frames, `<link>` elements and `<script type=speculationrules>`, refuses `document.write`, and a mutation observer removes those from the file's own markup); that is best-effort hardening, not a boundary, and the hostile `probe` fixture in `testdata/lens-e2e` pins each covered path. Installed lenses live in the lens store (`cli/beacon/internal/endpoint/lensstore`, `<BaseDir>/lenses/<id>.lens.html`, 0600 under 0700), written only by `beacon lenses add|remove` (`cli/beacon/cmd/lenses.go`; `add` prints the trust warning and confirms on a TTY, and refuses without one or in CI unless `--yes`); the dashboard rescans it per request and never writes it, and a store lens can never shadow a built-in. `asymptoteobserve.CheckLensFile` is the one file check every installer, server and linter uses. User docs are `docs/concepts/lenses.mdx` and `docs/cli/lenses.mdx`; keep them in sync with the commands and built-in lenses. The authoring loop is `beacon lenses spec` (the spec carried in the binary as `dashboard/lenses/SPEC.md`, kept byte-identical to `spec/lenses/SPEC.md` by a test), `beacon lenses data` (the exact `LensDataV1` for a session), `beacon lenses lint` (`lensstore.Lint`; built-ins must lint clean) and `beacon lenses preview` (the dashboard with `Options.LensFiles`, re-read per reload).
+- `spec/lenses`: the Lenses format — single-file HTML views of one trace that the local dashboard runs in a sandboxed, network-less frame and feeds once through `window.beacon.getTrace()`. The contract types (`LensManifestV1`, `LensDataV1`) live in `pkg/asymptoteobserve/lens.go`, and `lens_test.go` pins the spec's examples and manifest schema to them. The dashboard builds the data in `BuildLensData` (`/api/lens-data`), lists lenses at `/api/lenses`, and serves each lens at `/lenses/frame/<id>` under the spec's CSP with `lenses/prelude.js` (which defines `window.beacon`) injected ahead of it; that route is the only one that may be framed. Built-in lenses are `cli/beacon/internal/endpoint/dashboard/lenses/*.lens.html`, and `activity` is byte-identical to the spec example (a test enforces it). The session page (`static/session.html`, `initLensTabs` in `app.js`) shows lenses as tabs fed by `/api/lens-data?session=`, which projects exactly the events that page lists; it is the host half of the protocol and closes a lens that errors, stalls, or navigates its own frame. Trust model (SPEC "Trust model"): the opaque origin, sandbox and CSP keep a lens from touching Beacon or the dashboard and block ordinary network APIs, but cannot fully prevent a lens from sending trace data out through browser features no CSP governs (WebRTC, resource hints, speculative loading), so an installed lens is code the person trusts with the trace data it is shown; never describe the sandbox as making exfiltration impossible. `prelude.js` removes the `RTC*` globals and guards the document (refuses creating, inserting or parsing in nested frames, `<link>` elements and `<script type=speculationrules>`, parsing markup in the real call's document and context and inserting exactly the checked nodes so `<noscript>`/foreign-content parser differentials cannot slip through, refuses `document.write` and `execCommand("insertHTML")`, and a mutation observer removes those from the file's own markup); that is best-effort hardening, not a boundary, and the hostile `probe` fixture in `testdata/lens-e2e` pins each covered path. Installed lenses live in the lens store (`cli/beacon/internal/endpoint/lensstore`, `<BaseDir>/lenses/<id>.lens.html`, 0600 under 0700), written only by `beacon lenses add|remove` (`cli/beacon/cmd/lenses.go`; `add` prints the trust warning and confirms on a TTY, and refuses without one or in CI unless `--yes`); the dashboard rescans it per request and never writes it, and a store lens can never shadow a built-in. `asymptoteobserve.CheckLensFile` is the one file check every installer, server and linter uses. User docs are `docs/concepts/lenses.mdx` and `docs/cli/lenses.mdx`; keep them in sync with the commands and built-in lenses. The authoring loop is `beacon lenses spec` (the spec carried in the binary as `dashboard/lenses/SPEC.md`, kept byte-identical to `spec/lenses/SPEC.md` by a test), `beacon lenses data` (the exact `LensDataV1` for a session), `beacon lenses lint` (`lensstore.Lint`; built-ins must lint clean) and `beacon lenses preview` (the dashboard with `Options.LensFiles`, re-read per reload).
- `beacon-sandbox`: harness that runs a real Claude Code session in a disposable sandbox and checks what Beacon captured. See `beacon-sandbox/AGENTS.md`.
- `packaging`: macOS, Linux, and Windows packaging and deployment assets.
- `docs`: the published documentation site (docs.asymptotelabs.ai).
diff --git a/cli/beacon/internal/endpoint/dashboard/lenses/SPEC.md b/cli/beacon/internal/endpoint/dashboard/lenses/SPEC.md
index 0c4be5ab..c7cf70aa 100644
--- a/cli/beacon/internal/endpoint/dashboard/lenses/SPEC.md
+++ b/cli/beacon/internal/endpoint/dashboard/lenses/SPEC.md
@@ -194,10 +194,12 @@ The host enforces these rules; a lens does not opt into them.
`preconnect`, `prefetch` and `preload` are links), and
`<script type="speculationrules">`. Creating one, inserting one, or parsing
one in through `innerHTML`, `outerHTML`, `insertAdjacentHTML`,
- `setHTMLUnsafe` or `execCommand` throws a `NotSupportedError`
- `DOMException`; `document.write` and `document.writeln` always throw; and
- any the parser puts in from the lens file's own markup is removed before
- the next script runs.
+ `setHTMLUnsafe` or `Document.parseHTMLUnsafe` throws a `NotSupportedError`
+ `DOMException`. The host parses such markup in the same document and
+ context as the real call, so it checks what the browser would build;
+ `document.write`, `document.writeln` and `execCommand("insertHTML")`
+ always throw; and any the parser puts in from the lens file's own markup
+ is removed before the next script runs.
- The frame is served with `X-DNS-Prefetch-Control: off`, and the host
repeats it as a `<meta http-equiv>` in the document, so the browser does not
resolve hostnames the lens mentions on its own.
diff --git a/cli/beacon/internal/endpoint/dashboard/lenses/prelude.js b/cli/beacon/internal/endpoint/dashboard/lenses/prelude.js
index 463e4dee..123593f0 100644
--- a/cli/beacon/internal/endpoint/dashboard/lenses/prelude.js
+++ b/cli/beacon/internal/endpoint/dashboard/lenses/prelude.js
@@ -39,8 +39,10 @@
// object, embed, portal, fencedframe: a fresh realm with WebRTC intact), a <link> (a lens loads
// nothing by URL, and rel=preconnect/prefetch/prerender/dns-prefetch/preload can start a request
// the CSP does not see), or a <script type=speculationrules>. Creating, inserting or parsing one
- // in through the DOM APIs throws; document.write is refused outright; a mutation observer removes
- // any that the parser puts in from the lens file's own markup. Not covered: what the browser's
+ // in through the DOM APIs throws (markup is parsed in the real call's document and context, so
+ // the check sees what the browser builds); document.write and execCommand("insertHTML") are
+ // refused outright; a mutation observer removes any that the parser puts in from the lens file's
+ // own markup. Not covered: what the browser's
// preload scanner does with the file's own markup before any script runs, closed declarative
// shadow roots, and attribute changes made through Attr nodes. `beacon lenses lint` warns on these
// elements and on declarative shadow roots in source. Everything the guard calls is captured
@@ -70,6 +72,19 @@
var shadowRoot = getter(Element.prototype, "shadowRoot");
var listLength = getter(NodeList.prototype, "length");
var addedNodes = getter(MutationRecord.prototype, "addedNodes");
+ var ownerDocument = getter(Node.prototype, "ownerDocument");
+ var parentNode = getter(Node.prototype, "parentNode");
+ var childNodes = getter(Node.prototype, "childNodes");
+ var shadowHost = getter(ShadowRoot.prototype, "host");
+ var createElementNS = method(Document.prototype, "createElementNS");
+ var setInnerHTML = Object.getOwnPropertyDescriptor(Element.prototype, "innerHTML").set;
+ var indexOf = method(String.prototype, "indexOf");
+ // The native insertions, kept before they are wrapped below.
+ var insert = Object.create(null);
+ ["replaceChildren", "replaceWith", "before", "after", "prepend", "append"].forEach(function (name) {
+ insert[name] = method(Element.prototype, name);
+ });
+ insert.fragmentReplaceChildren = method(DocumentFragment.prototype, "replaceChildren");
var getAttribute = method(Element.prototype, "getAttribute");
var removeElement = method(Element.prototype, "remove");
var trim = method(String.prototype, "trim");
@@ -122,7 +137,46 @@
function checkNode(node) {
eachRefused(node, function (el) { refuse("add a <" + localName(el) + "> element"); });
}
- function checkMarkup(markup) {
+ // Parses markup as the browser does for the fragment parsing behind innerHTML and its kin: in the
+ // same document (so with the same scripting flag, which decides whether <noscript> is raw text)
+ // and with a context element of the same name and namespace (which decides how <svg>, <math>,
+ // tables and raw-text elements read it). The scratch context is detached, so nothing parsed into
+ // it loads. Returns the parsed nodes once none of them, template contents included, is refused;
+ // the caller inserts exactly these nodes, so the browser never parses the markup a second time.
+ function parseInContext(context, markup) {
+ var ns = namespaceURI(context);
+ var name = localName(context);
+ // An autonomous custom element parses like any unknown element; do not run its constructor.
+ if (ns === HTML_NS && indexOf(name, ["-"]) >= 0) name = "div";
+ var scratch = createElementNS(ownerDocument(context), [ns, name]);
+ apply(setInnerHTML, scratch, [markup]);
+ var root = ns === HTML_NS && name === "template" ? templateContent(scratch) : scratch;
+ var list = childNodes(root);
+ var nodes = Object.create(null);
+ nodes.length = listLength(list);
+ for (var i = 0; i < nodes.length; i++) nodes[i] = list[i];
+ for (var j = 0; j < nodes.length; j++) checkNode(nodes[j]);
+ return nodes;
+ }
+ // The context the browser uses for markup inserted beside or into node: a shadow root parses in
+ // its host's context, and a fragment or an <html> element in a new <body>'s.
+ function contextFor(node) {
+ var type = nodeType(node);
+ if (type === 11 && isShadowRoot(node)) return shadowHost(node);
+ if (type === 1 && !(namespaceURI(node) === HTML_NS && localName(node) === "html")) return node;
+ return createElementNS(ownerDocument(node), [HTML_NS, "body"]);
+ }
+ function isShadowRoot(node) {
+ try {
+ shadowHost(node);
+ return true;
+ } catch (e) {
+ return false;
+ }
+ }
+ // A whole document parsed with no browsing context (Document.parseHTMLUnsafe) parses like a
+ // DOMParser document: scripting off, no context element.
+ function checkDocumentMarkup(markup) {
checkNode(parseHTML(parser, [markup, "text/html"]));
}
@@ -134,16 +188,18 @@
return apply(original, this, arguments);
};
}
- function wrapSetter(proto, name, check, convert) {
+ // handle(target, value, set) replaces the setter; set(target, value) is the native one.
+ function wrapSetter(proto, name, handle, convert) {
var desc = proto && Object.getOwnPropertyDescriptor(proto, name);
if (!desc || !desc.set) return;
- var set = desc.set;
+ var native = desc.set;
+ function set(target, value) {
+ apply(native, target, [value]);
+ }
Object.defineProperty(proto, name, {
get: desc.get,
set: function (value) {
- var converted = (convert || text)(value);
- check(this, converted);
- apply(set, this, [converted]);
+ handle(this, (convert || text)(value), set);
},
enumerable: desc.enumerable,
configurable: true
@@ -174,26 +230,70 @@
wrapMethod(Range.prototype, "insertNode", checkNodeArgs);
wrapMethod(Range.prototype, "surroundContents", checkNodeArgs);
- // HTML parsing into the live document. Markup is parsed once into an inert document and refused
- // if it holds a refused element; the converted string is what then reaches the real parser.
+ // HTML parsing into a document. innerHTML, outerHTML and insertAdjacentHTML parse the markup once,
+ // in the real context, check the result and insert exactly those nodes (parseInContext).
+ function setInner(target, markup) {
+ var nodes = parseInContext(contextFor(target), markup);
+ if (nodeType(target) === 11) {
+ insert.fragmentReplaceChildren(target, nodes);
+ } else if (namespaceURI(target) === HTML_NS && localName(target) === "template") {
+ insert.fragmentReplaceChildren(templateContent(target), nodes);
+ } else {
+ insert.replaceChildren(target, nodes);
+ }
+ }
+ wrapSetter(Element.prototype, "innerHTML", setInner, nullToEmpty);
+ wrapSetter(ShadowRoot.prototype, "innerHTML", setInner, nullToEmpty);
+ wrapSetter(Element.prototype, "outerHTML", function (target, markup, set) {
+ var parent = parentNode(target);
+ // No parent: the native setter does nothing. A document parent: it throws before parsing.
+ if (parent === null || nodeType(parent) === 9) return set(target, markup);
+ insert.replaceWith(target, parseInContext(contextFor(parent), markup));
+ }, nullToEmpty);
+ var insertAdjacentHTML = Element.prototype.insertAdjacentHTML;
+ Element.prototype.insertAdjacentHTML = function (position, markup) {
+ var where = lower(text(position), []);
+ var outside = where === "beforebegin" || where === "afterend";
+ var parent = outside ? parentNode(this) : this;
+ if ((!outside && where !== "afterbegin" && where !== "beforeend") || parent === null || nodeType(parent) === 9) {
+ return apply(insertAdjacentHTML, this, arguments); // the native call throws (or does nothing)
+ }
+ var nodes = parseInContext(contextFor(parent), text(markup));
+ var into = { beforebegin: insert.before, afterbegin: insert.prepend, beforeend: insert.append, afterend: insert.after };
+ into[where](this, nodes);
+ };
+ // setHTMLUnsafe and setHTML also build declarative shadow roots, which parseInContext's nodes
+ // cannot carry, so they are checked in the real context (a closed root's content is checked as
+ // the template it is written in) and then handed to the native parser with the same string. As
+ // a second line, anything refused that the native parse still produced, where a scan can see it,
+ // is removed before the call returns.
[Element, ShadowRoot].forEach(function (type) {
- wrapSetter(type.prototype, "innerHTML", function (target, markup) { checkMarkup(markup); }, nullToEmpty);
["setHTMLUnsafe", "setHTML"].forEach(function (name) {
- wrapMethod(type.prototype, name, function (target, args) {
- args[0] = text(args[0]);
- checkMarkup(args[0]);
- });
+ var native = type.prototype[name];
+ if (typeof native !== "function") return;
+ type.prototype[name] = function (markup) {
+ var args = arguments;
+ args[0] = text(markup);
+ parseInContext(contextFor(this), args[0]);
+ var result = apply(native, this, args);
+ var removed = false;
+ eachRefused(this, function (el) { removeElement(el, []); removed = true; });
+ if (removed) refuse("add a nested frame, a <link> or speculation rules");
+ return result;
+ };
});
});
- wrapSetter(Element.prototype, "outerHTML", function (target, markup) { checkMarkup(markup); }, nullToEmpty);
- wrapMethod(Element.prototype, "insertAdjacentHTML", function (target, args) {
- args[1] = text(args[1]);
- checkMarkup(args[1]);
- });
+ if (typeof Document.parseHTMLUnsafe === "function") {
+ var parseHTMLUnsafe = Document.parseHTMLUnsafe;
+ Document.parseHTMLUnsafe = function (markup) {
+ var converted = text(markup);
+ checkDocumentMarkup(converted);
+ return apply(parseHTMLUnsafe, this, [converted]);
+ };
+ }
+ // insertHTML parses in whatever context the selection is in; a lens has no use for it.
wrapMethod(Document.prototype, "execCommand", function (doc, args) {
- if (args.length < 3 || lower(text(args[0]), []) !== "inserthtml") return;
- args[2] = text(args[2]);
- checkMarkup(args[2]);
+ if (lower(text(args[0]), []) === "inserthtml") refuse("use execCommand(\"insertHTML\")");
});
// document.write can split one element across calls, so no single call can be checked.
["write", "writeln"].forEach(function (name) {
@@ -206,8 +306,9 @@
.forEach(function (entry) {
wrapSetter(entry[0].prototype, entry[1], function () { refuse("load a nested frame"); });
});
- wrapSetter(HTMLScriptElement.prototype, "type", function (el, type) {
+ wrapSetter(HTMLScriptElement.prototype, "type", function (el, type, set) {
if (isSpeculationRules(type)) refuse("add speculation rules");
+ set(el, type);
});
function checkScriptType(el, name, value) {
if (lower(text(name), []) === "type" && namespaceURI(el) === HTML_NS && localName(el) === "script" && isSpeculationRules(value)) {
diff --git a/cli/beacon/internal/endpoint/dashboard/testdata/lens-e2e/fixtures/probe.lens.html b/cli/beacon/internal/endpoint/dashboard/testdata/lens-e2e/fixtures/probe.lens.html
index b5ebad86..41b957e8 100644
--- a/cli/beacon/internal/endpoint/dashboard/testdata/lens-e2e/fixtures/probe.lens.html
+++ b/cli/beacon/internal/endpoint/dashboard/testdata/lens-e2e/fixtures/probe.lens.html
@@ -190,6 +190,75 @@ window.beacon.getTrace().then(async function (data) {
t.content.firstChild.replaceWith(new DOMParser().parseFromString(childMarkup, "text/html").body.firstChild);
holder().appendChild(t.content.cloneNode(true));
});
+ // Markup the browser parses differently from a plain whole-document parse: with scripting on, a
+ // <noscript> is raw text, so the attribute below closes it and what follows is real markup; and in
+ // an <svg> or <math> context, <style> holds markup and an integration point turns it back into
+ // HTML. A check that parses differently from the real call sees only text here. Each probe also
+ // reports whether a refused element survived, so a run without the guard shows the differential.
+ var noscriptMarkup = '<noscript><p title="</noscript><link rel=preconnect href=http://127.0.0.1:9/?via=noscript><iframe></iframe>"></p></noscript>';
+ function survived(root, fn) {
+ return attempt(function () {
+ fn();
+ return root.querySelector("iframe, link") ? "present" : "absent";
+ });
+ }
+ var h;
+ h = holder(); r.noscriptInnerHTML = await survived(h, function () { h.innerHTML = noscriptMarkup; });
+ h = holder(); r.noscriptInsertAdjacentHTML = await survived(h, function () { h.insertAdjacentHTML("afterbegin", noscriptMarkup); });
+ h = holder(); r.noscriptSetHTMLUnsafe = await survived(h, function () { h.setHTMLUnsafe(noscriptMarkup); });
+ h = holder(); var inner = document.createElement("span"); h.appendChild(inner);
+ r.noscriptOuterHTML = await survived(h, function () { inner.outerHTML = noscriptMarkup; });
+ h = holder(); var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg"); h.appendChild(svg);
+ r.foreignSvg = await survived(h, function () {
+ svg.innerHTML = '<style><foreignObject><iframe></iframe></foreignObject></style>';
+ });
+ h = holder(); var math = document.createElementNS("http://www.w3.org/1998/Math/MathML", "math"); h.appendChild(math);
+ r.foreignMath = await survived(h, function () { math.innerHTML = '<style><mi><iframe></iframe></mi></style>'; });
+ // A closed declarative shadow root hides its content from every later scan, so only the check of
+ // the markup itself can stop this one.
+ h = holder();
+ r.templateClosedShadow = await survived(h, function () {
+ h.setHTMLUnsafe('<div><template shadowrootmode="closed">' + noscriptMarkup + "</template></div>");
+ });
+ r.parseHTMLUnsafeClosedShadow = await survived(h, function () {
+ if (typeof Document.parseHTMLUnsafe !== "function") throw new Error("unsupported");
+ var parsed = Document.parseHTMLUnsafe('<div id="shadow-host"><template shadowrootmode="closed"><iframe></iframe></template></div>');
+ h.appendChild(document.adoptNode(parsed.getElementById("shadow-host")));
+ });
+ r.execCommandInsertHTML = await added(function () {
+ var editable = holder();
+ editable.contentEditable = "true";
+ editable.focus();
+ document.getSelection().selectAllChildren(editable);
+ if (!document.execCommand("insertHTML", false, "<iframe></iframe>")) throw new Error("not run");
+ });
+ // Benign markup must come out exactly as the browser's own parsing builds it.
+ r.benignParsing = (function () {
+ var d = holder();
+ d.innerHTML = "<b>x</b><script>window.innerScriptRan = true<\/script>";
+ d.insertAdjacentHTML("beforeend", "<i>y</i>");
+ d.insertAdjacentHTML("beforebegin", "<hr id=before>");
+ d.firstChild.outerHTML = "<u>z</u><s>w</s>";
+ var svgEl = document.createElementNS("http://www.w3.org/2000/svg", "svg");
+ d.appendChild(svgEl);
+ svgEl.innerHTML = "<circle r='1'/>";
+ var table = document.createElement("table");
+ d.appendChild(table);
+ table.innerHTML = "<tr><td>2</td></tr>";
+ var template = document.createElement("template");
+ template.innerHTML = "<tr><td>1</td></tr>";
+ var shadow = holder().attachShadow({ mode: "open" });
+ shadow.innerHTML = "<em>s</em>";
+ var noscript = holder();
+ noscript.innerHTML = "<noscript><p>n</p></noscript>";
+ return [
+ Array.prototype.map.call(d.childNodes, function (n) { return n.localName; }).join("+"),
+ d.previousSibling.id, window.innerScriptRan === undefined ? "inert" : "ran",
+ svgEl.firstChild.namespaceURI === "http://www.w3.org/2000/svg" ? "svg" : "html",
+ table.firstChild.localName, template.content.firstChild.localName, shadow.firstChild.localName,
+ noscript.firstChild.firstChild.nodeType,
+ ].join(",");
+ })();
r.frameStatic = staticChildMessages.length ? "allowed:" + staticChildMessages[0]
: document.getElementById("static-frame") ? "present" : "blocked";
r.hintCreate = await added(function () { document.createElement("LINK"); });
diff --git a/cli/beacon/internal/endpoint/dashboard/testdata/lens-e2e/tests/lenses.spec.ts b/cli/beacon/internal/endpoint/dashboard/testdata/lens-e2e/tests/lenses.spec.ts
index d1aa52e8..68da2d64 100644
--- a/cli/beacon/internal/endpoint/dashboard/testdata/lens-e2e/tests/lenses.spec.ts
+++ b/cli/beacon/internal/endpoint/dashboard/testdata/lens-e2e/tests/lenses.spec.ts
@@ -88,9 +88,16 @@ test('a lens cannot reach the network, the dashboard, storage or code evaluation
'frameDocumentWrite', 'frameParsedAdopt', 'frameFragment', 'frameShadow', 'frameTemplateClone', 'frameStatic',
'hintCreate', 'hintInnerHTML', 'hintStatic',
'rulesTypeProperty', 'rulesSetAttribute', 'rulesMutateManifest', 'rulesInnerHTML', 'rulesStatic',
+ // Markup the real parser reads differently from a plain document parse: <noscript> with scripting
+ // on, foreign content contexts, and closed declarative shadow roots.
+ 'noscriptInnerHTML', 'noscriptInsertAdjacentHTML', 'noscriptSetHTMLUnsafe', 'noscriptOuterHTML',
+ 'foreignSvg', 'foreignMath', 'templateClosedShadow', 'parseHTMLUnsafeClosedShadow', 'execCommandInsertHTML',
]) {
expect(r[probe], probe).toBe('blocked');
}
+ // The guard parses markup itself; benign markup must come out exactly as the browser builds it
+ // (children, beside-insertion, context-dependent tbody, inert innerHTML scripts, <noscript> as text).
+ expect(r.benignParsing).toBe('u+s+script+i+svg+table,before,inert,svg,tbody,tr,em,3');
expect(r.dnsPrefetchMeta).toBe(true); // implicit DNS prefetching is off in the document
const frameResponse = await page.request.get('/lenses/frame/probe');
expect(frameResponse.headers()['x-dns-prefetch-control']).toBe('off');
diff --git a/spec/lenses/SPEC.md b/spec/lenses/SPEC.md
index 0c4be5ab..c7cf70aa 100644
--- a/spec/lenses/SPEC.md
+++ b/spec/lenses/SPEC.md
@@ -194,10 +194,12 @@ The host enforces these rules; a lens does not opt into them.
`preconnect`, `prefetch` and `preload` are links), and
`<script type="speculationrules">`. Creating one, inserting one, or parsing
one in through `innerHTML`, `outerHTML`, `insertAdjacentHTML`,
- `setHTMLUnsafe` or `execCommand` throws a `NotSupportedError`
- `DOMException`; `document.write` and `document.writeln` always throw; and
- any the parser puts in from the lens file's own markup is removed before
- the next script runs.
+ `setHTMLUnsafe` or `Document.parseHTMLUnsafe` throws a `NotSupportedError`
+ `DOMException`. The host parses such markup in the same document and
+ context as the real call, so it checks what the browser would build;
+ `document.write`, `document.writeln` and `execCommand("insertHTML")`
+ always throw; and any the parser puts in from the lens file's own markup
+ is removed before the next script runs.
- The frame is served with `X-DNS-Prefetch-Control: off`, and the host
repeats it as a `<meta http-equiv>` in the document, so the browser does not
resolve hostnames the lens mentions on its own.