From 7e266650b3a42f41cf6d916db30a57a999c246a2 Mon Sep 17 00:00:00 2001 From: Xavier Lacot Date: Mon, 23 Nov 2026 18:04:26 +0100 Subject: [PATCH] Load a page from its URL on the homepage of the demo, through a proxy at /load-url --- website/README.md | 101 +++++++++--------------------- website/assets/home.js | 50 +++++++++++++-- website/assets/loadUrl.js | 91 ++++++++++++++++++++++----- website/public/index.html | 35 +++++++---- website/tests/loadUrl.test.mjs | 108 ++++++++++++++++++++++++++++++--- 5 files changed, 274 insertions(+), 111 deletions(-) diff --git a/website/README.md b/website/README.md index eaf4760c4..bccd07cc4 100644 --- a/website/README.md +++ b/website/README.md @@ -3,87 +3,44 @@ > [!TIP] > This demo website is deployed under https://structured-data-validator.jolicode.com/ -Static pages, that run the library in the browser: PHP is built as WebAssembly, with +Static pages that run the library in the browser: PHP is built as WebAssembly, with [lyrixx/php-wasm-builder](https://github.com/lyrixx/php-wasm-builder), and the library of this -repository embedded in it. GitHub Pages serves `public/`, deployed from `main` by +repository is embedded in it. GitHub Pages serves `public/`, deployed from `main` by `.github/workflows/website.yml`. -- The **homepage**, at `/`, has the form of the validator, and its examples. -- The **validator**, at `/validator/`, audits a document, and shows the result. -- The **JSON-LD playground**, at `/playground/`, runs the JSON-LD algorithms on a document: expand, - compact, flatten, frame, to RDF and from RDF. - -The validator comes from -[jolicode/structured-data-validator-demo](https://github.com/jolicode/structured-data-validator-demo), -without its server: the editor and the tree of the properties are its ones, with another look. -Fetching a URL needs a server, and is not here: a page can not read another website. Pretty-printing -the document is the "Format" button of the result: `assets/format.js` runs Prettier in the browser, -as its `bin/format-document.js` does in node. +Page | Path | What it does +---- | ---- | ---- +Homepage | `/` | The form of the validator, and its examples +Validator | `/validator/` | Audits a document, and shows the result +JSON-LD playground | `/playground/` | Runs the JSON-LD algorithms on a document ## How it works -`assets/php.js` loads PHP, and runs a script of `bin/`: the request is on its standard input, and its -answer on its standard output, as JSON. - -### The state of the pages - -The validator and the playground share a state: the document, and what the playground adds to it -(its tab, its context, its frame, its options). `assets/pageState.js` writes it: - -- in the fragment of the URL of the page, compressed by `assets/permalink.js`: a link to the page - opens it as it is, and its "Copy link" button copies this link; -- in the links of the menu: the validator opens the playground with its document, and the - playground the validator, that validates what was typed there. - -A state too long for a link is kept in the session storage of the tab, and the fragment is `#local`: -the pages still open each other, and reload, but "Copy link" is disabled. +- `assets/php.js` loads PHP and runs a script of `bin/`, with the request as JSON on its standard + input and the answer as JSON on its standard output: `bin/audit.php` for the validator, + `bin/playground.php` for the playground. +- `assets/home.js` runs the homepage, and `assets/controllers/` the two other pages. Both run PHP + again as the visitor types. +- `assets/pageState.js` keeps the document in the fragment of the URL: a link opens a page as it + is, and the validator and the playground open each other with the same document. A document too + long for a link is kept in the session storage instead. +- PHP has no network in the browser: `assets/jsonLd.js` fetches the remote contexts the playground + needs, from the websites that allow it with CORS headers. -### The validator +## Loading a page from its URL -- `public/index.html` is the homepage. `assets/home.js` opens the page of the validator with the - document of its form, or one of `assets/examples.js`. Nothing is audited there: PHP is only - fetched ahead. -- `public/validator/index.html` is the page of the validator. It holds the frame of the result, the - editor and the toolbar, that shows as the page opens: PHP has to start before it answers, and the - document is there meanwhile. `assets/controllers/result_controller.js` runs the page: it gives - the document the page is opened with to PHP, and shows what it answers in this frame. Without a - document, it goes back to the homepage. The document is audited again as it is typed, once the - visitor pauses, as in the playground: PHP runs in the thread of the page, so a document that - takes long to audit waits for a longer pause. -- `bin/audit.php` is what PHP runs: it audits the document, and renders what is found with Twig, - the counts of the toolbar, `templates/counts.html.twig`, and the entities, - `templates/result.html.twig`. The settings of the audit are the ones of who opens the page: they - are not in the link. +A browser can not read a website that does not allow it with CORS headers, and most do not. The +"Load" button of the homepage posts the URL to `/load-url` instead (`loadPage()` in +`assets/loadUrl.js`), where a proxy downloads the page. -### The playground +This proxy is not in this repository, and only exists on the deployed website. Elsewhere, a local +build or a fork, the browser loads the page itself, which only works for the websites that allow it. -- `public/playground/index.html` is the page, and `assets/controllers/playground_controller.js` what - runs it: the algorithm of the selected tab runs again as the visitor types, on the document, with - the context or the frame it needs, and the options it reads. -- `bin/playground.php` is what PHP runs: an algorithm, on what it is given. It answers with the - output, or the error code of the specification. -- `assets/jsonLd.js` loads the remote contexts. PHP has no network in the browser: when a document - needs a context that is not there, `bin/playground.php` answers that it is missing, - `assets/loadUrl.js` fetches it, and PHP is asked again with it. The website of the context has to - allow it, with CORS headers. The schema.org context is the one the library ships, and is never - fetched. -- `assets/playgroundExamples.js` holds the examples. - -Canonicalization (RDFC-1.0) is not there: the library does not implement it. - -### Every page - -- `assets/editor.js` is the CodeMirror editor of the validator and of the playground. -- The header, with its menu, is written in each page: there is no layout to share it. The links are - relative: the website works under any path. -- The footer is the JoliCode open-source one, [jolicode/oss-theme](https://github.com/jolicode/oss-theme): - `castor website:build` downloads it to `public/build/joli-footer.html`, and the homepage and the - playground load it. +What is pasted never leaves the browser: only the URL of a page to load is sent. ## Build it -Docker, node and [Castor](https://github.com/jolicode/castor) are needed. The tasks are in -`.castor/website.php`: +Docker, node and [Castor](https://github.com/jolicode/castor) are needed. Command | Description ---- | ----- @@ -91,8 +48,6 @@ Command | Description `castor website:check` | Checks, in node, that PHP boots, and runs the tests of `tests/` `castor website:serve` | Serves the website on http://localhost:9999 -`composer.json` declares the parent directory as a path repository: the website is built with the -code of the working directory, not with a release. Run `castor website:build` again after a change: -only the last step of the build of PHP runs again. - -A test file of `tests/` runs once it is listed in the `check()` task. +The website is built with the code of the working directory, not with a release: run +`castor website:build` again after a change. A new test file of `tests/` has to be listed in the +`check()` task of `.castor/website.php`. diff --git a/website/assets/home.js b/website/assets/home.js index 5ff8d7fe1..e82aeb9d6 100644 --- a/website/assets/home.js +++ b/website/assets/home.js @@ -1,17 +1,32 @@ // The homepage, public/index.html: its form, or one of its examples, opens the -// page of the validator with a document. Nothing is audited here. +// page of the validator with a document, pasted or loaded from a URL. Nothing +// is audited here. import { examples } from "./examples.js"; +import { loadPage } from "./loadUrl.js"; import { stateUrl } from "./pageState.js"; const form = document.querySelector("form"); const errorElement = form.querySelector("[data-validation-error]"); +const errorMessage = errorElement.querySelector("[data-validation-error-message]"); +const errorAdvice = errorElement.querySelector("[data-validation-error-advice]"); +// "Load", that loads the page of the URL, and "Validate" +const submitButtons = form.querySelectorAll('button[type="submit"]'); +const enableSubmitButtons = (enabled) => submitButtons.forEach((button) => (button.disabled = !enabled)); + +// No message hides the error. "pasteable" is a page that could not be loaded: +// the error advises to paste it, or to validate it elsewhere +function showError(message, pasteable = false) { + errorMessage.textContent = message; + errorAdvice.hidden = !pasteable; + errorElement.hidden = message === ""; +} // The validator reads the document in the fragment of its URL, or in the // session storage when it is too long for a URL: see pageState.js async function validate(body) { if (body.trim() === "") { - errorElement.textContent = "Please enter some code to validate."; + showError("Please enter some code to validate."); return; } @@ -19,17 +34,40 @@ async function validate(body) { const url = await stateUrl("validator/", { document: body }); if (!url.includes("#")) { - errorElement.textContent = "This document is too long for a link, and your browser gives this page no storage to hand it to the validator."; + showError("This document is too long for a link, and your browser gives this page no storage to hand it to the validator."); return; } - errorElement.textContent = ""; + showError(""); location.assign(url); } -form.addEventListener("submit", (event) => { +form.addEventListener("submit", async (event) => { event.preventDefault(); + + // The "Load" button, the one of the Enter key in the URL too: the page of + // the URL is the document + if (event.submitter?.hasAttribute("data-load-url")) { + showError(""); + enableSubmitButtons(false); + + try { + const { body, error, pasteable } = await loadPage(form.elements.url.value); + + if (error) { + showError(error, pasteable); + + return; + } + + // Shown in the form too: it is there when the visitor comes back + form.elements.body.value = body; + } finally { + enableSubmitButtons(true); + } + } + validate(form.elements.body.value); }); @@ -45,4 +83,4 @@ document.addEventListener("click", (event) => { }); // Until then, submitting would reload the page -form.querySelector('button[type="submit"]').disabled = false; +enableSubmitButtons(true); diff --git a/website/assets/loadUrl.js b/website/assets/loadUrl.js index e91e9ad8d..4fdf01e10 100644 --- a/website/assets/loadUrl.js +++ b/website/assets/loadUrl.js @@ -1,10 +1,15 @@ -// Loads the document of a URL, without the DOM: home.js wires it to the page, -// the playground loads the remote contexts of a document with it, see -// jsonLd.js, and tests/loadUrl.test.mjs tests it in node. +// Loads the document of a URL, without the DOM: home.js wires it to the +// homepage, the playground loads the remote contexts of a document with it, +// see jsonLd.js, and tests/loadUrl.test.mjs tests it in node. // // A browser only lets a page read another website when that website allows it, -// with CORS headers, and most do not. Loading any page needs a server, a CORS -// proxy: it would be a second try here, when the website refuses. +// with CORS headers, and most do not. The homepage loads a page with +// loadPage(), by the proxy of the website: a server, that any website answers +// to. The playground loads its contexts with loadUrl(), by the browser. + +// Where the proxy answers, on the host of the website. It is not part of this +// repository: see the README. +const PROXY = "/load-url"; // The one of bin/audit.php, that refuses a larger document const MAX_DOCUMENT_SIZE = 2 * 1024 * 1024; @@ -13,14 +18,66 @@ const TIMEOUT = 15_000; const INVALID_URL = "Please enter the URL of a page, starting with http:// or https://."; const TOO_LARGE = "This document is too large to be validated."; +const UNSUPPORTED = "This URL is neither a HTML page nor a JSON document."; +const httpStatus = (status) => `This page answered with the HTTP status ${status}.`; // fetch does not say whether the website refused, or the network failed. // Exported for the playground, that says it of a context, not of a page. -export const UNREADABLE = - "This page could not be read from your browser: most websites do not let another website read their pages. Paste its source code instead."; +export const UNREADABLE = "This URL could not be loaded."; +const UNAVAILABLE = "Loading a page is not available for now."; + +// The error of a page that is not loaded, though the validator may read it: +// the homepage advises to paste its source code, or to validate it elsewhere. +// A document the validator refuses, too large or not a page, is not one. +const pasteable = (error) => ({ error, pasteable: true }); + +// What the proxy answers when it does not load the page +const PROXY_ERRORS = { + forbidden_target: pasteable("This URL can not be loaded: only the public websites are, on their standard port."), + rate_limited: pasteable("Too many pages were loaded lately: try again in a minute."), + too_large: { error: TOO_LARGE }, + unreachable: pasteable(UNREADABLE), + unsupported_type: { error: UNSUPPORTED }, +}; // A page, or a JSON-LD document const ACCEPT = "text/html,application/ld+json,application/json;q=0.9,*/*;q=0.8"; +/** + * Resolves with the { body } of the page, or the { error } that says why it is + * not loaded, "pasteable" when pasting the page would work. The page is loaded + * by the proxy, or by the browser, as loadUrl() does, where there is no proxy: + * the website served by a static host alone. + */ +export async function loadPage(url) { + const target = httpUrl(url); + if (target === null) { + return { error: INVALID_URL }; + } + + const response = await fetch(PROXY, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ url: target }), + signal: AbortSignal.timeout(TIMEOUT), + }).catch(() => null); + + // The proxy signs what it answers: a static host answers a 404 or a 405 + // here, and some of them a page + if (response === null || !response.headers.has("X-Load-Url")) { + response?.body?.cancel().catch(() => {}); + + return loadUrl(target); + } + + if (!response.ok) { + const { error, status } = await response.json().catch(() => ({})); + + return error === "http_status" && Number.isInteger(status) ? pasteable(httpStatus(status)) : (PROXY_ERRORS[error] ?? pasteable(UNAVAILABLE)); + } + + return read(response, response.headers.get("X-Load-Url-Content-Type") ?? "", UNAVAILABLE); +} + /** * Resolves with the { body } of the document, or the { error } that says why * it is not loaded. "accept" is what is asked for: the playground asks for @@ -41,25 +98,31 @@ export async function loadUrl(url, { accept = ACCEPT } = {}) { }).catch(() => null); if (response === null) { - return { error: UNREADABLE }; + return pasteable(UNREADABLE); } const contentType = response.headers.get("Content-Type") ?? ""; if (!response.ok) { - return refuse(response, `This page answered with the HTTP status ${response.status}.`); + return refuse(response, pasteable(httpStatus(response.status))); } if (contentType && !/html|json|^text\//i.test(contentType)) { - return refuse(response, "This URL is neither a HTML page nor a JSON document."); + return refuse(response, { error: UNSUPPORTED }); } if (Number(response.headers.get("Content-Length")) > MAX_DOCUMENT_SIZE) { - return refuse(response, TOO_LARGE); + return refuse(response, { error: TOO_LARGE }); } + return read(response, contentType, UNREADABLE); +} + +// The document a response holds, served as "contentType". "failure" is the +// error of a download that stops halfway. +async function read(response, contentType, failure) { const buffer = await response.arrayBuffer().catch(() => null); if (buffer === null) { - return { error: UNREADABLE }; + return pasteable(failure); } if (buffer.byteLength > MAX_DOCUMENT_SIZE) { return { error: TOO_LARGE }; @@ -78,11 +141,11 @@ function httpUrl(url) { } } -function refuse(response, error) { +function refuse(response, refusal) { // Not downloaded any further response.body?.cancel().catch(() => {}); - return { error }; + return refusal; } // response.text() reads everything as UTF-8: the charset is the one of the diff --git a/website/public/index.html b/website/public/index.html index f3733f693..e0421b9dd 100644 --- a/website/public/index.html +++ b/website/public/index.html @@ -46,18 +46,22 @@

structured data

- Paste a HTML page or a JSON-LD document to check it against schema.org and the + Paste a HTML page or a JSON-LD document, or load a page from its URL, to check it against schema.org and the Google Rich Results requirements, in your browser with webassembly.

- diff --git a/website/tests/loadUrl.test.mjs b/website/tests/loadUrl.test.mjs index efa1145ee..5fe6a989d 100644 --- a/website/tests/loadUrl.test.mjs +++ b/website/tests/loadUrl.test.mjs @@ -1,12 +1,15 @@ import assert from 'node:assert/strict'; import { test } from 'node:test'; -import { loadUrl } from '../assets/loadUrl.js'; +import { loadPage, loadUrl } from '../assets/loadUrl.js'; -// Runs assets/loadUrl.js, what the "Load" button of the homepage runs, in -// node, with a fetch that answers what a website would. +// Runs assets/loadUrl.js in node, with a fetch that answers what a website +// would, and what the proxy of the website would: loadUrl() is what the +// playground loads a context with, and loadPage() what the "Load" button of +// the homepage runs. -const UNREADABLE = /could not be read from your browser/; +// "pasteable": the homepage advises to paste the page, or to validate it elsewhere +const UNREADABLE = { error: 'This URL could not be loaded.', pasteable: true }; // The fetch of node is an accessor, that t.mock.method() does not replace const fetches = (t, implementation) => { @@ -83,7 +86,7 @@ test('says that the page can not be read, when the website does not allow it', a throw new TypeError('Failed to fetch'); }); - assert.match((await loadUrl('https://example.com/')).error, UNREADABLE); + assert.deepEqual(await loadUrl('https://example.com/'), UNREADABLE); }); test('says that the page can not be read, when its download fails', async (t) => { @@ -94,13 +97,13 @@ test('says that the page can not be read, when its download fails', async (t) => }); answer(t, body, { headers: { 'Content-Type': 'text/html' } }); - assert.match((await loadUrl('https://example.com/')).error, UNREADABLE); + assert.deepEqual(await loadUrl('https://example.com/'), UNREADABLE); }); test('reports the HTTP status of a page that is not found', async (t) => { answer(t, 'Not found', { status: 404, headers: { 'Content-Type': 'text/html' } }); - assert.deepEqual(await loadUrl('https://example.com/nope'), { error: 'This page answered with the HTTP status 404.' }); + assert.deepEqual(await loadUrl('https://example.com/nope'), { error: 'This page answered with the HTTP status 404.', pasteable: true }); }); test('refuses what is neither a page nor a JSON document', async (t) => { @@ -120,3 +123,94 @@ test('refuses a document that is too large', async (t) => { assert.deepEqual(await loadUrl('https://example.com/'), { error: 'This document is too large to be validated.' }); }); + +// The proxy signs what it answers +const proxied = (body, init = {}) => new Response(body, { ...init, headers: { 'X-Load-Url': '1', ...init.headers } }); +const refusal = (status, answer) => proxied(JSON.stringify(answer), { status, headers: { 'Content-Type': 'application/json' } }); + +// Answers the proxy with "proxy", and the website of the page with "website" +const serves = (t, { proxy, website = () => new Response('

Direct

', { headers: { 'Content-Type': 'text/html' } }) }) => + fetches(t, async (url) => (url === '/load-url' ? proxy() : website())); + +test('loads a page by the proxy', async (t) => { + const fetch = serves(t, { proxy: () => proxied('

Hello

', { headers: { 'X-Load-Url-Content-Type': 'text/html; charset=utf-8' } }) }); + + assert.deepEqual(await loadPage(' https://example.com/page '), { body: '

Hello

' }); + + assert.equal(fetch.mock.callCount(), 1); + const [url, options] = fetch.mock.calls[0].arguments; + assert.equal(url, '/load-url'); + assert.equal(options.method, 'POST'); + assert.equal(options.headers['Content-Type'], 'application/json'); + assert.deepEqual(JSON.parse(options.body), { url: 'https://example.com/page' }); +}); + +test('decodes the page the proxy loads with the charset of the page', async (t) => { + serves(t, { proxy: () => proxied(Buffer.from('

café

', 'latin1'), { headers: { 'X-Load-Url-Content-Type': 'text/html; charset=ISO-8859-1' } }) }); + + assert.deepEqual(await loadPage('https://example.com/'), { body: '

café

' }); +}); + +for (const url of ['', 'jolicode.com', 'ftp://example.com/page', 'javascript:alert(1)']) { + test(`refuses the page "${url}" without asking the proxy`, async (t) => { + const fetch = answer(t, ''); + + assert.match((await loadPage(url)).error, /starting with http/); + assert.equal(fetch.mock.callCount(), 0); + }); +} + +// The last one is "pasteable": a page that the validator would read, once pasted +for (const [answered, expected, pasteable] of [ + [refusal(429, { error: 'rate_limited' }), /Too many pages were loaded lately/, true], + [refusal(422, { error: 'forbidden_target' }), /only the public websites are/, true], + [refusal(422, { error: 'http_status', status: 404 }), /^This page answered with the HTTP status 404\.$/, true], + [refusal(422, { error: 'unsupported_type' }), /neither a HTML page nor a JSON document/, false], + [refusal(422, { error: 'too_large' }), /too large to be validated/, false], + [refusal(422, { error: 'unreachable' }), /^This URL could not be loaded\.$/, true], + [refusal(403, { error: 'forbidden' }), /not available for now/, true], + [refusal(400, { error: 'invalid_request' }), /not available for now/, true], + [refusal(422, { error: 'http_status' }), /not available for now/, true], + [proxied('Oops', { status: 500 }), /not available for now/, true], +]) { + test(`says why the proxy does not load a page: ${answered.status} ${JSON.stringify(expected.source)}`, async (t) => { + const fetch = serves(t, { proxy: () => answered }); + const result = await loadPage('https://example.com/'); + + assert.match(result.error, expected); + assert.equal(result.pasteable ?? false, pasteable); + // The browser does not try by itself what the proxy refuses + assert.equal(fetch.mock.callCount(), 1); + }); +} + +test('refuses a page the proxy loads when it is too large', async (t) => { + serves(t, { proxy: () => proxied(new Uint8Array(2 * 1024 * 1024 + 1), { headers: { 'X-Load-Url-Content-Type': 'text/html' } }) }); + + assert.deepEqual(await loadPage('https://example.com/'), { error: 'This document is too large to be validated.' }); +}); + +for (const [name, proxy] of [ + ['a 404', () => new Response('Not found', { status: 404 })], + ['a 405', () => new Response('', { status: 405 })], + ['a page', () => new Response('

The homepage

', { headers: { 'Content-Type': 'text/html' } })], + ['nothing', () => Promise.reject(new TypeError('Failed to fetch'))], +]) { + test(`loads the page by the browser where there is no proxy, and ${name} answers`, async (t) => { + const fetch = serves(t, { proxy }); + + assert.deepEqual(await loadPage('https://example.com/page'), { body: '

Direct

' }); + + assert.equal(fetch.mock.callCount(), 2); + assert.equal(fetch.mock.calls[1].arguments[0], 'https://example.com/page'); + }); +} + +test('says that the page can not be read by the browser, where there is no proxy', async (t) => { + serves(t, { + proxy: () => new Response('', { status: 405 }), + website: () => Promise.reject(new TypeError('Failed to fetch')), + }); + + assert.deepEqual(await loadPage('https://example.com/'), UNREADABLE); +});