diff --git a/AGENTS.md b/AGENTS.md index 47b0d8ce..e3cbebbc 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -202,7 +202,8 @@ apps/demo/ the demo app: the dev server for the whole repository, demo/element.js is the one import of the element every page loads; demo/page-common.js what the player page, the cmi5 page and the app share: the message box, the log, `foreignHost` (whether a package is another - site's) and the trust prompt, one copy since 2026-10-15; + site's), `packageUrl` (the address the element is given) and the + trust prompt, one copy since 2026-10-15; demo/theme.js the light/dark switch, a classic script every page loads in its head before the stylesheet, since the CSP allows no inline script and a pinned theme has to be on before the @@ -2418,8 +2419,25 @@ SPA-fallback trap described above cannot happen there. partitioned by the embedding site, so a page only reaches what was played under its own embed; framed by this origin, or opened on its own, it plays untrusted like the rest, and a page that passes `askInOwnFrame: false` — a site's own preview — plays as it is. Every check fails closed: a - `data:` URL, with no host, counts as another site's. The rule stays: any package whose own code - runs on an origin can read every other package's data there. + `data:` URL, with no host, counts as another site's, and no page gives the element one (next + bullet). The rule stays: any package whose own code runs on an origin can read every other + package's data there. +- **A package address from a link, a field or a launch reaches `src` parsed, and only as `http` + or `https`** (2026-10-23, #71). `packageUrl` in `demo/page-common.js` for the player page, the cmi5 + page and the app; its copy in the embed page's `embed.js`; `webAddress` in + `@missing-elements/h5p-cmi5`, with the page's address as its base, which reports what it passes + over as `unsafe-src`. Each resolves the text with `new URL`, refuses any other scheme with a + message, and sets the parsed URL's `href`, never the text. The element fetches its `src` and + never navigates to it, so a `javascript:` address could not have run. But CodeQL cannot know + what the element does with `src`: it flagged every + `setAttribute('src', …)` fed by a link, a field or the launch under `js/xss`, + `js/xss-through-dom` and `js/client-side-unvalidated-url-redirection`, 22 alerts dismissed as + false positives from 2026-10-06 to -18, each filed again once a line around it moved. Its model of + `new URL(x)` carries taint into `search`, `hash` and `searchParams` alone, so the parsed URL's + `href` is clean to all three queries. A check on the text, such as `startsWith('https:')`, + satisfies `js/xss` only, and the redirect query accepts nothing short of a fixed host, which a + player of any host's packages cannot have. New code that sets `src` from outside takes the same + path, rather than another dismissal. - **Page views are counted by Vercel Web Analytics**, through `demo/analytics.js` in every page's head, including `/embed` and the app: `inject()` from `@vercel/analytics`, which loads `/_vercel/insights/script.js` from the site's own origin and reports to it, so the CSP needs no diff --git a/apps/demo/app/app.js b/apps/demo/app/app.js index 7d66bdb0..9bd3f8eb 100644 --- a/apps/demo/app/app.js +++ b/apps/demo/app/app.js @@ -12,7 +12,7 @@ * browser's or Android's, closes the file rather than leaving the app. */ -import { foreignHost, messageIn, trustPrompt } from '../demo/page-common.js' +import { foreignHost, messageIn, packageUrl, trustPrompt } from '../demo/page-common.js' import { pack } from '@missing-elements/h5p-libraries' import librariesNotice from '@missing-elements/h5p-libraries/libraries.txt?url' import { copyOf, fileKey, forget, forgetAll, linkKey, recentFiles, remember } from './recent.js' @@ -388,11 +388,9 @@ function linkName(url) { * another site plays untrusted unless the learner said otherwise: see `foreignHost`. */ async function openUrl(src, { libraries = PACK, title = null, trusted = !foreignHost(src) } = {}) { - let url - try { - url = new URL(src, location.href) - } catch { - show(`That is not a URL: ${src}`, 'error') + const url = packageUrl(src) + if (!url) { + show(`That is not an http or https address: ${src}`, 'error') return } const token = ++opens diff --git a/apps/demo/demo/cmi5-page.js b/apps/demo/demo/cmi5-page.js index a7eed987..bb2a1cce 100644 --- a/apps/demo/demo/cmi5-page.js +++ b/apps/demo/demo/cmi5-page.js @@ -11,7 +11,7 @@ * lands in the log instead. */ -import { foreignHost, logInto, trustPrompt } from './page-common.js' +import { foreignHost, logInto, packageUrl, trustPrompt } from './page-common.js' import { createCmi5Client, isCmi5Launch, startCmi5 } from '@missing-elements/h5p-cmi5' import { pack } from '@missing-elements/h5p-libraries' @@ -51,8 +51,13 @@ const play = (src) => { say('No package to play: add ?src= to the AU URL, or set launchParameters.') return } + const address = packageUrl(src) + if (!address) { + say(`That is not an http or https address: ${src}`) + return + } player.untrusted = foreignHost(src) !== null - player.setAttribute('src', src) + player.setAttribute('src', address.href) } /** Played untrusted, a package from another site needs its own code: the learner decides. */ diff --git a/apps/demo/demo/page-common.js b/apps/demo/demo/page-common.js index 48df4888..d6f38214 100644 --- a/apps/demo/demo/page-common.js +++ b/apps/demo/demo/page-common.js @@ -41,6 +41,21 @@ export const foreignHost = (src) => { } } +/** + * A package's address as the element is given it: resolved against this page, and only when it + * is `http` or `https`. `null` for anything else, a `javascript:` or `data:` URL or text that is + * not a URL, which the caller reports. The element gets the parsed URL's `href`, never the text, + * so `src` holds what was checked. + */ +export const packageUrl = (src) => { + try { + const url = new URL(src, location.href) + return url.protocol === 'http:' || url.protocol === 'https:' ? url : null + } catch { + return null + } +} + /** * The question before a package from another site plays with its own code. `ask(host, go)` shows * the box naming the host and runs `go` on the one click; a later `ask` replaces what was diff --git a/apps/demo/demo/player-page.js b/apps/demo/demo/player-page.js index d3f392e2..2932b49a 100644 --- a/apps/demo/demo/player-page.js +++ b/apps/demo/demo/player-page.js @@ -4,7 +4,7 @@ * no URL field, no file picker, no progress bar and no "open in another browser" banner. */ -import { foreignHost, logInto, messageIn, trustPrompt } from './page-common.js' +import { foreignHost, logInto, messageIn, packageUrl, trustPrompt } from './page-common.js' import { pack } from '@missing-elements/h5p-libraries' const player = document.querySelector('h5p-player') @@ -264,6 +264,11 @@ const applyMode = () => { /** Plays a package at a URL, in the switch's mode. */ const loadUrl = (url) => { + const address = packageUrl(url) + if (!address) { + show(`That is not an http or https address: ${url}`, 'error') + return + } log.textContent = '' trust.dismiss() reload = () => loadUrl(url) @@ -275,7 +280,7 @@ const loadUrl = (url) => { // player at once, through `idle`, which stops the clock: so the clock starts after it. player.removeAttribute('src') startClock() - player.setAttribute('src', url) + player.setAttribute('src', address.href) } const loadFile = (file) => { diff --git a/apps/demo/tests/app.test.ts b/apps/demo/tests/app.test.ts index ac0cae23..978e4ab0 100644 --- a/apps/demo/tests/app.test.ts +++ b/apps/demo/tests/app.test.ts @@ -536,6 +536,15 @@ it('plays a file dropped on it, and says what went wrong with a link that fails' await page.close() }) +it('refuses a link that is not http or https, and plays nothing', async () => { + const { page, errors } = await openApp(`/app/?src=${encodeURIComponent('javascript:alert(1)')}`) + await page.waitForFunction(() => !document.querySelector('#message')!.hidden) + expect(await seen(page)).toMatchObject({ screen: 'home', message: 'That is not an http or https address: javascript:alert(1)' }) + expect(await page.evaluate(() => document.querySelector('h5p-player')!.hasAttribute('src'))).toBe(false) + expect(errors).toEqual([]) + await page.close() +}) + it('gives the window’s title bar the page’s colour, in either theme', async () => { const { page } = await openApp() const color = () => page.evaluate(() => [...document.querySelectorAll('meta[name="theme-color"]')].map((meta) => meta.content)) diff --git a/docs/cmi5.md b/docs/cmi5.md index 874c18fe..e6724542 100644 --- a/docs/cmi5.md +++ b/docs/cmi5.md @@ -27,10 +27,13 @@ if (isCmi5Launch()) { The options of `startCmi5(player, options)`, detailed in the package's README: - `onEvent(event)` — told about each step: `initialized`, `sent`, `rejected` (with the LMS's - reason), `recorded`, `skipped`, `registration-unread`, `terminated`, `unsafe-return-url`. + reason), `recorded`, `skipped`, `registration-unread`, `terminated`, `unsafe-return-url`, + `unsafe-src`. - `src` — the package to play; by default the address's `?src=`, then the AU's - `launchParameters`. Pass `false` to set the element's `src` yourself, which a page anyone can - link to should do after checking the package's origin. + `launchParameters`. Only an `http` or `https` address is played, resolved against the page's; + anything else is an `unsafe-src` event, and the next source is tried. Pass `false` to set the + element's `src` yourself, which a page anyone can link to should do after checking the + package's origin. - `storage` — where the session is kept across a reload; default `null`. See *Credentials*. - `url` — the page's address, which the launch parameters and the default `src` are read from; default `location.href`. diff --git a/packages/cmi5/README.md b/packages/cmi5/README.md index 3ba2f80a..e90dc59e 100644 --- a/packages/cmi5/README.md +++ b/packages/cmi5/README.md @@ -69,8 +69,8 @@ window, and a framed page stays, so tell the learner to go back to the course. | Option | Default | What it is for | |---|---|---| -| `onEvent(event)` | none | Each step: `initialized`, `sent`, `rejected` (with the LMS's reason), `recorded`, `skipped` (Browse or Review mode, or already recorded), `registration-unread`, `terminated`, `unsafe-return-url` | -| `src` | the address's `src`, then `launchParameters` | The package; `false` leaves `src` to you. On a page anyone can link to, pass `false` and check the package's origin before setting `src` | +| `onEvent(event)` | none | Each step: `initialized`, `sent`, `rejected` (with the LMS's reason), `recorded`, `skipped` (Browse or Review mode, or already recorded), `registration-unread`, `terminated`, `unsafe-return-url`, `unsafe-src` | +| `src` | the address's `src`, then `launchParameters` | The package; `false` leaves `src` to you. Only an `http` or `https` address is played, resolved against the page's; anything else is an `unsafe-src` event. On a page anyone can link to, pass `false` and check the package's origin before setting `src` | | `storage` | `null` | Keeps the session across a reload; only for a trusted package and origin | | `client` | `createCmi5Client()` | A client of your own, such as a simulated LMS | diff --git a/packages/cmi5/src/index.ts b/packages/cmi5/src/index.ts index 09e8eb6f..9f3c4355 100644 --- a/packages/cmi5/src/index.ts +++ b/packages/cmi5/src/index.ts @@ -129,6 +129,8 @@ export type Cmi5Event = | { type: 'skipped'; reason: string } | { type: 'terminated' } | { type: 'unsafe-return-url'; value: string } + /** A package named by the address or the launch that is not an http or https address: not played. */ + | { type: 'unsafe-src'; value: string } /** The element, or anything that dispatches its `xapi` and `finished` events and takes `src`. */ export type PlayerLike = Pick & { @@ -143,7 +145,9 @@ export interface Cmi5Options { client?: Cmi5Client /** * The package to play. By default the `src` parameter of the page's address, then the AU's - * `launchParameters` from the launch data. `false` leaves the element's `src` alone. + * `launchParameters` from the launch data. `false` leaves the element's `src` alone. Only an + * http or https address reaches the element, resolved against `url`; anything else is an + * `unsafe-src` event, and the next source is tried. */ src?: string | false /** The page's address, for `src`; `location.href` by default. */ @@ -161,7 +165,7 @@ export interface Cmi5Session { readonly learnerPreferences: LearnerPreferences /** A reload picked this session up. */ readonly resumed: boolean - /** The package the element was given, or null when neither the address nor the launch named one. */ + /** The package the element was given, as an absolute address; null when neither the address nor the launch named one it plays. */ readonly src: string | null /** The launch data's `returnURL`, when it is an http or https address. */ readonly returnURL: string | null @@ -208,11 +212,15 @@ export function cmi5Score(score: Statement | undefined | null): Cmi5Score | unde return { scaled, ...(hasRange ? { raw: score.raw, min: typeof score.min === 'number' ? score.min : 0, max: score.max } : {}) } } -/** An absolute http or https address, or null: all a page may send a learner to. A `javascript:` return URL would run in the page. */ -export function webAddress(value: unknown): string | null { +/** + * An absolute http or https address, or null: all a page may send a learner to, or give the element + * as its package. A `javascript:` return URL would run in the page. With `base`, a relative address + * is resolved against it. + */ +export function webAddress(value: unknown, base?: string): string | null { if (typeof value !== 'string' || !value.trim()) return null try { - const url = new URL(value.trim()) + const url = new URL(value.trim(), base) return url.protocol === 'https:' || url.protocol === 'http:' ? url.href : null } catch { return null @@ -422,9 +430,17 @@ export async function startCmi5(player: PlayerLike, options: Cmi5Options = {}): readyPhase.stop() } + /** The package as the element is given it, resolved against the page's address; anything else is reported. */ + const playable = (value: string) => { + const address = webAddress(value, url || undefined) + if (!address) emit({ type: 'unsafe-src', value }) + return address + } + let src: string | null = null if (options.src !== false) { - src = options.src ?? readSrc(url) + const named = options.src ?? readSrc(url) + src = named ? playable(named) : null if (src) player.setAttribute('src', src) } @@ -446,8 +462,8 @@ export async function startCmi5(player: PlayerLike, options: Cmi5Options = {}): if (options.src !== false && !src) { const fromLaunch = data.launchParameters?.trim() if (fromLaunch) { - src = fromLaunch - player.setAttribute('src', src) + src = playable(fromLaunch) + if (src) player.setAttribute('src', src) } } diff --git a/packages/cmi5/tests/cmi5.test.ts b/packages/cmi5/tests/cmi5.test.ts index a223b7ce..405fe98d 100644 --- a/packages/cmi5/tests/cmi5.test.ts +++ b/packages/cmi5/tests/cmi5.test.ts @@ -136,6 +136,8 @@ describe('the pure parts', () => { expect(webAddress('javascript:alert(1)')).toBeNull() expect(webAddress('/relative')).toBeNull() expect(webAddress(undefined)).toBeNull() + expect(webAddress('quiz.h5p', 'https://au.example/au/')).toBe('https://au.example/au/quiz.h5p') + expect(webAddress('data:application/zip;base64,UEsFBg==', 'https://au.example/')).toBeNull() }) it('reads the LMS\'s reason out of a refusal', () => { @@ -362,6 +364,24 @@ describe('startCmi5', () => { expect(session.src).toBe('https://host/from-launch.h5p') }) + it('gives the element only an http or https package, resolved against the page', async () => { + const relative = new FakePlayer() + await startCmi5(relative, { client: fakeClient().client, storage: null, url: 'https://au.example/au/?src=quiz.h5p' }) + expect(relative.src).toBe('https://au.example/au/quiz.h5p') + + // The address's is reported and passed over; the launch's is held to the same rule. + const { client } = fakeClient({ launchParameters: 'javascript:alert(2)' }) + const player = new FakePlayer() + const events: Cmi5Event[] = [] + const session = await startCmi5(player, { client, storage: null, url: 'https://au.example/?src=javascript:alert(1)', onEvent: (e) => events.push(e) }) + expect(events.filter((e) => e.type === 'unsafe-src')).toEqual([ + { type: 'unsafe-src', value: 'javascript:alert(1)' }, + { type: 'unsafe-src', value: 'javascript:alert(2)' } + ]) + expect(player.src).toBeNull() + expect(session.src).toBeNull() + }) + it('passes the content\'s own verdict on when the launch has no mastery score', async () => { const { client, calls } = fakeClient({ masteryScore: undefined }) const events: Cmi5Event[] = [] diff --git a/packages/embed/README.md b/packages/embed/README.md index 21d0f7be..45bbbe01 100644 --- a/packages/embed/README.md +++ b/packages/embed/README.md @@ -77,7 +77,7 @@ To update, run the command again with `--force` and redeploy. | Parameter | Effect | |---|---| -| `src=` | The package, required. Encode `&`, `#`, `+`, `%` and spaces | +| `src=` | The package, required: an `http` or `https` URL, or a path on the player domain. Encode `&`, `#`, `+`, `%` and spaces | | `libraries=pack`, `` or `none` | Where libraries come from; several are tried in order. `pack` is this domain's copy, or jsDelivr's without one: a package gets the libraries it lacks from it, and those it carries at the pack's newer versions. `none` turns off `--default-libraries` | | `refresh-libraries=off` | Play the libraries a package carries as exported; `pack` then only fills gaps | | `frame`, `copyright`, `export`, `icon`, `reporting` | H5P's action bar and its buttons | diff --git a/packages/embed/site/embed.js b/packages/embed/site/embed.js index a9dff130..88403900 100644 --- a/packages/embed/site/embed.js +++ b/packages/embed/site/embed.js @@ -256,6 +256,22 @@ export function startEmbed({ packBase = null, pack = null, librariesPack = null, } } + /** + * A package's address as the element is given it: resolved against this page, and only when it + * is `http` or `https`. `null` for anything else, a `javascript:` or `data:` URL or text that is + * not a URL. The element gets the parsed URL's `href`, never the text, so `src` holds what was + * checked. + * @param {string} value + */ + const packageUrl = (value) => { + try { + const url = new URL(value, location.href) + return url.protocol === 'http:' || url.protocol === 'https:' ? url : null + } catch { + return null + } + } + const allowed = packages ? new Set(packages) : null /** * Whether this player was told it may fetch from `origin`. Always true without a list. @@ -355,11 +371,12 @@ export function startEmbed({ packBase = null, pack = null, librariesPack = null, refuse('No package given. Add ?src= to the address.', 'no-src') return } - const origin = urlOrigin(src) - if (!origin) { - refuse('The package address is not a URL.') + const address = packageUrl(src) + if (!address) { + refuse('The package address is not an http or https URL.') return } + const { origin } = address if (!permitted(origin)) { refuse(`This player does not play packages from ${origin}.`) return @@ -375,14 +392,14 @@ export function startEmbed({ packBase = null, pack = null, librariesPack = null, // A host on the list was vouched for when the site was set up, and in another site's frame the // storage is that site's own: those play as they are. if (origin === location.origin || allowed || !sharesOriginStorage()) { - start(src, sources.value) + start(address.href, sources.value) return } // Anything else from another origin would share this origin's storage. It plays untrusted, as // data with the library pack's code and none of its own, and waits for a click that names the // host only when it cannot play without its own, or there is no pack to play it with. - const host = new URL(src, location.href).host || origin + const { host } = address askToTrust = () => { loader.hidden = true const button = document.createElement('button') @@ -393,7 +410,7 @@ export function startEmbed({ packBase = null, pack = null, librariesPack = null, loader.hidden = false player.untrusted = false player.removeAttribute('src') - start(src, sources.value) + start(address.href, sources.value) }) say( `This package from ${host} plays only with its own scripts. They would run on this site and ` + @@ -411,5 +428,5 @@ export function startEmbed({ packBase = null, pack = null, librariesPack = null, return } player.untrusted = true - start(src, sitesSources) + start(address.href, sitesSources) } diff --git a/packages/embed/tests/site.test.ts b/packages/embed/tests/site.test.ts index 80af6949..ceee2706 100644 --- a/packages/embed/tests/site.test.ts +++ b/packages/embed/tests/site.test.ts @@ -357,6 +357,17 @@ describe('a written site, framed from another site', () => { await page.close() }) + it('refuses a package address that is not http or https, and gives the element nothing', async () => { + const page = await browser.newPage() + for (const src of ['javascript:alert(1)', 'data:application/zip;base64,UEsFBg==']) { + await page.goto(`${open.origin}/?src=${encodeURIComponent(src)}`) + await page.waitForSelector('#notice:not([hidden])') + expect(await page.textContent('#notice')).toBe('The package address is not an http or https URL.') + expect(await page.evaluate(() => document.querySelector('h5p-player')!.getAttribute('src'))).toBeNull() + } + await page.close() + }) + it('plays a package from elsewhere untrusted when opened on its own, with no question', async () => { const page = await browser.newPage() await page.goto(`${open.origin}/?src=${embedding.origin}/quiz.h5p`)