Skip to content

An open-source, self-hosted system for apps built with web technologies.

Serve program frames with initial desktop theme

zohayrslileh7b67bee98914
diff --git a/bun.lock b/bun.lock
index 365f802..e7fc63c 100644
--- a/bun.lock
+++ b/bun.lock
@@ -9,7 +9,7 @@
"@hono/node-server": "^2.1.1",
"@jitl/quickjs-ng-wasmfile-release-sync": "^0.32.0",
"@phreshos/core": "^0.1.63",
- "@phreshos/react-ui": "^0.1.43",
+ "@phreshos/react-ui": "^0.1.45",
"@the-link/core": "^0.3.1",
"@the-link/http": "^0.1.1",
"@the-link/ipc": "^0.2.2",
@@ -19,6 +19,7 @@
"hono": "^4.13.8",
"keyv": "^5.6.0",
"motion": "^13.4.0",
+ "parse5": "^8.0.1",
"quickjs-emscripten-core": "^0.32.0",
"react": "^19.3.0",
"react-dom": "^19.3.0",
@@ -201,7 +202,7 @@
"@phreshos/core": ["@phreshos/[email protected]", "", { "dependencies": { "zod": "^4.6.5" } }, "sha512-wzIRrjok93QJQb/cpm5A/PVRm50x6FTP4Agj2l8kUsg1rkrTLZAU/iX63DlQ02hrkYypM0aEfhbpuZJn9jpV3Q=="],
- "@phreshos/react-ui": ["@phreshos/[email protected]", "", { "dependencies": { "@base-ui/react": "^1.7.0", "@internationalized/date": "^3.12.3", "@phreshos/core": "^0.1.63", "colorjs.io": "^0.7.1", "lucide-react": "^1.48.0", "react-aria": "^3.51.0", "react-aria-components": "^1.20.0" }, "peerDependencies": { "react": "^19.2.0", "react-dom": "^19.2.0" } }, "sha512-v8SFWHo3LVdBEMfIkFDdbBOnBbIlG5UB5iuOQSjbl1OB64wTdBW4R44QPZsCkKeiW/9dzYQWAVirZ68XFYdVsA=="],
+ "@phreshos/react-ui": ["@phreshos/[email protected]", "", { "dependencies": { "@base-ui/react": "^1.7.0", "@internationalized/date": "^3.12.3", "@phreshos/core": "^0.1.63", "colorjs.io": "^0.7.1", "lucide-react": "^1.48.0", "react-aria": "^3.51.0", "react-aria-components": "^1.20.0" }, "peerDependencies": { "react": "^19.2.0", "react-dom": "^19.2.0" } }, "sha512-6Y+k5EFSIpuSxzcJymjOJQQiBW9zmdkVb5U9qYDryfWPYyqOvua5FqI2F5ZiQ++gJiFDdJgkaYokJCCiC3m7IA=="],
"@react-types/shared": ["@react-types/[email protected]", "", { "peerDependencies": { "react": "^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1" } }, "sha512-AzsuD9OfxTOZMMvTRhlN3oHBwOmFN7tDh27LzqmHt4+uOgPhJT7ZM7/kVs/8/o0WxayMUIk3hBmCFRHv1FUoag=="],
@@ -355,6 +356,8 @@
"enhanced-resolve": ["[email protected]", "", { "dependencies": { "graceful-fs": "^4.2.4", "tapable": "^2.3.3" } }, "sha512-nGXts5znJzmWPu+mIE9izCOzdg63oJca2mDzGWWTth7sr4aCToKcoyFVBQwN75Ij5Pf6p510EwkTqViTRzDV+w=="],
+ "entities": ["[email protected]", "", {}, "sha512-kxL7msIffSuh9aaFAMD7rxAIuTRMAHMeBtgHW2yUdWw732ZNh4MehkF2gdjvtdmikkaIP9bFDDJOPlsvm7avrA=="],
+
"es-module-lexer": ["[email protected]", "", {}, "sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw=="],
"escalade": ["[email protected]", "", {}, "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA=="],
@@ -447,6 +450,8 @@
"obug": ["[email protected]", "", {}, "sha512-XrsrhT5sybtKI6wakr2SPOlGZWWYbUXZ7a0jT8/QOeAPau+1X/bSegNe5YR75oJmEZQbKningirmGOEJCIk61Q=="],
+ "parse5": ["[email protected]", "", { "dependencies": { "entities": "^8.0.0" } }, "sha512-z1e/HMG90obSGeidlli3hj7cbocou0/wa5HacvI3ASx34PecNjNQeaHNo5WIZpWofN9kgkqV1q5YvXe3F0FoPw=="],
+
"pathe": ["[email protected]", "", {}, "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w=="],
"picocolors": ["[email protected]", "", {}, "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA=="],
diff --git a/package.json b/package.json
index 470cc10..14a4589 100644
--- a/package.json
+++ b/package.json
@@ -1,7 +1,7 @@
{
"name": "phreshos",
"displayName": "PhreshOS",
- "version": "0.1.98",
+ "version": "0.1.99",
"description": "The PhreshOS server, desktop, and authoritative system runtime.",
"type": "module",
"private": true,
@@ -38,7 +38,7 @@
"@hono/node-server": "^2.1.1",
"@jitl/quickjs-ng-wasmfile-release-sync": "^0.32.0",
"@phreshos/core": "^0.1.63",
- "@phreshos/react-ui": "^0.1.43",
+ "@phreshos/react-ui": "^0.1.45",
"@the-link/core": "^0.3.1",
"@the-link/http": "^0.1.1",
"@the-link/ipc": "^0.2.2",
@@ -48,6 +48,7 @@
"hono": "^4.13.8",
"keyv": "^5.6.0",
"motion": "^13.4.0",
+ "parse5": "^8.0.1",
"quickjs-emscripten-core": "^0.32.0",
"react": "^19.3.0",
"react-dom": "^19.3.0",
diff --git a/source/client/view/components/program-frame.tsx b/source/client/view/components/program-frame.tsx
index 9483584..5b90e79 100644
--- a/source/client/view/components/program-frame.tsx
+++ b/source/client/view/components/program-frame.tsx
@@ -2,7 +2,7 @@ import Process from "@client/core/link-manager/auth-manager/process-manager/proc
import ClientState from "@client/core/link-manager/auth-manager/process-manager/client-state"
import { blockedProgramDocument, type ProgramAccess } from "./program-access"
import { type Theme } from "@phreshos/core"
-import { type ReactEventHandler, useCallback } from "react"
+import { type ReactEventHandler, useCallback, useRef } from "react"
export function programFrameSource(assetId: string, door: string) {
@@ -14,6 +14,14 @@ export default function ProgramFrame({ record, assetId, client, title, door, acc
const source = useCallback((element: HTMLIFrameElement | null) => onFrame(record.identity, element), [onFrame, record.identity])
+ // The document is served in the Desktop's theme at the moment the frame loads it. A later theme
+ // change must not change the address, which would reload the Program; the Program follows it itself.
+ const frameSource = programFrameSource(assetId, door)
+
+ const themed = useRef({ frameSource, source: `${frameSource}?theme=${theme}` })
+
+ if (themed.current.frameSource !== frameSource) themed.current = { frameSource, source: `${frameSource}?theme=${theme}` }
+
if (access === "checking") return null
if (access === "blocked") return <iframe
@@ -28,9 +36,7 @@ export default function ProgramFrame({ record, assetId, client, title, door, acc
return <iframe
- style={{ colorScheme: theme }}
-
- src={programFrameSource(assetId, door)}
+ src={themed.current.source}
title={title}
diff --git a/source/server/view/http/program/frame-document.ts b/source/server/view/http/program/frame-document.ts
new file mode 100644
index 0000000..d565b03
--- /dev/null
+++ b/source/server/view/http/program/frame-document.ts
@@ -0,0 +1,77 @@
+import { parse } from "parse5"
+
+type Theme = "light" | "dark"
+
+/**
+ * The Desktop theme a Program frame document is requested with. The Desktop
+ * names it in the frame's address when it creates the frame; only the frame's
+ * own document is shaped, never another HTML asset.
+ */
+export function frameTheme(request: Request): Theme | null {
+
+ if (request.headers.get("sec-fetch-dest") !== "iframe") return null
+
+ const theme = new URL(request.url).searchParams.get("theme")
+
+ return theme === "light" || theme === "dark" ? theme : null
+}
+
+/**
+ * Serves a Program frame document in the Desktop's theme from its first byte.
+ * A frame whose document's color scheme differs from the Desktop's is painted
+ * opaque by the browser, so the document declares the Desktop's theme before
+ * any of its code runs. A document that declares its own color scheme keeps it.
+ */
+export async function themedFrameDocument(response: Response, theme: Theme | null) {
+
+ if (theme === null || !response.ok || response.headers.has("content-encoding")) return response
+
+ if (!response.headers.get("content-type")?.toLowerCase().startsWith("text/html")) return response
+
+ const html = colorScheme(await response.text(), theme)
+
+ const headers = new Headers(response.headers)
+
+ headers.delete("content-length")
+
+ headers.delete("etag")
+
+ return new Response(html, { status: response.status, statusText: response.statusText, headers })
+}
+
+/** Adds `<meta name="color-scheme">` at the start of the document's head, leaving every other byte as written. */
+export function colorScheme(html: string, theme: Theme) {
+
+ const document = parse(html, { sourceCodeLocationInfo: true })
+
+ const root = document.childNodes.find(node => node.nodeName === "html")
+
+ const head = root && "childNodes" in root ? root.childNodes.find(node => node.nodeName === "head") : undefined
+
+ if (!head || !("childNodes" in head)) return html
+
+ const declared = head.childNodes.some(node => node.nodeName === "meta" && "attrs" in node
+ && node.attrs.some(attribute => attribute.name === "name" && attribute.value.trim().toLowerCase() === "color-scheme"))
+
+ if (declared) return html
+
+ const meta = `<meta name="color-scheme" content="${theme}">`
+
+ // After the head's start tag, or where the head begins when the document leaves its tags out:
+ // after the html start tag, or after the doctype, never before it.
+ const doctype = document.childNodes.find(node => node.nodeName === "#documentType")
+
+ const offset = startTagEnd(head) ?? startTagEnd(root) ?? doctype?.sourceCodeLocation?.endOffset ?? 0
+
+ return html.slice(0, offset) + meta + html.slice(offset)
+}
+
+/** Where a written start tag ends; nothing when the parser implied the element. */
+function startTagEnd(node: object | undefined) {
+
+ const location = node && "sourceCodeLocation" in node ? node.sourceCodeLocation : undefined
+
+ return location && typeof location === "object" && "startTag" in location
+ ? (location.startTag as { endOffset: number } | undefined)?.endOffset
+ : undefined
+}
diff --git a/source/server/view/http/program/program.ts b/source/server/view/http/program/program.ts
index b24d150..81cb4aa 100644
--- a/source/server/view/http/program/program.ts
+++ b/source/server/view/http/program/program.ts
@@ -5,6 +5,7 @@ import { existsSync } from "node:fs"
import { Hono } from "hono"
import doors from "../doors"
import { developmentResponse, developmentSocket, developmentTarget } from "./development"
+import { frameTheme, themedFrameDocument } from "./frame-document"
/**
* The browser representation of one Program domain.
@@ -65,20 +66,24 @@ export default function (application: Application) {
const target = developmentTarget(found, context.req.url)
- if (target) return await developmentResponse(context, target)
+ const theme = frameTheme(context.req.raw)
+
+ if (target) return await themedFrameDocument(await developmentResponse(context, target), theme)
const root = found.clientPath
// A retained Program may outlive files removed by uninstall().
if (!root || !existsSync(root)) return context.text("The program has no assets", 404)
- return await serveStatic({
+ const response = await serveStatic({
root,
rewriteRequestPath: path => path.slice(`${doors.program}/${assetId}/assets`.length)
})(context, async () => undefined)
+
+ return response ? await themedFrameDocument(response, theme) : response
})
program.get("/:assetId{[0-9a-f-]{36}}/icons/:file", async context => {
diff --git a/tests/frame-document.test.ts b/tests/frame-document.test.ts
new file mode 100644
index 0000000..25c9067
--- /dev/null
+++ b/tests/frame-document.test.ts
@@ -0,0 +1,58 @@
+import assert from "node:assert/strict"
+import { colorScheme, frameTheme, themedFrameDocument } from "@server/view/http/program/frame-document"
+import { test } from "vitest"
+
+const page = `<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8" />
+ <title>Program</title>
+</head>
+<body><div id="root"></div></body>
+</html>`
+
+function frameRequest(query: string, destination = "iframe") {
+ return new Request(`http://localhost/program/id/assets/${query}`, { headers: { "sec-fetch-dest": destination } })
+}
+
+test("reads the theme only from a frame document request", () => {
+ assert.equal(frameTheme(frameRequest("?theme=dark")), "dark")
+ assert.equal(frameTheme(frameRequest("?theme=light")), "light")
+ assert.equal(frameTheme(frameRequest("?theme=sepia")), null)
+ assert.equal(frameTheme(frameRequest("")), null)
+ assert.equal(frameTheme(frameRequest("?theme=dark", "document")), null)
+})
+
+test("declares the theme at the start of the head, leaving every other byte as written", () => {
+ const themed = colorScheme(page, "dark")
+ assert.equal(themed, page.replace("<head>", `<head><meta name="color-scheme" content="dark">`))
+})
+
+test("finds the head where the document leaves its tags out, never before the doctype", () => {
+ assert.equal(colorScheme(`<!DOCTYPE html><title>Program</title>`, "light"), `<!DOCTYPE html><meta name="color-scheme" content="light"><title>Program</title>`)
+ assert.equal(colorScheme(`<!DOCTYPE html><html><body>Program</body></html>`, "light"), `<!DOCTYPE html><html><meta name="color-scheme" content="light"><body>Program</body></html>`)
+ // A head in a comment is text, not the head.
+ assert.equal(colorScheme(`<!-- <head> --><!DOCTYPE html><head></head>`, "dark"), `<!-- <head> --><!DOCTYPE html><head><meta name="color-scheme" content="dark"></head>`)
+})
+
+test("keeps a color scheme the document declares itself", () => {
+ const declared = page.replace("<title>", `<meta name="Color-Scheme" content="light dark"><title>`)
+ assert.equal(colorScheme(declared, "dark"), declared)
+})
+
+test("shapes only successful, uncompressed HTML responses", async () => {
+ const html = (body: string, headers: Record<string, string> = {}) => new Response(body, { headers: { "content-type": "text/html; charset=utf-8", "content-length": String(body.length), ...headers } })
+
+ const themed = await themedFrameDocument(html(page), "dark")
+ assert.match(await themed.text(), /<meta name="color-scheme" content="dark">/)
+ assert.equal(themed.headers.get("content-length"), null)
+
+ const script = new Response("console.log(1)", { headers: { "content-type": "text/javascript" } })
+ assert.equal(await themedFrameDocument(script, "dark"), script)
+
+ const compressed = html(page, { "content-encoding": "gzip" })
+ assert.equal(await themedFrameDocument(compressed, "dark"), compressed)
+
+ const unthemed = html(page)
+ assert.equal(await themedFrameDocument(unthemed, null), unthemed)
+})
diff --git a/tests/program-frame.test.tsx b/tests/program-frame.test.tsx
index 969db3e..66e63df 100644
--- a/tests/program-frame.test.tsx
+++ b/tests/program-frame.test.tsx
@@ -24,9 +24,10 @@ test("program frame contract", async () => {
const trusted = renderToStaticMarkup(<ProgramFrame {...common} client={{ ...client, sandbox: false } as ClientState} theme="light" />)
- assert.match(dark, /style="color-scheme:dark"/)
- assert.match(light, /style="color-scheme:light"/)
+ // The frame asks for its document in the Desktop's theme; the frame element itself is not styled.
+ assert.match(dark, /src="\/program\/00000000-0000-4000-8000-000000000000\/assets\/\?theme=dark"/)
+ assert.match(light, /src="\/program\/00000000-0000-4000-8000-000000000000\/assets\/\?theme=light"/)
+ assert.doesNotMatch(dark, /color-scheme/)
assert.match(dark, /sandbox="allow-scripts allow-forms"/)
assert.doesNotMatch(trusted, /sandbox=/)
- assert.match(trusted, /src="\/program\/00000000-0000-4000-8000-000000000000\/assets\/"/)
}, 120_000)