Skip to content
Closed
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
65 changes: 65 additions & 0 deletions packages/playground/client/src/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,65 @@ describe('startPlaygroundWeb', () => {
expect(mocks.BlueprintsV1Handler).not.toHaveBeenCalled();
expect(iframe.src).not.toContain('blueprints-runner');
});
it('does not disclose a top-level caller’s previous page as an embedder', async () => {
mocks.BlueprintsV1Handler.mockImplementation(() => ({
bootPlayground: mocks.bootPlaygroundV1,
}));
const iframe = createIframe();
const view = { origin: 'https://sdk.example' };
Object.assign(view, { parent: view });
Object.assign(iframe.ownerDocument, {
URL: 'https://sdk.example/',
referrer: 'https://previous.example/article',
defaultView: view,
});

await startPlaygroundWeb({
iframe,
remoteUrl: 'http://localhost/remote.html',
progressTracker: createProgressTracker(),
});

expect(
new URL(iframe.src).searchParams.getAll('embedder-origin')
).toEqual(['https://sdk.example']);
});
it('carries external ancestors through a referrer-free inner frame', async () => {
mocks.BlueprintsV1Handler.mockImplementation(() => ({
bootPlayground: mocks.bootPlaygroundV1,
}));
const iframe = createIframe();
Object.assign(iframe.ownerDocument, {
URL: 'http://localhost/?embedder-origin=https%3A%2F%2Fouter.example',
referrer: 'https://inner.example/article',
});
await startPlaygroundWeb({
iframe,
remoteUrl: 'http://localhost/remote.html',
progressTracker: createProgressTracker(),
});
expect(
new URL(iframe.src).searchParams.getAll('embedder-origin')
).toEqual(['https://outer.example', 'https://inner.example']);
});
it('declares the actual origin of an about:blank SDK caller', async () => {
mocks.BlueprintsV1Handler.mockImplementation(() => ({
bootPlayground: mocks.bootPlaygroundV1,
}));
const iframe = createIframe();
Object.assign(iframe.ownerDocument, {
URL: 'about:blank',
defaultView: { origin: 'https://embedder.example' },
});
await startPlaygroundWeb({
iframe,
remoteUrl: 'http://localhost/remote.html',
progressTracker: createProgressTracker(),
});
expect(
new URL(iframe.src).searchParams.getAll('embedder-origin')
).toEqual(['https://embedder.example']);
});
});

describe('startPlaygroundAPI', () => {
Expand All @@ -135,9 +194,15 @@ describe('startPlaygroundAPI', () => {
});
});

/** Supply the SDK caller document without booting a browser runtime. */
function createIframe() {
return {
src: '',
ownerDocument: {
URL: 'http://localhost/',
referrer: '',
defaultView: { parent: {} },
},
addEventListener: vi.fn((_event, callback: () => void) => {
callback();
}),
Expand Down
28 changes: 27 additions & 1 deletion packages/playground/client/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -292,10 +292,36 @@ export async function startPlaygroundAPI(
return api;
}

/**
* Carry the embedding chain into trusted inner documents, even with no referrer.
* These are declarations, not permission grants: the server excludes WordPress
* and the browser checks the actual ancestor chain against its response policy.
*/
function loadIframe(iframe: HTMLIFrameElement, url: string): Promise<void> {
const target = new URL(url);
const document = iframe.ownerDocument;
const view = document.defaultView;
const parent = new URL(document.URL);
const origins = new Set([
...target.searchParams.getAll('embedder-origin'),
...parent.searchParams.getAll('embedder-origin'),
// about:blank/srcdoc documents can inherit an origin despite their opaque URL.
view?.origin ?? parent.origin,
]);
// An embedded caller's referrer can name a frame above it. At the top level,
// it names the previous page, which must not be copied into this iframe URL.
if (document.referrer && view && view.parent !== view) {
origins.add(new URL(document.referrer).origin);
}
target.searchParams.delete('embedder-origin');
for (const origin of origins) {
if (origin !== target.origin && origin !== 'null') {
target.searchParams.append('embedder-origin', origin);
}
}
return new Promise((resolve) => {
iframe.addEventListener('load', () => resolve(), { once: true });
iframe.src = url;
iframe.src = target.href;
});
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,16 @@ test('boots a replacement runtime without reloading the new tab after retirement
async () => (await fetch('/scope:default/wp-json/')).status
)
).toBe(503);
// Vite redirects / to /website-server/. Check the final document response,
// not that redirect, while still reporting an error response immediately.
const reloadedDocument = page.waitForResponse(
(response) =>
response.request().isNavigationRequest() &&
response.request().frame() === page.mainFrame() &&
(response.status() < 300 || response.status() >= 400)
);
await page.getByRole('button', { name: 'Reload this tab' }).click();
expect((await reloadedDocument).ok()).toBe(true);
await page.waitForFunction(() => !!(window as any).playground);
await page.evaluate(() => (window as any).playground.isReady());
expect(
Expand Down
17 changes: 17 additions & 0 deletions packages/playground/personal-wp/vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,23 @@ export default defineConfig(({ command, mode }) => {
},
'^[/]((?!website-server).)': {
target: `http://${remoteDevServerHost}:${remoteDevServerPort}`,
/**
* Reload WordPress directory URLs through the app shell, not the remote server.
* The service worker forwards reloads with destination "empty", so check Accept.
* Scoped WordPress documents and runtime files must still use the proxy.
*/
bypass(request) {
const pathname = new URL(
request.url!,
'http://localhost'
).pathname;
if (
request.headers.accept?.includes('text/html') &&
pathname.endsWith('/') &&
!pathname.startsWith('/scope:')
)
return '/website-server/index.html';
},
},
},
fs: {
Expand Down
55 changes: 55 additions & 0 deletions packages/playground/remote/src/lib/frame-ancestors.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { describe, expect, it } from 'vitest';
import { getFrameAncestors } from './frame-ancestors';

const root = 'https://playground.example';
const wordpress = 'https://wp.playground.example';

describe('trusted document framing policy', () => {
it('allows normal referrers and explicit origins for all external ancestors', () => {
const url = new URL('/remote.html', root);
url.searchParams.append('embedder-origin', 'https://outer.example');
url.searchParams.append('embedder-origin', 'https://inner.example');
expect(
getFrameAncestors(url, 'https://inner.example/article', wordpress)
).toBe(
"frame-ancestors 'self' https://outer.example https://inner.example"
);
});

it.each([
wordpress,
wordpress + '/scope:example/',
'http://wp.playground.example',
'http://wp.playground.example:443',
'https://wp.playground.example:9443',
'https://user:password@wp.playground.example',
'data:text/html,test',
'null',
'https://*.example',
'https://example.com;frame-ancestors',
"https://example.com'",
'https://example.com,https:',
"'none'; frame-ancestors *",
])('never grants framing permission for %s', (value) => {
const url = new URL('/api.html', root);
url.searchParams.append('embedder-origin', value);
expect(getFrameAncestors(url, value, wordpress)).toBe(
"frame-ancestors 'self'"
);
});

it('keeps WordPress excluded when an external origin is declared alongside it', () => {
const url = new URL('/api.html', root);
url.searchParams.append('embedder-origin', wordpress);
url.searchParams.append('embedder-origin', 'https://external.example');
expect(getFrameAncestors(url, wordpress, wordpress)).toBe(
"frame-ancestors 'self' https://external.example"
);
});

it('fails closed without either an explicit origin or a referrer', () => {
expect(
getFrameAncestors(new URL('/api.html', root), '', wordpress)
).toBe("frame-ancestors 'self'");
});
});
36 changes: 36 additions & 0 deletions packages/playground/remote/src/lib/frame-ancestors.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/**
* Allow declared external embedders, never the untrusted WordPress origin.
* CSP checks every ancestor, so an external intermediary cannot hide WordPress.
* Referrer-free plain iframes must declare their embedder-origin in the URL.
*/
export function getFrameAncestors(
url: URL,
referrer: string,
wordPressOrigin: string
): string {
const wordPressHostname = new URL(wordPressOrigin).hostname;
const origins = new Set<string>();
for (const value of [
...url.searchParams.getAll('embedder-origin'),
referrer,
]) {
try {
const candidate = new URL(value);
const origin = candidate.origin;
if (
!/^https?:\/\//.test(origin) ||
/[\s,;'*]/.test(origin) ||
// CSP permits HTTP sources to match HTTPS. Exclude the WordPress host
// on every scheme and port rather than checking exact origin strings.
candidate.hostname === wordPressHostname ||
origin === url.origin
) {
continue;
}
origins.add(origin);
} catch {
// Invalid and opaque origins cannot grant permission to frame root documents.
}
}
return ["frame-ancestors 'self'", ...origins].join(' ');
}
25 changes: 25 additions & 0 deletions packages/playground/remote/src/lib/wordpress-popup.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { getURLScope } from '@php-wasm/scopes';
import { wordPressSiteUrl } from './config';

/**
* Opens a WordPress tool in a popup with the same frame layout as the main app:
* an app-origin top-level page containing a WordPress-origin iframe.
*
* Browsers can select service-worker registrations using both the WordPress
* origin and the top-level site. Opening WordPress directly can then miss the
* worker serving it inside the main app. This app-origin wrapper preserves
* that top-level site, so #wp can use the existing worker and PHP instance.
*
* The hash supplies the destination. Accept only scoped WordPress URLs so this
* wrapper cannot be used to load trusted app documents into the iframe.
*/
function bootWordPressPopup() {
const target = new URL(location.hash.substring(1), wordPressSiteUrl);
if (target.origin !== wordPressSiteUrl || !getURLScope(target)) {
throw new Error('The popup URL must name a scoped WordPress page.');
}
const frame = document.querySelector('#wp') as HTMLIFrameElement;
frame.src = target.href;
}

bootWordPressPopup();
1 change: 1 addition & 0 deletions packages/playground/remote/vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,7 @@ export default defineConfig(({ mode }) => {
rollupOptions: {
input: {
wordpress: path('/remote.html'),
'wordpress-popup': path('/wordpress-popup.html'),
},
output: {
assetFileNames: (chunkInfo) => {
Expand Down
28 changes: 28 additions & 0 deletions packages/playground/remote/wordpress-popup.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<!doctype html>
<html>
<head>
<title>WordPress Playground</title>
<style>
html,
body,
iframe {
width: 100%;
height: 100%;
margin: 0;
border: 0;
}
iframe {
display: block;
}
</style>
</head>
<body>
<iframe
id="wp"
name="wordpress-popup"
title="The WordPress site"
sandbox="allow-same-origin allow-scripts allow-popups allow-forms allow-downloads allow-modals"
></iframe>
<script type="module" src="./src/lib/wordpress-popup.ts"></script>
</body>
</html>
5 changes: 5 additions & 0 deletions packages/playground/tools/src/phpmyadmin/config.inc.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,11 @@
$cfg['ShowCreateDb'] = false;
$cfg['ShowChgPassword'] = false;

// Split-origin popups keep phpMyAdmin in a WordPress iframe. Its frame-busting
// script must not try to replace the app-origin wrapper; the iframe's sandbox
// and the browser's origin checks still prevent access to app documents/storage.
$cfg['AllowThirdPartyFraming'] = defined('PLAYGROUND_PARENT_ORIGIN');

// Cookie authentication secret.
$cfg['blowfish_secret'] = 'r/g+J#&)L2&p!z5gUS)d(vEU#KAynq#g';

Expand Down
Loading