Plan · area

Host page

The host page is a static document that sits between a shell and each napplet. It exists because a srcdoc frame inherits its parent's Content Security Policy, and any shell with a strict policy blocks every napplet. The page has no welshman dependencies, so any web shell can bundle it.

Why it exists#

Flotilla's script-src lists hashes of the inline scripts in app.html and has no 'unsafe-inline'. Browsers ignore 'unsafe-inline' when a hash is present, and every napplet is inline script. A test in Chrome 158 confirmed that no napplet can run as a direct child of Flotilla's document, and that a host page fixes it.

Parent of the napplet frameNapplet script runs
A page with Flotilla's policy: script-src 'self' plus a hash, frame-src 'none'No
The same page with 'unsafe-inline' added beside the hashNo
A page with script-src 'self' 'unsafe-inline' and frame-src 'none'Yes
A sandboxed host page with its own policy, inside a page with Flotilla's policy plus frame-src 'self'Yes

In the last case the napplet's port reached the top page and the two exchanged messages directly. The napplet's origin was null, and it couldn't touch localStorage. The third case shows that frame-src 'none' doesn't block srcdoc frames, because loading one makes no navigation request.

The two tests

Both scripts are in .local/napplets/tests/. Each serves its pages from a local HTTP server and connects to bridge chrome --headless on port 9222.

tests/csp-test.mjsjs
import http from "node:http"
import {createHash} from "node:crypto"
import {createRequire} from "node:module"
const require = createRequire("/path/to/build-report/package.json")
const puppeteer = require("puppeteer-core")
const hostScript = `
window.results = []
window.addEventListener("message", e => window.results.push(e.data))
const f = document.createElement("iframe")
f.sandbox.value = "allow-scripts"
f.srcdoc = "<script>parent.postMessage('inline-ran', '*')<\\/script>"
document.body.append(f)
`
const hash = "'sha256-" + createHash("sha256").update(hostScript).digest("base64") + "'"
const policies = {
flotilla: `script-src 'self' 'wasm-unsafe-eval' ${hash}; frame-src 'none'; child-src 'none'`,
flotillaPlusUnsafeInline: `script-src 'self' 'unsafe-inline' ${hash}; frame-src 'none'; child-src 'none'`,
separateHost: `script-src 'self' 'unsafe-inline'; frame-src 'none'; child-src 'none'`,
}
const page = csp => `<!doctype html><html><head><meta http-equiv="Content-Security-Policy" content="${csp}"></head><body><script>${hostScript}</script></body></html>`
const server = http.createServer((req, res) => {
const name = req.url.slice(1)
res.setHeader("content-type", "text/html")
res.end(page(policies[name] ?? ""))
}).listen(0)
const port = server.address().port
const browser = await puppeteer.connect({browserURL: "http://127.0.0.1:9222"})
const tab = await browser.newPage()
for (const name of Object.keys(policies)) {
const violations = []
const onConsole = m => violations.push(m.text().slice(0, 140))
tab.on("console", onConsole)
await tab.goto(`http://127.0.0.1:${port}/${name}`)
await new Promise(r => setTimeout(r, 800))
const results = await tab.evaluate(() => window.results)
tab.off("console", onConsole)
console.log(name.padEnd(26), "napplet script ran:", results.includes("inline-ran"), "| console:", violations.join(" / ") || "-")
}
console.log("browser:", await browser.version())
await tab.close()
browser.disconnect()
server.close()
tests/relay-test.mjsjs
// Strict-CSP top page -> sandboxed same-origin host page with its own CSP -> sandboxed srcdoc napplet.
// The napplet's port is handed up through the host page; the top page talks to the napplet over it.
import http from "node:http"
import {createHash} from "node:crypto"
import {createRequire} from "node:module"
const require = createRequire("/path/to/build-report/package.json")
const puppeteer = require("puppeteer-core")
const nappletHtml = `<script>
const channel = new MessageChannel()
channel.port1.onmessage = e => channel.port1.postMessage({type: "pong", got: e.data.type, origin: self.origin, canStore: (() => { try { localStorage; return true } catch { return false } })()})
parent.postMessage({type: "napplet.hello"}, "*", [channel.port2])
</script>`
const hostScript = `
const frame = document.createElement("iframe")
frame.sandbox.value = "allow-scripts"
window.addEventListener("message", e => {
if (e.source === frame.contentWindow && e.data?.type === "napplet.hello" && e.ports.length === 1) {
parent.postMessage({type: "napplet.hello"}, "*", [e.ports[0]])
} else if (e.source === parent && e.data?.type === "load") {
frame.srcdoc = e.data.html
document.body.append(frame)
}
})
parent.postMessage({type: "host.ready"}, "*")
`
const topScript = `
window.results = []
const host = document.createElement("iframe")
host.sandbox.value = "allow-scripts"
host.src = "/host"
window.addEventListener("message", e => {
if (e.source !== host.contentWindow) return
if (e.data.type === "host.ready") host.contentWindow.postMessage({type: "load", html: ${JSON.stringify(nappletHtml).replace(/<\//g, "<\\/")}}, "*")
if (e.data.type === "napplet.hello") {
const port = e.ports[0]
port.onmessage = m => window.results.push(m.data)
port.postMessage({type: "ping"})
}
})
document.body.append(host)
`
const sha = s => "'sha256-" + createHash("sha256").update(s).digest("base64") + "'"
const pages = {
top: [`script-src 'self' ${sha(topScript)}; frame-src 'self'; child-src 'self'`, topScript],
host: [`default-src 'none'; script-src 'unsafe-inline'; frame-src 'none'; child-src 'none'`, hostScript],
}
const server = http.createServer((req, res) => {
const [csp, script] = pages[req.url.slice(1)] ?? pages.top
res.setHeader("content-type", "text/html")
res.end(`<!doctype html><html><head><meta http-equiv="Content-Security-Policy" content="${csp}"></head><body><script>${script}</script></body></html>`)
}).listen(0)
const browser = await puppeteer.connect({browserURL: "http://127.0.0.1:9222"})
const tab = await browser.newPage()
tab.on("console", m => console.log("console:", m.text().slice(0, 200)))
tab.on("pageerror", e => console.log("pageerror:", e.message))
await tab.goto(`http://127.0.0.1:${server.address().port}/top`)
await new Promise(r => setTimeout(r, 1000))
console.log("top page received over port:", JSON.stringify(await tab.evaluate(() => window.results)))
await tab.close()
browser.disconnect()
server.close()

Layout#

Shell
strict CSP
Verifies bytes, binds the port, serves requests. Adds frame-src 'self'.
Host page
host.html
sandbox="allow-scripts". Prepares the frame, hands the port up, reports faults.
Napplet
srcdoc
sandbox="allow-scripts", under the host page's CSP and the injected one

The host page has an opaque origin, so it can't reach the shell's storage. It makes no network requests. Each host page holds one napplet, and the shell creates a new one for each instance.

Responsibilities#

The host page doesThe shell does
Prepares the srcdoc: the CSP meta, the window.napplet bootstrap for the domains the shell names, and Kehto's WebRTC and nested-frame locksResolves the manifest and verifies the artifact's signature and hash
Refuses bytes that contain dns-prefetch, preconnect or prerender linksDecides which domains to expose
Accepts exactly one napplet.hello with exactly one port, from its own childBinds the napplet's identity and scope to the port it receives
Transfers that port to the shellServes every request on the port
Reports a second hello, any other window message, a second load event or a child frame inside the nappletCloses the port and revokes grants on any fault
Forwards diagnostics: CSP violations, errors and unhandled rejectionsShows napplet failures in its own UI

The shell verifies the bytes, so identity never depends on the host page. The host page is still part of the shell's trusted code, because it holds the port before handing it over.

The CSP floor#

The host page's own policy is inherited by the napplet and by every srcdoc or about:blank frame the napplet creates, and the napplet can't relax it. The host page therefore sets a floor beneath the policy injected into each napplet.

host.html (policy)html
<meta http-equiv="Content-Security-Policy"
content="default-src 'none'; script-src 'unsafe-inline' 'wasm-unsafe-eval'; style-src 'unsafe-inline';
img-src data: blob:; font-src data:; connect-src 'none'; worker-src 'none';
frame-src 'none'; base-uri 'none'; form-action 'none'">

frame-src 'none' doesn't stop the host page from creating the napplet's srcdoc frame, as the tests show. connect-src 'none' is the reason the host page fetches nothing itself.

Shell API#

sketchts
type HostPage = {
load: (html: string, domains: string[]) => void
destroy: () => void
}
type HostPageEvents = {
onPort: (port: MessagePort) => void
onFault: (fault: HostFault) => void
onDiagnostic: (diagnostic: HostDiagnostic) => void
}
declare function mountHostPage(container: HTMLElement, src: string, events: HostPageEvents): HostPage

src is the bundled host.html. The function creates the sandboxed frame, waits for the page to load, and accepts messages only from that frame's window.

Distribution#

Each shell bundles the page. A host page loaded from another origin would sit inside every embedding shell's trust boundary: its operator could swap bytes or keep ports, and a shell can't check a cross-origin frame's code. Bundling also keeps napplets working offline in Capacitor builds. Flotilla copies the page to static/napplet/host.html at build time.

A hosted copy at a versioned path still suits prototypes and shells that can't ship static files.

The package starts in the welshman monorepo, with no welshman dependencies. It moves to the napplet org once its API settles.

Work#

ItemMilestone
Static host.html with its CSP and the handoff scriptM1
Frame preparation with Kehto's prepareNappletSrcdoc, pinned exactlyM1
Shell-side mountHostPage and its fault eventsM1
Scan for resource hints and refuse bytes that contain themM1
Forward CSP violations, errors and unhandled rejections as diagnosticsM1
Browser matrix: Chrome, Firefox, Safari, Android WebView, WKWebViewM1
Hosted copy at a versioned path for prototypesM2
Offer the package to the napplet orgAfter M2

@napplet/conformance's bootAndCollect accepts a custom host, so the conformance suite runs through the host page as well as through the shell.