Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 61 additions & 0 deletions e2e/structureddata.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import { expect, test } from "@playwright/test";
import { clearMailbox, row, sendMessage } from "./helpers.js";

// JSON-LD blocks in the HTML body are listed, as written, in the HTML Source tab (the HTML preview removes them).

const page = (...blocks) =>
`<html><head>${blocks.map((b) => `<script type="application/ld+json">${b}</script>`).join("")}</head><body><p>Hi</p></body></html>`;

const open = async (page, subject) => {
await page.goto("./");
await row(page, subject).click();
await page.locator("#nav-html-source-tab:visible").click();
};

test.beforeEach(async ({ request }) => {
await clearMailbox(request);
});

test("JSON-LD blocks are listed pretty-printed", async ({ page: p, request }) => {
await sendMessage(request, {
subject: "With data",
html: page('{"@type":"EmailMessage","name":"x"}', '{"@type":"Order"}'),
});
await open(p, "With data");

const blocks = p.getByTestId("structured-data-block");
await expect(blocks).toHaveCount(2);
await expect(blocks.nth(0)).toContainText('"@type": "EmailMessage"');
await expect(blocks.nth(1)).toContainText('"@type": "Order"');
await expect(p.getByTestId("structured-data")).toContainText("2 blocks");
});

test("nothing is validated: invalid JSON is shown as written with the error", async ({ page: p, request }) => {
await sendMessage(request, { subject: "Broken", html: page('{"a": oops') });
await open(p, "Broken");

await expect(p.getByTestId("structured-data-block")).toContainText('{"a": oops');
await expect(p.getByTestId("structured-data")).toContainText("Invalid JSON");
});

test("valid but extremely nested JSON is shown as written, and is not reported as invalid", async ({
page: p,
request,
}) => {
const nested = "[".repeat(4000) + "]".repeat(4000);
await sendMessage(request, { subject: "Deep", html: page(nested) });
await open(p, "Deep");

const section = p.getByTestId("structured-data");
await expect(p.getByTestId("structured-data-block")).toHaveCount(1);
await expect(section).toContainText("Not formatted");
await expect(section).not.toContainText("Invalid JSON");
});

test("a message without JSON-LD has no structured data section", async ({ page: p, request }) => {
await sendMessage(request, { subject: "Plain", html: "<p>nothing</p>" });
await open(p, "Plain");

await expect(p.locator("#nav-html-source")).toContainText("nothing");
await expect(p.getByTestId("structured-data")).toHaveCount(0);
});
26 changes: 26 additions & 0 deletions server/ui-src/components/message/MessageItem.vue
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { Tooltip } from "bootstrap";
import commonMixins from "../../mixins/CommonMixins";
import { mailbox } from "../../stores/mailbox";
import { sanitizeHTML } from "../../utils/sanitize";
import { extractStructuredData } from "../../utils/structuredData";
import { textToHTML } from "../../utils/textToHTML";
import hljs from "highlight.js/lib/core";
import xml from "highlight.js/lib/languages/xml";
Expand Down Expand Up @@ -87,6 +88,11 @@ export default {
);
},

// JSON-LD blocks in the HTML, which are removed from the preview
structuredData() {
return extractStructuredData(this.message.HTML);
},

// remove bad HTML, JavaScript, iframes etc
sanitizedHTML() {
const clean = sanitizeHTML(this.message.HTML);
Expand Down Expand Up @@ -787,6 +793,26 @@ export default {
aria-labelledby="nav-html-source-tab"
tabindex="0"
>
<div v-if="structuredData.blocks.length" data-testid="structured-data" class="mb-3">
<h6 class="mb-1">
Structured data (JSON-LD)
<span class="text-muted small fw-normal">
- {{ structuredData.blocks.length }}
{{ structuredData.blocks.length === 1 ? "block" : "blocks" }} found in the HTML, not
validated or interpreted
</span>
</h6>
<div v-for="(b, i) in structuredData.blocks" :key="i" class="mb-2">
<div v-if="b.error" class="small text-danger">Invalid JSON: {{ b.error }}</div>
<div v-if="b.note" class="small text-muted">{{ b.note }}</div>
<pre data-testid="structured-data-block"><code>{{ b.text }}</code></pre>
</div>
<div v-if="structuredData.truncated" class="small text-muted">
Some blocks are not shown because there are too many, or they are too large.
</div>
<hr />
<h6 class="mb-1">HTML source</h6>
</div>
<pre class="language-html"><code class="language-html">{{ message.HTML }}</code></pre>
</div>
<div
Expand Down
74 changes: 74 additions & 0 deletions server/ui-src/utils/structuredData.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
// Structured data (JSON-LD) found in the HTML of a message

// the most blocks and the largest block (in characters) that is read, so a large message stays cheap to view
export const MAX_BLOCKS = 20;
export const MAX_BLOCK_LENGTH = 64 << 10;
// Pretty-printing indents every level, so deeply nested JSON grows much larger than its source (8 KB can become
// 32 MB). A block is shown as written if its formatted version is over MAX_FORMATTED_LENGTH, and no more than
// MAX_TOTAL_LENGTH characters are shown in all.
export const MAX_FORMATTED_LENGTH = 128 << 10;
export const MAX_TOTAL_LENGTH = 512 << 10;

const hint = /ld\+json/i;

/**
* Returns the `application/ld+json` script blocks in an HTML message, as
* `{ text, error, note }`: `text` is the pretty-printed JSON, or the original text if it
* is not valid JSON (`error` says why) or its formatted version would be too large
* (`note` says so). The content is only read, never validated or interpreted. Blocks
* over the limits are not included, and `truncated` is set if any block was left out.
*
* A DOMParser may be supplied (e.g. one from a jsdom window for testing).
*/
export const extractStructuredData = (html, parser = new DOMParser()) => {
const result = { blocks: [], truncated: false };
let total = 0;
if (!html || !hint.test(html)) {
return result;
}

// a DOMParser document never runs scripts
const doc = parser.parseFromString(html, "text/html");

for (const script of doc.querySelectorAll("script")) {
if ((script.getAttribute("type") || "").trim().toLowerCase() !== "application/ld+json") {
continue;
}
if (result.blocks.length >= MAX_BLOCKS || script.textContent.length > MAX_BLOCK_LENGTH) {
result.truncated = true;
continue;
}

const raw = script.textContent.trim();
const block = { text: raw, error: "", note: "" };
let value;
try {
value = JSON.parse(raw);
} catch (e) {
block.error = e.message;
}

if (!block.error) {
try {
const formatted = JSON.stringify(value, null, 2);
if (formatted.length <= MAX_FORMATTED_LENGTH) {
block.text = formatted;
} else {
block.note = "Not formatted, as the formatted JSON would be too large";
}
} catch {
// very deeply nested JSON is valid, but exceeds the call stack when formatted
block.note = "Not formatted, as the JSON is too deeply nested";
}
}

if (total + block.text.length > MAX_TOTAL_LENGTH) {
result.truncated = true;
continue;
}
total += block.text.length;
result.blocks.push(block);
}

return result;
};
98 changes: 98 additions & 0 deletions server/ui-src/utils/structuredData.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import assert from "node:assert/strict";
import test from "node:test";
import { JSDOM } from "jsdom";
import {
extractStructuredData,
MAX_BLOCK_LENGTH,
MAX_BLOCKS,
MAX_FORMATTED_LENGTH,
MAX_TOTAL_LENGTH,
} from "./structuredData.js";

const parser = new new JSDOM("").window.DOMParser();
const extract = (html) => extractStructuredData(html, parser);
const page = (...scripts) => `<html><head>${scripts.join("")}</head><body><p>Hi</p></body></html>`;
const ld = (s, type = "application/ld+json") => `<script type="${type}">${s}</script>`;

test("HTML without structured data has no blocks", () => {
assert.deepEqual(extract("<p>hello</p>"), { blocks: [], truncated: false });
assert.deepEqual(extract(""), { blocks: [], truncated: false });
assert.deepEqual(extract(undefined), { blocks: [], truncated: false });
});

test("a block is pretty-printed", () => {
const r = extract(page(ld('{"@type":"EmailMessage","a":[1,2]}')));
assert.equal(r.blocks.length, 1);
assert.equal(r.blocks[0].error, "");
assert.equal(r.blocks[0].text, JSON.stringify({ "@type": "EmailMessage", a: [1, 2] }, null, 2));
});

test("the content is not interpreted or validated", () => {
// not an EmailMessage, no name, an http URL: shown exactly as it is
const json = { "@type": "Order", potentialAction: { "@type": "Nope", target: "http://example.com" } };
assert.equal(extract(page(ld(JSON.stringify(json)))).blocks[0].text, JSON.stringify(json, null, 2));
});

test("several blocks keep their order; other scripts are ignored", () => {
const r = extract(
page(ld('{"n":1}'), "<script>var x = 1;</script>", ld('{"n":2}', "text/javascript"), ld('{"n":3}')),
);
assert.deepEqual(
r.blocks.map((b) => JSON.parse(b.text).n),
[1, 3],
);
});

test("the script type is matched without regard to case", () => {
assert.equal(extract(page(ld('{"a":1}', " Application/LD+JSON "))).blocks.length, 1);
});

test("invalid JSON is shown as written, with the error", () => {
const r = extract(page(ld('{"a": oops')));
assert.equal(r.blocks.length, 1);
assert.equal(r.blocks[0].text, '{"a": oops');
assert.notEqual(r.blocks[0].error, "");
});

test("markup in the JSON stays text", () => {
const r = extract(page(ld('{"name":"x"}')));
assert.equal(r.blocks[0].text.includes("<"), false);
});

test("the number and size of blocks is limited", () => {
const many = extract(page(...Array.from({ length: MAX_BLOCKS + 5 }, (_, i) => ld(`{"n":${i}}`))));
assert.equal(many.blocks.length, MAX_BLOCKS);
assert.equal(many.truncated, true);

const big = extract(page(ld(`"${"a".repeat(MAX_BLOCK_LENGTH)}"`), ld('{"ok":true}')));
assert.equal(big.blocks.length, 1);
assert.equal(big.truncated, true);
});

const nested = (depth) => "[".repeat(depth) + "]".repeat(depth);

test("deeply nested JSON is not expanded by formatting", () => {
// 4000 levels is 8 KB of JSON, which formats to 32 MB
const r = extract(page(ld(nested(4000))));
assert.equal(r.blocks.length, 1);
assert.equal(r.blocks[0].text, nested(4000));
assert.equal(r.blocks[0].error, "");
assert.notEqual(r.blocks[0].note, "");
assert.ok(r.blocks[0].text.length <= MAX_FORMATTED_LENGTH);

// so deep that it cannot be formatted at all: still valid JSON, so it is not reported as an error
const deep = extract(page(ld(nested(30000))));
assert.equal(deep.blocks.length, 1);
assert.equal(deep.blocks[0].text, nested(30000));
assert.equal(deep.blocks[0].error, "");
assert.notEqual(deep.blocks[0].note, "");
});

test("the total size shown is limited", () => {
// each block is just under the size limit and is shown in full, but together they are over the total limit
const block = ld(JSON.stringify({ a: "x".repeat(MAX_BLOCK_LENGTH - 100) }));
const r = extract(page(...Array.from({ length: 12 }, () => block)));
assert.ok(r.blocks.length > 1 && r.blocks.length < 12);
assert.equal(r.truncated, true);
assert.ok(r.blocks.reduce((n, b) => n + b.text.length, 0) <= MAX_TOTAL_LENGTH);
});