From ce7f4ebd870eff6de503a378f6279b697df3ff3c Mon Sep 17 00:00:00 2001 From: Augustine Kim Date: Mon, 16 Nov 2026 17:09:46 -0800 Subject: [PATCH 1/4] fix(project)!: don't fetch when loading the config property Setting the `config` property on or used to fetch any file listed without `content`, follow `extends`, and adopt `cdnBaseUrl` from the config. The `config` property is the documented way to load a shared project, so a config from an untrusted source (e.g. decoded from a URL) could make the host page fetch arbitrary URLs with the user's credentials. The responses became project files, which code running in the preview could then read. The `config` property now only uses files with inline string `content` and the `importMap`. Files without `content`, `extends`, and `cdnBaseUrl` are ignored with a console warning, and malformed file entries are skipped instead of throwing. Manifests loaded with `project-src` are unchanged. BREAKING CHANGE: configs set through the `config` property that rely on fetched files, `extends`, or `cdnBaseUrl` must be loaded with `project-src` instead, with the CDN set through the `cdnBaseUrl` property or `cdn-base-url` attribute. --- CHANGELOG.md | 15 +- README.md | 28 ++- src/playground-ide.ts | 7 + src/playground-project.ts | 78 +++++- src/shared/worker-api.ts | 16 +- src/test/playground-project-config_test.ts | 278 +++++++++++++++++++++ 6 files changed, 407 insertions(+), 15 deletions(-) create mode 100644 src/test/playground-project-config_test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index d7e9d576..46fbc1b3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,7 +12,20 @@ and this project adheres to [Semantic Versioning](http://semver.org/). - +## [Unreleased] + +### Changed + +- **BREAKING** (security) Setting the `config` property on `` + or `` no longer fetches anything to load the config. + Files without inline `content`, `extends`, and `cdnBaseUrl` are now ignored + with a console warning. Previously, a config from an untrusted source (e.g. a + shared URL) could make the host page fetch arbitrary URLs with the user's + credentials and expose the responses to code running in the preview. + + To migrate, load manifests that rely on fetched files or `extends` with + `project-src`, and set the CDN with the `cdnBaseUrl` property or + `cdn-base-url` attribute. Manifests loaded with `project-src` are unchanged. ## [0.21.3] - 2026-11-17 diff --git a/README.md b/README.md index a2db26ad..41f3bf13 100644 --- a/README.md +++ b/README.md @@ -240,13 +240,24 @@ Set the `project-src` attribute or `projectSrc` property to a JSON file with for ### Option 3: Config property In JavaScript, directly set the `config` property to an object. The format is -identical to the JSON config file. +the same as the JSON config file, except that nothing is fetched to load it: + +- Every file must have inline `content`. Files without `content` are ignored. +- `extends` is ignored. +- `cdnBaseUrl` is ignored. Set the `cdnBaseUrl` property or `cdn-base-url` + attribute on the element instead. + +A warning is logged to the console when something is ignored. Use +[`project-src`](#option-2-json-configuration) for a manifest that needs any of +these. ```js const ide = document.querySelector('playground-ide'); ide.config = { files: { - 'index.html': {}, + 'index.html': { + content: '', + }, 'typescript.ts': { content: "console.log('hello');", }, @@ -254,6 +265,12 @@ ide.config = { }; ``` +> The `config` property is restricted in this way because it is the usual way +> to load a project from untrusted input, such as a [shared +> URL](#how-do-i-save-and-share-a-project). If it fetched files, then whoever +> wrote the config could make your page request any URL with your user's +> credentials, and read the response from the preview. + If both `project-src` and `config` are set, then the one set most recently has precedence. When either are set, inline scripts are ignored. @@ -1073,6 +1090,13 @@ Use the `config` property of a `` or `` to get or set the current state of the project ([details](#option-3-config-property)). +The value returned by `config` contains every file's content inline, so it can +be serialized and set again later. Setting `config` does not fetch project +files or other manifests, so a config from an untrusted source cannot have your +page fetch a URL and expose the response to the preview. The code in the +project is still untrusted, so see [sandbox security](#sandbox-security) if you +change the sandbox base URL. + How you persist and retrieve serialized project state is up to you. Here are a few ideas: diff --git a/src/playground-ide.ts b/src/playground-ide.ts index ed25f439..f35ced17 100644 --- a/src/playground-ide.ts +++ b/src/playground-ide.ts @@ -170,6 +170,13 @@ export class PlaygroundIde extends LitElement { /** * Get or set the project config. * + * Setting this property does not fetch project files or other manifests, + * because it is commonly populated from untrusted input (e.g. a shared + * URL). Only files with inline string `content` and the `importMap` are + * used. Files without `content`, `extends`, and `cdnBaseUrl` are ignored + * with a console warning; use `projectSrc` for manifests that need those, + * and the `cdnBaseUrl` property to change the CDN. + * * When both `projectSrc` and `config` are set, the one set most recently * wins. Slotted children win only if both `projectSrc` and `config` are * undefined. diff --git a/src/playground-project.ts b/src/playground-project.ts index 906c86f3..484ce53f 100644 --- a/src/playground-project.ts +++ b/src/playground-project.ts @@ -10,6 +10,7 @@ import {wrap, Remote, proxy} from 'comlink'; import { SampleFile, + FileOptions, ServiceWorkerAPI, ProjectManifest, PlaygroundMessage, @@ -97,6 +98,13 @@ export class PlaygroundProject extends LitElement { /** * Get or set the project config. * + * Setting this property does not fetch project files or other manifests, + * because it is commonly populated from untrusted input (e.g. a shared + * URL). Only files with inline string `content` and the `importMap` are + * used. Files without `content`, `extends`, and `cdnBaseUrl` are ignored + * with a console warning; use `projectSrc` for manifests that need those, + * and the `cdnBaseUrl` property to change the CDN. + * * When both `projectSrc` and `config` are set, the one set most recently * wins. Slotted children win only if both `projectSrc` and `config` are * undefined. @@ -354,18 +362,13 @@ export class PlaygroundProject extends LitElement { break; case 'direct': { - const {files, importMap} = await expandProjectConfig( - source.config, - document.baseURI - ); - // Note the source could have changed while fetching, hence the - // double-check here. - if (source !== this._source) { - return; - } + // A config set directly is treated as untrusted, so unlike the + // 'url' case below, it must never cause this page to make network + // requests or change where the worker fetches from. + const {files, importMap} = readDirectProjectConfig(source.config); this._files = files; this._importMap = importMap; - this._configCdnBaseUrl = source.config.cdnBaseUrl; + this._configCdnBaseUrl = undefined; } break; case 'slot': @@ -837,6 +840,61 @@ const fetchProjectConfig = async ( }; }; +/** + * Reads a project config that was set directly through the `config` property. + * + * Such configs often come from untrusted input (e.g. decoded from a shared + * URL), so unlike `expandProjectConfig` this never makes network requests. + * Otherwise, whoever controls the config could have this page fetch any URL + * with the user's credentials and then read the response from the preview. + * + * Only files with inline string content and the import map are used. + * Everything that would be fetched or that changes where we fetch from is + * ignored with a warning: files without content, `extends`, and `cdnBaseUrl`. + */ +const readDirectProjectConfig = ( + config: ProjectManifest +): { + files: Array; + importMap: ModuleImportMap; +} => { + const ignored: string[] = []; + if (config.extends !== undefined) { + ignored.push('"extends"'); + } + if (config.cdnBaseUrl !== undefined) { + ignored.push('"cdnBaseUrl" (set the cdnBaseUrl property instead)'); + } + const files: Array = []; + // Note the values here are not guaranteed to match our types, because the + // config may have been parsed from arbitrary JSON. + const entries: Array<[string, Partial | null | undefined]> = + typeof config.files === 'object' && config.files !== null + ? Object.entries(config.files) + : []; + for (const [filename, info] of entries) { + const content = info?.content; + if (typeof content !== 'string') { + ignored.push(`file "${filename}" (no inline string "content")`); + continue; + } + files.push({ + ...info, + name: filename, + content, + contentType: typeFromFilename(filename) ?? 'text/plain', + }); + } + if (ignored.length > 0) { + console.warn( + `[playground-project] The config property does not fetch, so these ` + + `were ignored: ${ignored.join(', ')}. ` + + `Load the manifest with project-src if it needs them.` + ); + } + return {files, importMap: config.importMap ?? {}}; +}; + /** * Expands a partial project config by following its `extends` property, and * fetching the content for all files. diff --git a/src/shared/worker-api.ts b/src/shared/worker-api.ts index f3931238..9d6c5fcd 100755 --- a/src/shared/worker-api.ts +++ b/src/shared/worker-api.ts @@ -167,7 +167,11 @@ export interface SampleFile { } export interface FileOptions { - /** Optional file content. If omitted, files are fetched by name. */ + /** + * Optional file content. If omitted, files are fetched by name when the + * manifest is loaded with `project-src`. Required for files in a config set + * through the `config` property, which never fetches files. + */ content?: string; /** * Optional content MIME type. If omitted, type is taken from fetch @@ -183,10 +187,18 @@ export interface FileOptions { } export interface ProjectManifest { - /** Optional project manifest URL to extend from */ + /** + * Optional project manifest URL to extend from. Only applies to manifests + * loaded with `project-src`; ignored in the `config` property. + */ extends?: string; files?: {[filename: string]: FileOptions}; importMap?: ModuleImportMap; + /** + * Optional npm CDN base URL. Only applies to manifests loaded with + * `project-src`; ignored in the `config` property (set the `cdnBaseUrl` + * property on the element instead). + */ cdnBaseUrl?: string; } diff --git a/src/test/playground-project-config_test.ts b/src/test/playground-project-config_test.ts new file mode 100644 index 00000000..ffd2a295 --- /dev/null +++ b/src/test/playground-project-config_test.ts @@ -0,0 +1,278 @@ +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: BSD-3-Clause + */ + +import {assert} from '@esm-bundle/chai'; +import {PlaygroundProject} from '../playground-project.js'; +import '../playground-project.js'; +import {ProjectManifest} from '../shared/worker-api.js'; + +/** + * The `config` property is commonly set from untrusted input (e.g. a shared + * URL), so it must never make this page fetch something on behalf of the + * config. These tests check that, and that `project-src` still does fetch. + */ +suite('playground-project config property', () => { + let container: HTMLDivElement; + let realFetch: typeof window.fetch; + let realWarn: typeof console.warn; + /** Absolute URLs of every fetch made by this page during the test. */ + let fetched: string[]; + /** Fake responses by absolute URL. Anything else goes to the network. */ + let responses: Map; + /** Warnings logged by playground-project during the test. */ + let warnings: string[]; + + const absolute = (url: string) => new URL(url, document.baseURI).href; + + setup(() => { + container = document.createElement('div'); + document.body.appendChild(container); + fetched = []; + responses = new Map(); + warnings = []; + + realFetch = window.fetch; + window.fetch = (input: RequestInfo | URL, init?: RequestInit) => { + const url = absolute( + input instanceof Request ? input.url : String(input) + ); + fetched.push(url); + const fake = responses.get(url); + if (fake !== undefined) { + return Promise.resolve( + new Response(fake.body, { + status: 200, + headers: {'Content-Type': fake.contentType}, + }) + ); + } + return realFetch(input, init); + }; + + realWarn = console.warn; + console.warn = (...args: unknown[]) => { + const message = args.join(' '); + if (message.startsWith('[playground-project]')) { + warnings.push(message); + } else { + realWarn(...args); + } + }; + }); + + teardown(() => { + window.fetch = realFetch; + console.warn = realWarn; + container.remove(); + }); + + /** + * Create a project, apply the given source to it, and wait until its files + * have loaded. + */ + const loadProject = async ( + setSource: (project: PlaygroundProject) => void + ): Promise => { + const project = document.createElement('playground-project'); + project.sandboxBaseUrl = '/'; + const loaded = new Promise((resolve) => { + project.addEventListener('filesChanged', (event) => { + if (event.projectLoaded) { + resolve(); + } + }); + }); + setSource(project); + container.appendChild(project); + await loaded; + return project; + }; + + const loadConfig = (config: unknown) => + loadProject((project) => { + project.config = config as ProjectManifest; + }); + + const filenames = (project: PlaygroundProject) => + (project.files ?? []).map((file) => file.name); + + const effectiveCdnBaseUrl = (project: PlaygroundProject) => + ( + project as unknown as {_getEffectiveCdnBaseUrl(): string} + )._getEffectiveCdnBaseUrl(); + + const assertNothingFetchedMatching = (marker: string) => { + assert.deepEqual( + fetched.filter((url) => url.includes(marker)), + [] + ); + }; + + test('loads files with inline content', async () => { + const project = await loadConfig({ + files: { + 'index.html': {content: '

hi

', label: 'Home', selected: true}, + 'empty.js': {content: ''}, + 'hidden.css': {content: 'p {}', hidden: true}, + }, + }); + assert.deepEqual(project.files, [ + { + name: 'index.html', + content: '

hi

', + contentType: 'text/html; charset=utf-8', + label: 'Home', + selected: true, + }, + { + name: 'empty.js', + content: '', + contentType: 'application/javascript; charset=utf-8', + }, + { + name: 'hidden.css', + content: 'p {}', + contentType: 'text/css; charset=utf-8', + hidden: true, + }, + ]); + assert.deepEqual(warnings, []); + }); + + test('a serialized config can be loaded again', async () => { + const first = await loadConfig({ + files: { + 'index.html': {content: '

hi

', selected: true}, + 'a.ts': {content: 'export const a = 1;', hidden: true}, + }, + importMap: {imports: {foo: 'https://example.com/foo.js'}}, + }); + const serialized = JSON.stringify(first.config); + const second = await loadConfig(JSON.parse(serialized)); + assert.deepEqual(second.files, first.files); + assert.deepEqual(second.config, first.config); + assert.deepEqual(warnings, []); + }); + + test('does not fetch files that have no content', async () => { + const project = await loadConfig({ + files: { + 'index.html': {content: 'hello'}, + 'no-fetch-marker/relative.txt': {}, + '/no-fetch-marker/root-relative.txt': {}, + [absolute('/no-fetch-marker/absolute.txt')]: {}, + 'no-fetch-marker/undefined.txt': {content: undefined}, + }, + }); + assert.deepEqual(filenames(project), ['index.html']); + assertNothingFetchedMatching('no-fetch-marker'); + assert.equal(warnings.length, 1); + assert.include(warnings[0], 'no-fetch-marker/relative.txt'); + assert.include(warnings[0], '/no-fetch-marker/root-relative.txt'); + assert.include(warnings[0], 'no-fetch-marker/absolute.txt'); + assert.include(warnings[0], 'no-fetch-marker/undefined.txt'); + }); + + test('does not follow extends', async () => { + responses.set(absolute('/no-fetch-marker/base.json'), { + body: JSON.stringify({files: {'inherited.txt': {content: 'inherited'}}}), + contentType: 'application/json', + }); + const project = await loadConfig({ + extends: '/no-fetch-marker/base.json', + files: {'index.html': {content: 'hello'}}, + }); + assert.deepEqual(filenames(project), ['index.html']); + assertNothingFetchedMatching('no-fetch-marker'); + assert.equal(warnings.length, 1); + assert.include(warnings[0], '"extends"'); + }); + + test('does not use cdnBaseUrl from the config', async () => { + const project = await loadConfig({ + cdnBaseUrl: absolute('/no-fetch-marker/api#'), + files: {'index.html': {content: 'hello'}}, + }); + assert.equal(effectiveCdnBaseUrl(project), 'https://unpkg.com'); + assert.equal(warnings.length, 1); + assert.include(warnings[0], '"cdnBaseUrl"'); + }); + + test('cdnBaseUrl property still applies with a config', async () => { + const project = await loadProject((p) => { + p.cdnBaseUrl = 'https://cdn.example.com/npm'; + p.config = {files: {'index.html': {content: 'hello'}}}; + }); + assert.equal(effectiveCdnBaseUrl(project), 'https://cdn.example.com/npm'); + assert.deepEqual(warnings, []); + }); + + test('ignores malformed file entries', async () => { + const project = await loadConfig( + JSON.parse(`{ + "files": { + "index.html": {"content": "hello"}, + "no-fetch-marker/null.txt": null, + "no-fetch-marker/string.txt": "not an object", + "no-fetch-marker/number.txt": 1, + "no-fetch-marker/null-content.txt": {"content": null}, + "no-fetch-marker/number-content.txt": {"content": 1}, + "no-fetch-marker/object-content.txt": {"content": {}} + } + }`) + ); + assert.deepEqual(filenames(project), ['index.html']); + assertNothingFetchedMatching('no-fetch-marker'); + assert.equal(warnings.length, 1); + }); + + test('tolerates a malformed files property', async () => { + for (const files of [null, 'not an object', 1]) { + const project = await loadConfig({files}); + assert.deepEqual(filenames(project), []); + } + }); + + test('project-src still fetches files, extends, and cdnBaseUrl', async () => { + responses.set(absolute('/fetch-marker/project.json'), { + body: JSON.stringify({ + extends: 'base.json', + cdnBaseUrl: 'https://cdn.example.com/npm', + files: { + 'index.html': {}, + 'inline.txt': {content: 'inline'}, + }, + }), + contentType: 'application/json', + }); + responses.set(absolute('/fetch-marker/index.html'), { + body: 'fetched', + contentType: 'text/html', + }); + responses.set(absolute('/fetch-marker/base.json'), { + body: JSON.stringify({files: {'inherited.txt': {content: 'inherited'}}}), + contentType: 'application/json', + }); + const project = await loadProject((p) => { + p.projectSrc = '/fetch-marker/project.json'; + }); + assert.deepEqual( + (project.files ?? []).map(({name, content}) => ({name, content})), + [ + {name: 'index.html', content: 'fetched'}, + {name: 'inline.txt', content: 'inline'}, + {name: 'inherited.txt', content: 'inherited'}, + ] + ); + assert.includeMembers(fetched, [ + absolute('/fetch-marker/project.json'), + absolute('/fetch-marker/index.html'), + absolute('/fetch-marker/base.json'), + ]); + assert.equal(effectiveCdnBaseUrl(project), 'https://cdn.example.com/npm'); + assert.deepEqual(warnings, []); + }); +}); From 8bb04cf0796813d85fd3e10a39cd66f885499af5 Mon Sep 17 00:00:00 2001 From: Augustine Kim Date: Mon, 23 Nov 2026 14:19:11 -0800 Subject: [PATCH 2/4] Give the config property a narrower type The config property now has its own type, ProjectConfig, instead of ProjectManifest. It requires inline content for every file and has no extends or cdnBaseUrl, which the setter does not support. Setting them in a config object literal is now a compile error in TypeScript, rather than only a console warning at runtime. The runtime handling stays, because configs parsed from JSON bypass the type. ProjectManifest goes back to describing only manifests loaded with project-src. The README and changelog now describe the config format in its own terms, and say that these are not allowed rather than ignored. --- CHANGELOG.md | 18 ++++++--- README.md | 39 +++++++++++--------- src/playground-ide.ts | 15 ++++---- src/playground-project.ts | 18 ++++++--- src/shared/worker-api.ts | 43 +++++++++++++++------- src/test/cdn-base-url_test.ts | 4 +- src/test/playground-project-config_test.ts | 19 +++++++++- 7 files changed, 101 insertions(+), 55 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 46fbc1b3..c4c664d3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,12 +16,18 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ### Changed -- **BREAKING** (security) Setting the `config` property on `` - or `` no longer fetches anything to load the config. - Files without inline `content`, `extends`, and `cdnBaseUrl` are now ignored - with a console warning. Previously, a config from an untrusted source (e.g. a - shared URL) could make the host page fetch arbitrary URLs with the user's - credentials and expose the responses to code running in the preview. +- **BREAKING** (security) Files without inline `content`, `extends`, and + `cdnBaseUrl` are no longer allowed in the `config` property of + `` and ``, so that setting `config` does + not fetch project files or other manifests, or change the CDN. The type of + the property is now `ProjectConfig`, which does not have them. If they are + set anyway, they are dropped with a console warning: such files and any + files inherited through `extends` will be missing from the project, and the + CDN falls back to the element's `cdnBaseUrl`, or to unpkg.com. + + Previously, a config from an untrusted source (e.g. a shared URL) could make + the host page fetch arbitrary URLs with the user's credentials and expose the + responses to code running in the preview. To migrate, load manifests that rely on fetched files or `extends` with `project-src`, and set the CDN with the `cdnBaseUrl` property or diff --git a/README.md b/README.md index 41f3bf13..8e501811 100644 --- a/README.md +++ b/README.md @@ -239,17 +239,18 @@ Set the `project-src` attribute or `projectSrc` property to a JSON file with for ### Option 3: Config property -In JavaScript, directly set the `config` property to an object. The format is -the same as the JSON config file, except that nothing is fetched to load it: - -- Every file must have inline `content`. Files without `content` are ignored. -- `extends` is ignored. -- `cdnBaseUrl` is ignored. Set the `cdnBaseUrl` property or `cdn-base-url` - attribute on the element instead. - -A warning is logged to the console when something is ignored. Use -[`project-src`](#option-2-json-configuration) for a manifest that needs any of -these. +In JavaScript, directly set the `config` property to an object with format +(`ProjectConfig` in TypeScript, exported from +`playground-elements/shared/worker-api.js`): + +| Property | Description | +| ---------------- | ----------------------------------------------------------------------------------------------------------------- | +| `files` | An object mapping filenames to file data. | +| `files.content` | Required text content of the file. | +| `files.label` | Optional label for display in `playground-tab-bar`. If omitted, the filename is displayed. | +| `files.hidden` | If `true`, the file won't be visible in `playground-tab-bar`. | +| `files.selected` | If `true`, this file's tab will be selected when the project is loaded. Only one file should have this field set. | +| `importMap` | Optional [import map](#import-maps). | ```js const ide = document.querySelector('playground-ide'); @@ -265,11 +266,13 @@ ide.config = { }; ``` -> The `config` property is restricted in this way because it is the usual way -> to load a project from untrusted input, such as a [shared -> URL](#how-do-i-save-and-share-a-project). If it fetched files, then whoever -> wrote the config could make your page request any URL with your user's -> credentials, and read the response from the preview. +Setting `config` does not fetch project files or other manifests, and a config +cannot change the CDN, which makes it suitable for loading a project from +untrusted input, such as a [shared URL](#how-do-i-save-and-share-a-project). A +project that needs fetched files or `extends` must be loaded with +[`project-src`](#option-2-json-configuration) instead, and the CDN is set with +the `cdnBaseUrl` property or `cdn-base-url` attribute. Files without `content`, +`extends` and `cdnBaseUrl` in a config are ignored with a console warning. If both `project-src` and `config` are set, then the one set most recently has precedence. When either are set, inline scripts are ignored. @@ -753,7 +756,7 @@ All-in-one project, editor, file switcher, and preview with a horizontal side-by | Name | Type | Default | Description | | -------------------- | -------------------------------- | ------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `projectSrc` | `string` | `undefined` | URL of the [project manifest](#project-manifest) to load | -| `config` | `ProjectManifest` | `undefined` | Get or set the project configuration and files, ([details](#option-3-config-property)). | +| `config` | `ProjectConfig` | `undefined` | Get or set the project configuration and files, ([details](#option-3-config-property)). | | `cdnBaseUrl` | `string` | `""` | Change the underlying npm CDN base url. Confirmed tested are `htts://unpkg.com` and `https://cdn.jsdelivr.net/npm`. Note: Default `""` resolves to `https://unpkg.com` | | `lineNumbers` | `boolean` | `false` | Render a gutter with line numbers in the editor | | `lineWrapping` | `boolean` | `false` | If `true`, long lines are wrapped, otherwise the editor will scroll. | @@ -786,7 +789,7 @@ project element. | Name | Type | Default | Description | | ---------------- | ----------------------------- | ------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `projectSrc` | `string` | `undefined` | URL of a [project files manifest](#option-2-json-manifest) to load. | -| `config` | `ProjectManifest` | `undefined` | Get or set the project configuration and files, ([details](#option-3-config-property)). | +| `config` | `ProjectConfig` | `undefined` | Get or set the project configuration and files, ([details](#option-3-config-property)). | | `cdnBaseUrl` | `string` | `""` | Change the underlying npm CDN base url. Confirmed tested are `htts://unpkg.com` and `https://cdn.jsdelivr.net/npm`. Note: Default `""` resolves to `https://unpkg.com` | | `sandboxScope` | `string` | `"playground-elements"` | The service worker scope to register on. | | `sandboxBaseUrl` | `string` | _module parent directory_ | Base URL for untrusted JavaScript execution (⚠️ use with caution, see [sandbox security](#sandbox-security)). Resolved relative to the module containing the definition of ``. | diff --git a/src/playground-ide.ts b/src/playground-ide.ts index f35ced17..6646a450 100644 --- a/src/playground-ide.ts +++ b/src/playground-ide.ts @@ -13,7 +13,7 @@ import './playground-tab-bar.js'; import './playground-file-editor.js'; import './playground-preview.js'; import {PlaygroundProject} from './playground-project.js'; -import {ProjectManifest} from './shared/worker-api.js'; +import {ProjectConfig} from './shared/worker-api.js'; import {npmVersion, serviceWorkerHash} from './shared/version.js'; /** @@ -173,22 +173,23 @@ export class PlaygroundIde extends LitElement { * Setting this property does not fetch project files or other manifests, * because it is commonly populated from untrusted input (e.g. a shared * URL). Only files with inline string `content` and the `importMap` are - * used. Files without `content`, `extends`, and `cdnBaseUrl` are ignored - * with a console warning; use `projectSrc` for manifests that need those, - * and the `cdnBaseUrl` property to change the CDN. + * used. Files without `content`, `extends`, and `cdnBaseUrl` are not + * allowed by the `ProjectConfig` type. If they are present anyway, they are + * ignored with a console warning. Use `projectSrc` for manifests that need + * those, and the `cdnBaseUrl` property to change the CDN. * * When both `projectSrc` and `config` are set, the one set most recently * wins. Slotted children win only if both `projectSrc` and `config` are * undefined. */ @property({attribute: false, hasChanged: () => false}) - get config(): ProjectManifest | undefined { + get config(): ProjectConfig | undefined { // Note this is declared a @property only to capture properties set before // upgrade. Attribute reflection and update lifecycle disabled because they // are not needed in this case. return this._project?.config ?? this._configSetBeforeRender; } - set config(config: ProjectManifest | undefined) { + set config(config: ProjectConfig | undefined) { const project = this._project; if (project) { project.config = config; @@ -312,7 +313,7 @@ export class PlaygroundIde extends LitElement { @query('#rhs') private _rhs!: HTMLDivElement; - private _configSetBeforeRender?: ProjectManifest; + private _configSetBeforeRender?: ProjectConfig; private _projectSrcSetBeforeRender?: string; override render() { diff --git a/src/playground-project.ts b/src/playground-project.ts index 484ce53f..07d50bf7 100644 --- a/src/playground-project.ts +++ b/src/playground-project.ts @@ -13,6 +13,7 @@ import { FileOptions, ServiceWorkerAPI, ProjectManifest, + ProjectConfig, PlaygroundMessage, WorkerAPI, CONFIGURE_PROXY, @@ -101,16 +102,17 @@ export class PlaygroundProject extends LitElement { * Setting this property does not fetch project files or other manifests, * because it is commonly populated from untrusted input (e.g. a shared * URL). Only files with inline string `content` and the `importMap` are - * used. Files without `content`, `extends`, and `cdnBaseUrl` are ignored - * with a console warning; use `projectSrc` for manifests that need those, - * and the `cdnBaseUrl` property to change the CDN. + * used. Files without `content`, `extends`, and `cdnBaseUrl` are not + * allowed by the `ProjectConfig` type. If they are present anyway, they are + * ignored with a console warning. Use `projectSrc` for manifests that need + * those, and the `cdnBaseUrl` property to change the CDN. * * When both `projectSrc` and `config` are set, the one set most recently * wins. Slotted children win only if both `projectSrc` and `config` are * undefined. */ @property({attribute: false, hasChanged: () => false}) - get config(): ProjectManifest | undefined { + get config(): ProjectConfig | undefined { // Note this is declared a @property only to capture properties set before // upgrade. Attribute reflection and update lifecycle disabled because they // are not needed in this case. @@ -127,7 +129,7 @@ export class PlaygroundProject extends LitElement { importMap: this._validImportMap, }; } - set config(config: ProjectManifest | undefined) { + set config(config: ProjectConfig | undefined) { if (config) { this._source = {type: 'direct', config}; } else if (this._source.type === 'direct') { @@ -150,7 +152,7 @@ export class PlaygroundProject extends LitElement { } | { type: 'direct'; - config: ProjectManifest; + config: ProjectConfig; } | { type: 'url'; @@ -851,6 +853,10 @@ const fetchProjectConfig = async ( * Only files with inline string content and the import map are used. * Everything that would be fetched or that changes where we fetch from is * ignored with a warning: files without content, `extends`, and `cdnBaseUrl`. + * + * The parameter is the wider `ProjectManifest` type rather than + * `ProjectConfig`, because the config may have come from untyped JSON, so we + * also have to handle the fields that `ProjectConfig` does not allow. */ const readDirectProjectConfig = ( config: ProjectManifest diff --git a/src/shared/worker-api.ts b/src/shared/worker-api.ts index 9d6c5fcd..d7548dde 100755 --- a/src/shared/worker-api.ts +++ b/src/shared/worker-api.ts @@ -167,11 +167,7 @@ export interface SampleFile { } export interface FileOptions { - /** - * Optional file content. If omitted, files are fetched by name when the - * manifest is loaded with `project-src`. Required for files in a config set - * through the `config` property, which never fetches files. - */ + /** Optional file content. If omitted, files are fetched by name. */ content?: string; /** * Optional content MIME type. If omitted, type is taken from fetch @@ -186,22 +182,41 @@ export interface FileOptions { selected?: boolean; } +/** + * A file in a `ProjectConfig`. The same as `FileOptions`, except that + * `content` is required, because the `config` property never fetches files. + */ +export interface ProjectConfigFile extends FileOptions { + /** File content. */ + content: string; +} + +/** + * A project manifest, as loaded from a JSON file with `project-src`. See + * `ProjectConfig` for the narrower type of the `config` property. + */ export interface ProjectManifest { - /** - * Optional project manifest URL to extend from. Only applies to manifests - * loaded with `project-src`; ignored in the `config` property. - */ + /** Optional project manifest URL to extend from */ extends?: string; files?: {[filename: string]: FileOptions}; importMap?: ModuleImportMap; - /** - * Optional npm CDN base URL. Only applies to manifests loaded with - * `project-src`; ignored in the `config` property (set the `cdnBaseUrl` - * property on the element instead). - */ cdnBaseUrl?: string; } +/** + * The type of the `config` property. + * + * Setting `config` does not fetch project files or other manifests, and a + * config cannot change the CDN. So unlike in a `ProjectManifest`, every file + * must have inline `content`, and there is no `extends` or `cdnBaseUrl`. Load + * a manifest that needs those with `project-src`, and set the CDN with the + * element's `cdnBaseUrl` property. + */ +export interface ProjectConfig { + files?: {[filename: string]: ProjectConfigFile}; + importMap?: ModuleImportMap; +} + export interface ModuleImportMap { imports?: {[name: string]: string}; // No scopes for now. diff --git a/src/test/cdn-base-url_test.ts b/src/test/cdn-base-url_test.ts index 62858e64..b078a6a8 100644 --- a/src/test/cdn-base-url_test.ts +++ b/src/test/cdn-base-url_test.ts @@ -11,7 +11,7 @@ import {PlaygroundIde} from '../playground-ide.js'; import { SampleFile, BuildOutput, - ProjectManifest, + ProjectConfig, DiagnosticBuildOutput, } from '../shared/worker-api.js'; import {CdnData} from './fake-cdn-plugin.js'; @@ -308,7 +308,7 @@ suite('CDN Base URL Configuration', () => { ide.cdnBaseUrl = customCdnBaseUrl; // Add a simple project that imports from a bare module - const projectConfig: ProjectManifest = { + const projectConfig: ProjectConfig = { files: { 'index.ts': { content: 'import {html} from "lit";\nconsole.log(html`Hello`);', diff --git a/src/test/playground-project-config_test.ts b/src/test/playground-project-config_test.ts index ffd2a295..3299e7c2 100644 --- a/src/test/playground-project-config_test.ts +++ b/src/test/playground-project-config_test.ts @@ -7,7 +7,7 @@ import {assert} from '@esm-bundle/chai'; import {PlaygroundProject} from '../playground-project.js'; import '../playground-project.js'; -import {ProjectManifest} from '../shared/worker-api.js'; +import {ProjectConfig, ProjectManifest} from '../shared/worker-api.js'; /** * The `config` property is commonly set from untrusted input (e.g. a shared @@ -93,7 +93,7 @@ suite('playground-project config property', () => { const loadConfig = (config: unknown) => loadProject((project) => { - project.config = config as ProjectManifest; + project.config = config as ProjectConfig; }); const filenames = (project: PlaygroundProject) => @@ -157,6 +157,21 @@ suite('playground-project config property', () => { assert.deepEqual(warnings, []); }); + test('type does not allow what the setter ignores', () => { + // These are compile-time checks: each @ts-expect-error fails the build if + // the type starts to allow the line below it. + const check = (config: ProjectConfig) => config; + // @ts-expect-error Files must have inline content. + check({files: {'index.html': {}}}); + // @ts-expect-error "extends" is not allowed. + check({extends: '/base.json'}); + // @ts-expect-error "cdnBaseUrl" is not allowed. + check({cdnBaseUrl: 'https://cdn.example.com/npm'}); + const manifest: ProjectManifest = {}; + // @ts-expect-error A manifest is not a config. + check(manifest); + }); + test('does not fetch files that have no content', async () => { const project = await loadConfig({ files: { From d01b96a7bf33176cc4c3fbcb119ca0f7b438e8bb Mon Sep 17 00:00:00 2001 From: Augustine Kim Date: Mon, 23 Nov 2026 15:43:51 -0800 Subject: [PATCH 3/4] Fetch import map typings without credentials The TypeScript worker fetched typings for import map URLs with the page's credentials. An import map from an untrusted config could use that to make the host page send authenticated requests to URLs of its choosing. Fetch them with credentials: 'omit' instead. Typings that can only be fetched with credentials will no longer load. Also stop overstating what loading a config guarantees. A code comment, the console warning, the README's sharing FAQ and a test comment said or implied that it never makes the page fetch anything, but a project can still make the worker fetch modules from the CDN and fetch typings. Say what it does guarantee: loading a config does not fetch the files or manifests it names, and the config cannot change the CDN. Likewise, a test used a fetch-marker URL for cdnBaseUrl without checking for fetches. That check could not work, because CDN fetches happen in the worker, so use a plain URL. --- CHANGELOG.md | 6 +++ README.md | 8 ++-- src/playground-project.ts | 11 +++-- src/test/playground-project-config_test.ts | 9 ++-- src/test/types-fetcher_test.ts | 53 ++++++++++++++++++++++ src/typescript-worker/types-fetcher.ts | 6 ++- 6 files changed, 80 insertions(+), 13 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c4c664d3..c30211fc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -33,6 +33,12 @@ and this project adheres to [Semantic Versioning](http://semver.org/). `project-src`, and set the CDN with the `cdnBaseUrl` property or `cdn-base-url` attribute. Manifests loaded with `project-src` are unchanged. +- **POTENTIALLY BREAKING** (security) Typings for modules in an import map are + now fetched without credentials (e.g. cookies). Otherwise an import map from + an untrusted config could make the host page send authenticated requests to + URLs of its choosing. Typings that can only be fetched with credentials will + no longer load. + ## [0.21.3] - 2026-11-17 ### Fixed diff --git a/README.md b/README.md index 8e501811..dac5b052 100644 --- a/README.md +++ b/README.md @@ -1095,10 +1095,10 @@ get or set the current state of the project The value returned by `config` contains every file's content inline, so it can be serialized and set again later. Setting `config` does not fetch project -files or other manifests, so a config from an untrusted source cannot have your -page fetch a URL and expose the response to the preview. The code in the -project is still untrusted, so see [sandbox security](#sandbox-security) if you -change the sandbox base URL. +files or other manifests, and a config cannot change the CDN, so it can be used +with a config from an untrusted source. Modules that the project imports are +still fetched from the CDN. The code in the project is still untrusted, so see +[sandbox security](#sandbox-security) if you change the sandbox base URL. How you persist and retrieve serialized project state is up to you. Here are a few ideas: diff --git a/src/playground-project.ts b/src/playground-project.ts index 07d50bf7..6fd6357e 100644 --- a/src/playground-project.ts +++ b/src/playground-project.ts @@ -364,9 +364,10 @@ export class PlaygroundProject extends LitElement { break; case 'direct': { - // A config set directly is treated as untrusted, so unlike the - // 'url' case below, it must never cause this page to make network - // requests or change where the worker fetches from. + // A config set directly is treated as untrusted. Unlike the 'url' + // case below, loading it must not make this page fetch anything + // the config names (files or other manifests), and the config must + // not be able to change which CDN the worker fetches from. const {files, importMap} = readDirectProjectConfig(source.config); this._files = files; this._importMap = importMap; @@ -893,8 +894,8 @@ const readDirectProjectConfig = ( } if (ignored.length > 0) { console.warn( - `[playground-project] The config property does not fetch, so these ` + - `were ignored: ${ignored.join(', ')}. ` + + `[playground-project] Setting config does not fetch project files or ` + + `other manifests, so these were ignored: ${ignored.join(', ')}. ` + `Load the manifest with project-src if it needs them.` ); } diff --git a/src/test/playground-project-config_test.ts b/src/test/playground-project-config_test.ts index 3299e7c2..3f5aca5e 100644 --- a/src/test/playground-project-config_test.ts +++ b/src/test/playground-project-config_test.ts @@ -11,8 +11,11 @@ import {ProjectConfig, ProjectManifest} from '../shared/worker-api.js'; /** * The `config` property is commonly set from untrusted input (e.g. a shared - * URL), so it must never make this page fetch something on behalf of the - * config. These tests check that, and that `project-src` still does fetch. + * URL), so loading a config must not fetch project files or other manifests, + * and a config must not be able to change the CDN. These tests check that, and + * that `project-src` still does fetch. + * + * Note they only see fetches made by the page, not by the TypeScript worker. */ suite('playground-project config property', () => { let container: HTMLDivElement; @@ -208,7 +211,7 @@ suite('playground-project config property', () => { test('does not use cdnBaseUrl from the config', async () => { const project = await loadConfig({ - cdnBaseUrl: absolute('/no-fetch-marker/api#'), + cdnBaseUrl: 'https://cdn.example.com/npm', files: {'index.html': {content: 'hello'}}, }); assert.equal(effectiveCdnBaseUrl(project), 'https://unpkg.com'); diff --git a/src/test/types-fetcher_test.ts b/src/test/types-fetcher_test.ts index 2af807eb..197528f5 100644 --- a/src/test/types-fetcher_test.ts +++ b/src/test/types-fetcher_test.ts @@ -1008,6 +1008,59 @@ suite('types fetcher', () => { } }); + test('import map: typings are fetched without credentials', async () => { + const sourceTexts: string[] = [`import {foo} from 'foo/foo.js';`]; + const packageJson: PackageJson = {}; + const cdnData: CdnData = { + foo: { + versions: { + '1.2.3': { + files: { + 'foo.d.ts': { + content: 'declare export const foo: string;', + }, + }, + }, + }, + }, + }; + const {cdnBaseUrl, deleteCdnData} = await configureFakeCdn(cdnData); + const importMap: ModuleImportMap = { + imports: { + 'foo/': `${cdnBaseUrl}foo@1.2.3/`, + }, + }; + const expectedFiles = new Map([ + ['foo/foo.d.ts', 'declare export const foo: string;'], + ]); + // An import map can come from an untrusted project, so its URLs must never + // be fetched with the user's credentials. + const credentialsByUrl = new Map(); + const realFetch = window.fetch; + window.fetch = (input: RequestInfo | URL, init?: RequestInit) => { + credentialsByUrl.set(String(input), init?.credentials); + return realFetch(input, init); + }; + try { + await checkTypesFetcherImpl( + { + sourceTexts, + packageJson, + cdnData, + importMap, + expectedFiles, + }, + cdnBaseUrl + ); + } finally { + window.fetch = realFetch; + await deleteCdnData(); + } + const typingsUrl = `${cdnBaseUrl}foo@1.2.3/foo.d.ts`; + assert.isTrue(credentialsByUrl.has(typingsUrl), 'typings were not fetched'); + assert.equal(credentialsByUrl.get(typingsUrl), 'omit'); + }); + test('import map: dependency has relative import', async () => { const sourceTexts: string[] = [`import {foo} from 'foo/foo.js';`]; const packageJson: PackageJson = {}; diff --git a/src/typescript-worker/types-fetcher.ts b/src/typescript-worker/types-fetcher.ts index 310f171b..e0395bca 100644 --- a/src/typescript-worker/types-fetcher.ts +++ b/src/typescript-worker/types-fetcher.ts @@ -344,7 +344,11 @@ export class TypesFetcher { let content; if (importMapUrl !== null) { - const r = await fetch(importMapUrl); + // The import map can come from an untrusted project, so this URL could + // point anywhere, including at the origin we are running on. Never send + // credentials, so that it can't be used to make authenticated requests + // on behalf of the user. + const r = await fetch(importMapUrl, {credentials: 'omit'}); if (r.status !== 200) { const err = {error: r.status}; deferred.resolve(err); From 31217888d233ce9e10e5b0a7b93e745b5fa3d79e Mon Sep 17 00:00:00 2001 From: Augustine Kim Date: Mon, 23 Nov 2026 19:07:36 -0800 Subject: [PATCH 4/4] Rename _configCdnBaseUrl to _manifestCdnBaseUrl The field now only ever holds the CDN base URL of a manifest loaded with project-src, since a config can no longer set one. Rename it and fix its comment. Also test that the value does not carry over when config is set after project-src. --- src/playground-project.ts | 15 +++---- src/test/playground-project-config_test.ts | 47 ++++++++++++++++++---- 2 files changed, 47 insertions(+), 15 deletions(-) diff --git a/src/playground-project.ts b/src/playground-project.ts index 6fd6357e..df9da8c3 100644 --- a/src/playground-project.ts +++ b/src/playground-project.ts @@ -220,8 +220,9 @@ export class PlaygroundProject extends LitElement { */ private _pristineFiles?: SampleFile[]; - // Store config value separately to maintain proper resolution order - private _configCdnBaseUrl?: string; + // The CDN base URL from the manifest loaded with projectSrc, if it has one. + // Kept separate from the cdnBaseUrl property, which takes precedence. + private _manifestCdnBaseUrl?: string; /** * Cached value for the `modified` getter. When undefined, the modified state @@ -359,7 +360,7 @@ export class PlaygroundProject extends LitElement { switch (source.type) { case 'none': this._files = undefined; - this._configCdnBaseUrl = undefined; + this._manifestCdnBaseUrl = undefined; this._importMap = {}; break; case 'direct': @@ -371,13 +372,13 @@ export class PlaygroundProject extends LitElement { const {files, importMap} = readDirectProjectConfig(source.config); this._files = files; this._importMap = importMap; - this._configCdnBaseUrl = undefined; + this._manifestCdnBaseUrl = undefined; } break; case 'slot': this._files = source.files; this._importMap = source.importMap; - this._configCdnBaseUrl = undefined; + this._manifestCdnBaseUrl = undefined; break; case 'url': { @@ -391,7 +392,7 @@ export class PlaygroundProject extends LitElement { } this._files = files; this._importMap = importMap; - this._configCdnBaseUrl = cdnBaseUrl; + this._manifestCdnBaseUrl = cdnBaseUrl; } break; default: @@ -789,7 +790,7 @@ export class PlaygroundProject extends LitElement { * in the correct priority order. */ private _getEffectiveCdnBaseUrl(): string { - return this.cdnBaseUrl || this._configCdnBaseUrl || 'https://unpkg.com'; + return this.cdnBaseUrl || this._manifestCdnBaseUrl || 'https://unpkg.com'; } } diff --git a/src/test/playground-project-config_test.ts b/src/test/playground-project-config_test.ts index 3f5aca5e..91e577ac 100644 --- a/src/test/playground-project-config_test.ts +++ b/src/test/playground-project-config_test.ts @@ -5,7 +5,7 @@ */ import {assert} from '@esm-bundle/chai'; -import {PlaygroundProject} from '../playground-project.js'; +import {FilesChangedEvent, PlaygroundProject} from '../playground-project.js'; import '../playground-project.js'; import {ProjectConfig, ProjectManifest} from '../shared/worker-api.js'; @@ -72,6 +72,20 @@ suite('playground-project config property', () => { container.remove(); }); + /** + * Resolves the next time the given project has loaded its files. + */ + const nextLoad = (project: PlaygroundProject) => + new Promise((resolve) => { + const onFilesChanged = (event: FilesChangedEvent) => { + if (event.projectLoaded) { + project.removeEventListener('filesChanged', onFilesChanged); + resolve(); + } + }; + project.addEventListener('filesChanged', onFilesChanged); + }); + /** * Create a project, apply the given source to it, and wait until its files * have loaded. @@ -81,13 +95,7 @@ suite('playground-project config property', () => { ): Promise => { const project = document.createElement('playground-project'); project.sandboxBaseUrl = '/'; - const loaded = new Promise((resolve) => { - project.addEventListener('filesChanged', (event) => { - if (event.projectLoaded) { - resolve(); - } - }); - }); + const loaded = nextLoad(project); setSource(project); container.appendChild(project); await loaded; @@ -219,6 +227,29 @@ suite('playground-project config property', () => { assert.include(warnings[0], '"cdnBaseUrl"'); }); + test('cdnBaseUrl from project-src does not carry over to a config', async () => { + responses.set(absolute('/fetch-marker/project.json'), { + body: JSON.stringify({ + cdnBaseUrl: 'https://cdn.example.com/npm', + files: {'index.html': {content: 'from manifest'}}, + }), + contentType: 'application/json', + }); + const project = await loadProject((p) => { + p.projectSrc = '/fetch-marker/project.json'; + }); + assert.equal(effectiveCdnBaseUrl(project), 'https://cdn.example.com/npm'); + const loaded = nextLoad(project); + project.config = {files: {'index.html': {content: 'from config'}}}; + await loaded; + assert.deepEqual( + (project.files ?? []).map(({name, content}) => ({name, content})), + [{name: 'index.html', content: 'from config'}] + ); + assert.equal(effectiveCdnBaseUrl(project), 'https://unpkg.com'); + assert.deepEqual(warnings, []); + }); + test('cdnBaseUrl property still applies with a config', async () => { const project = await loadProject((p) => { p.cdnBaseUrl = 'https://cdn.example.com/npm';