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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 26 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,32 @@ and this project adheres to [Semantic Versioning](http://semver.org/).

<!-- ## [X.Y.Z] - YYYY-MM-DD -->

<!-- ## [Unreleased] -->
## [Unreleased]

### Changed

- **BREAKING** (security) Files without inline `content`, `extends`, and
`cdnBaseUrl` are no longer allowed in the `config` property of
`<playground-ide>` and `<playground-project>`, 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
`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

Expand Down
37 changes: 32 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -239,21 +239,41 @@ 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.
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');
ide.config = {
files: {
'index.html': {},
'index.html': {
content: '<script type="module" src="./typescript.js"></script>',
},
'typescript.ts': {
content: "console.log('hello');",
},
},
};
```

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.

Expand Down Expand Up @@ -736,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. |
Expand Down Expand Up @@ -769,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 `<playground-project>`. |
Expand Down Expand Up @@ -1073,6 +1093,13 @@ Use the `config` property of a `<playground-ide>` or `<playground-project>` 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, 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:

Expand Down
16 changes: 12 additions & 4 deletions src/playground-ide.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

/**
Expand Down Expand Up @@ -170,18 +170,26 @@ 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 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;
Expand Down Expand Up @@ -305,7 +313,7 @@ export class PlaygroundIde extends LitElement {
@query('#rhs')
private _rhs!: HTMLDivElement;

private _configSetBeforeRender?: ProjectManifest;
private _configSetBeforeRender?: ProjectConfig;
private _projectSrcSetBeforeRender?: string;

override render() {
Expand Down
104 changes: 85 additions & 19 deletions src/playground-project.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,10 @@ import {wrap, Remote, proxy} from 'comlink';

import {
SampleFile,
FileOptions,
ServiceWorkerAPI,
ProjectManifest,
ProjectConfig,
PlaygroundMessage,
WorkerAPI,
CONFIGURE_PROXY,
Expand Down Expand Up @@ -97,12 +99,20 @@ 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 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.
Expand All @@ -119,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') {
Expand All @@ -142,7 +152,7 @@ export class PlaygroundProject extends LitElement {
}
| {
type: 'direct';
config: ProjectManifest;
config: ProjectConfig;
}
| {
type: 'url';
Expand Down Expand Up @@ -210,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
Expand Down Expand Up @@ -349,29 +360,25 @@ export class PlaygroundProject extends LitElement {
switch (source.type) {
case 'none':
this._files = undefined;
this._configCdnBaseUrl = undefined;
this._manifestCdnBaseUrl = undefined;
this._importMap = {};
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. 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;
this._configCdnBaseUrl = source.config.cdnBaseUrl;
this._manifestCdnBaseUrl = undefined;
}
break;
case 'slot':
this._files = source.files;
this._importMap = source.importMap;
this._configCdnBaseUrl = undefined;
this._manifestCdnBaseUrl = undefined;
break;
case 'url':
{
Expand All @@ -385,7 +392,7 @@ export class PlaygroundProject extends LitElement {
}
this._files = files;
this._importMap = importMap;
this._configCdnBaseUrl = cdnBaseUrl;
this._manifestCdnBaseUrl = cdnBaseUrl;
}
break;
default:
Expand Down Expand Up @@ -783,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';
}
}

Expand Down Expand Up @@ -837,6 +844,65 @@ 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`.
*
* 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
): {
files: Array<SampleFile>;
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<SampleFile> = [];
// 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<FileOptions> | 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] 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.`
);
}
return {files, importMap: config.importMap ?? {}};
};

/**
* Expands a partial project config by following its `extends` property, and
* fetching the content for all files.
Expand Down
27 changes: 27 additions & 0 deletions src/shared/worker-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,19 @@ 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 */
extends?: string;
Expand All @@ -190,6 +203,20 @@ export interface ProjectManifest {
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.
Expand Down
Loading
Loading