From e16ab8e1d1bb60a8b40598a4fa9b3a9e84942ae7 Mon Sep 17 00:00:00 2001 From: Sam Verschueren Date: Wed, 1 Jul 2026 12:55:39 +0200 Subject: [PATCH 1/2] fix: allow cross-origin-isolation for the run endpoint --- examples/embed-project-node/index.html | 23 +++++++ examples/embed-project-node/index.ts | 83 ++++++++++++++++++++++++ examples/embed-project-node/package.json | 9 +++ examples/embed-project-node/styles.css | 54 +++++++++++++++ examples/index.html | 5 ++ src/constants.ts | 45 +++++++++++++ src/helpers.ts | 68 +++++++++++++++++-- test/unit/helpers.spec.ts | 64 +++++++++++++++++- 8 files changed, 346 insertions(+), 5 deletions(-) create mode 100644 examples/embed-project-node/index.html create mode 100644 examples/embed-project-node/index.ts create mode 100644 examples/embed-project-node/package.json create mode 100644 examples/embed-project-node/styles.css diff --git a/examples/embed-project-node/index.html b/examples/embed-project-node/index.html new file mode 100644 index 0000000..ebb97bb --- /dev/null +++ b/examples/embed-project-node/index.html @@ -0,0 +1,23 @@ + + + + + + Embed a dynamically generated Node project with the StackBlitz SDK + + + +
+

Embed a dynamically generated Node project with the StackBlitz SDK

+
+ +
+ +
+
+

Embed will go here

+
+ + diff --git a/examples/embed-project-node/index.ts b/examples/embed-project-node/index.ts new file mode 100644 index 0000000..adf15dc --- /dev/null +++ b/examples/embed-project-node/index.ts @@ -0,0 +1,83 @@ +import sdk, { Project } from '@stackblitz/sdk'; + +import './styles.css'; + +// A dynamically generated WebContainers (`node`) project. +// For `node` projects, npm dependencies must be declared in the +// `package.json` file (the `dependencies` field of the Project is ignored). +const project: Project = { + title: 'Dynamically Generated Node Project', + description: 'A Node.js Express server created with the StackBlitz SDK!', + template: 'node', + files: { + 'package.json': JSON.stringify( + { + name: 'sdk-node-project', + version: '0.0.0', + private: true, + type: 'module', + scripts: { + start: 'node index.js', + }, + dependencies: { + express: '^4.18.2', + }, + }, + null, + 2 + ), + 'index.js': `import express from 'express'; + +const app = express(); +const port = 3000; + +app.get('/', (_req, res) => { + res.send('

Hello from a dynamically generated Node project!

'); +}); + +app.listen(port, () => { + console.log(\`Server listening on http://localhost:\${port}\`); +}); +`, + }, +}; + +function embedProject() { + const queryParams = new URLSearchParams(window.location.search); + + sdk.embedProject('embed', project, { + openFile: 'index.js', + startScript: 'start', + crossOriginIsolated: queryParams.get('corp') === '1', + }); +} + +function toggleCorp(event: Event) { + const queryParams = new URLSearchParams(window.location.search); + const isChecked = (event.target as any)?.checked; + + if (isChecked) { + if (!queryParams.has('corp') || queryParams.get('corp') !== '1') { + queryParams.set('corp', '1'); + } + } else { + queryParams.delete('corp'); + } + + window.location.search = queryParams.toString(); +} + +function setup() { + const embedButton = document.querySelector('[name=embed-project]') as HTMLButtonElement; + const corpCheckbox = document.querySelector('[name=corp]') as HTMLInputElement; + + embedButton.addEventListener('click', embedProject); + corpCheckbox.addEventListener('change', toggleCorp); + + // mark the checkbox checked if the corp param is already set + const queryParams = new URLSearchParams(window.location.search); + + corpCheckbox.checked = queryParams.get('corp') === '1'; +} + +setup(); diff --git a/examples/embed-project-node/package.json b/examples/embed-project-node/package.json new file mode 100644 index 0000000..552d803 --- /dev/null +++ b/examples/embed-project-node/package.json @@ -0,0 +1,9 @@ +{ + "name": "sdk-example-embed-project-node", + "description": "Demo of the StackBlitz SDK's embedProject method for creating a dynamic WebContainers (node) project", + "version": "0.0.0", + "private": true, + "dependencies": { + "@stackblitz/sdk": "^1.8.1" + } +} diff --git a/examples/embed-project-node/styles.css b/examples/embed-project-node/styles.css new file mode 100644 index 0000000..a7539ed --- /dev/null +++ b/examples/embed-project-node/styles.css @@ -0,0 +1,54 @@ +html { + height: 100%; + text-align: center; + font-family: system-ui, sans-serif; + color: black; + background-color: white; +} + +body { + height: 100%; + margin: 0; + display: flex; + flex-direction: column; +} + +h1 { + margin: 1rem; + font-size: 1.25rem; +} + +nav { + margin: 1rem; + font-size: 0.9rem; +} + +select, +button { + margin: 0.2em; + padding: 0.2em 0.5em; + font-size: inherit; + font-family: inherit; +} + +#embed { + display: flex; + flex: 1 1 60%; + flex-direction: column; + justify-content: center; + overflow: hidden; + width: 100%; + height: auto; + margin: 0; + border: 0; +} + +#embed > p { + width: min(300px, 100%); + margin: 2rem auto; + padding: 4rem 1rem; + border: dashed 2px #ccc; + border-radius: 0.5em; + font-size: 85%; + color: #777; +} diff --git a/examples/index.html b/examples/index.html index 2ac8751..ac08ff8 100644 --- a/examples/index.html +++ b/examples/index.html @@ -31,6 +31,11 @@

StackBlitz SDK Examples

  • Open and embed a GitHub repo
  • Control an embedded project with the SDK
  • +
  • + Embed a dynamically generated Node (WebContainers) project +
  • diff --git a/src/constants.ts b/src/constants.ts index 74bdec4..44de9c2 100644 --- a/src/constants.ts +++ b/src/constants.ts @@ -51,3 +51,48 @@ export const UI_THEMES = ['light', 'dark'] as const; * Supported editor view modes */ export const UI_VIEWS = ['editor', 'preview'] as const; + +/** + * Permissions Policy features delegated to the embed iframe. + * + * Each feature is delegated to any origin (`feature *`) so that the embedded + * StackBlitz document — and any (potentially cross-origin) iframes it nests, + * such as project previews — can actually use them. A feature can only be used + * in a nested frame if every ancestor frame was granted it, so the outer embed + * frame must delegate the feature for it to reach a preview iframe deeper down. + * + * `cross-origin-isolated` is intentionally omitted: it does not accept the `*` + * allowlist value and is delegated separately to the StackBlitz origin. + */ +export const EMBED_ALLOW_FEATURES = [ + 'accelerometer', + 'ambient-light-sensor', + 'autoplay', + 'battery', + 'bluetooth', + 'camera', + 'clipboard-read', + 'clipboard-write', + 'display-capture', + 'encrypted-media', + 'fullscreen', + 'gamepad', + 'geolocation', + 'gyroscope', + 'hid', + 'idle-detection', + 'local-network', + 'local-network-access', + 'loopback-network', + 'magnetometer', + 'microphone', + 'midi', + 'payment', + 'picture-in-picture', + 'publickey-credentials-get', + 'screen-wake-lock', + 'serial', + 'usb', + 'web-share', + 'xr-spatial-tracking', +] as const; diff --git a/src/helpers.ts b/src/helpers.ts index c21eb9a..7114ca6 100644 --- a/src/helpers.ts +++ b/src/helpers.ts @@ -1,5 +1,5 @@ import type { EmbedOptions, OpenOptions } from './interfaces'; -import { DEFAULT_FRAME_HEIGHT, DEFAULT_ORIGIN } from './constants'; +import { DEFAULT_FRAME_HEIGHT, DEFAULT_ORIGIN, EMBED_ALLOW_FEATURES } from './constants'; import { buildParams } from './params'; type Route = '/run' | `/edit/${string}` | `/github/${string}` | `/fork/${string}`; @@ -88,13 +88,73 @@ function setFrameAllowList( frame: HTMLIFrameElement, options: EmbedOptions = {} ) { - const allowList = target.allow?.split(';')?.map((key) => key.trim()) ?? []; + const allowList = + target.allow + ?.split(';') + ?.map((key) => key.trim()) + .filter(Boolean) ?? []; - if (options.crossOriginIsolated && !allowList.includes('cross-origin-isolated')) { - allowList.push('cross-origin-isolated'); + const declaredFeatures = new Set(allowList.map((entry) => entry.split(/\s+/)[0])); + + /** + * Delegate every Permissions Policy feature to any origin (`feature *`) so + * the embedded document and any (cross-origin) iframes it nests — e.g. project + * previews — can use them. A feature only reaches a nested frame if each + * ancestor frame was granted it, so the outer embed frame must delegate it. + */ + for (const feature of getDelegatableFeatures()) { + if (!declaredFeatures.has(feature)) { + allowList.push(`${feature} *`); + declaredFeatures.add(feature); + } + } + + if (options.crossOriginIsolated && !declaredFeatures.has('cross-origin-isolated')) { + /** + * Delegate the `cross-origin-isolated` permission to the StackBlitz origin + * explicitly. A bare `cross-origin-isolated` token is scoped to the iframe's + * `src` origin, but `embedProject` creates the frame without a `src` and only + * navigates to StackBlitz cross-origin via a form POST, so the permission + * would never reach the embedded document. Naming the origin makes it apply + * regardless of how the frame is populated. It also does not accept the `*` + * allowlist value, which is why it is handled separately here. + */ + allowList.push(`cross-origin-isolated ${getOrigin(options)}`); + declaredFeatures.add('cross-origin-isolated'); } if (allowList.length > 0) { frame.allow = allowList.join('; '); } } + +/** + * The set of Permissions Policy features to delegate to the embed frame. + * + * When available, the browser's own list of features currently allowed in this + * document (`document.featurePolicy.allowedFeatures()`) is used so we pick up + * any features the browser supports without maintaining them by hand. That API + * is non-standard and Chromium-only, so it is unioned with `EMBED_ALLOW_FEATURES` + * as a fallback for browsers (Firefox, Safari) that don't implement it. + * + * `cross-origin-isolated` is removed because it does not accept the `*` + * allowlist value and is delegated separately to the StackBlitz origin. + */ +function getDelegatableFeatures(): string[] { + const features = new Set(EMBED_ALLOW_FEATURES); + + try { + const policy = (document as any)?.featurePolicy; + if (policy && typeof policy.allowedFeatures === 'function') { + for (const feature of policy.allowedFeatures() as string[]) { + features.add(feature); + } + } + } catch { + // Non-standard API; fall back to the static list. + } + + features.delete('cross-origin-isolated'); + + return [...features]; +} diff --git a/test/unit/helpers.spec.ts b/test/unit/helpers.spec.ts index bbd4900..9dcab8c 100644 --- a/test/unit/helpers.spec.ts +++ b/test/unit/helpers.spec.ts @@ -1,10 +1,13 @@ /** @vitest-environment happy-dom */ import { afterEach, describe, expect, test } from 'vitest'; -import { DEFAULT_FRAME_HEIGHT } from '$src/constants'; +import { DEFAULT_FRAME_HEIGHT, EMBED_ALLOW_FEATURES } from '$src/constants'; import { embedUrl, findElement, genID, openTarget, openUrl, replaceAndEmbed } from '$src/helpers'; import { h, makeContainer, removeContainer } from './utils/dom'; +/** The default `allow` value: every Permissions Policy feature delegated to any origin. */ +const ALL_FEATURES_ALLOW = EMBED_ALLOW_FEATURES.map((feature) => `${feature} *`).join('; '); + describe('embedUrl', () => { test('works with custom origins', () => { expect(embedUrl('/edit/test', { origin: 'http://localhost:8000' })).toBe( @@ -178,4 +181,63 @@ describe('replaceAndEmbed', () => { expect(iframe.getAttribute('width')).toBe('500'); expect(iframe.getAttribute('style')).toBe(null); }); + + test('delegates every Permissions Policy feature to any origin by default', () => { + const div = makeContainer().appendChild(h('div')); + const iframe = h('iframe', { src: 'about:blank' }) as HTMLIFrameElement; + + replaceAndEmbed(div, iframe); + + expect(iframe.getAttribute('allow')).toBe(ALL_FEATURES_ALLOW); + expect(iframe.getAttribute('allow')).toContain('geolocation *'); + }); + + test('delegates cross-origin-isolated to the explicit StackBlitz origin', () => { + const div = makeContainer().appendChild(h('div')); + const iframe = h('iframe', { src: 'about:blank' }) as HTMLIFrameElement; + + replaceAndEmbed(div, iframe, { crossOriginIsolated: true }); + + expect(iframe.getAttribute('allow')).toBe( + `${ALL_FEATURES_ALLOW}; cross-origin-isolated https://stackblitz.com` + ); + }); + + test('delegates cross-origin-isolated to a custom origin', () => { + const div = makeContainer().appendChild(h('div')); + const iframe = h('iframe', { src: 'about:blank' }) as HTMLIFrameElement; + + replaceAndEmbed(div, iframe, { + crossOriginIsolated: true, + origin: 'https://example.com/', + }); + + expect(iframe.getAttribute('allow')).toBe( + `${ALL_FEATURES_ALLOW}; cross-origin-isolated https://example.com` + ); + }); + + test('does not duplicate an existing cross-origin-isolated allowlist entry', () => { + const div = makeContainer().appendChild(h('div')) as HTMLElement & { allow?: string }; + div.allow = 'cross-origin-isolated https://example.com'; + const iframe = h('iframe', { src: 'about:blank' }) as HTMLIFrameElement; + + replaceAndEmbed(div, iframe, { crossOriginIsolated: true }); + + expect(iframe.getAttribute('allow')).toBe( + `cross-origin-isolated https://example.com; ${ALL_FEATURES_ALLOW}` + ); + }); + + test('preserves pre-existing allowlist entries without duplicating features', () => { + const div = makeContainer().appendChild(h('div')) as HTMLElement & { allow?: string }; + div.allow = 'geolocation self'; + const iframe = h('iframe', { src: 'about:blank' }) as HTMLIFrameElement; + + replaceAndEmbed(div, iframe); + + const allow = iframe.getAttribute('allow') ?? ''; + expect(allow.startsWith('geolocation self')).toBe(true); + expect(allow).not.toContain('geolocation *'); + }); }); From b3471ad2fd6ad8c39e112c7afa7fd0f930f468a5 Mon Sep 17 00:00:00 2001 From: Sam Verschueren Date: Wed, 1 Jul 2026 17:08:31 +0200 Subject: [PATCH 2/2] fix: update playwright --- package-lock.json | 73 +++++++++++++++++++++++++++++++---------------- package.json | 2 +- 2 files changed, 50 insertions(+), 25 deletions(-) diff --git a/package-lock.json b/package-lock.json index 6aafd30..8023290 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,7 +9,7 @@ "version": "1.11.0", "license": "MIT", "devDependencies": { - "@playwright/test": "^1.32.2", + "@playwright/test": "^1.61.1", "@rollup/plugin-replace": "^5.0.2", "@types/body-parser": "^1.19.2", "@types/lodash": "^4.14.192", @@ -454,22 +454,19 @@ } }, "node_modules/@playwright/test": { - "version": "1.32.2", - "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.32.2.tgz", - "integrity": "sha512-nhaTSDpEdTTttdkDE8Z6K3icuG1DVRxrl98Qq0Lfc63SS9a2sjc9+x8ezysh7MzCKz6Y+nArml3/mmt+gqRmQQ==", + "version": "1.61.1", + "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.61.1.tgz", + "integrity": "sha512-8nKv6+0RJSL9FE4jYOEGXnPeM/Hg12qZpmqzZjRh3qM0Y7c3z1mrOTfFLids72RDQYVh9WpLEfR5WdpNX4fkig==", "dev": true, + "license": "Apache-2.0", "dependencies": { - "@types/node": "*", - "playwright-core": "1.32.2" + "playwright": "1.61.1" }, "bin": { "playwright": "cli.js" }, "engines": { - "node": ">=14" - }, - "optionalDependencies": { - "fsevents": "2.3.2" + "node": ">=18" } }, "node_modules/@polka/url": { @@ -1923,16 +1920,36 @@ "pathe": "^1.1.0" } }, - "node_modules/playwright-core": { - "version": "1.32.2", - "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.32.2.tgz", - "integrity": "sha512-zD7aonO+07kOTthsrCR3YCVnDcqSHIJpdFUtZEMOb6//1Rc7/6mZDRdw+nlzcQiQltOOsiqI3rrSyn/SlyjnJQ==", + "node_modules/playwright": { + "version": "1.61.1", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.61.1.tgz", + "integrity": "sha512-DWnY5o3YbLWK4GovuAVwpqL+1VwGNdUGrRr++8j8PtQQzvAVZUIMjKQ90fY689sEJZJBbZVw1rXaOKSTitkzPQ==", "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright-core": "1.61.1" + }, "bin": { "playwright": "cli.js" }, "engines": { - "node": ">=14" + "node": ">=18" + }, + "optionalDependencies": { + "fsevents": "2.3.2" + } + }, + "node_modules/playwright-core": { + "version": "1.61.1", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.61.1.tgz", + "integrity": "sha512-h7Qlt6m4REp25qvIdvbDtVmD4LqVXfpRxhORv9L0jzETM05p4fuPJ3dKyuSXQxDSbXnmS79HAgi9589lGSpLkg==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "playwright-core": "cli.js" + }, + "engines": { + "node": ">=18" } }, "node_modules/postcss": { @@ -3186,14 +3203,12 @@ } }, "@playwright/test": { - "version": "1.32.2", - "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.32.2.tgz", - "integrity": "sha512-nhaTSDpEdTTttdkDE8Z6K3icuG1DVRxrl98Qq0Lfc63SS9a2sjc9+x8ezysh7MzCKz6Y+nArml3/mmt+gqRmQQ==", + "version": "1.61.1", + "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.61.1.tgz", + "integrity": "sha512-8nKv6+0RJSL9FE4jYOEGXnPeM/Hg12qZpmqzZjRh3qM0Y7c3z1mrOTfFLids72RDQYVh9WpLEfR5WdpNX4fkig==", "dev": true, "requires": { - "@types/node": "*", - "fsevents": "2.3.2", - "playwright-core": "1.32.2" + "playwright": "1.61.1" } }, "@polka/url": { @@ -4306,10 +4321,20 @@ "pathe": "^1.1.0" } }, + "playwright": { + "version": "1.61.1", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.61.1.tgz", + "integrity": "sha512-DWnY5o3YbLWK4GovuAVwpqL+1VwGNdUGrRr++8j8PtQQzvAVZUIMjKQ90fY689sEJZJBbZVw1rXaOKSTitkzPQ==", + "dev": true, + "requires": { + "fsevents": "2.3.2", + "playwright-core": "1.61.1" + } + }, "playwright-core": { - "version": "1.32.2", - "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.32.2.tgz", - "integrity": "sha512-zD7aonO+07kOTthsrCR3YCVnDcqSHIJpdFUtZEMOb6//1Rc7/6mZDRdw+nlzcQiQltOOsiqI3rrSyn/SlyjnJQ==", + "version": "1.61.1", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.61.1.tgz", + "integrity": "sha512-h7Qlt6m4REp25qvIdvbDtVmD4LqVXfpRxhORv9L0jzETM05p4fuPJ3dKyuSXQxDSbXnmS79HAgi9589lGSpLkg==", "dev": true }, "postcss": { diff --git a/package.json b/package.json index d640e79..ebe84f2 100644 --- a/package.json +++ b/package.json @@ -36,7 +36,7 @@ "test:format": "npx prettier --check ." }, "devDependencies": { - "@playwright/test": "^1.32.2", + "@playwright/test": "^1.61.1", "@rollup/plugin-replace": "^5.0.2", "@types/body-parser": "^1.19.2", "@types/lodash": "^4.14.192",