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
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { useColorScheme } from "./openui/scheme";
// ArkWeb serves this URL locally. Its response policy applies to the whole
// authored document, independently of the stricter parent rawfile policy.
const SANDBOX_URL = "https://genui-sandbox.openbitfun.invalid/view";
const INLINE_POLICY = "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src data: blob:; media-src data: blob:; font-src data:; connect-src 'none'; frame-src 'none'; object-src 'none'; form-action 'none'; base-uri 'none'";
const REPORTER = `<script>
(function () {
function post(type, details) { parent.postMessage(Object.assign({ type: type }, details), "*"); }
Expand All @@ -18,14 +19,18 @@ const REPORTER = `<script>
})();
</script>`;

function documentFor(html: string, scheme: "light" | "dark") {
return `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><style>:root{color-scheme:${scheme}}html,body{margin:0}body{font:14px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Helvetica,Arial,sans-serif}</style>${REPORTER}${html}`;
function documentFor(html: string, scheme: "light" | "dark", inline: boolean) {
const policy = inline ? `<meta http-equiv="Content-Security-Policy" content="${INLINE_POLICY}">` : "";
return `<!doctype html><meta charset="utf-8">${policy}<meta name="viewport" content="width=device-width,initial-scale=1"><style>:root{color-scheme:${scheme}}html,body{margin:0}body{font:14px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Helvetica,Arial,sans-serif}</style>${REPORTER}${html}`;
}

export function HtmlSandboxFrame({ html, height, title }: { html: string; height: number; title: string }) {
const frame = useRef<HTMLIFrameElement>(null);
const scheme = useColorScheme(frame);
const srcDoc = useMemo(() => documentFor(html, scheme), [html, scheme]);
// Exported MiniApps run inside the desktop storage bridge. That host allows
// inline scripts but cannot serve the phone's synthetic ArkWeb address.
const desktop = Boolean((window as Window & { app?: { storage?: unknown } }).app?.storage);
const srcDoc = useMemo(() => documentFor(html, scheme, desktop), [html, scheme, desktop]);
const gameInput = useMemo(() => /data-openbitfun-game|<canvas(?:\s|>)/i.test(html), [html]);

useEffect(() => {
Expand All @@ -52,10 +57,12 @@ export function HtmlSandboxFrame({ html, height, title }: { html: string; height
title={title}
style={{ height, touchAction: gameInput ? "none" : "auto" }}
sandbox="allow-scripts"
src={SANDBOX_URL}
src={desktop ? undefined : SANDBOX_URL}
srcDoc={desktop ? srcDoc : undefined}
referrerPolicy="no-referrer"
data-html-view-status="pending"
onLoad={event => {
if (desktop) return;
const iframe = event.currentTarget;
if (iframe.dataset.mountSent) return;
iframe.dataset.mountSent = "true";
Expand Down
58 changes: 58 additions & 0 deletions tests/browser/harmony-local-genui-browser.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,64 @@ const assets = new Map([
['/fonts/hm-symbol/HMSymbolVF.ttf', ['fonts/hm-symbol/HMSymbolVF.ttf', 'font/ttf']],
]);

test('a desktop MiniApp runs an offline game under the strict parent policy', { timeout: 30000 }, async () => {
const manifest = JSON.parse(await readFile(new URL('runtime-manifest.json', resources), 'utf8'));
const runtime = await readFile(new URL('runtime/runtime.js', resources), 'utf8');
const browser = await launchBrowser();
const server = createServer((_request, response) => {
response.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }).end(`<!doctype html>
<meta http-equiv="Content-Security-Policy"
content="default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; frame-src 'none'">
<div id="root"></div><script>window.app = { storage: {} };</script>
<script type="module">${runtime.replace(/<\/script/gi, '<\\/script')}</script>`);
});
try {
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
const page = await browser.newPage();
const errors = [];
page.on('pageerror', error => errors.push(error.message));
await page.goto(`http://127.0.0.1:${server.address().port}/`);
const requests = [];
page.on('request', request => {
if (request.url().startsWith('https://')) requests.push(request.url());
});
assert.deepEqual(errors, []);
assert.equal(await page.evaluate(() => typeof window.__genuiHost), 'object');
await page.evaluate(() => {
const channel = new MessageChannel();
window.dispatchEvent(new MessageEvent('message', { data: 'local-genui-port', ports: [channel.port2] }));
});
const html = '<button>Start</button><canvas width="8" height="8"></canvas><script>' +
'document.querySelector("button").onclick = () => {' +
'document.querySelector("canvas").getContext("2d").fillRect(0,0,8,8);' +
'fetch("https://example.invalid/game").catch(() => {});' +
'};</script>';
await page.evaluate(message => window.__genuiHost.receive(JSON.stringify(message)), {
type: 'init', manifest,
identity: {
appId: 'local-genui:desktop', title: 'Desktop game',
template: manifest.template, libraryId: manifest.libraryId, libraryRevision: manifest.libraryRevision,
designSpec: manifest.designSpec, sourceFormat: 'openui-lang',
},
mode: 'live', sourceRevision: 1, stateRevision: 0, streaming: false, state: {}, scheme: 'light', locale: 'en-US',
source: 'root = Page([game], "Desktop game")\ngame = HtmlView(' + JSON.stringify(html) + ', 300, "Game")',
});
await page.waitForSelector('iframe[data-html-view-status="ready"]', { timeout: 5000 });
const game = await page.waitForFrame(frame => frame.url() === 'about:srcdoc', { timeout: 5000 });
await game.$eval('button', button => button.click());
assert.deepEqual(await game.evaluate(() => ({
url: document.URL,
alpha: document.querySelector('canvas').getContext('2d').getImageData(0, 0, 1, 1).data[3],
origin: self.origin,
desktopBridge: typeof window.app,
})), { url: 'about:srcdoc', alpha: 255, origin: 'null', desktopBridge: 'undefined' });
assert.deepEqual(requests, []);
} finally {
await browser.close();
server.close();
}
});

test('the standalone Harmony GenUI bundle boots and renders at phone and foldable widths', { timeout: 30000 }, async () => {
const manifest = JSON.parse(await readFile(new URL('runtime-manifest.json', resources), 'utf8'));
const browser = await launchBrowser();
Expand Down
Loading