diff --git a/CHANGELOG.md b/CHANGELOG.md index d7e9d576..c30211fc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,7 +12,32 @@ and this project adheres to [Semantic Versioning](http://semver.org/). - +## [Unreleased] + +### Changed + +- **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 + `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 diff --git a/README.md b/README.md index a2db26ad..dac5b052 100644 --- a/README.md +++ b/README.md @@ -239,14 +239,26 @@ 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: '', + }, 'typescript.ts': { content: "console.log('hello');", }, @@ -254,6 +266,14 @@ ide.config = { }; ``` +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. @@ -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. | @@ -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 ``. | @@ -1073,6 +1093,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, 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-ide.ts b/src/playground-ide.ts index ed25f439..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'; /** @@ -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; @@ -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() { diff --git a/src/playground-project.ts b/src/playground-project.ts index 906c86f3..df9da8c3 100644 --- a/src/playground-project.ts +++ b/src/playground-project.ts @@ -10,8 +10,10 @@ import {wrap, Remote, proxy} from 'comlink'; import { SampleFile, + FileOptions, ServiceWorkerAPI, ProjectManifest, + ProjectConfig, PlaygroundMessage, WorkerAPI, CONFIGURE_PROXY, @@ -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. @@ -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') { @@ -142,7 +152,7 @@ export class PlaygroundProject extends LitElement { } | { type: 'direct'; - config: ProjectManifest; + config: ProjectConfig; } | { type: 'url'; @@ -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 @@ -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': { @@ -385,7 +392,7 @@ export class PlaygroundProject extends LitElement { } this._files = files; this._importMap = importMap; - this._configCdnBaseUrl = cdnBaseUrl; + this._manifestCdnBaseUrl = cdnBaseUrl; } break; default: @@ -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'; } } @@ -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; + 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] 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. diff --git a/src/shared/worker-api.ts b/src/shared/worker-api.ts index f3931238..d7548dde 100755 --- a/src/shared/worker-api.ts +++ b/src/shared/worker-api.ts @@ -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; @@ -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. 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 new file mode 100644 index 00000000..91e577ac --- /dev/null +++ b/src/test/playground-project-config_test.ts @@ -0,0 +1,327 @@ +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: BSD-3-Clause + */ + +import {assert} from '@esm-bundle/chai'; +import {FilesChangedEvent, PlaygroundProject} from '../playground-project.js'; +import '../playground-project.js'; +import {ProjectConfig, ProjectManifest} from '../shared/worker-api.js'; + +/** + * The `config` property is commonly set from untrusted input (e.g. a shared + * 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; + 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(); + }); + + /** + * 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. + */ + const loadProject = async ( + setSource: (project: PlaygroundProject) => void + ): Promise => { + const project = document.createElement('playground-project'); + project.sandboxBaseUrl = '/'; + const loaded = nextLoad(project); + setSource(project); + container.appendChild(project); + await loaded; + return project; + }; + + const loadConfig = (config: unknown) => + loadProject((project) => { + project.config = config as ProjectConfig; + }); + + 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('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: { + '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: 'https://cdn.example.com/npm', + files: {'index.html': {content: 'hello'}}, + }); + assert.equal(effectiveCdnBaseUrl(project), 'https://unpkg.com'); + assert.equal(warnings.length, 1); + 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'; + 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, []); + }); +}); 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);