diff --git a/src/browser/CdpCaptureDocuments.baseUrl.test.ts b/src/browser/CdpCaptureDocuments.baseUrl.test.ts index e5ff1fd59..a5481c161 100644 --- a/src/browser/CdpCaptureDocuments.baseUrl.test.ts +++ b/src/browser/CdpCaptureDocuments.baseUrl.test.ts @@ -606,3 +606,402 @@ describe("SVG xlink:href context", () => { expect(dangling.urls).toEqual([]); }); }); + +const SVG_NAMESPACE = "http://www.w3.org/2000/svg"; +const XLINK_NAMESPACE = "http://www.w3.org/1999/xlink"; +const XHTML_NAMESPACE = "http://www.w3.org/1999/xhtml"; + +const xhtmlRoot = ( + attributes: readonly (readonly [string, string])[] = [ + ["xmlns", XHTML_NAMESPACE], + ["xmlns:svg", SVG_NAMESPACE], + ["xmlns:xlink", XLINK_NAMESPACE], + ], +): SvgSnapshotNode => ({ + name: "html", + parent: 0, + attributes, +}); + +const approvedHref = ( + nodeIndex: number, + url: string, +): { + readonly node_index: number; + readonly attribute: "href"; + readonly url: string; + readonly destination_scope: "approved"; +} => ({ + node_index: nodeIndex, + attribute: "href", + url, + destination_scope: "approved", +}); + +describe("XML SVG roots and namespace scope restoration", () => { + it.each(["svg", "document"])( + "resolves namespaces under an unprefixed XML %s root", + (name) => { + const result = captureSvg( + svgDocument([ + { + name, + parent: 0, + attributes: [ + ["xmlns", SVG_NAMESPACE], + ["xmlns:p", XLINK_NAMESPACE], + ], + }, + { name: "a", parent: 1, attributes: [["p:href", "/linked"]] }, + ]), + ); + expect(result.urls).toEqual([approvedHref(2, `${origin}/linked`)]); + }, + ); + + it.each([2, 3, 99])( + "rejects self-parent, cyclic and dangling XML ancestry (%s)", + (parent) => { + const result = captureSvg( + svgDocument([ + xhtmlRoot(), + { + name: "svg:a", + parent, + attributes: [ + ["xmlns:svg", SVG_NAMESPACE], + ["xmlns:p", XLINK_NAMESPACE], + ["p:href", "/invalid"], + ], + }, + { name: "svg:g", parent: 2 }, + ]), + ); + expect(result.urls).toEqual([]); + }, + ); + + it("restores namespace declarations and undeclarations before visiting siblings", () => { + const result = captureSvg( + svgDocument([ + xhtmlRoot(), + { + name: "svg:a", + parent: 1, + attributes: [ + ["xmlns:xlink", ""], + ["xlink:href", "/undeclared"], + ], + }, + { + name: "svg:a", + parent: 1, + attributes: [["xlink:href", "/inherited"]], + }, + { + name: "svg:a", + parent: 1, + attributes: [ + ["xmlns:svg", "other"], + ["xlink:href", "/rebound"], + ], + }, + { name: "svg:a", parent: 1, attributes: [["xlink:href", "/restored"]] }, + ]), + ); + expect(result.urls).toEqual([ + approvedHref(3, `${origin}/inherited`), + approvedHref(5, `${origin}/restored`), + ]); + }); +}); + +describe("XHTML and XML SVG namespace prefixes", () => { + it("reports prefixed svg:a, svg:image, and an svg:a with no svg parent", () => { + const result = captureSvg( + svgDocument([ + xhtmlRoot(), + { name: "svg:svg", parent: 1 }, + { + name: "svg:a", + parent: 2, + attributes: [ + ["xlink:href", "/xl-pa1"], + ["xlink:href", "/later"], + ], + }, + { + name: "svg:image", + parent: 2, + attributes: [["xlink:href", "guide"]], + }, + { + name: "svg:a", + parent: 1, + attributes: [["xlink:href", "/xl-orphan"]], + }, + ]), + ); + expect(result.nodes[3]?.node_name).toBe("svg:a"); + expect(result.nodes[3]?.attribute_names).toEqual(["xlink:href"]); + expect(result.urls).toEqual([ + approvedHref(3, `${origin}/xl-pa1`), + approvedHref(4, `${origin}/screens/assets/guide`), + approvedHref(5, `${origin}/xl-orphan`), + ]); + }); + + it("reports svg:a under svg:foreignObject and skips XHTML anchors there", () => { + const result = captureSvg( + svgDocument([ + xhtmlRoot([ + ["xmlns", XHTML_NAMESPACE], + ["xmlns:svg", SVG_NAMESPACE], + ["xmlns:xlink", XLINK_NAMESPACE], + ["xmlns:h", XHTML_NAMESPACE], + ]), + { name: "svg:svg", parent: 1 }, + { name: "svg:foreignObject", parent: 2 }, + { + name: "a", + parent: 3, + attributes: [["xlink:href", "/xl-html-fo"]], + }, + { + name: "h:a", + parent: 3, + attributes: [["xlink:href", "/xl-h"]], + }, + { + name: "svg:a", + parent: 3, + attributes: [["xlink:href", "/xl-fo-svg"]], + }, + ]), + ); + expect(urlFor(result, 4)).toBeUndefined(); + expect(urlFor(result, 5)).toBeUndefined(); + expect(result.urls).toEqual([approvedHref(6, `${origin}/xl-fo-svg`)]); + }); + + it("reads XLink by namespace, including a prefix other than xlink", () => { + const result = captureSvg( + svgDocument([ + xhtmlRoot([["xmlns", XHTML_NAMESPACE]]), + { + name: "svg", + parent: 1, + attributes: [ + ["xmlns", SVG_NAMESPACE], + ["xmlns:xlink", "http://example.com/not-xlink"], + ["xmlns:x", XLINK_NAMESPACE], + ], + }, + { + name: "a", + parent: 2, + attributes: [ + ["xlink:href", "/not-xlink"], + ["x:href", "/xl-custom"], + ["x:href", "/later"], + ], + }, + ]), + ); + expect(result.nodes[3]?.attribute_names).toEqual(["xlink:href", "x:href"]); + expect(result.urls).toEqual([approvedHref(3, `${origin}/xl-custom`)]); + }); + + it("keeps plain href ahead of a namespaced XLink href, including an empty href", () => { + const baseUrl = `${origin}/screens/assets/`; + const anchor = ( + parent: number, + attributes: readonly (readonly [string, string])[], + ): SvgSnapshotNode => ({ + name: "svg:a", + parent, + attributes, + }); + const result = captureSvg( + svgDocument( + [ + xhtmlRoot(), + { name: "svg:svg", parent: 1 }, + anchor(2, [ + ["xlink:href", "/xlink-loses"], + ["href", "/href-wins"], + ]), + anchor(2, [ + ["href", "/href-wins"], + ["xlink:href", "/xlink-loses"], + ]), + anchor(2, [ + ["href", ""], + ["xlink:href", "/xlink-should-lose"], + ]), + ], + baseUrl, + ), + ); + expect(result.urls).toEqual([ + approvedHref(3, `${origin}/href-wins`), + approvedHref(4, `${origin}/href-wins`), + approvedHref(5, baseUrl), + ]); + }); +}); + +describe("XHTML SVG exclusions, HTML documents, and prefix scope", () => { + it("classifies a prefixed SVG xlink:href outside the allowed origins as outside_policy", () => { + const result = captureSvg( + svgDocument([ + xhtmlRoot(), + { name: "svg:svg", parent: 1 }, + { + name: "svg:a", + parent: 2, + attributes: [["xlink:href", "https://cdn.example.test/out"]], + }, + ]), + ); + expect(result.urls).toEqual([ + { + node_index: 3, + attribute: "href", + url: null, + destination_scope: "outside_policy", + }, + ]); + }); + + it("does not treat bogus:svg in another namespace as SVG", () => { + const result = captureSvg( + svgDocument([ + xhtmlRoot([ + ["xmlns", XHTML_NAMESPACE], + ["xmlns:svg", SVG_NAMESPACE], + ["xmlns:xlink", XLINK_NAMESPACE], + ["xmlns:bogus", "http://example.com/not-svg"], + ]), + { + name: "bogus:svg", + parent: 1, + attributes: [["xlink:href", "/xl-bogus"]], + }, + { + name: "bogus:a", + parent: 2, + attributes: [["xlink:href", "/xl-bogus-a"]], + }, + { + name: "svg:a", + parent: 1, + attributes: [["xlink:href", "/xl-kept"]], + }, + ]), + ); + expect(result.nodes[2]?.node_name).toBe("bogus:svg"); + expect(result.urls).toEqual([approvedHref(4, `${origin}/xl-kept`)]); + }); + + it("leaves HTML documents on literal svg and xlink:href names", () => { + const result = captureSvg( + svgDocument([ + { name: "HTML", parent: 0 }, + { + name: "svg", + parent: 1, + attributes: [ + ["xmlns", SVG_NAMESPACE], + ["xmlns:x", XLINK_NAMESPACE], + ], + }, + { + name: "a", + parent: 2, + attributes: [["xlink:href", "/xl-literal"]], + }, + { + name: "a", + parent: 2, + attributes: [["x:href", "/xl-custom-html"]], + }, + { + name: "svg:a", + parent: 1, + attributes: [ + ["xmlns:svg", SVG_NAMESPACE], + ["xmlns:xlink", XLINK_NAMESPACE], + ["xlink:href", "/xl-prefixed-html"], + ], + }, + { + name: "A", + parent: 1, + attributes: [["xlink:href", "/xl-html-anchor"]], + }, + ]), + ); + expect(result.urls).toEqual([approvedHref(3, `${origin}/xl-literal`)]); + }); + + it("applies an element's own xmlns declarations to its name and href", () => { + const result = captureSvg( + svgDocument([ + { name: "html", parent: 0, attributes: [["xmlns", XHTML_NAMESPACE]] }, + { + name: "svg:a", + parent: 1, + attributes: [ + ["xmlns:svg", SVG_NAMESPACE], + ["xmlns:xlink", XLINK_NAMESPACE], + ["xlink:href", "/xl-self"], + ], + }, + ]), + ); + expect(result.urls).toEqual([approvedHref(2, `${origin}/xl-self`)]); + }); + + it("resolves a prefix declared on a later ancestor", () => { + const result = captureSvg( + svgDocument([ + { + name: "svg:a", + parent: 2, + attributes: [["xlink:href", "/forward"]], + }, + { name: "svg:svg", parent: 3 }, + xhtmlRoot(), + ]), + ); + expect(result.urls).toEqual([approvedHref(1, `${origin}/forward`)]); + }); + + it("resolves a deep chain with distinct namespace declarations without quadratic expansion", () => { + const depth = 12_000; + const elements: SvgSnapshotNode[] = [ + xhtmlRoot(), + { name: "svg:svg", parent: 1 }, + ]; + let parent = 2; + for (let index = 0; index < depth; index += 1) { + elements.push({ + name: "svg:g", + parent, + attributes: [[`xmlns:p${index}`, `urn:prefix:${index}`]], + }); + parent = elements.length; + } + elements.push({ + name: "svg:a", + parent, + attributes: [["xlink:href", "/deep"]], + }); + const snapshot = svgDocument(elements); + const result = captureSvg(snapshot); + expect(result.urls).toEqual([ + approvedHref(elements.length, `${origin}/deep`), + ]); + }, 30_000); +}); diff --git a/src/browser/CdpCaptureDocuments.ts b/src/browser/CdpCaptureDocuments.ts index bccc08447..0b93059f2 100644 --- a/src/browser/CdpCaptureDocuments.ts +++ b/src/browser/CdpCaptureDocuments.ts @@ -11,6 +11,7 @@ import { } from "./CdpCaptureValues.js"; import { exclusionReasonForUrl } from "./CdpCaptureEventHelpers.js"; import type { CdpCaptureCompleteness } from "./CdpCaptureCompleteness.js"; +import { createDocumentSvgAncestry, domSvgLink } from "./CdpCaptureDomSvg.js"; export type CapturedResource = Omit< WebPageInspection["resources"][number], @@ -171,24 +172,20 @@ export const captureDom = ( ? documentNodes.attributes : []; const baseIndex = nodes.length; - const svgContexts = new Map(); + const ancestry = createDocumentSvgAncestry({ + nodeTypes, + nodeNames, + parents, + strings, + attributes, + }); total += nodeTypes.length; for (let index = 0; index < nodeTypes.length; index += 1) { const attributeIndexes = numberArray(attributes[index]); const parent = Math.trunc(parents[index] ?? -1); const nodeIndex = nodes.length; const nodeName = indexedString(strings, nodeNames[index]); - const rawAttributeNames = attributeIndexes - .filter((_value, attributeIndex) => attributeIndex % 2 === 0) - .map((value) => indexedString(strings, value)); - const seenAttributeNames = new Set(); - const attributeNames: string[] = []; - for (const name of rawAttributeNames) { - if (!seenAttributeNames.has(name)) { - seenAttributeNames.add(name); - attributeNames.push(name); - } - } + const attributeNames = uniqueAttributeNames(attributeIndexes, strings); nodes.push({ index: nodeIndex, parent_index: parent < 0 ? -1 : baseIndex + parent, @@ -206,13 +203,7 @@ export const captureDom = ( nodeIndex, nodeName, allowedOrigins, - svgElement: elementInSvgContext( - index, - nodeNames, - parents, - strings, - svgContexts, - ), + ...domSvgLink(ancestry, index), }); for (const url of metadata.urls) { urls.push(url); @@ -367,6 +358,21 @@ const indexedString = (strings: readonly string[], index: unknown): string => { return integer === undefined ? "" : (strings[Math.trunc(integer)] ?? ""); }; +const uniqueAttributeNames = ( + attributeIndexes: readonly number[], + strings: readonly string[], +): string[] => { + const names: string[] = []; + const seen = new Set(); + for (let index = 0; index < attributeIndexes.length; index += 2) { + const name = indexedString(strings, attributeIndexes[index]); + if (seen.has(name)) continue; + seen.add(name); + names.push(name); + } + return names; +}; + const numberArray = (value: unknown): readonly number[] => Array.isArray(value) ? value.flatMap((item) => { @@ -384,41 +390,22 @@ interface DomMetadataOptions { readonly nodeName: string; readonly allowedOrigins: ReadonlySet; readonly svgElement: boolean; + readonly xmlDocument: boolean; + readonly xlinkHref: string | undefined; } -// DOMSnapshot carries no namespace URI. Chrome's HTML parser records SVG -// local names (`svg`, `foreignObject`). Descendants of foreignObject are HTML -// until a nested `svg`. -const elementInSvgContext = ( - index: number, - nodeNames: readonly number[], - parents: readonly number[], - strings: readonly string[], - contexts: Map, -): boolean => { - let current = index; - const seen = new Set(); - let inSvg = false; - while (current >= 0 && current < nodeNames.length && !seen.has(current)) { - const cached = contexts.get(current); - if (cached !== undefined) { - inSvg = cached; - break; - } - seen.add(current); - if (indexedString(strings, nodeNames[current]) === "svg") { - inSvg = true; - break; - } - const parent = Math.trunc(parents[current] ?? -1); - if (parent < 0 || parent === current) break; - if (indexedString(strings, nodeNames[parent]) === "foreignObject") break; - current = parent; - } - // Cache the entire examined chain, including forward references and cycles, - // so shared ancestors are examined once per document. - for (const node of seen) contexts.set(node, inSvg); - return inSvg; +// Chrome reads an SVG XLink href only when href itself is absent, and an +// empty href still wins. HTML keeps the literal attribute name `xlink:href`. +// XML uses any prefix bound to the XLink namespace. Both are stored as href. +const hrefAttributeValue = ( + pairs: ReadonlyMap, + attribute: string, + options: DomMetadataOptions, +): string | undefined => { + const declared = pairs.get(attribute); + if (declared !== undefined) return declared; + if (attribute !== "href" || !options.svgElement) return undefined; + return options.xmlDocument ? options.xlinkHref : pairs.get("xlink:href"); }; const domMetadata = ( @@ -435,7 +422,6 @@ const domMetadata = ( nodeIndex, nodeName, allowedOrigins, - svgElement, } = options; const pairs = new Map(); for (let index = 0; index + 1 < attributes.length; index += 2) { @@ -447,13 +433,7 @@ const domMetadata = ( } const urls: WebPageInspection["metadata"]["dom_urls"] = []; for (const attribute of domUrlAttributes) { - // Chrome reads SVG xlink:href only when href itself is absent, and an - // empty href still wins. Report the fallback as href. - const value = - pairs.get(attribute) ?? - (attribute === "href" && svgElement - ? pairs.get("xlink:href") - : undefined); + const value = hrefAttributeValue(pairs, attribute, options); if (value === undefined) continue; const tagName = nodeName.toLowerCase(); // Chrome strips HTML whitespace for FORM.action, while submit controls diff --git a/src/browser/CdpCaptureDomSvg.ts b/src/browser/CdpCaptureDomSvg.ts new file mode 100644 index 000000000..3d1a5c977 --- /dev/null +++ b/src/browser/CdpCaptureDomSvg.ts @@ -0,0 +1,275 @@ +import { numberValue } from "./CdpCaptureValues.js"; + +const SVG_NAMESPACE = "http://www.w3.org/2000/svg"; +const XLINK_NAMESPACE = "http://www.w3.org/1999/xlink"; + +interface DomSnapshotNodes { + readonly nodeTypes: readonly number[]; + readonly nodeNames: readonly number[]; + readonly parents: readonly number[]; + readonly strings: readonly string[]; + readonly attributes: readonly unknown[]; +} + +interface XmlSvgLink { + readonly svgElement: boolean; + readonly xlinkHref: string | undefined; +} + +interface DocumentSvgAncestry { + readonly xml: boolean; + readonly nodes: DomSnapshotNodes; + readonly svgContexts: Map; + readonly xmlLinks: Map; +} + +interface DomSvgLink { + readonly svgElement: boolean; + readonly xmlDocument: boolean; + readonly xlinkHref: string | undefined; +} + +const UNRESOLVED: XmlSvgLink = { + svgElement: false, + xlinkHref: undefined, +}; + +const stringAt = (strings: readonly string[], index: unknown): string => { + const integer = numberValue(index); + return integer === undefined ? "" : (strings[Math.trunc(integer)] ?? ""); +}; + +const numberArray = (value: unknown): readonly number[] => + Array.isArray(value) + ? value.flatMap((item) => { + const number = numberValue(item); + return number === undefined ? [] : [number]; + }) + : []; + +// DOMSnapshot has no namespace URI. HTML documents use uppercase `HTML` and +// the parser's local names. XML documents preserve prefixed names and xmlns +// declarations, including those on standalone SVG roots. +const xmlDocument = (nodes: DomSnapshotNodes): boolean => { + const documentIndex = nodes.nodeTypes.findIndex( + (nodeType) => Math.trunc(nodeType) === 9, + ); + if (documentIndex < 0) return false; + for (let index = 0; index < nodes.nodeTypes.length; index += 1) { + if (Math.trunc(nodes.nodeTypes[index] ?? 0) !== 1) continue; + if (Math.trunc(nodes.parents[index] ?? -1) !== documentIndex) continue; + const name = stringAt(nodes.strings, nodes.nodeNames[index]); + if (name === "HTML") return false; + if (name === "html" || name.includes(":")) return true; + // Explicit namespaces also identify standalone SVG and other XML roots. + // Namespace-free synthetic snapshots retain the legacy HTML behavior. + const attributes = numberArray(nodes.attributes[index]); + return attributes.some( + (value, offset) => + offset % 2 === 0 && + xmlnsPrefix(stringAt(nodes.strings, value)) !== undefined, + ); + } + return false; +}; + +export const createDocumentSvgAncestry = ( + nodes: DomSnapshotNodes, +): DocumentSvgAncestry => { + const xml = xmlDocument(nodes); + return { + xml, + nodes, + svgContexts: new Map(), + xmlLinks: xml ? resolveXmlElements(nodes) : new Map(), + }; +}; + +export const domSvgLink = ( + ancestry: DocumentSvgAncestry, + index: number, +): DomSvgLink => { + if (!ancestry.xml) { + return { + svgElement: elementInSvgContext( + index, + ancestry.nodes, + ancestry.svgContexts, + ), + xmlDocument: false, + xlinkHref: undefined, + }; + } + const resolved = ancestry.xmlLinks.get(index) ?? UNRESOLVED; + return { + svgElement: resolved.svgElement, + xmlDocument: true, + xlinkHref: resolved.xlinkHref, + }; +}; + +// Chrome's HTML parser records SVG local names (`svg`, `foreignObject`). +// Descendants of foreignObject are HTML until a nested `svg`. +const elementInSvgContext = ( + index: number, + nodes: DomSnapshotNodes, + contexts: Map, +): boolean => { + let current = index; + const seen = new Set(); + let inSvg = false; + while ( + current >= 0 && + current < nodes.nodeNames.length && + !seen.has(current) + ) { + const cached = contexts.get(current); + if (cached !== undefined) { + inSvg = cached; + break; + } + seen.add(current); + if (stringAt(nodes.strings, nodes.nodeNames[current]) === "svg") { + inSvg = true; + break; + } + const parent = Math.trunc(nodes.parents[current] ?? -1); + if (parent < 0 || parent === current) break; + if (stringAt(nodes.strings, nodes.nodeNames[parent]) === "foreignObject") + break; + current = parent; + } + // Cache the entire examined chain, including forward references and cycles, + // so shared ancestors are examined once per document. + for (const node of seen) contexts.set(node, inSvg); + return inSvg; +}; + +interface NamespaceRestore { + readonly prefix: string; + readonly previous: string | undefined; +} + +type XmlWalkStep = + | { readonly node: number } + | { readonly restore: readonly NamespaceRestore[] }; + +// Walk parent-before-child with one mutable namespace environment. Restore +// declarations on exit so siblings retain their own scope. Only declarations +// on the active path are retained, rather than cumulative maps at every node. +const resolveXmlElements = ( + nodes: DomSnapshotNodes, +): Map => { + const children = new Map(); + const pending: XmlWalkStep[] = []; + for (let node = 0; node < nodes.nodeNames.length; node += 1) { + const parent = Math.trunc(nodes.parents[node] ?? -1); + if (parent < 0) pending.push({ node }); + else if (parent < nodes.nodeNames.length && parent !== node) { + const siblings = children.get(parent); + if (siblings === undefined) children.set(parent, [node]); + else siblings.push(node); + } + } + const bindings = new Map(); + const resolved = new Map(); + while (pending.length > 0) { + const step = pending.pop(); + if (step === undefined) break; + if ("restore" in step) { + for (const { prefix, previous } of step.restore) { + if (previous === undefined) bindings.delete(prefix); + else bindings.set(prefix, previous); + } + continue; + } + const { node } = step; + const attributes = numberArray(nodes.attributes[node]); + const restore = applyDeclarations(bindings, attributes, nodes.strings); + const svgElement = + Math.trunc(nodes.nodeTypes[node] ?? 0) === 1 && + elementNamespace( + stringAt(nodes.strings, nodes.nodeNames[node]), + bindings, + ) === SVG_NAMESPACE; + resolved.set(node, { + svgElement, + xlinkHref: svgElement + ? xlinkHrefValue(attributes, nodes.strings, bindings) + : undefined, + }); + pending.push({ restore }); + for (const child of children.get(node) ?? []) pending.push({ node: child }); + } + // Cycles (including self-parents) and dangling chains cannot reach a root, + // so remain unresolved instead of deriving URLs from an invalid ancestry. + return resolved; +}; + +const applyDeclarations = ( + bindings: Map, + attributes: readonly number[], + strings: readonly string[], +): readonly NamespaceRestore[] => { + const restore: NamespaceRestore[] = []; + const seen = new Set(); + for (let index = 0; index + 1 < attributes.length; index += 2) { + const prefix = xmlnsPrefix(stringAt(strings, attributes[index])); + if (prefix === undefined || seen.has(prefix)) continue; + seen.add(prefix); + restore.push({ prefix, previous: bindings.get(prefix) }); + const value = stringAt(strings, attributes[index + 1]); + if (value.length === 0) bindings.delete(prefix); + else bindings.set(prefix, value); + } + return restore; +}; + +const xmlnsPrefix = (name: string): string | undefined => { + if (name === "xmlns") return ""; + if (!name.startsWith("xmlns:")) return undefined; + const prefix = name.slice("xmlns:".length); + if (prefix.length === 0 || prefix === "xmlns" || prefix.includes(":")) + return undefined; + return prefix; +}; + +const elementNamespace = ( + nodeName: string, + bindings: ReadonlyMap, +): string => { + const colon = nodeName.indexOf(":"); + if (colon < 0) return bindings.get("") ?? ""; + const prefix = nodeName.slice(0, colon); + const local = nodeName.slice(colon + 1); + if ( + prefix.length === 0 || + local.length === 0 || + local.includes(":") || + prefix === "xmlns" + ) + return ""; + return bindings.get(prefix) ?? ""; +}; + +// First prefixed href bound to the XLink namespace. Duplicate names keep the +// earlier value. Plain href is applied by the caller and wins even when empty. +const xlinkHrefValue = ( + attributes: readonly number[], + strings: readonly string[], + bindings: ReadonlyMap, +): string | undefined => { + const seen = new Set(); + for (let index = 0; index + 1 < attributes.length; index += 2) { + const name = stringAt(strings, attributes[index]); + if (seen.has(name)) continue; + seen.add(name); + const colon = name.indexOf(":"); + if (colon <= 0) continue; + const prefix = name.slice(0, colon); + const local = name.slice(colon + 1); + if (local !== "href" || bindings.get(prefix) !== XLINK_NAMESPACE) continue; + return stringAt(strings, attributes[index + 1]); + } + return undefined; +}; diff --git a/tests/boundary/browser/cdpSvgXlinkHref.test.ts b/tests/boundary/browser/cdpSvgXlinkHref.test.ts index da69ed7bc..be4fe268e 100644 --- a/tests/boundary/browser/cdpSvgXlinkHref.test.ts +++ b/tests/boundary/browser/cdpSvgXlinkHref.test.ts @@ -30,8 +30,9 @@ const chromeExecutable = [ ); // Issue 1586's page, plus the HTML, image, use, and foreign-origin cases the -// real snapshot must distinguish. The test is skipped when no Chrome-family -// executable is installed. +// real snapshot must distinguish. The XHTML page is the prefixed-svg gap +// reported on PR 1602. The tests are skipped when no Chrome-family executable +// is installed. const pageHtml = `x s2 @@ -159,6 +160,161 @@ it.skipIf(chromeExecutable === undefined)( }, ); +const xhtmlPage = ` + +x + + + p + + + no + no + y + + +o + + c + b + e + +out + +no + + +`; + +for (const { format, page, contentType, nodeNames, link, destinations } of [ + { + format: "XHTML", + page: xhtmlPage, + contentType: "application/xhtml+xml", + nodeNames: ["html", "svg:a", "bogus:svg"], + link: { name: "svg:a", attribute: "xlink:href" }, + destinations: [ + "/xl-pa1", + "/xl-image", + "/xl-fo-svg", + "/xl-orphan", + "/xl-custom", + "/href-wins", + "", + null, + ], + }, + { + format: "SVG", + page: `link`, + contentType: "image/svg+xml", + nodeNames: ["svg", "a"], + link: { name: "a", attribute: "p:href" }, + destinations: ["/linked"], + }, +]) { + it.skipIf(chromeExecutable === undefined)( + `reports namespaced SVG links from a standalone ${format} document through headless Chrome`, + async ({ processes }) => { + const executable = chromeExecutable; + if (executable === undefined) return; + const profile = await createTestTempDirectory("rea-svg-xhtml-"); + const server = createServer((_request, response) => { + response.writeHead(200, { + "content-type": `${contentType}; charset=utf-8`, + }); + response.end(page); + }); + await new Promise((resolve) => { + server.listen(0, "127.0.0.1", resolve); + }); + const address = server.address(); + if (address === null || typeof address === "string") + throw new Error("XHTML fixture server did not bind a TCP port"); + const origin = `http://127.0.0.1:${String(address.port)}`; + const pageUrl = `${origin}/page.xhtml`; + let stderr = ""; + const child = processes.spawn(executable, [ + "--headless=new", + ...(process.env.REA_BROWSER_NO_SANDBOX === "true" + ? ["--no-sandbox"] + : []), + "--remote-debugging-address=127.0.0.1", + "--remote-debugging-port=0", + `--user-data-dir=${profile}`, + "--no-first-run", + "--no-default-browser-check", + "--disable-background-networking", + "--disable-component-update", + "--disable-dev-shm-usage", + "--disable-sync", + "--metrics-recording-only", + pageUrl, + ]); + child.stdout.on("data", () => undefined); + child.stderr.on("data", (chunk: Buffer) => { + if (stderr.length < 8_192) stderr += chunk.toString("utf8"); + }); + try { + const port = await waitForBrowserDevtoolsPort({ + child, + executable, + activePortPath: join(profile, "DevToolsActivePort"), + stderr: () => stderr, + timeoutMs: 20_000, + }); + const endpoint = `http://127.0.0.1:${String(port)}`; + const provider = new CdpBrowserProvider(); + const targetId = await pageTarget(provider, endpoint, origin, pageUrl); + const result = await provider.inspectPage( + inspectWebPageInputSchema.parse({ + cdp_endpoint: endpoint, + allowed_origins: [origin], + target_id: targetId, + observation_ms: 0, + }), + ); + if (!result.ok) throw result.error; + const urls = result.value.metadata.dom_urls; + for (const name of nodeNames) { + expect( + result.value.dom.nodes.some((node) => node.node_name === name), + ).toBe(true); + } + expect( + result.value.dom.nodes.some( + (node) => + node.node_name === link.name && + node.attribute_names.includes(link.attribute), + ), + ).toBe(true); + expect(urls).toEqual( + destinations.map((destination) => + expect.objectContaining({ + attribute: "href", + url: + destination === null + ? null + : destination === "" + ? pageUrl + : `${origin}${destination}`, + destination_scope: + destination === null ? "outside_policy" : "approved", + }), + ), + ); + } finally { + child.kill("SIGTERM"); + if (!(await waitForExit(child, 2_000))) child.kill("SIGKILL"); + await waitForExit(child, 2_000); + await new Promise((resolve) => { + server.close(() => resolve()); + }); + } + }, + ); +} + const pageTarget = async ( provider: CdpBrowserProvider, endpoint: string,