Skip to content

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

Unify Program asset hosting

zohayrslilehaad1792cde68
diff --git a/scripts/contracts/client-sandbox.ts b/scripts/contracts/client-sandbox.ts
new file mode 100644
index 0000000..b66a86b
--- /dev/null
+++ b/scripts/contracts/client-sandbox.ts
@@ -0,0 +1,43 @@
+import assert from "node:assert/strict"
+import Process from "@server/core/link-manager/auth-manager/process-manager/process"
+import Window from "@server/core/link-manager/auth-manager/process-manager/window"
+import type Program from "@server/core/link-manager/auth-manager/program-manager/program"
+import type HostTraffic from "@server/core/link-manager/auth-manager/process-manager/host-traffic"
+
+const process = new Process(
+
+ "process",
+
+ null,
+
+ { identity: "program" } as Program,
+
+ {},
+
+ { server: null, client: null, options: {} },
+
+ null,
+
+ {} as HostTraffic,
+
+ false
+)
+
+process.startClient(new Window(
+
+ { title: "Client", layer: "window", location: "/" },
+
+ { x: 0, y: 0 },
+
+ { width: 640, height: 480 },
+
+ 1,
+
+ false
+), false)
+
+assert.equal(process.hosted().client?.sameOrigin, false)
+
+process.setClientSameOrigin(true)
+
+assert.equal(process.hosted().client?.sameOrigin, true)
diff --git a/scripts/contracts/client-surface.ts b/scripts/contracts/client-surface.ts
index 83113f9..d8f7922 100644
--- a/scripts/contracts/client-surface.ts
+++ b/scripts/contracts/client-surface.ts
@@ -10,7 +10,7 @@ import type { LocalWindowState } from "@client/view/components/desktop-host/loca
import type { Transaction, WindowLayer } from "@phreshos/core"
const authoritativeWindow = new ServerWindow(
- { title: "Target", url: null, layer: "over", location: "/" },
+ { title: "Target", layer: "over", location: "/" },
{ x: 0, y: 0 },
{ width: 100, height: 100 },
1,
diff --git a/scripts/contracts/permissions.ts b/scripts/contracts/permissions.ts
index fa0b67e..0af1e72 100644
--- a/scripts/contracts/permissions.ts
+++ b/scripts/contracts/permissions.ts
@@ -74,6 +74,7 @@ assert.deepEqual(permissionCatalog.resolve("system", true), ["all"])
assert.deepEqual(permissionCatalog.declarations({ system: true }), { system: ["all"] })
assert(permissionCatalog.grants(["all"], ["all"]))
assert(!permissionCatalog.grants(null, ["all"]))
-assert(!permissionCatalog.needReload("system", null, ["all"]))
-assert(!permissionCatalog.needReload("system", ["all"], null))
+assert(permissionCatalog.needReload("system", null, ["all"]))
+assert(permissionCatalog.needReload("system", ["all"], null))
+assert(!permissionCatalog.needReload("system", ["all"], ["all"]))
assert.throws(() => permissionCatalog.definition("files"), /does not know/)
diff --git a/scripts/contracts/process-lifecycle.ts b/scripts/contracts/process-lifecycle.ts
index 2aed9a9..5428c01 100644
--- a/scripts/contracts/process-lifecycle.ts
+++ b/scripts/contracts/process-lifecycle.ts
@@ -15,6 +15,9 @@ function processManager() {
const manager = new ProcessManager(authManager)
Object.assign(authManager, {
+ programManager: {
+ permission() { return null }
+ },
linkManager: {
application: {
system: {
diff --git a/scripts/contracts/program-development.ts b/scripts/contracts/program-development.ts
new file mode 100644
index 0000000..5f0f512
--- /dev/null
+++ b/scripts/contracts/program-development.ts
@@ -0,0 +1,28 @@
+import assert from "node:assert/strict"
+import Program from "@server/core/link-manager/auth-manager/program-manager/program"
+import { developmentTarget } from "@server/view/program-development"
+
+const development = new Program({
+
+ identity: "example",
+
+ client: { location: "http://localhost:5173/start" }
+})
+
+const target = developmentTarget(
+
+ development,
+
+ "http://localhost:4300/program/example/assets/main.ts?direct"
+)
+
+assert.equal(target?.href, "http://localhost:5173/program/example/assets/main.ts?direct")
+
+const production = new Program({
+
+ identity: "example",
+
+ client: { location: "dist/client" }
+})
+
+assert.equal(developmentTarget(production, "http://localhost:4300/program/example/assets/"), null)
diff --git a/scripts/contracts/program-frame.tsx b/scripts/contracts/program-frame.tsx
index 5bbd46e..8f1af54 100644
--- a/scripts/contracts/program-frame.tsx
+++ b/scripts/contracts/program-frame.tsx
@@ -4,13 +4,14 @@ import ProgramFrame from "@client/view/components/program-frame"
import type Process from "@client/core/link-manager/auth-manager/process-manager/process"
import type ClientState from "@client/core/link-manager/auth-manager/process-manager/client-state"
-const record = { identity: "process", assetId: "asset" } as Process
-const client = { window: { url: null, location: "/" } } as ClientState
+const record = { identity: "process", program: "program" } as Process
+const client = { sameOrigin: false, window: { location: "/" } } as ClientState
const common = {
record,
client,
title: "Program",
door: "/program",
+ access: "available" as const,
onFrame() {},
onLoad() {}
}
@@ -18,6 +19,12 @@ const common = {
const dark = renderToStaticMarkup(<ProgramFrame {...common} theme="dark" />)
const light = renderToStaticMarkup(<ProgramFrame {...common} theme="light" />)
+client.sameOrigin = true
+
+const fullAccess = renderToStaticMarkup(<ProgramFrame {...common} theme="light" />)
+
assert.match(dark, /style="color-scheme:dark"/)
assert.match(light, /style="color-scheme:light"/)
-assert.doesNotMatch(dark, /sandbox=/)
+assert.match(dark, /sandbox="allow-scripts allow-forms"/)
+assert.match(fullAccess, /sandbox="allow-scripts allow-forms allow-same-origin"/)
+assert.match(fullAccess, /src="\/program\/program\/assets\/"/)
diff --git a/scripts/contracts/window-geometry.ts b/scripts/contracts/window-geometry.ts
index ed48ebf..46906d6 100644
--- a/scripts/contracts/window-geometry.ts
+++ b/scripts/contracts/window-geometry.ts
@@ -10,7 +10,7 @@ const initial = {
}
const authority = new ServerWindow(
- { title: "Geometry", url: null, layer: "window", location: "/" },
+ { title: "Geometry", layer: "window", location: "/" },
initial.position,
initial.size,
1,
diff --git a/source/client/core/link-manager/auth-manager/process-manager/client-state.ts b/source/client/core/link-manager/auth-manager/process-manager/client-state.ts
index de9007e..84a0666 100644
--- a/source/client/core/link-manager/auth-manager/process-manager/client-state.ts
+++ b/source/client/core/link-manager/auth-manager/process-manager/client-state.ts
@@ -7,8 +7,12 @@ export default class ClientState {
public readonly window: Window
+ public sameOrigin: boolean
+
public constructor(processManager: ProcessManager, process: string, payload: NonNullable<TransmittedProcess["client"]>) {
this.window = new Window(processManager, process, payload.window)
+
+ this.sameOrigin = payload.sameOrigin
}
}
diff --git a/source/client/core/link-manager/auth-manager/process-manager/process-manager.ts b/source/client/core/link-manager/auth-manager/process-manager/process-manager.ts
index e253d22..d74206a 100644
--- a/source/client/core/link-manager/auth-manager/process-manager/process-manager.ts
+++ b/source/client/core/link-manager/auth-manager/process-manager/process-manager.ts
@@ -282,6 +282,17 @@ export default class ProcessManager extends TheLink {
return this.list()
}
+ @Subscribe("/client-access")
+ @Publish("/processes", "inbound")
+ protected async clientAccessHandle(identity: string | null, payload: TransmittedProcess | null) {
+
+ if (!identity || !payload) return
+
+ this.processes.get(identity)?.clientAccessChanged(payload)
+
+ return this.list()
+ }
+
@Subscribe("/exited")
@Publish("/processes", "inbound")
protected async exitedHandle(payload: TransmittedProcess | null) {
diff --git a/source/client/core/link-manager/auth-manager/process-manager/process.ts b/source/client/core/link-manager/auth-manager/process-manager/process.ts
index 1d001b3..56161f0 100644
--- a/source/client/core/link-manager/auth-manager/process-manager/process.ts
+++ b/source/client/core/link-manager/auth-manager/process-manager/process.ts
@@ -20,10 +20,6 @@ export default class Process {
public readonly program: string
- // Private hosting address from the trusted core payload. It never
- // crosses into a framed program's SDK record.
- public readonly assetId: string
-
// A real date on this side: the link carries dates rather than
// stringifying them.
public readonly startedAt: Date
@@ -52,8 +48,6 @@ export default class Process {
this.program = payload.program
- this.assetId = payload.assetId
-
this.startedAt = payload.startedAt
this.server = payload.server
@@ -100,6 +94,8 @@ export default class Process {
this.client.window.follow(payload.client.window)
+ this.client.sameOrigin = payload.client.sameOrigin
+
return
}
@@ -110,6 +106,11 @@ export default class Process {
this.client = null
}
+
+ public clientAccessChanged(payload: TransmittedProcess) {
+
+ if (this.client && payload.client) this.client.sameOrigin = payload.client.sameOrigin
+ }
}
export interface ProcessRecord {
diff --git a/source/client/core/link-manager/auth-manager/process-manager/window.ts b/source/client/core/link-manager/auth-manager/process-manager/window.ts
index 43bf4e1..d3ad9ac 100644
--- a/source/client/core/link-manager/auth-manager/process-manager/window.ts
+++ b/source/client/core/link-manager/auth-manager/process-manager/window.ts
@@ -31,8 +31,6 @@ export default class Window {
// window owns it.
public title: string
- public url: string | null
-
// The authoritative Desktop layer.
public layer: WindowLayer
@@ -47,8 +45,6 @@ export default class Window {
this.location = payload.location
- this.url = payload.url
-
this.processManager = processManager
this.process = process
@@ -68,8 +64,6 @@ export default class Window {
this.title = payload.title
- this.url = payload.url
-
this.layer = payload.layer
this.location = payload.location
diff --git a/source/client/core/link-manager/auth-manager/program-manager/program-manager.ts b/source/client/core/link-manager/auth-manager/program-manager/program-manager.ts
index d601f11..7843df0 100644
--- a/source/client/core/link-manager/auth-manager/program-manager/program-manager.ts
+++ b/source/client/core/link-manager/auth-manager/program-manager/program-manager.ts
@@ -1,5 +1,5 @@
import { TransmittedProgramManager } from "@server/core/link-manager/auth-manager/program-manager/program-manager"
-import { HostedEntry } from "@server/core/link-manager/auth-manager/program-manager/entry"
+import { ProgramRecord } from "@server/core/link-manager/auth-manager/program-manager/entry"
import { Publish, Subscribe } from "@the-link/core/decorators"
import { TheLink } from "@the-link/core"
import AuthManager from "../auth-manager"
@@ -166,12 +166,12 @@ export default class ProgramManager extends TheLink {
@Subscribe("/install")
@Publish("/programs", "inbound")
- protected async installed(payload: HostedEntry | null) {
+ protected async installed(payload: ProgramRecord | null) {
return this.arrived(payload)
}
- private arrived(payload: HostedEntry | null) {
+ private arrived(payload: ProgramRecord | null) {
if (!payload) return
@@ -182,14 +182,14 @@ export default class ProgramManager extends TheLink {
@Subscribe("/create")
@Publish("/programs", "inbound")
- protected async created(payload: HostedEntry | null) {
+ protected async created(payload: ProgramRecord | null) {
return this.arrived(payload)
}
@Subscribe("/uninstall")
@Publish("/programs", "inbound")
- protected async uninstalled(payload: HostedEntry | null) {
+ protected async uninstalled(payload: ProgramRecord | null) {
return this.arrived(payload)
}
diff --git a/source/client/core/link-manager/auth-manager/program-manager/program.ts b/source/client/core/link-manager/auth-manager/program-manager/program.ts
index f97c13c..7fdb222 100644
--- a/source/client/core/link-manager/auth-manager/program-manager/program.ts
+++ b/source/client/core/link-manager/auth-manager/program-manager/program.ts
@@ -1,4 +1,4 @@
-import { HostedEntry } from "@server/core/link-manager/auth-manager/program-manager/entry"
+import { ProgramRecord } from "@server/core/link-manager/auth-manager/program-manager/entry"
import { type Launch } from "@phreshos/core"
import ProgramManager from "./program-manager"
import type { Transmitted } from "@libs/messagepack"
@@ -22,8 +22,6 @@ export default class Program {
public readonly installed: boolean
- public readonly assetId: string
-
public readonly name: string
public readonly version: string | null
@@ -32,11 +30,11 @@ export default class Program {
public readonly hasAgent: boolean
- public readonly server: Transmitted<HostedEntry>["server"]
+ public readonly server: Transmitted<ProgramRecord>["server"]
- public readonly client: Transmitted<HostedEntry>["client"]
+ public readonly client: Transmitted<ProgramRecord>["client"]
- public constructor(programManager: ProgramManager, payload: Transmitted<HostedEntry>) {
+ public constructor(programManager: ProgramManager, payload: Transmitted<ProgramRecord>) {
this.programManager = programManager
@@ -46,8 +44,6 @@ export default class Program {
this.installed = payload.installed
- this.assetId = payload.assetId
-
this.name = payload.name
this.version = payload.version
diff --git a/source/client/view/components/desktop-host/announcements.ts b/source/client/view/components/desktop-host/announcements.ts
index a72f28e..56b2085 100644
--- a/source/client/view/components/desktop-host/announcements.ts
+++ b/source/client/view/components/desktop-host/announcements.ts
@@ -1,5 +1,5 @@
import { type default as AuthManager } from "@client/core/link-manager/auth-manager/auth-manager"
-import { type HostedEntry } from "@server/core/link-manager/auth-manager/program-manager/entry"
+import { type ProgramRecord } from "@server/core/link-manager/auth-manager/program-manager/entry"
import { ReactTunnel } from "@the-link/react"
import { useCallback } from "react"
import ClientProcessBoundary from "./client-process-boundary"
@@ -72,7 +72,7 @@ export default function useAnnouncements(authManager: AuthManager, panes: Map<st
}, [authManager, post]))
- const programEvent = useCallback((event: "create" | "install" | "uninstall" | "forget", entry: HostedEntry | null, everything?: boolean) => {
+ const programEvent = useCallback((event: "create" | "install" | "uninstall" | "forget", entry: ProgramRecord | null, everything?: boolean) => {
if (!entry) return
@@ -85,10 +85,10 @@ export default function useAnnouncements(authManager: AuthManager, panes: Map<st
}, [post])
- programs.useSubscribe("/create", useCallback((entry: HostedEntry | null) => programEvent("create", entry), [programEvent]))
- programs.useSubscribe("/install", useCallback((entry: HostedEntry | null) => programEvent("install", entry), [programEvent]))
- programs.useSubscribe("/uninstall", useCallback((entry: HostedEntry | null, everything: boolean) => programEvent("uninstall", entry, everything), [programEvent]))
- programs.useSubscribe("/forgotten", useCallback((entry: HostedEntry | null) => programEvent("forget", entry), [programEvent]))
+ programs.useSubscribe("/create", useCallback((entry: ProgramRecord | null) => programEvent("create", entry), [programEvent]))
+ programs.useSubscribe("/install", useCallback((entry: ProgramRecord | null) => programEvent("install", entry), [programEvent]))
+ programs.useSubscribe("/uninstall", useCallback((entry: ProgramRecord | null, everything: boolean) => programEvent("uninstall", entry, everything), [programEvent]))
+ programs.useSubscribe("/forgotten", useCallback((entry: ProgramRecord | null) => programEvent("forget", entry), [programEvent]))
}
function processRecord(authManager: AuthManager, process: ProcessRecord) {
diff --git a/source/client/view/components/program-access.tsx b/source/client/view/components/program-access.tsx
new file mode 100644
index 0000000..535ac5f
--- /dev/null
+++ b/source/client/view/components/program-access.tsx
@@ -0,0 +1,97 @@
+import { type Dispatch, type SetStateAction, useLayoutEffect, useMemo, useRef } from "react"
+
+export type ProgramAccess = "checking" | "available" | "blocked"
+
+const request = "program-access-request"
+const response = "program-access"
+const timeout = 10_000
+
+/** Tests the Desktop's Program asset address from an opaque CORS origin. */
+export default function ProgramAccessProbe({ door, setAccess }: ProgramAccessProbeProps) {
+
+ const frame = useRef<HTMLIFrameElement>(null)
+
+ const document = useMemo(function () {
+
+ const url = new URL(`${door}/ping`, window.location.href).href
+
+ return `<!doctype html><meta charset="utf-8"><script>
+let requested = false;
+let result;
+function report() {
+ if (requested && typeof result === "boolean") parent.postMessage([${JSON.stringify(response)}, result], "*");
+}
+addEventListener("message", event => {
+ if (event.data !== ${JSON.stringify(request)}) return;
+ requested = true;
+ report();
+});
+fetch(${JSON.stringify(url)}, { cache: "no-store" })
+ .then(value => { result = value.ok; report(); })
+ .catch(() => { result = false; report(); });
+</script>`
+
+ }, [door])
+
+ useLayoutEffect(function () {
+
+ const timer = window.setTimeout(() => setAccess("blocked"), timeout)
+
+ function receive(event: MessageEvent) {
+
+ if (event.source !== frame.current?.contentWindow) return
+
+ if (!Array.isArray(event.data) || event.data[0] !== response || typeof event.data[1] !== "boolean") return
+
+ window.clearTimeout(timer)
+
+ setAccess(event.data[1] ? "available" : "blocked")
+ }
+
+ window.addEventListener("message", receive)
+
+ return function () {
+
+ window.clearTimeout(timer)
+
+ window.removeEventListener("message", receive)
+ }
+
+ }, [setAccess])
+
+ return <iframe
+
+ ref={frame}
+
+ srcDoc={document}
+
+ title="Program asset compatibility check"
+
+ sandbox="allow-scripts"
+
+ onLoad={event => event.currentTarget.contentWindow?.postMessage(request, "*")}
+
+ hidden
+
+ />
+}
+
+interface ProgramAccessProbeProps {
+
+ door: string
+
+ setAccess: Dispatch<SetStateAction<ProgramAccess>>
+}
+
+export const blockedProgramDocument = `<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<title>Program unavailable</title>
+</head>
+<body>
+<h1>This Program cannot load</h1>
+<p>The Desktop address or its reverse proxy does not preserve CORS access to <code>/program/*</code>.</p>
+</body>
+</html>`
diff --git a/source/client/view/components/program-frame.tsx b/source/client/view/components/program-frame.tsx
index 9ae1108..6c82b2e 100644
--- a/source/client/view/components/program-frame.tsx
+++ b/source/client/view/components/program-frame.tsx
@@ -1,24 +1,31 @@
import Process from "@client/core/link-manager/auth-manager/process-manager/process"
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"
export function programFrameSource(record: Process, client: ClientState, door: string) {
- const window = client.window
-
- return window.url
-
- ? new URL(window.location.slice(1), window.url).href
-
- : `${door}/${record.assetId}/assets/${window.location.slice(1)}`
+ return `${door}/${record.program}/assets/${client.window.location.slice(1)}`
}
/** The document representation shared by every Client role. */
-export default function ProgramFrame({ record, client, title, door, theme, className = "size-full border-0", onFrame, onLoad }: ProgramFrameProps) {
+export default function ProgramFrame({ record, client, title, door, access, theme, className = "size-full border-0", onFrame, onLoad }: ProgramFrameProps) {
const source = useCallback((element: HTMLIFrameElement | null) => onFrame(record.identity, element), [onFrame, record.identity])
+ if (access === "checking") return null
+
+ if (access === "blocked") return <iframe
+
+ srcDoc={blockedProgramDocument}
+
+ title={`${title}: Program unavailable`}
+
+ className={className}
+
+ />
+
return <iframe
style={{ colorScheme: theme }}
@@ -27,6 +34,8 @@ export default function ProgramFrame({ record, client, title, door, theme, class
title={title}
+ sandbox={`allow-scripts allow-forms${client.sameOrigin ? " allow-same-origin" : ""}`}
+
className={className}
ref={source}
@@ -46,6 +55,8 @@ interface ProgramFrameProps {
door: string
+ access: ProgramAccess
+
theme: Theme
className?: string
diff --git a/source/client/view/structure/desktop/desktop.tsx b/source/client/view/structure/desktop/desktop.tsx
index de8bedd..bb12fa4 100644
--- a/source/client/view/structure/desktop/desktop.tsx
+++ b/source/client/view/structure/desktop/desktop.tsx
@@ -5,6 +5,7 @@ import useClientHost from "../../components/desktop-host/client-host"
import DesktopDisplay from "./desktop-display"
import useDesktopFocus from "./desktop-focus"
import programIcon from "./programs/program-icon"
+import ProgramAccessProbe, { type ProgramAccess } from "../../components/program-access"
import StartMenu from "./taskbar/launcher/start-menu"
import OverflowRow from "./taskbar/programs/overflow-row"
import SignOut from "./taskbar/system/sign-out"
@@ -48,9 +49,11 @@ export default function Workspace() {
const desktop = useRef<HTMLDivElement>(null)
+ const [programAccess, setProgramAccess] = useState<ProgramAccess>("checking")
+
const currentPrograms = new Set(windows.records.map(record => record.identity))
- const initialProgramsReady = [...initialPrograms.current].every(identity => readyPrograms.has(identity) || !currentPrograms.has(identity))
+ const initialProgramsReady = programAccess === "blocked" || [...initialPrograms.current].every(identity => readyPrograms.has(identity) || !currentPrograms.has(identity))
useEffect(function () {
@@ -88,9 +91,9 @@ export default function Workspace() {
// taskbar item would repeat the same linear scan for each process.
const fronts = windows.fronts
- function icon(record: { assetId: string }) {
+ function icon(record: { program: string }) {
- return programIcon(application.doors.program, record.assetId)
+ return programIcon(application.doors.program, record.program)
}
function renderWindows(layer: Layer) {
@@ -141,6 +144,8 @@ export default function Workspace() {
door={application.doors.program}
+ programAccess={programAccess}
+
theme={theme}
onFrame={frame}
@@ -215,6 +220,8 @@ export default function Workspace() {
return <div ref={desktop} tabIndex={-1} aria-label="Desktop" onFocusCapture={focus.remember} className="relative isolate grid min-h-0 grid-cols-1 grid-rows-1 outline-none" style={{ color: foreground }}>
+ <ProgramAccessProbe door={application.doors.program} setAccess={setProgramAccess} />
+
<DesktopDisplay
wallpaper={wallpaper}
diff --git a/source/client/view/structure/desktop/programs/program-icon.ts b/source/client/view/structure/desktop/programs/program-icon.ts
index 18f4650..3de0244 100644
--- a/source/client/view/structure/desktop/programs/program-icon.ts
+++ b/source/client/view/structure/desktop/programs/program-icon.ts
@@ -1,7 +1,7 @@
const icon = "icons/medium.png"
/** The one browser location used for a program's desktop representation. */
-export default function programIcon(door: string, assetId: string) {
+export default function programIcon(door: string, identity: string) {
- return `${door}/${assetId}/${icon}`
+ return `${door}/${identity}/${icon}`
}
diff --git a/source/client/view/structure/desktop/taskbar/launcher/programs-section.tsx b/source/client/view/structure/desktop/taskbar/launcher/programs-section.tsx
index 687f698..7a65122 100644
--- a/source/client/view/structure/desktop/taskbar/launcher/programs-section.tsx
+++ b/source/client/view/structure/desktop/taskbar/launcher/programs-section.tsx
@@ -26,7 +26,7 @@ export default function ProgramsSection({ onChoose }: ProgramsSectionProps) {
key={record.identity}
- icon={programIcon(application.doors.program, record.assetId)}
+ icon={programIcon(application.doors.program, record.identity)}
record={record}
diff --git a/source/client/view/structure/desktop/windows/process-window.tsx b/source/client/view/structure/desktop/windows/process-window.tsx
index a49d0c2..d840425 100644
--- a/source/client/view/structure/desktop/windows/process-window.tsx
+++ b/source/client/view/structure/desktop/windows/process-window.tsx
@@ -7,6 +7,7 @@ import { type Position, type Size, type Theme } from "@phreshos/core"
import Spinner from "@client/view/components/spinner"
import Window from "./window"
import ProgramFrame, { programFrameSource } from "@client/view/components/program-frame"
+import { type ProgramAccess } from "@client/view/components/program-access"
import { memo, type SyntheticEvent, useCallback, useEffect, useState } from "react"
const settleDelay = 80
@@ -16,7 +17,7 @@ const settleDelay = 80
* props so memoization can see which process actually changed even though
* the peer deliberately keeps each Process instance alive and mutates it.
*/
-export default memo(function ({ identity, record, client, title, icon, position, size, localSurface, geometryAnimation, onLocalAnimationComplete, onLocalRepresentation, paintSurfaceSize, depth, active, minimized, closing, stopping, entering, bare, door, theme, onFrame, onFrameLoad, onReady, onRaise, onMinimize, onFill, onClose, onClosed, onUnavailable, onMove, onResize, onSnap }: ProcessWindowProps) {
+export default memo(function ({ identity, record, client, title, icon, position, size, localSurface, geometryAnimation, onLocalAnimationComplete, onLocalRepresentation, paintSurfaceSize, depth, active, minimized, closing, stopping, entering, bare, door, programAccess, theme, onFrame, onFrameLoad, onReady, onRaise, onMinimize, onFill, onClose, onClosed, onUnavailable, onMove, onResize, onSnap }: ProcessWindowProps) {
const activate = useCallback(() => onRaise(record), [onRaise, record])
@@ -83,7 +84,7 @@ export default memo(function ({ identity, record, client, title, icon, position,
}, [frameSource, loading, onReady, record.identity])
- const frameLoading = loading.source !== frameSource || loading.phase !== "ready"
+ const frameLoading = programAccess === "available" && (loading.source !== frameSource || loading.phase !== "ready")
const progress = !bare && (stopping || closing ? "Closing" : frameLoading ? "Loading" : null)
@@ -155,6 +156,8 @@ export default memo(function ({ identity, record, client, title, icon, position,
door={door}
+ access={programAccess}
+
theme={theme}
className={`size-full border-0 ${frameLoading ? "opacity-0" : ""}`}
@@ -227,6 +230,8 @@ interface ProcessWindowProps {
door: string
+ programAccess: ProgramAccess
+
theme: Theme
onFrame: (identity: string, element: HTMLIFrameElement | null) => void
diff --git a/source/server/core/link-manager/auth-manager/process-manager/process-manager.ts b/source/server/core/link-manager/auth-manager/process-manager/process-manager.ts
index 0cc94f8..833d32f 100644
--- a/source/server/core/link-manager/auth-manager/process-manager/process-manager.ts
+++ b/source/server/core/link-manager/auth-manager/process-manager/process-manager.ts
@@ -756,9 +756,9 @@ export default class ProcessManager extends TheLink {
return server
}
- private window(program: Program, shape: Shape) {
+ private window(shape: Shape) {
- const shown = { title: shape.title, url: program.clientRoot, layer: shape.layer, location: shape.location }
+ const shown = { title: shape.title, layer: shape.layer, location: shape.location }
return new Window(shown, shape.position, shape.size, ++this.highest, shape.minimize)
}
@@ -785,9 +785,33 @@ export default class ProcessManager extends TheLink {
// do not hear about it.
const front = shape && this.front(shape.layer)
- const window = shape ? this.window(program, shape) : null
+ const window = shape ? this.window(shape) : null
- const process = new Process(identity, name, program, options, launch, parent, this.hostTraffic)
+ const process = new Process(
+
+ identity,
+
+ name,
+
+ program,
+
+ options,
+
+ launch,
+
+ parent,
+
+ this.hostTraffic,
+
+ permissionCatalog.grants(permissionCatalog.effective(
+
+ "system",
+
+ program.clientPermissions.system ?? null,
+
+ this.authManager.programManager.permission(program, "system")
+ ), ["all"])
+ )
this.processes.set(identity, process)
@@ -1021,7 +1045,7 @@ export default class ProcessManager extends TheLink {
const shape = this.authManager.programManager.clientShape(process.program, launch)
- const window = this.window(process.program, shape)
+ const window = this.window(shape)
const before = this.front(window.layer)
@@ -1390,7 +1414,16 @@ export default class ProcessManager extends TheLink {
process.permissions.set(name, permission)
- return permissionChange(next, permissionCatalog.needReload(name, effective, next))
+ const needReload = permissionCatalog.needReload(name, effective, next)
+
+ if (needReload) {
+
+ process.setClientSameOrigin(permissionCatalog.grants(next, ["all"]))
+
+ await this.$outbound.publish("/client-access", process.identity, process.hosted())
+ }
+
+ return permissionChange(next, needReload)
}
if (choice === "always") {
@@ -1398,7 +1431,7 @@ export default class ProcessManager extends TheLink {
const permission = permissionCatalog.merge(name, stored, requested)
const next = permissionCatalog.effective(name, declared, temporary, permission)
- this.authManager.programManager.setPermission(process.program, name, permission)
+ await this.authManager.programManager.setPermission(process.program, name, permission)
return permissionChange(next, permissionCatalog.needReload(name, effective, next))
}
@@ -1416,6 +1449,38 @@ export default class ProcessManager extends TheLink {
)
}
+ /** Publishes the Client access shape changed by one stored grant. */
+ public async storedPermissionChanged(program: Program, name: string, before: Permission, permission: Permission) {
+
+ let needReload = false
+
+ for (const process of this.processes.values()) {
+
+ if (process.program !== program || !process.client) continue
+
+ const declared = program.clientPermissions[name] ?? null
+ const temporary = process.permissions.get(name) ?? null
+ const changed = permissionCatalog.needReload(
+
+ name,
+
+ permissionCatalog.effective(name, declared, temporary, before),
+
+ permissionCatalog.effective(name, declared, temporary, permission)
+ )
+
+ if (!changed) continue
+
+ needReload = true
+
+ process.setClientSameOrigin(permissionCatalog.grants(this.effectivePermission(process, "system", permission), ["all"]))
+
+ await this.$outbound.publish("/client-access", process.identity, process.hosted())
+ }
+
+ return needReload
+ }
+
public cancelPermission(identity: string, request: string) {
const process = this.processes.get(identity)
@@ -1466,8 +1531,8 @@ export default class ProcessManager extends TheLink {
if (operation === "all") return [this.authManager.programManager.permissions(program)]
if (operation === "get") return [this.authManager.programManager.permission(program, String(rest[2]))]
- if (operation === "set") return [this.authManager.programManager.setPermission(program, String(rest[2]), rest[3] as never)]
- if (operation === "delete") return [this.authManager.programManager.deletePermission(program, String(rest[2]))]
+ if (operation === "set") return [await this.authManager.programManager.setPermission(program, String(rest[2]), rest[3] as never)]
+ if (operation === "delete") return [await this.authManager.programManager.deletePermission(program, String(rest[2]))]
throw new Error(`The System does not know the Program permission operation "${String(operation)}"`)
}
diff --git a/source/server/core/link-manager/auth-manager/process-manager/process.ts b/source/server/core/link-manager/auth-manager/process-manager/process.ts
index 99d84db..178066a 100644
--- a/source/server/core/link-manager/auth-manager/process-manager/process.ts
+++ b/source/server/core/link-manager/auth-manager/process-manager/process.ts
@@ -82,6 +82,8 @@ export default class Process {
private readonly hostTraffic: HostTraffic
+ private clientSameOrigin: boolean
+
private readonly serverStarts: ((server: ServerProcessBoundary) => void)[] = []
private readonly serverStops: ((code: number | null, signal: NodeJS.Signals | null) => void)[] = []
@@ -101,7 +103,7 @@ export default class Process {
private exitProcess: (() => Promise<unknown>) | null = null
- public constructor(identity: string, name: string | null, program: Program, options: Options, launch: ProcessLaunch, parent: Process | null, hostTraffic: HostTraffic) {
+ public constructor(identity: string, name: string | null, program: Program, options: Options, launch: ProcessLaunch, parent: Process | null, hostTraffic: HostTraffic, clientSameOrigin: boolean) {
this.identity = identity
@@ -116,6 +118,13 @@ export default class Process {
this.parent = parent
this.hostTraffic = hostTraffic
+
+ this.clientSameOrigin = clientSameOrigin
+ }
+
+ public setClientSameOrigin(sameOrigin: boolean) {
+
+ this.clientSameOrigin = sameOrigin
}
public startServer(runtime: ServerRuntime, service: boolean, ended: (boundary: ServerProcessBoundary, code: number | null, signal: NodeJS.Signals | null) => Promise<void> | void, unanswered: (values: unknown[], reason: string) => void, appearance: Tunnel) {
@@ -322,9 +331,7 @@ export default class Process {
// pane never receives this record whole.
parent: this.parent?.record() ?? null,
- assetId: this.program.assetId,
-
- client: this.client
+ client: this.client ? { ...this.client, sameOrigin: this.clientSameOrigin } : null
}
}
diff --git a/source/server/core/link-manager/auth-manager/process-manager/window.ts b/source/server/core/link-manager/auth-manager/process-manager/window.ts
index ae991dd..1fe4a0c 100644
--- a/source/server/core/link-manager/auth-manager/process-manager/window.ts
+++ b/source/server/core/link-manager/auth-manager/process-manager/window.ts
@@ -47,8 +47,6 @@ export interface Shown {
title: string
- url: string | null
-
// Which structurally isolated Desktop layer this Window occupies.
layer: WindowLayer
@@ -74,11 +72,6 @@ export default class Window {
// own afterwards.
public title: string
- // Where the frame is filled from, when it is not the program asset route: a
- // client half may name a URL instead of a directory, which is what
- // lets a program under development be shown from its own dev server.
- public readonly url: string | null
-
// The Window's authoritative Desktop layer.
public readonly layer: WindowLayer
@@ -89,8 +82,6 @@ export default class Window {
this.title = shown.title
- this.url = shown.url
-
this.layer = shown.layer
this.location = shown.location
@@ -176,8 +167,6 @@ export default class Window {
title: this.title,
- url: this.url,
-
layer: this.layer,
location: this.location,
diff --git a/source/server/core/link-manager/auth-manager/program-manager/entry.ts b/source/server/core/link-manager/auth-manager/program-manager/entry.ts
index 534d092..5bd2c26 100644
--- a/source/server/core/link-manager/auth-manager/program-manager/entry.ts
+++ b/source/server/core/link-manager/auth-manager/program-manager/entry.ts
@@ -41,14 +41,6 @@ export default class Entry {
}
}
- // Only the trusted desktop needs the private route that hosts this
- // program's files. It is deliberately absent from `toJSON`, which is
- // also what crosses into program SDKs.
- public hosted() {
-
- return { ...this.record(), assetId: this.program.assetId }
- }
-
public toJSON() {
return this.record()
@@ -57,6 +49,4 @@ export default class Entry {
export type ProgramRecord = ReturnType<Entry["record"]>
-export type HostedEntry = ReturnType<Entry["hosted"]>
-
export type TransmittedEntry = Transmitted<ProgramRecord>
diff --git a/source/server/core/link-manager/auth-manager/program-manager/program-manager.ts b/source/server/core/link-manager/auth-manager/program-manager/program-manager.ts
index 112a6ed..a70111a 100644
--- a/source/server/core/link-manager/auth-manager/program-manager/program-manager.ts
+++ b/source/server/core/link-manager/auth-manager/program-manager/program-manager.ts
@@ -16,7 +16,7 @@ import { type ClientLaunch, type Launch, type ProgramCommandChunk } from "@phres
import { type default as Process, type ProcessLaunch, type Stream } from "../process-manager/process"
import { type StandardShape } from "../process-manager/process-manager"
import Program, { type CommandOutput, type InstallOutput } from "./program"
-import Entry, { type HostedEntry } from "./entry"
+import Entry, { type ProgramRecord } from "./entry"
import Keyv from "keyv"
import { isIconSize, ProgramIcons } from "./icon"
import { readStartup, removeStartup, writeStartup } from "./startup"
@@ -167,26 +167,24 @@ export default class ProgramManager extends TheLink {
}
/** Stores one canonical user grant and reports its Client activation need. */
- public setPermission(program: Program, name: string, value: Exclude<PermissionInput, null>): PermissionChange {
+ public async setPermission(program: Program, name: string, value: Exclude<PermissionInput, null>): Promise<PermissionChange> {
if (value === null) throw new Error("A stored Program permission cannot be null")
const permissions = readPermissions(program)
const before = permissions[name] ?? null
const permission = permissionCatalog.resolve(name, value)
- const change = this.permissionChange(program, name, before, permission)
-
if (permissionCatalog.changed(before, permission)) {
permissions[name] = permission
writePermissions(program, permissions)
}
- return change
+ return await this.permissionChange(program, name, before, permission)
}
/** Removes one stored user grant without changing Program declarations. */
- public deletePermission(program: Program, name: string): PermissionChange {
+ public async deletePermission(program: Program, name: string): Promise<PermissionChange> {
permissionCatalog.definition(name)
@@ -199,7 +197,7 @@ export default class ProgramManager extends TheLink {
writePermissions(program, permissions)
}
- return this.permissionChange(program, name, before, null)
+ return await this.permissionChange(program, name, before, null)
}
@Connect("/permissions")
@@ -209,27 +207,15 @@ export default class ProgramManager extends TheLink {
if (operation === "all") return this.permissions(program)
if (operation === "get") return this.permission(program, String(name))
- if (operation === "set") return this.setPermission(program, String(name), value as Exclude<PermissionInput, null>)
- if (operation === "delete") return this.deletePermission(program, String(name))
+ if (operation === "set") return await this.setPermission(program, String(name), value as Exclude<PermissionInput, null>)
+ if (operation === "delete") return await this.deletePermission(program, String(name))
throw new Error(`The System does not know the Program permission operation "${String(operation)}"`)
}
- private permissionChange(program: Program, name: string, before: Permission, permission: Permission): PermissionChange {
-
- const needReload = [...this.authManager.processManager.processes.values()].some(process => {
-
- if (process.program !== program || process.client === null) return false
-
- const declared = program.clientPermissions[name] ?? null
- const temporary = process.permissions.get(name) ?? null
+ private async permissionChange(program: Program, name: string, before: Permission, permission: Permission): Promise<PermissionChange> {
- return permissionCatalog.needReload(
- name,
- permissionCatalog.effective(name, declared, temporary, before),
- permissionCatalog.effective(name, declared, temporary, permission)
- )
- })
+ const needReload = await this.authManager.processManager.storedPermissionChanged(program, name, before, permission)
return Object.freeze({
permission: clonePermission(permission),
@@ -279,14 +265,6 @@ export default class ProgramManager extends TheLink {
return program
}
- // Resolve the browser-only hosting address. This is intentionally a
- // separate lookup from public identity: stable program identities
- // must never become stable asset routes.
- public fromAsset(assetId: string) {
-
- return [...this.programs.values()].find(entry => entry.program.assetId === assetId)?.program ?? null
- }
-
// A program created in memory. From the moment it exists it is an
// ordinary record in the same runtime registry as every installed
// program. Only its installed flag differs, so it survives no
@@ -422,7 +400,7 @@ export default class ProgramManager extends TheLink {
await this.authManager.processManager.announceHost("program", "create", entry.identity, entry)
- await this.$outbound.publish("/create", entry.hosted())
+ await this.$outbound.publish("/create", entry.record())
}
private async change<T>(identity: string, operation: () => Promise<T>) {
@@ -966,7 +944,7 @@ export default class ProgramManager extends TheLink {
// and removing the road took the echo with it — a desktop
// that never learns a program arrived is a desktop showing
// yesterday's list.
- await this.$outbound.publish("/install", entry.hosted())
+ await this.$outbound.publish("/install", entry.record())
return entry
}
@@ -1041,7 +1019,7 @@ export default class ProgramManager extends TheLink {
await this.authManager.processManager.announceSubject("program", "uninstall", entry.program.reference, everything)
- await this.$outbound.publish("/uninstall", entry.hosted(), everything)
+ await this.$outbound.publish("/uninstall", entry.record(), everything)
if (everything) await this.forgetEntry(entry)
@@ -1374,7 +1352,7 @@ export default class ProgramManager extends TheLink {
return {
- programs: [...this.programs].map(([identity, entry]) => [identity, entry.hosted()] as [string, HostedEntry])
+ programs: [...this.programs].map(([identity, entry]) => [identity, entry.record()] as [string, ProgramRecord])
}
}
}
diff --git a/source/server/core/link-manager/auth-manager/program-manager/program.ts b/source/server/core/link-manager/auth-manager/program-manager/program.ts
index 091d35c..c7a8ef4 100644
--- a/source/server/core/link-manager/auth-manager/program-manager/program.ts
+++ b/source/server/core/link-manager/auth-manager/program-manager/program.ts
@@ -26,8 +26,8 @@ import { permissionCatalog } from "@server/core/permissions"
* again by whatever uses it, because the world moves in between.
*
* Identity is the program's one public address, whether or not it is
- * installed. Client files use a separate random address whose only job
- * is hosting: a stable identity never becomes a stable asset URL.
+ * installed. The browser asset view uses that same domain address rather
+ * than inventing a second identity for the same Program.
*/
export default class Program {
@@ -36,8 +36,6 @@ export default class Program {
/** Opaque identity of this runtime Program entity. */
public readonly reference = randomUUID()
- public readonly assetId = randomUUID()
-
/** Changes whenever this runtime Program is replaced in place. */
public revision = 0
@@ -73,8 +71,8 @@ export default class Program {
}
// Installation lays the same logical program out in the system's
- // canonical place. Its public identity and private asset address do
- // not change; only the description and root it runs from do.
+ // canonical place. Its identity does not change; only the description
+ // and root it runs from do.
public replace(source: Program) {
if (source.identity !== this.identity) throw new Error("A program cannot change its identity")
@@ -121,9 +119,9 @@ export default class Program {
} : null
}
- // A client half may name a URL instead of a directory, which is how
- // a program under development is framed from a live dev server. An
- // installed program cannot: its paths are not its own to choose.
+ // A client half may name a URL instead of a directory. The Program asset
+ // view proxies that development source beneath the same browser address
+ // used for installed files. An installed program cannot name a URL.
public get clientUrl() {
const location = this.config.client?.location
@@ -131,26 +129,6 @@ export default class Program {
return location && /^https?:\/\//i.test(location) ? location : null
}
- // A URL declaration says two things in one ordinary URL: its last
- // slash ends the place this client may be launched beneath, and the
- // remainder is the page it opens on when a launch says nothing.
- public get clientRoot() {
-
- const location = this.clientUrl
-
- if (!location) return null
-
- const url = new URL(location)
-
- url.pathname = url.pathname.slice(0, url.pathname.lastIndexOf("/") + 1)
-
- url.search = ""
-
- url.hash = ""
-
- return url.href
- }
-
public get clientLocation() {
const location = this.clientUrl
diff --git a/source/server/core/permissions.ts b/source/server/core/permissions.ts
index bf6e081..52fe634 100644
--- a/source/server/core/permissions.ts
+++ b/source/server/core/permissions.ts
@@ -176,6 +176,12 @@ export const permissionCatalog = new PermissionCatalog({
values: ["all"],
default: ["all"],
title: "System",
- description: "Access every System capability."
+ description: "Access every System capability.",
+ requiresReload: (before, permission) => grantsAll(before) !== grantsAll(permission)
}
})
+
+function grantsAll(permission: Permission) {
+
+ return Array.isArray(permission) && permission.includes("all")
+}
diff --git a/source/server/view/program-development.ts b/source/server/view/program-development.ts
new file mode 100644
index 0000000..f6aab01
--- /dev/null
+++ b/source/server/view/program-development.ts
@@ -0,0 +1,185 @@
+import { upgradeWebSocket } from "@hono/node-server"
+import type Program from "@server/core/link-manager/auth-manager/program-manager/program"
+import { proxy } from "hono/proxy"
+import type { Context } from "hono"
+import { WebSocket, type RawData } from "ws"
+
+/** Maps one public Program asset request onto its development server. */
+export function developmentTarget(program: Program, request: string) {
+
+ if (!program.clientUrl) return null
+
+ const source = new URL(program.clientUrl)
+ const asked = new URL(request)
+
+ source.pathname = asked.pathname
+ source.search = asked.search
+ source.hash = ""
+
+ return source
+}
+
+/** Forwards one HTTP asset request without exposing its source to the Desktop. */
+export async function developmentResponse(context: Context, target: URL) {
+
+ const headers = new Headers(context.req.raw.headers)
+
+ headers.delete("host")
+ headers.set("x-forwarded-host", new URL(context.req.url).host)
+ headers.set("x-forwarded-proto", new URL(context.req.url).protocol.slice(0, -1))
+
+ try {
+
+ const response = await proxy(target, {
+
+ raw: context.req.raw,
+
+ headers,
+
+ redirect: "manual"
+ })
+
+ rewriteLocation(response, target, context.req.url)
+
+ return response
+ }
+
+ catch {
+
+ return context.text("The development Client is unavailable", 502)
+ }
+}
+
+/** Bridges one WebSocket through the same Program asset address as HTTP. */
+export function developmentSocket(context: Context, target: URL) {
+
+ return upgradeWebSocket(context, bridge(target, context.req.header("sec-websocket-protocol")), {
+
+ onError(error) { console.error(error) }
+ })
+}
+
+function rewriteLocation(response: Response, target: URL, request: string) {
+
+ const location = response.headers.get("location")
+
+ if (!location) return
+
+ const upstream = new URL(location, target)
+
+ if (upstream.origin !== target.origin) return
+
+ const publicOrigin = new URL(request).origin
+
+ response.headers.set("location", new URL(`${upstream.pathname}${upstream.search}${upstream.hash}`, publicOrigin).href)
+}
+
+function bridge(target: URL, protocolHeader: string | undefined) {
+
+ const protocols = protocolHeader?.split(",").map(value => value.trim()).filter(Boolean) ?? []
+ const queued: DevelopmentMessage[] = []
+ let server: WebSocket | null = null
+
+ return {
+
+ onOpen(_event: Event, client: import("hono/ws").WSContext) {
+
+ const address = new URL(target)
+
+ address.protocol = address.protocol === "https:" ? "wss:" : "ws:"
+
+ const upstream = new WebSocket(address, protocols, { origin: target.origin })
+
+ server = upstream
+
+ upstream.on("open", () => {
+
+ for (const message of queued.splice(0)) upstream.send(message)
+ })
+
+ upstream.on("message", (message, binary) => sendClient(client, message, binary))
+
+ upstream.on("close", (code, reason) => closeClient(client, code, reason.toString()))
+
+ upstream.on("error", () => client.close(1011, "The development Client WebSocket failed"))
+ },
+
+ onMessage(event: MessageEvent, client: import("hono/ws").WSContext) {
+
+ forwardServer(server, queued, event.data).catch(() => client.close(1011, "The development Client WebSocket failed"))
+ },
+
+ onClose(event: CloseEvent) {
+
+ closeServer(server, event.code, event.reason)
+ },
+
+ onError() {
+
+ server?.close(1011, "The Desktop WebSocket failed")
+ }
+ }
+}
+
+type DevelopmentMessage = string | ArrayBuffer | Uint8Array<ArrayBuffer>
+
+async function forwardServer(server: WebSocket | null, queued: DevelopmentMessage[], source: unknown) {
+
+ const message = source instanceof Blob ? await source.arrayBuffer() : source
+
+ if (typeof message !== "string" && !(message instanceof ArrayBuffer) && !ArrayBuffer.isView(message)) return
+
+ let value: DevelopmentMessage
+
+ if (typeof message === "string" || message instanceof ArrayBuffer) value = message
+
+ else {
+
+ const bytes = new Uint8Array(message.byteLength)
+
+ bytes.set(new Uint8Array(message.buffer, message.byteOffset, message.byteLength))
+
+ value = bytes
+ }
+
+ if (server?.readyState === WebSocket.OPEN) server.send(value)
+
+ else queued.push(value)
+}
+
+function sendClient(client: import("hono/ws").WSContext, source: RawData, binary: boolean) {
+
+ if (!binary) {
+
+ client.send(String(source))
+
+ return
+ }
+
+ const value = Array.isArray(source) ? Buffer.concat(source) : source
+
+ if (value instanceof ArrayBuffer) client.send(value)
+
+ else client.send(Uint8Array.from(value))
+}
+
+function closeClient(client: import("hono/ws").WSContext, code: number, reason: string) {
+
+ if (validCloseCode(code)) client.close(code, reason)
+
+ else client.close()
+}
+
+function closeServer(server: WebSocket | null, code: number, reason: string) {
+
+ if (!server) return
+
+ if (validCloseCode(code)) server.close(code, reason)
+
+ else server.close()
+}
+
+function validCloseCode(code: number) {
+
+ return code === 1000 || (code >= 1001 && code <= 1014 && ![1004, 1005, 1006].includes(code)) || (code >= 3000 && code <= 4999)
+}
diff --git a/source/server/view/program.ts b/source/server/view/program.ts
index 8bda6c2..4a36bcd 100644
--- a/source/server/view/program.ts
+++ b/source/server/view/program.ts
@@ -2,20 +2,16 @@ import { serveStatic } from "@hono/node-server/serve-static"
import Application from "@server/core/application"
import { isIconSize } from "@server/core/link-manager/auth-manager/program-manager/icon"
import { existsSync } from "node:fs"
-import doors from "./doors"
import { Hono } from "hono"
+import doors from "./doors"
+import { developmentResponse, developmentSocket, developmentTarget } from "./program-development"
/**
- * What a program shows: its client half at `/program/<assetId>/assets`,
- * and how it is drawn at `/program/<assetId>/icons`.
- *
- * The asset id is a private runtime address, separate from public
- * program identity. Both are reachable only while the runtime registry
- * retains the program.
+ * The browser representation of one Program domain.
*
- * No authorization: these are files a browser reads, with no link and
- * no operations. Nothing here can be found from a program's stable
- * identity.
+ * Every Client document uses `/program/<identity>/assets`, independently of
+ * whether its source is an installed directory or a live development server.
+ * Icons use the same Program identity beneath `/program/<identity>/icons`.
*/
export default function (application: Application) {
@@ -23,18 +19,54 @@ export default function (application: Application) {
const program = new Hono()
- // A client is entered at its directory: the trailing slash makes
- // the page's relative assets resolve beneath it.
- program.get("/:assetId{[0-9a-f-]{36}}/assets", context => context.redirect(`${new URL(context.req.url).pathname}/`))
+ // The hidden Desktop probe deliberately asks from an opaque origin. Keep
+ // this header on every Program response so an outer reverse proxy becomes
+ // part of the same observable hosting contract.
+ program.use("*", async (context, next) => {
+
+ await next()
+
+ context.header("Access-Control-Allow-Origin", "*")
+ })
+
+ program.get("/ping", context => {
+
+ context.header("Cache-Control", "no-store")
+
+ return context.text("Program assets are available")
+ })
+
+ program.get("/:identity/assets", context => context.redirect(`${new URL(context.req.url).pathname}/`))
- program.use("/:assetId{[0-9a-f-]{36}}/assets/:path{.*}", async (context, next) => {
+ // A development Client's WebSocket is the same asset source as its HTTP
+ // documents. Bridging it here keeps HMR beneath the Program asset address.
+ program.use("/:identity/assets/:path{.*}", async (context, next) => {
- const assetId = context.req.param("assetId") ?? ""
+ if (context.req.header("upgrade")?.toLowerCase() !== "websocket") return await next()
- const found = programManager.fromAsset(assetId)
+ const found = programManager.reach(context.req.param("identity"))
if (!found) return context.text("Unknown program", 404)
+ const target = developmentTarget(found, context.req.url)
+
+ if (!target) return context.text("The program has no development Client", 404)
+
+ return developmentSocket(context, target)
+ })
+
+ program.all("/:identity/assets/:path{.*}", async context => {
+
+ const identity = context.req.param("identity")
+
+ const found = programManager.reach(identity)
+
+ if (!found) return context.text("Unknown program", 404)
+
+ const target = developmentTarget(found, context.req.url)
+
+ if (target) return await developmentResponse(context, target)
+
const root = found.clientPath
// A retained Program may outlive files removed by uninstall(false).
@@ -44,14 +76,14 @@ export default function (application: Application) {
root,
- rewriteRequestPath: path => path.slice(`${doors.program}/${assetId}/assets`.length)
+ rewriteRequestPath: path => path.slice(`${doors.program}/${identity}/assets`.length)
- })(context, next)
+ })(context, async () => undefined)
})
- program.get("/:assetId{[0-9a-f-]{36}}/icons/:file", async context => {
+ program.get("/:identity/icons/:file", async context => {
- const found = programManager.fromAsset(context.req.param("assetId") ?? "")
+ const found = programManager.reach(context.req.param("identity"))
if (!found) return context.text("Unknown program", 404)