An open-source, self-hosted system for apps built with web technologies.
Add the permission-constrained Sandbox runtime
zohayrslilehea66a46d4fa0
diff --git a/bun.lock b/bun.lockindex aae30fd..99a44d2 100644--- a/bun.lock+++ b/bun.lock@@ -7,6 +7,7 @@"dependencies": {"@fontsource/roboto": "^5.3.0","@hono/node-server": "^2.1.1",+ "@jitl/quickjs-ng-wasmfile-release-sync": "^0.32.0","@phreshos/core": "^0.1.52","@phreshos/react-ui": "^0.1.27","@the-link/core": "^0.3.0",@@ -18,6 +19,7 @@"hono": "^4.13.2","keyv": "^5.6.0","motion": "^13.2.0",+ "quickjs-emscripten-core": "^0.32.0","react": "^19.2.8","react-dom": "^19.2.8","sharp": "^0.35.3",@@ -228,6 +230,10 @@"@internationalized/string": ["@internationalized/[email protected]", "", { "dependencies": { "@swc/helpers": "^0.5.0" } }, "sha512-PDx6//vHSpRnHfxqMqto11zQvhsaU74O3mKv2F/0eicGZcl9NLjQmGlbHz/LsJh5tLKp4A4L7ZVTzN1/MmMTvA=="],+ "@jitl/quickjs-ffi-types": ["@jitl/[email protected]", "", {}, "sha512-v9T+GQpmk43VDJ7d72sf0Nexhk+ArvtUihW27dy7lqAl0zBObFKtSBBIm5RBjwIhE8VwsPPm9PNuvPvNqLWUEg=="],++ "@jitl/quickjs-ng-wasmfile-release-sync": ["@jitl/[email protected]", "", { "dependencies": { "@jitl/quickjs-ffi-types": "0.32.0" } }, "sha512-XAX2jjZWWh3M0YaRqi82xMKNW/gkF6mo3MpW3UY2cmVxnQai1JuboVsJQVoLU629iEL4XWvHtO4h5lo7NRnAcg=="],+"@jridgewell/gen-mapping": ["@jridgewell/[email protected]", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.0", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA=="],"@jridgewell/remapping": ["@jridgewell/[email protected]", "", { "dependencies": { "@jridgewell/gen-mapping": "^0.3.5", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ=="],@@ -498,6 +504,8 @@"postcss": ["[email protected]", "", { "dependencies": { "nanoid": "^3.3.17", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-u82N74LFzG8ca+dD8puPnplTXoGH4fTPpVGuIbt36G3qvNlkvfD0lEAZSxaly3KX8TS/L1A1gsCEmvKmBcVbkQ=="],+ "quickjs-emscripten-core": ["[email protected]", "", { "dependencies": { "@jitl/quickjs-ffi-types": "0.32.0" } }, "sha512-QFnPfjFey8EqknSrSxe1hZrf1/8z7/6s1QzGOmKo6++02r7QRRX7ZoyNaZh7JuVjWsVW87KnQrbZqnHkOAzUyg=="],+"react": ["[email protected]", "", {}, "sha512-PWaYA1L/q9u2u7xYQi+Y3L3Yfnie7XyLeaJICV1MGD6LprsBxcAqGjYyr0eY3p+QdsA+x/Irkt4Qif8D63+Sbw=="],"react-aria": ["[email protected]", "", { "dependencies": { "@internationalized/date": "^3.12.3", "@internationalized/number": "^3.6.7", "@internationalized/string": "^3.2.10", "@react-types/shared": "^3.36.1", "@swc/helpers": "^0.5.0", "aria-hidden": "^1.2.3", "clsx": "^2.0.0", "react-stately": "3.49.0", "use-sync-external-store": "^1.6.0" }, "peerDependencies": { "react": "^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1", "react-dom": "^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1" } }, "sha512-AyWLw0XR38cFPwBu/ErgGaVrc5dupLEKmRlMXTGvFKOtbaGRQ2+yQJkjVhpdHhoRhU4+G+tJDFeHDTS8tK3bfQ=="],diff --git a/package.json b/package.jsonindex f770840..23dad33 100644--- a/package.json+++ b/package.json@@ -36,6 +36,7 @@"dependencies": {"@fontsource/roboto": "^5.3.0","@hono/node-server": "^2.1.1",+ "@jitl/quickjs-ng-wasmfile-release-sync": "^0.32.0","@phreshos/core": "^0.1.52","@phreshos/react-ui": "^0.1.27","@the-link/core": "^0.3.0",@@ -47,6 +48,7 @@"hono": "^4.13.2","keyv": "^5.6.0","motion": "^13.2.0",+ "quickjs-emscripten-core": "^0.32.0","react": "^19.2.8","react-dom": "^19.2.8","sharp": "^0.35.3",diff --git a/scripts/build.ts b/scripts/build.tsindex 0a01395..59b4009 100644--- a/scripts/build.ts+++ b/scripts/build.ts@@ -1,5 +1,7 @@import { externalDependencies } from "@/vite.config"-import { rm, writeFile } from "node:fs/promises"+import { copyFile, mkdir, rm, writeFile } from "node:fs/promises"+import { createRequire } from "node:module"+import { dirname, resolve } from "node:path"import packageConfig from "@/package.json"process.env.NODE_ENV = "production"@@ -17,6 +19,12 @@ for (const externalDependency of externalDependencies) {await build({ configFile: "vite.config.ts", ssr: { noExternal: true } })+const require = createRequire(import.meta.url)+const sandboxWasm = require.resolve("@jitl/quickjs-ng-wasmfile-release-sync/wasm")+const sandboxWasmDestination = resolve("dist/server/assets/emscripten-module.wasm")+await mkdir(dirname(sandboxWasmDestination), { recursive: true })+await copyFile(sandboxWasm, sandboxWasmDestination)+await build({ configFile: "vite.client.ts" })await writeFile("dist/package.json", JSON.stringify({diff --git a/source/client/view/components/desktop-host/client-process-boundary.ts b/source/client/view/components/desktop-host/client-process-boundary.tsindex e7df706..674f7da 100644--- a/source/client/view/components/desktop-host/client-process-boundary.ts+++ b/source/client/view/components/desktop-host/client-process-boundary.ts@@ -148,6 +148,8 @@ export default class ClientProcessBoundary extends TheLink {if (route === "boundary") {+ if (!this.owner) this.pending.push(message)+this.control(values)returndiff --git a/source/server/core/application.ts b/source/server/core/application.tsindex 9e3a473..8570cb1 100644--- a/source/server/core/application.ts+++ b/source/server/core/application.ts@@ -9,8 +9,7 @@ import Keyv from "keyv"import FileArea, { FileSystem } from "@libs/file-area"import { homedir } from "node:os"import System from "./system"-import type Program from "./link-manager/auth-manager/program-manager/program"-import type { ServerRuntimeFactory } from "./server-runtime"+import createServerRuntime from "./server-runtime/factory"export default class Application {@@ -44,8 +43,8 @@ export default class Application {/** One authoritative System domain shared by every trusted adapter. */public readonly system: System- /** Runtime creation supplied by the host boundary. */- public readonly createServerRuntime: ServerRuntimeFactory<Program>+ /** Core-owned factory for every Server execution environment. */+ public readonly createServerRuntime: typeof createServerRuntimeprivate constructor(payload: ApplicationPayload) {@@ -69,7 +68,7 @@ export default class Application {this.appearanceManager = payload.appearanceManager- this.createServerRuntime = payload.createServerRuntime+ this.createServerRuntime = createServerRuntimethis.dialogManager = new DialogManager()@@ -78,7 +77,7 @@ export default class Application {this.system = new System(this)}- public static async initialize(name: string, displayName: string, version: string, homePath: string, defaultProgramIcon: string, createServerRuntime: ServerRuntimeFactory<Program>) {+ public static async initialize(name: string, displayName: string, version: string, homePath: string, defaultProgramIcon: string) {const storage = new FileManager(homePath)@@ -92,7 +91,7 @@ export default class Application {const appearanceManager = await AppearanceManager.open(store, uploads)- const application = new Application({ name, displayName, version, defaultProgramIcon, storage, home, store, authentication, appearanceManager, uploads, createServerRuntime })+ const application = new Application({ name, displayName, version, defaultProgramIcon, storage, home, store, authentication, appearanceManager, uploads })await application.linkManager.authManager.programManager.initialize()@@ -121,6 +120,4 @@ interface ApplicationPayload {appearanceManager: AppearanceManageruploads: UploadManager-- createServerRuntime: ServerRuntimeFactory<Program>}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.tsindex 985951d..40da407 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@@ -1,5 +1,4 @@import { Connect, Subscribe } from "@the-link/core/decorators"-import { uploadLimit } from "@server/core/upload-manager"import { type Options } from "../program-manager/program-manager"import Program from "../program-manager/program"import { Layer } from "../program-manager/config"@@ -18,6 +17,7 @@ import EndpointServices, { serviceTimeout } from "./endpoint-services"import OutsideQuestions from "./outside-questions"import {isServiceKey,+ isUploadFile,parsePermissionName,parseProgramInstallOptions,parseProgramUninstallOptions,@@ -37,6 +37,8 @@ import {import { isDesktopReplacementLayer, type DesktopReplacementLayer } from "@shared/desktop-replacement"import type { ServerRuntime, ServerRuntimeFactory } from "@server/core/server-runtime"import { permissionCatalog } from "@server/core/permissions"+import SystemAccess from "./system-access"+import { WebSocket } from "ws"/*** The core's processes: the wire and the collection. Each process owns@@ -79,6 +81,8 @@ export default class ProcessManager extends TheLink {/** Live observations owned by an authenticated System representation. */private readonly connectionObservations = new Map<string, Map<string, () => void>>()+ private readonly serverSockets = new WeakMap<ServerProcessBoundary, Map<string, WebSocket>>()+// Endpoint transitions for one Process are serialized. State is changed in// one place, so two simultaneous stop requests cannot both believe the// other endpoint will preserve the Process lifetime.@@ -895,7 +899,9 @@ export default class ProcessManager extends TheLink {(values, reason) => this.rejectQuestion(values, reason),- this.authManager.linkManager.appearance.tunnel+ this.authManager.linkManager.appearance.tunnel,++ (domain, subject) => this.serverHostVisible(process, domain, subject))this.bindServer(process, server)@@ -903,6 +909,26 @@ export default class ProcessManager extends TheLink {return server}+ private serverHostVisible(process: Process, domain: "program" | "process" | "connection" | "session" | "window", subject: string | null) {++ const access = new SystemAccess(this, process)++ if (domain === "connection" || domain === "session") return access.canConnections()++ if (!subject) return false++ if (domain === "program") {++ const program = [...this.authManager.programManager.programs.values()].find(entry => entry.program.reference === subject)?.program++ return program ? access.canProgram(program) : false+ }++ const target = [...this.processes.values()].find(candidate => candidate.reference === subject)++ return target ? access.canProcess(target) : false+ }+private window(shape: Shape) {const shown = { title: shape.title, layer: shape.layer }@@ -1659,22 +1685,57 @@ export default class ProcessManager extends TheLink {const [word, ...rest] = args- if (word === "host-program-list") return [this.system.listPrograms(rest[0] === true)]+ const access = new SystemAccess(this, process)++ const heldProgram = (value: unknown, fallback: Program = process.program) => access.program(this.system.holdProgram(value, fallback))++ const heldProcess = (value: unknown, fallback: Process = process) => access.process(this.system.holdProcess(value, fallback))++ const heldWindow = (value: unknown) => {++ const window = this.heldWindow(value, process)++ access.process(window.process)++ return window+ }++ const heldService = (value: unknown) => {++ if (!isServiceKey(value)) throw new Error("A complete Service key is required")++ const program = value.program ?? this.services.target(value)?.process.program.identity ?? null++ if (program !== process.program.identity && !this.grants(process.identity, "services", program === null ? [] : [program])) {++ throw new Error("The Service represented by this key does not exist")+ }++ return value+ }++ if (word === "host-program-list") return [this.system.listPrograms(rest[0] === true).filter(program => access.canProgram(program))]if (typeof word === "string" && (word.startsWith("host-connection-") || word.startsWith("host-session-"))) {if (word === "host-connection-list") {+ if (!access.canConnections()) return [[]]+return [this.system.listConnections().map(connection => this.authManager.linkManager.connectionSnapshot(connection))]}if (word === "host-connection-find") {+ if (!access.canConnections()) return [null]+const connection = this.system.findConnection(String(rest[0]))return [connection ? this.authManager.linkManager.connectionSnapshot(connection) : null]}+ if (word.startsWith("host-connection-") && !access.canConnections()) throw new Error("Connection not found")+if (word === "host-connection-state") return [this.system.connectionSnapshot(String(rest[0]))]if (word === "host-connection-session") return [this.system.connectionSession(String(rest[0]))]@@ -1683,16 +1744,22 @@ export default class ProcessManager extends TheLink {if (word === "host-session-list") {+ if (!access.canConnections()) return [[]]+return [this.system.listSessions().map(identity => this.authManager.linkManager.sessionSnapshot(identity))]}if (word === "host-session-find") {+ if (!access.canConnections()) return [null]+const session = this.system.findSession(String(rest[0]))return [session ? this.authManager.linkManager.sessionSnapshot(session) : null]}+ if (!access.canConnections()) throw new Error("Session not found")+if (word === "host-session-state") return [this.system.sessionSnapshot(String(rest[0]))]if (word === "host-session-connections") {@@ -1712,14 +1779,37 @@ export default class ProcessManager extends TheLink {const identity = String(rest[0])- return [this.system.findProgram(identity)]+ const found = this.system.findProgram(identity)++ return [found && access.canProgram(found) ? found : null]}if (word === "current-program") return [this.system.requireProgram(process.program.identity)]+ if (word === "context-permission-get") {++ return [this.permission(process.identity, parsePermissionName(rest[0]))]+ }++ if (word === "context-permission-allows") {++ const permission = parsePermissionName(rest[0])++ return [this.authManager.programManager.allowsPermission(process.program, permission, rest[1] as PermissionRequest<typeof permission>)]+ }++ if (word === "context-permission-request") {++ const permission = parsePermissionName(rest[1])++ return [await this.requestPermission(process.identity, String(rest[0]), permission, rest[2] as PermissionRequest<typeof permission>)]+ }+if (word === "program-permissions") {- const program = this.system.holdProgram(rest[0], process.program)+ const program = heldProgram(rest[0])++ access.requireAll()const operation = rest[1]if (operation === "all") return [this.authManager.programManager.permissions(program)]@@ -1754,7 +1844,7 @@ export default class ProcessManager extends TheLink {if (word === "program-agent") {- const program = this.system.holdProgram(rest[0], process.program)+ const program = heldProgram(rest[0])return [await this.system.programAgent(program)]}@@ -1763,21 +1853,25 @@ export default class ProcessManager extends TheLink {if (word === "icon") {- return [await this.system.programIcon(this.system.holdProgram(rest[0], process.program), rest[1])]+ return [await this.system.programIcon(heldProgram(rest[0]), rest[1])]}if (word === "launch") {- const program = this.system.holdProgram(rest[0], process.program)+ const program = heldProgram(rest[0])++ const value = rest[1] === "set" ? access.launch(rest[2]) : rest[2]- return [await this.system.programLaunch(program, String(rest[1]), rest[2])]+ return [await this.system.programLaunch(program, String(rest[1]), value)]}if (word === "startup") {- const program = this.system.holdProgram(rest[0], process.program)+ const program = heldProgram(rest[0])++ const value = rest[1] === "enable" ? access.launch(rest[2]) : rest[2]- return [await this.system.programStartup(program, String(rest[1]), rest[2])]+ return [await this.system.programStartup(program, String(rest[1]), value)]}// Which exact process made this one through `program.createProcess()`.@@ -1785,7 +1879,7 @@ export default class ProcessManager extends TheLink {// Process handle rather than to this relationship.if (word === "parent") {- const target = this.system.holdProcess(rest[0], process)+ const target = heldProcess(rest[0])if (!target.parent) return [null]@@ -1797,6 +1891,8 @@ export default class ProcessManager extends TheLink {// program. Its installed flag begins false.if (word === "host-program-create") {+ access.requireAll()+const source = rest[0]if (typeof source !== "string" && (typeof source !== "object" || source === null)) throw new Error("A program is created from a config or a path")@@ -1808,6 +1904,8 @@ export default class ProcessManager extends TheLink {if (word === "host-program-force-create") {+ access.requireAll()+const source = rest[0]if (typeof source !== "string" && (typeof source !== "object" || source === null)) throw new Error("A program is created from a config or a path")@@ -1821,6 +1919,8 @@ export default class ProcessManager extends TheLink {if (word === "update-appearance") {+ access.require("appearance", [])+await this.system.updateAppearance(rest[0])return []@@ -1828,33 +1928,33 @@ export default class ProcessManager extends TheLink {if (word === "installed") {- return [this.system.programInstalled(this.system.holdProgram(rest[0]))]+ return [this.system.programInstalled(heldProgram(rest[0]))]}if (word === "forget") {- const program = this.system.holdProgram(rest[0])+ const program = heldProgram(rest[0])return [await this.system.forgetProgram(program, process.identity)]}if (word === "program-create-process") {- const program = this.system.holdProgram(rest[0])+ const program = heldProgram(rest[0])// The whole record, not the identity alone: the kit builds a// Process from this answer, and a record invented at the// other end — identity and program, nothing else — was how every// process held by its launcher had no startedAt while every// other road's did.- return [processReference(this.system.requireProcess(await this.system.createProcess(program, rest[1] as Launch, process)))]+ return [processReference(this.system.requireProcess(await this.system.createProcess(program, access.launch(rest[1]), process)))]}if (word === "program-find-or-create-process") {- const program = this.system.holdProgram(rest[0])+ const program = heldProgram(rest[0])- return [processReference(this.system.requireProcess(await this.system.findOrCreateProcess(program, rest[1] as Launch & { name: string }, process)))]+ return [processReference(this.system.requireProcess(await this.system.findOrCreateProcess(program, access.launch(rest[1]) as Launch & { name: string }, process)))]}// Named, only that program's instances; unnamed, every one.@@ -1862,7 +1962,7 @@ export default class ProcessManager extends TheLink {const living = this.system.listProcesses()- if (word === "host-process-list") return [living.map(processReference)]+ if (word === "host-process-list") return [living.filter(target => access.canProcess(target)).map(processReference)]// Resolved before it is filtered. Filtering alone answered// an empty list for a program the system does not know,@@ -1870,14 +1970,14 @@ export default class ProcessManager extends TheLink {// from *there is no such program* — every other act on one// refuses, and a word that answers falsely where its// neighbours refuse is worse than either.- const program = this.system.holdProgram(rest[0])+ const program = heldProgram(rest[0])return [this.system.listProcesses(program).map(processReference)]}if (word === "program-find-process") {- const program = this.system.holdProgram(rest[0])+ const program = heldProgram(rest[0])const wanted = String(rest[1])@@ -1892,7 +1992,7 @@ export default class ProcessManager extends TheLink {const target = this.system.findProcess(rest[0])- return [target ? processReference(target) : null]+ return [target && access.canProcess(target) ? processReference(target) : null]}return [null]@@ -1900,7 +2000,7 @@ export default class ProcessManager extends TheLink {if (word === "exists") {- const target = this.system.holdProcess(rest[1], process)+ const target = heldProcess(rest[1])if (rest[0] === "server") return [target.server !== null]@@ -1911,7 +2011,7 @@ export default class ProcessManager extends TheLink {if (word === "is-service") {- const target = this.system.holdProcess(rest[1], process)+ const target = heldProcess(rest[1])const endpoint = rest[0] ?? "server"if (endpoint !== "server" && endpoint !== "client") throw new Error("A Process endpoint is server or client")@@ -1921,18 +2021,18 @@ export default class ProcessManager extends TheLink {if (word === "start-endpoint") {- const target = this.system.holdProcess(rest[0], process)+ const target = heldProcess(rest[0])if (rest[1] === "server") return [await this.system.startEndpoint(target, "server", rest[2] as ServerLaunch | undefined)]- if (rest[1] === "client") return [await this.system.startEndpoint(target, "client", rest[2] as ClientLaunch | undefined)]+ if (rest[1] === "client") return [await this.system.startEndpoint(target, "client", access.clientLaunch(rest[2]))]throw new Error("A Process endpoint is server or client")}if (word === "stop-endpoint") {- const target = this.system.holdProcess(rest[0], process)+ const target = heldProcess(rest[0])if (rest[1] === "server") return [await this.system.stopEndpoint(target, "server")]@@ -1943,9 +2043,9 @@ export default class ProcessManager extends TheLink {if (word === "stop-current") return [await this.system.stopEndpoint(process, "server")]- if (word === "service-exists") return [this.services.exists(rest[0])]+ if (word === "service-exists") return [this.services.exists(heldService(rest[0]))]- if (word === "service-wait-ready") return [await this.services.waitReady(rest[0], rest[1])]+ if (word === "service-wait-ready") return [await this.services.waitReady(heldService(rest[0]), rest[1])]if (word === "service-follow") {@@ -1957,7 +2057,7 @@ export default class ProcessManager extends TheLink {if (event !== null && typeof event !== "string") return []- server.followService(this.services, subscription, key, scope, event)+ server.followService(this.services, subscription, heldService(key), scope, event)return []}@@ -1975,7 +2075,7 @@ export default class ProcessManager extends TheLink {if (!isServiceKey(key) || typeof event !== "string") return []- const target = this.services.target(key)+ const target = this.services.target(heldService(key))if (target) await this.publish(process.identity, "server", target.process.identity, target.endpoint, [event, payload])@@ -1993,7 +2093,7 @@ export default class ProcessManager extends TheLink {return []}- const target = this.services.target(key, "server")+ const target = this.services.target(heldService(key), "server")if (!target?.process.server) {@@ -2031,14 +2131,14 @@ export default class ProcessManager extends TheLink {// depth was being used to ask.if (word === "window") {- const target = this.heldWindow(rest[0], process).process+ const target = heldWindow(rest[0]).processreturn [this.system.windowSnapshot(target)]}if (word === "move") {- const target = this.heldWindow(rest[0], process).process+ const target = heldWindow(rest[0]).processawait this.system.moveWindow(target, rest[1] as Position)@@ -2047,7 +2147,7 @@ export default class ProcessManager extends TheLink {if (word === "resize") {- const target = this.heldWindow(rest[0], process).process+ const target = heldWindow(rest[0]).processawait this.system.resizeWindow(target, rest[1] as Size)@@ -2056,7 +2156,7 @@ export default class ProcessManager extends TheLink {if (word === "setGeometry") {- const target = this.heldWindow(rest[0], process).process+ const target = heldWindow(rest[0]).processawait this.system.setWindowGeometry(target, rest[1] as WindowGeometry)@@ -2065,7 +2165,7 @@ export default class ProcessManager extends TheLink {if (word === "changeTitle") {- const target = this.heldWindow(rest[0], process).process+ const target = heldWindow(rest[0]).processawait this.system.changeWindowTitle(target, String(rest[1] ?? ""))@@ -2074,7 +2174,7 @@ export default class ProcessManager extends TheLink {if (word === "raise") {- const target = this.heldWindow(rest[0], process).process+ const target = heldWindow(rest[0]).processawait this.system.raiseWindow(target)@@ -2083,14 +2183,14 @@ export default class ProcessManager extends TheLink {if (word === "maximize") {- const target = this.heldWindow(rest[0], process).process+ const target = heldWindow(rest[0]).processawait this.system.maximizeWindow(target, rest[1] !== false)return [target.identity]}if (word === "minimize") {- const target = this.heldWindow(rest[0], process).process+ const target = heldWindow(rest[0]).processawait this.system.minimizeWindow(target, rest[1] !== false)@@ -2099,14 +2199,14 @@ export default class ProcessManager extends TheLink {if (word === "exit") {- const target = this.system.holdProcess(rest[0], process)+ const target = heldProcess(rest[0])await this.system.exitProcess(target)return [target.identity]}- if (word === "program-exit-processes") return [await this.system.exitProgramProcesses(this.system.holdProgram(rest[0]), process.identity)]+ if (word === "program-exit-processes") return [await this.system.exitProgramProcesses(heldProgram(rest[0]), process.identity)]if (word === "observe") {@@ -2120,7 +2220,7 @@ export default class ProcessManager extends TheLink {if (event !== null && typeof event !== "string") return []- const target = this.system.holdProcess(rest[1], process)+ const target = heldProcess(rest[1])this.observeServer(process, String(rest[0]), target, String(rest[2]), kind, event, reportImpossible)@@ -2140,7 +2240,7 @@ export default class ProcessManager extends TheLink {if (event !== null && typeof event !== "string") return []- const target = this.system.holdProcess(rest[1], process)+ const target = heldProcess(rest[1])this.followServer(process, String(rest[0]), target, String(rest[2]), event, rest[4] === true)@@ -2184,7 +2284,7 @@ export default class ProcessManager extends TheLink {if (half !== "server" && half !== "client") throw new Error(`A process has no "${String(half)}" end`)- const target = this.system.holdProcess(rest[0])+ const target = heldProcess(rest[0])await this.publish(process.identity, "server", target.identity, half, rest.slice(2))@@ -2209,7 +2309,7 @@ export default class ProcessManager extends TheLink {if (typeof rest[3] !== "string" || typeof rest[4] !== "string") throw new Error("A question needs a public id and an event name")- const targetProcess = this.system.holdProcess(rest[0])+ const targetProcess = heldProcess(rest[0])const target = targetProcess.server@@ -2227,30 +2327,112 @@ export default class ProcessManager extends TheLink {return []}- // A server SDK asks the host only where a Program's area begins;- // every filesystem operation belongs to the SDK after that. The- // area is shared by every Process, so the Program is named rather- // than the Process. With no name, it is the asker's own Program.+ if (word === "fetch") {++ const description = rest[0] as { url?: unknown, method?: unknown, headers?: unknown, redirect?: unknown }++ if (!description || typeof description.url !== "string") throw new Error("A network request needs a URL")++ access.require("network", [description.url])++ const response = await fetch(description.url, {+ method: typeof description.method === "string" ? description.method : "GET",+ headers: Array.isArray(description.headers) ? description.headers as [string, string][] : undefined,+ redirect: description.redirect === "error" || description.redirect === "manual" ? description.redirect : "follow",+ body: rest[1] === null || rest[1] === undefined ? null : Buffer.from(byteValue(rest[1]))+ })++ return [{+ body: response.body ? new Uint8Array(await response.arrayBuffer()) : null,+ headers: [...response.headers.entries()],+ redirected: response.redirected,+ status: response.status,+ statusText: response.statusText,+ type: response.type,+ url: response.url+ }]+ }++ if (word === "websocket-open") {++ const identity = String(rest[0])+ const url = String(rest[1])+ const protocols = rest[2]++ access.require("network", [url])++ if (!identity) throw new Error("A WebSocket needs an identity")+ if (protocols !== undefined && typeof protocols !== "string" && (!Array.isArray(protocols) || protocols.some(value => typeof value !== "string"))) {+ throw new Error("WebSocket protocols must be text")+ }++ const sockets = this.serverSockets.get(server) ?? new Map<string, WebSocket>()+ if (sockets.has(identity)) throw new Error("The WebSocket identity already exists")+ this.serverSockets.set(server, sockets)++ const socket = new WebSocket(url, protocols as string | string[] | undefined)+ sockets.set(identity, socket)+ const release = server.retainResource(() => {+ sockets.delete(identity)+ socket.close()+ })++ socket.on("message", (data, binary) => {+ const value = binary ? Uint8Array.from(data as Buffer) : String(data)+ server.deliver("host-websocket", identity, "message", value).catch(() => undefined)+ })+ socket.on("error", () => server.deliver("host-websocket", identity, "error").catch(() => undefined))+ socket.on("close", (code, reason) => {+ release()+ server.deliver("host-websocket", identity, "close", { code, reason: reason.toString(), wasClean: true }).catch(() => undefined)+ })++ await new Promise<void>((resolve, reject) => {+ socket.once("open", resolve)+ socket.once("error", reject)+ })++ return [{ extensions: socket.extensions, protocol: socket.protocol }]+ }++ if (word === "websocket-send" || word === "websocket-close") {++ const socket = this.serverSockets.get(server)?.get(String(rest[0]))+ if (!socket) throw new Error("The WebSocket does not exist")++ if (word === "websocket-send") socket.send(typeof rest[1] === "string" ? rest[1] : byteValue(rest[1]))+ else socket.close(typeof rest[1] === "number" ? rest[1] : undefined, typeof rest[2] === "string" ? rest[2] : undefined)++ return []+ }++ // Program-owned storage uses the same System operation vocabulary in+ // every execution environment. The runtime never receives a native+ // filesystem capability.if (word === "data" || word === "cache") {// The one registry is the authority for every program,// installed or not. Naming the current program explicitly// must therefore be equivalent to leaving the subject empty.- const program = this.system.holdProgram(rest[0], process.program)-- if (rest[1] !== "path") throw new Error("A server half asks the host only for an area path")+ const program = heldProgram(rest[0])- return [this.system.programArea(program, word, "path", [])]+ return [this.system.programArea(program, word, String(rest[1]), rest.slice(2))]}- // Native filesystem work remains local to the Server SDK. The System- // supplies the user's home as the relative entry point; the- // SDK may resolve beyond it without turning the host into a file proxy.+ // Native storage remains a System capability even when the selected+ // runtime could reach the host directly by another route.if (word === "host-storage") {- if (rest[0] !== "path") throw new Error("A server half asks the host only for its Storage path")+ const operation = String(rest[0])+ const joins = stringPath(rest[1])+ const path = this.system.nativeStorage("path", joins) as string+ const required = operation === "delete-storage" || operation === "delete-file" || operation === "clear"+ ? "delete"+ : operation === "create" ? "write" : "read"- return [this.system.storagePath]+ access.requireStorage(path, required)++ return [this.system.nativeStorage(operation, joins, rest[2])]}// What a program has said, asked for and never told. The@@ -2259,7 +2441,7 @@ export default class ProcessManager extends TheLink {// anything here deciding what a query means.if (word === "logs") {- const program = this.system.holdProgram(rest[0], process.program)+ const program = heldProgram(rest[0])return [this.system.programQuery(program, "logs", String(rest[1]), Array.isArray(rest[2]) ? rest[2] : [])]}@@ -2269,21 +2451,42 @@ export default class ProcessManager extends TheLink {// is the program's own, which is why they are two files.if (word === "database") {- const program = this.system.holdProgram(rest[0], process.program)+ const program = heldProgram(rest[0])return [this.system.programQuery(program, "database", String(rest[1]), Array.isArray(rest[2]) ? rest[2] : [])]}- // A Server Endpoint performs upload byte I/O locally. The SDK receives- // the managed root only for stream and write operations; upload keys- // remain flat and validated by both sides.if (word === "uploads") {const { uploads } = this.system- if (rest[0] === "access") return [uploads.fileManager.path, uploadLimit]+ if (rest[0] === "path") {++ access.requireStorage(uploads.fileManager.path)++ return [uploads.fileManager.path]+ }if (rest[0] === "stat") return [uploads.stat(String(rest[1]))]+ if (rest[0] === "write") {++ access.require("uploads", [])++ const bytes = byteValue(rest[1])++ const description = rest[2] as { extension?: unknown } | null++ if (!description || typeof description.extension !== "string") throw new Error("Uploads write takes a value description")++ const file = await uploads.write(description.extension, byteStream(bytes))++ const stat = uploads.stat(file)++ if (!stat) throw new Error("The completed upload could not be described")++ return [{ file, ...stat }]+ }+throw new Error(`The uploads capability does not know the operation "${String(rest[0])}"`)}@@ -2295,7 +2498,7 @@ export default class ProcessManager extends TheLink {const [operation, key, value, ttl] = rest.slice(1) as [string, string, unknown, number | undefined]- const whose = this.system.holdProgram(rest[0], process.program)+ const whose = heldProgram(rest[0])return [await this.system.programStore(whose, operation, key, value, ttl)]}@@ -2309,7 +2512,9 @@ export default class ProcessManager extends TheLink {if (args[0] === "wait-ready") {- const target = this.system.holdProcess(args[1], process)+ const access = new SystemAccess(this, process)++ const target = access.process(this.system.holdProcess(args[1], process))const endpoint = args[2]@@ -2414,7 +2619,162 @@ export default class ProcessManager extends TheLink {const operation = args[0]- const program = this.system.holdProgram(args[1])+ const access = new SystemAccess(this, process)++ if (operation === "shell") {++ access.requireAll()++ const controller = new AbortController()++ cancel = () => { active = false; controller.abort(new Error("The shell command was cancelled")) }++ for await (const event of this.system.shell(String(args[1]), { ...(args[2] as object), signal: controller.signal })) {++ if (!active) return++ await this.say(server, "host-end", "stream", question, "data", event)+ }++ if (active) await this.say(server, "host-end", "stream", question, "answer", succeeded(undefined))++ return+ }++ if (operation === "uploads-stream") {++ const file = String(args[1])++ if (!isUploadFile(file)) throw new Error("That is not an upload file")++ for await (const chunk of this.system.uploads.stream(file)) {++ if (!active) return++ await this.say(server, "host-end", "stream", question, "data", Uint8Array.from(chunk))+ }++ if (active) await this.say(server, "host-end", "stream", question, "answer", succeeded(undefined))++ return+ }++ if (operation === "storage-content") {++ const scope = args[1]++ const program = scope === "program" ? access.program(this.system.holdProgram(args[2], process.program)) : null++ const area = scope === "program" && (args[3] === "data" || args[3] === "cache") ? args[3] : null++ const action = String(args[scope === "program" ? 4 : 2])++ const joins = stringPath(args[scope === "program" ? 5 : 3])++ const value = args[scope === "program" ? 6 : 4]++ const input = args[scope === "program" ? 7 : 5] as { offset?: number, length?: number, overwrite?: boolean } | undefined++ if (scope !== "program" && scope !== "system") throw new Error("Storage content needs a scope")++ if (scope === "program" && !area) throw new Error("Program storage needs an area")++ if (scope === "system") {++ const path = this.system.nativeStorage("path", joins) as string++ access.requireStorage(path, action === "stream" ? "read" : "write")+ }++ if (action === "stream") {++ const stream = program+ ? this.authManager.programManager.streamArea(program, area!, joins, [input?.offset, input?.length])+ : this.system.nativeStorageStream(joins, input)++ for await (const chunk of stream) {++ if (!active) return++ await this.say(server, "host-end", "stream", question, "data", Uint8Array.from(chunk))+ }+ }++ else {++ const bytes = byteStream(byteValue(value))++ if (action === "write") {++ if (program) await this.authManager.programManager.writeArea(program, area!, joins, bytes, undefined, input?.overwrite !== false)++ else await this.system.nativeStorageWrite(joins, bytes, input?.overwrite !== false)+ }++ else if (action === "append") {++ if (program) await this.authManager.programManager.appendArea(program, area!, joins, bytes)++ else await this.system.nativeStorageAppend(joins, bytes)+ }++ else throw new Error(`The host does not know the Storage content operation "${action}"`)+ }++ if (active) await this.say(server, "host-end", "stream", question, "answer", succeeded(undefined))++ return+ }++ if (operation === "storage-watch") {++ const scope = args[1]++ const controller = new AbortController()++ cancel = () => { active = false; controller.abort(new Error("The Storage watch was cancelled")) }++ let changes: AsyncIterable<{ event: "rename" | "change", path: string | null }>++ if (scope === "program") {++ const program = access.program(this.system.holdProgram(args[2], process.program))++ if (args[3] !== "data" && args[3] !== "cache") throw new Error("Program storage needs an area")++ const options = args[5] as { recursive?: boolean } | undefined++ changes = this.authManager.programManager.watchArea(program, args[3], stringPath(args[4]), options?.recursive === true, controller.signal)+ }++ else if (scope === "system") {++ const joins = stringPath(args[2])++ const path = this.system.nativeStorage("path", joins) as string++ access.requireStorage(path, "read")++ const options = args[3] as { recursive?: boolean } | undefined++ changes = this.system.nativeStorageWatch(joins, options?.recursive === true, controller.signal)+ }++ else throw new Error("Storage watch needs a scope")++ for await (const change of changes) {++ if (!active) return++ await this.say(server, "host-end", "stream", question, "data", change)+ }++ if (active) await this.say(server, "host-end", "stream", question, "answer", succeeded(undefined))++ return+ }++ const program = access.program(this.system.holdProgram(args[1]))if (operation === "run") {@@ -2437,7 +2797,7 @@ export default class ProcessManager extends TheLink {if (running) this.system.exitProcess(running).catch(() => undefined)}- const identity = await this.system.runProcess(program, args[2] as Launch ?? {}, {+ const identity = await this.system.runProcess(program, access.launch(args[2]), {started: created => {running = created@@ -2887,6 +3247,39 @@ function isHandleAddress(value: unknown): value is HandleAddress {&& typeof value.identity === "string" && typeof value.reference === "string"}+function stringPath(value: unknown) {++ if (!Array.isArray(value) || value.some(part => typeof part !== "string")) throw new Error("A Storage path is a list of names")++ return value as string[]+}++function byteValue(value: unknown) {++ if (value instanceof Uint8Array) return value++ if (value instanceof ArrayBuffer) return new Uint8Array(value)++ if (ArrayBuffer.isView(value)) return new Uint8Array(value.buffer, value.byteOffset, value.byteLength)++ if (Array.isArray(value) && value.every(byte => Number.isInteger(byte) && byte >= 0 && byte <= 255)) return Uint8Array.from(value)++ throw new Error("The operation requires bytes")+}++function byteStream(value: Uint8Array) {++ return new ReadableStream<Uint8Array>({++ start(controller) {++ controller.enqueue(value)++ controller.close()+ }+ })+}+type Completion = () => unknown | PromiseLike<unknown>/** Run every teardown step, preserving all failures until cleanup is complete. */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.tsindex 14a1b66..2b7b2bd 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@@ -1,7 +1,7 @@import { Options } from "../program-manager/program-manager"import Program from "../program-manager/program"import Window, { Position, Size } from "./window"-import ServerProcessBoundary from "./server-process-boundary"+import ServerProcessBoundary, { type HostVisibility } from "./server-process-boundary"import HostTraffic from "./host-traffic"import ClientState from "./client-state"import { randomUUID } from "node:crypto"@@ -121,13 +121,13 @@ export default class Process {return true}- 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) {+ 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, hostVisible: HostVisibility) {if (this.server) return this.serverlet boundary!: ServerProcessBoundary- boundary = new ServerProcessBoundary(runtime, this.program.client !== null, service, (code, signal) => ended(boundary, code, signal), unanswered, this.hostTraffic, appearance)+ boundary = new ServerProcessBoundary(runtime, this.program.client !== null, service, (code, signal) => ended(boundary, code, signal), unanswered, this.hostTraffic, appearance, hostVisible)this.server = boundarydiff --git a/source/server/core/link-manager/auth-manager/process-manager/server-process-boundary.ts b/source/server/core/link-manager/auth-manager/process-manager/server-process-boundary.tsindex f86de9a..ecc6f0b 100644--- a/source/server/core/link-manager/auth-manager/process-manager/server-process-boundary.ts+++ b/source/server/core/link-manager/auth-manager/process-manager/server-process-boundary.ts@@ -43,6 +43,8 @@ export default class ServerProcessBoundary extends TheLink {private readonly hostSubscriptions = new Map<string, () => void>()+ private readonly resources = new Set<() => void>()+private readonly appearanceSubscriptions = new Set<string>()private stopAppearance: (() => void) | null = null@@ -57,7 +59,7 @@ export default class ServerProcessBoundary extends TheLink {public readonly finished: Promise<{ code: number | null, signal: NodeJS.Signals | null }>- public constructor(runtime: ServerRuntime, clientDeclared: boolean, service: boolean, ended: Ending, unanswered: (values: unknown[], reason: string) => void, hostTraffic: HostTraffic, appearance: Tunnel) {+ public constructor(runtime: ServerRuntime, clientDeclared: boolean, service: boolean, ended: Ending, unanswered: (values: unknown[], reason: string) => void, hostTraffic: HostTraffic, appearance: Tunnel, private readonly hostVisible: HostVisibility) {super()@@ -67,6 +69,8 @@ export default class ServerProcessBoundary extends TheLink {this.runtime = runtime+ this.$inbound.subscribe("boundary", (...values) => this.control(values))+runtime.onMessage((event, ...values) => { this.$inbound.publish(event, ...values).catch(() => undefined) })this.$outbound.forwardTo((event, ...values) => {@@ -90,8 +94,6 @@ export default class ServerProcessBoundary extends TheLink {this.appearance = appearancethis.unanswered = unanswered-- this.$inbound.subscribe("boundary", (...values) => this.control(values))}/** Deliver one routed envelope only when this endpoint requested it. */@@ -261,6 +263,8 @@ export default class ServerProcessBoundary extends TheLink {for (const stop of this.hostSubscriptions.values()) stop()+ for (const release of this.resources) release()+this.requests.clear()this.observations.clear()@@ -271,6 +275,8 @@ export default class ServerProcessBoundary extends TheLink {this.hostSubscriptions.clear()+ this.resources.clear()+this.appearanceSubscriptions.clear()this.stopAppearance?.()@@ -290,6 +296,18 @@ export default class ServerProcessBoundary extends TheLink {for (const values of incoming) this.unanswered(values, reason)}+ public retainResource(release: () => void) {++ this.resources.add(release)++ return () => {++ if (!this.resources.delete(release)) return++ release()+ }+ }+public stop() {this.runtime.stop()@@ -362,6 +380,12 @@ export default class ServerProcessBoundary extends TheLink {this.hostSubscriptions.set(subscription, this.hostTraffic.observe(hostDomain, event, subject, (_delivery, word, ...values) => {+ const eventSubject = typeof values[0] === "object" && values[0] !== null && "reference" in values[0]+ ? String((values[0] as { reference: unknown }).reference)+ : subject++ if (!this.hostVisible(hostDomain, eventSubject)) return+this.deliver(route, word, ...values).catch(() => undefined)}))}@@ -507,3 +531,5 @@ interface WaitingQuestion {export type { Stream } from "@server/core/server-runtime"export type Ending = (code: number | null, signal: NodeJS.Signals | null) => void++export type HostVisibility = (domain: "program" | "process" | "connection" | "session" | "window", subject: string | null) => booleandiff --git a/source/server/core/link-manager/auth-manager/process-manager/system-access.ts b/source/server/core/link-manager/auth-manager/process-manager/system-access.tsnew file mode 100644index 0000000..c594a40--- /dev/null+++ b/source/server/core/link-manager/auth-manager/process-manager/system-access.ts@@ -0,0 +1,80 @@+import { parseLaunch, type ClientLaunch, type PermissionName, type PermissionValue } from "@phreshos/core"+import type Program from "../program-manager/program"+import type Process from "./process"+import type ProcessManager from "./process-manager"++const denied = "Execution is not permitted"++/** The permission-constrained System authority of one Server Endpoint. */+export default class SystemAccess {++ public constructor(private readonly manager: ProcessManager, private readonly owner: Process) { }++ public ownsProgram(program: Pick<Program, "identity">) { return this.owner.program.identity === program.identity }+ public ownsProcess(process: Pick<Process, "program">) { return this.owner.program === process.program }++ public all() { return this.manager.grants(this.owner.identity, "all", []) }++ public canProgram(program: Pick<Program, "identity">) {++ return this.ownsProgram(program) || this.manager.grants(this.owner.identity, "programs", [program.identity])+ }++ public canProcess(process: Pick<Process, "program">) {++ return this.ownsProcess(process) || this.manager.grants(this.owner.identity, "programs", [process.program.identity])+ }++ public canConnections() { return this.manager.grants(this.owner.identity, "connections", []) }++ public program<Subject extends Program>(program: Subject) {++ if (!this.canProgram(program)) throw new Error("The Program represented by this handle does not exist")++ return program+ }++ public process<Subject extends Process>(process: Subject) {++ if (!this.canProcess(process)) throw new Error("The Process represented by this handle does not exist")++ return process+ }++ public requireAll() { if (!this.all()) throw new Error(denied) }++ public require<Name extends PermissionName>(name: Name, values: readonly PermissionValue<Name>[]) {++ if (!this.manager.grants(this.owner.identity, name, values)) throw new Error(denied)+ }++ public requireStorage(path: string, operation?: "read" | "write" | "delete") {++ if (!this.manager.grantsStorage(this.owner.identity, path, operation)) throw new Error(denied)+ }++ public launch(value: unknown = {}) {++ const launch = parseLaunch(value)++ if (typeof launch.client === "object") this.clientLayer(launch.client)++ return launch+ }++ public clientLaunch(value: unknown = {}) {++ const launch = parseLaunch({ client: value }).client++ if (!launch || typeof launch !== "object") throw new Error("A Client launch must be an object")++ this.clientLayer(launch)++ return launch+ }++ private clientLayer(launch: ClientLaunch) {++ if (launch.layer !== undefined && launch.layer !== "window") this.require("layers", [launch.layer])+ }+}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.tsindex 918e80b..337735a 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@@ -106,7 +106,7 @@ export default class Program {/** Canonical permission entries applied to storage at creation and installation. */public get declaredPermissions(): DeclaredPermissions {- return permissionCatalog.declarations(this.config.client?.permissions)+ return permissionCatalog.declarations(this.config.permissions)}// A client half may name a URL instead of a directory. The Program asset@@ -128,7 +128,7 @@ export default class Program {public get serverEntryPath() {- const entry = this.config.server?.entryFile+ const entry = this.config.server?.worker ?? this.config.server?.sandboxreturn entry && this.serverPath ? resolve(this.serverPath, entry) : null}@@ -409,13 +409,18 @@ type Resolved<Half extends { start?: boolean, service?: boolean }> = Half extend? Omit<Half, "start" | "service"> & { start: boolean, service: boolean }: never-function execution(server: { startCommand?: unknown, entryFile?: unknown }) {+function execution(server: { command?: unknown, worker?: unknown, sandbox?: unknown }) {- if ((server.startCommand === undefined) === (server.entryFile === undefined)) throw new Error("A server half must declare exactly one startCommand or entryFile")+ const selected = [server.command, server.worker, server.sandbox].filter(value => value !== undefined)- if (server.startCommand !== undefined && (typeof server.startCommand !== "string" || server.startCommand.trim().length === 0)) throw new Error("A server half's startCommand must be non-empty text")+ if (selected.length !== 1) throw new Error("A server half must declare exactly one command, worker, or sandbox")- if (server.entryFile !== undefined && (typeof server.entryFile !== "string" || server.entryFile.trim().length === 0 || !containedEntry(server.entryFile))) throw new Error("A server half's entryFile must be a non-empty path inside its Server directory")+ if (server.command !== undefined && (typeof server.command !== "string" || server.command.trim().length === 0)) throw new Error("A server half's command must be non-empty text")++ for (const [name, entry] of [["worker", server.worker], ["sandbox", server.sandbox]] as const) {++ if (entry !== undefined && (typeof entry !== "string" || entry.trim().length === 0 || !containedEntry(entry))) throw new Error(`A server half's ${name} entry must be a non-empty path inside its Server directory`)+ }}function containedEntry(entry: string) {diff --git a/source/server/core/permissions.ts b/source/server/core/permissions.tsindex 13640b4..5bc696e 100644--- a/source/server/core/permissions.ts+++ b/source/server/core/permissions.ts@@ -1,5 +1,5 @@import {- clientPermissionCatalog,+ programPermissionCatalog,networkScopeCovers,parsePermission,parsePermissionName,@@ -21,7 +21,7 @@ export class PermissionCatalog {const validated: Partial<Record<PermissionName, StoredDefinition>> = {}- for (const name of Object.keys(clientPermissionCatalog) as PermissionName[]) {+ for (const name of Object.keys(programPermissionCatalog) as PermissionName[]) {const rule = rules[name]if (!rule || typeof rule !== "object") throw new Error(`Permission "${name}" needs a definition`)@@ -45,7 +45,7 @@ export class PermissionCatalog {}validated[name] = Object.freeze({- valueDomain: clientPermissionCatalog[name],+ valueDomain: programPermissionCatalog[name],default: Object.freeze(defaults),title: rule.title,description: rule.description@@ -53,7 +53,7 @@ export class PermissionCatalog {}- for (const name of Object.keys(clientPermissionCatalog) as PermissionName[]) {+ for (const name of Object.keys(programPermissionCatalog) as PermissionName[]) {if (!validated[name]) throw new Error(`Permission "${name}" needs a definition`)}@@ -94,17 +94,17 @@ export class PermissionCatalog {public declarations(value: unknown): DeclaredPermissions {if (value === undefined) return Object.freeze({})- if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("A Client's permissions must be a record")+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("A Program's permissions must be a record")const resolved: Partial<Record<PermissionName, readonly string[]>> = {}for (const [unknownName, assignment] of Object.entries(value)) {- if (!Object.hasOwn(clientPermissionCatalog, unknownName)) continue+ if (!Object.hasOwn(programPermissionCatalog, unknownName)) continueconst name = parsePermissionName(unknownName)const permission = this.resolve(name, assignment)- if (!Array.isArray(permission)) throw new Error("A Client-declared permission must be true or a list of values")+ if (!Array.isArray(permission)) throw new Error("A Program-declared permission must be true or a list of values")resolved[name] = Object.freeze(permission)}@@ -120,7 +120,7 @@ export class PermissionCatalog {for (const [unknownName, assignment] of Object.entries(value)) {- if (!Object.hasOwn(clientPermissionCatalog, unknownName)) continue+ if (!Object.hasOwn(programPermissionCatalog, unknownName)) continueconst name = parsePermissionName(unknownName)if (assignment === true) throw new Error("The Program permissions file contains unresolved shorthand")@@ -303,7 +303,7 @@ export const permissionCatalog = new PermissionCatalog({all: {default: [],title: "All permissions",- description: "Grant every available Client permission."+ description: "Grant every available Program permission."},services: {default: [],diff --git a/source/server/view/server-runtime/command.ts b/source/server/core/server-runtime/command.tssimilarity index 79%rename from source/server/view/server-runtime/command.tsrename to source/server/core/server-runtime/command.tsindex f8fca23..d6a6b23 100644--- a/source/server/view/server-runtime/command.ts+++ b/source/server/core/server-runtime/command.ts@@ -1,5 +1,5 @@import ProcessTree from "@libs/process-tree"-import type { ServerRuntime, ServerRuntimeEnding, Stream } from "@server/core/server-runtime"+import type { ServerRuntime, ServerRuntimeEnding, Stream } from "../server-runtime"import messagepack from "@the-link/messagepack"import { spawn, type ChildProcess } from "node:child_process"import { delimiter, join } from "node:path"@@ -7,40 +7,29 @@ import RuntimeInbox, { runtimeMessageBytes } from "./inbox"type OutputListener = (stream: Stream, text: string) => void-/** Represents one Server Endpoint as an isolated operating-system process tree. */+/** Runs one Server Endpoint as an operating-system process tree. */export default class CommandServerRuntime implements ServerRuntime {public readonly finished: Promise<ServerRuntimeEnding>-private readonly child: ChildProcess-private readonly tree: ProcessTree-private readonly inbox = new RuntimeInbox()public constructor(command: string, directory: string) {this.child = spawn(command, {-shell: true,-detached: true,-cwd: directory,-stdio: ["ignore", "pipe", "pipe", "ipc"],-serialization: "advanced",-env: commandServerEnvironment(directory)})if (typeof this.child.send !== "function") throw new Error("The server process has no IPC channel")let finish!: (ending: ServerRuntimeEnding) => void-this.finished = new Promise(resolve => { finish = resolve })-this.tree = new ProcessTree(this.child, (code, signal) => finish({ code, signal }))this.child.on("message", message => {@@ -53,37 +42,22 @@ export default class CommandServerRuntime implements ServerRuntime {this.child.on("error", () => undefined)}- public send(event: string, ...values: unknown[]) {-- this.child.send!(messagepack.serialize([event, ...values]))- }-- public onMessage(listener: (event: string, ...values: unknown[]) => void) {-- this.inbox.listen(listener)- }+ public send(event: string, ...values: unknown[]) { this.child.send!(messagepack.serialize([event, ...values])) }+ public onMessage(listener: (event: string, ...values: unknown[]) => void) { this.inbox.listen(listener) }public onOutput(listener: OutputListener) {this.child.stdout?.on("data", chunk => listener("out", String(chunk)))-this.child.stderr?.on("data", chunk => listener("err", String(chunk)))}public stop() { this.tree.stop() }}-/** Gives a command the package-local executables belonging to its directory. */export function commandServerEnvironment(directory: string, environment: NodeJS.ProcessEnv = process.env) {const key = Object.keys(environment).find(name => name.toLowerCase() === "path") ?? "PATH"-const inherited = environment[key]- return {-- ...environment,-- [key]: [join(directory, "node_modules", ".bin"), inherited].filter(Boolean).join(delimiter)- }+ return { ...environment, [key]: [join(directory, "node_modules", ".bin"), inherited].filter(Boolean).join(delimiter) }}diff --git a/source/server/core/server-runtime/factory.ts b/source/server/core/server-runtime/factory.tsnew file mode 100644index 0000000..3eaec28--- /dev/null+++ b/source/server/core/server-runtime/factory.ts@@ -0,0 +1,17 @@+import type Program from "../link-manager/auth-manager/program-manager/program"+import type { ServerRuntime } from "../server-runtime"+import CommandServerRuntime from "./command"+import SandboxServerRuntime from "./sandbox"+import WorkerServerRuntime from "./worker"++/** Creates the Core-owned execution adapter selected by a Program declaration. */+export default function createServerRuntime(program: Program): ServerRuntime {++ const server = program.server++ if (!server || !program.serverPath) throw new Error("This Program declared no Server Endpoint")++ if (server.command !== undefined) return new CommandServerRuntime(server.command, program.serverPath)+ if (server.worker !== undefined) return new WorkerServerRuntime(program.serverEntryPath!)+ return new SandboxServerRuntime(program.serverEntryPath!, program.serverPath)+}diff --git a/source/server/view/server-runtime/inbox.ts b/source/server/core/server-runtime/inbox.tssimilarity index 91%rename from source/server/view/server-runtime/inbox.tsrename to source/server/core/server-runtime/inbox.tsindex 415f56b..430b13e 100644--- a/source/server/view/server-runtime/inbox.ts+++ b/source/server/core/server-runtime/inbox.ts@@ -1,15 +1,14 @@-import type { ServerRuntimeMessage } from "@server/core/server-runtime"+import type { ServerRuntimeMessage } from "../server-runtime"import messagepack from "@the-link/messagepack"type Listener = (event: string, ...values: unknown[]) => voidconst maximumPendingMessages = 256-/** Preserves ordered runtime messages until the View installs their sole listener. */+/** Preserves ordered runtime messages until Core installs their sole listener. */export default class RuntimeInbox {private listener: Listener | null = null-private readonly pending: ServerRuntimeMessage[] = []public receive(message: unknown) {@@ -19,9 +18,7 @@ export default class RuntimeInbox {if (!bytes) returnlet decoded: unknown-try { decoded = messagepack.deserialize(bytes) }-catch { return }if (!Array.isArray(decoded) || typeof decoded[0] !== "string") return@@ -29,7 +26,6 @@ export default class RuntimeInbox {const envelope = decoded as ServerRuntimeMessageif (this.listener) this.listener(...envelope)-else if (this.pending.length < maximumPendingMessages) this.pending.push(envelope)}@@ -46,15 +42,11 @@ export default class RuntimeInbox {export function runtimeMessageBytes(value: unknown) {if (value instanceof Uint8Array) return Uint8Array.from(value)-if (value instanceof ArrayBuffer) return new Uint8Array(value)-if (ArrayBuffer.isView(value)) return Uint8Array.from(new Uint8Array(value.buffer, value.byteOffset, value.byteLength))-if (value === null || typeof value !== "object") return nullconst record = value as Record<string, unknown>-const bytes = new Uint8Array(Object.keys(record).length)for (let index = 0; index < bytes.length; index++) {diff --git a/source/server/core/server-runtime/sandbox-bootstrap.ts b/source/server/core/server-runtime/sandbox-bootstrap.tsnew file mode 100644index 0000000..e683563--- /dev/null+++ b/source/server/core/server-runtime/sandbox-bootstrap.ts@@ -0,0 +1,389 @@+import variant from "@jitl/quickjs-ng-wasmfile-release-sync"+import { newQuickJSWASMModuleFromVariant, type QuickJSContext, type QuickJSHandle } from "quickjs-emscripten-core"+import { parentPort, workerData } from "node:worker_threads"+import { readFileSync, realpathSync } from "node:fs"+import { dirname, isAbsolute, relative, resolve, sep } from "node:path"+import { randomUUID } from "node:crypto"++if (!parentPort) throw new Error("A Sandbox Server runtime requires a parent port")++const root = realpathSync(resolve(String(workerData.root)))+const entry = confined(String(workerData.entry))+const QuickJS = await newQuickJSWASMModuleFromVariant(variant)+const runtime = QuickJS.newRuntime({ memoryLimitBytes: 128 * 1024 * 1024, maxStackSizeBytes: 2 * 1024 * 1024 })+const context = runtime.newContext()+const timers = new Map<number, { timer: ReturnType<typeof setTimeout>, callback: QuickJSHandle }>()+const rejectedModule = "sandbox:rejected:"+let nextTimer = 1+let stopped = false++runtime.setModuleLoader(+ module => {++ if (module.startsWith(rejectedModule)) throw new Error(decodeURIComponent(module.slice(rejectedModule.length)))+ if (!isAbsolute(module)) throw new Error(`The Sandbox cannot import the package "${module}"; bundle package dependencies into the Server build`)++ return readFileSync(confined(module), "utf8")+ },+ (base, requested) => {++ if (!requested.startsWith(".")) return rejectModule(`The Sandbox cannot import the package "${requested}"; bundle package dependencies into the Server build`)++ try { return confined(resolve(dirname(base), requested)) }+ catch (error) { return rejectModule(error instanceof Error ? error.message : "A Sandbox module is invalid") }+ }+)++installEnvironment(context)+evaluate(readFileSync(entry, "utf8"), entry, { type: "module" })+pump()++parentPort.on("message", message => {++ const bytes = bytesOf(message)+ if (!bytes || stopped) return+ evaluate(`globalThis.__phreshosReceive(new Uint8Array(${JSON.stringify([...bytes])}))`, "phreshos:transport")+ pump()+})++parentPort.once("close", dispose)++function installEnvironment(vm: QuickJSContext) {++ expose("__phreshosSend", value => {++ const bytes = numericBytes(vm.dump(value))+ parentPort!.postMessage(bytes)+ })+ expose("__phreshosUUID", () => vm.newString(randomUUID()))+ expose("__phreshosEncode", value => {++ const bytes = new TextEncoder().encode(String(vm.dump(value)))+ return vm.newArrayBuffer(bytes.buffer)+ })+ expose("__phreshosDecode", value => vm.newString(new TextDecoder().decode(numericBytes(vm.dump(value)))))+ expose("__phreshosURL", (value, base, property, replacement) => {++ const input = String(vm.dump(value))+ const baseValue = vm.dump(base)+ const url = baseValue === undefined ? new URL(input) : new URL(input, String(baseValue))+ const propertyName = vm.dump(property)++ if (typeof propertyName === "string") (url as unknown as Record<string, string>)[propertyName] = String(vm.dump(replacement))++ return vm.newString(JSON.stringify({+ hash: url.hash,+ host: url.host,+ hostname: url.hostname,+ href: url.href,+ origin: url.origin,+ password: url.password,+ pathname: url.pathname,+ port: url.port,+ protocol: url.protocol,+ search: url.search,+ username: url.username+ }))+ })+ expose("__phreshosPrint", (stream, values) => {++ const target = vm.dump(stream) === "err" ? process.stderr : process.stdout+ const dumped = vm.dump(values)+ target.write(`${Array.isArray(dumped) ? dumped.map(printable).join(" ") : printable(dumped)}\n`)+ })+ expose("__phreshosSetTimeout", (callback, delay) => {++ const identity = nextTimer+++ const retained = callback.dup()+ const milliseconds = Math.max(0, Number(vm.dump(delay)) || 0)+ const timer = setTimeout(() => {++ timers.delete(identity)+ call(retained)+ retained.dispose()+ }, milliseconds)+ timers.set(identity, { timer, callback: retained })+ return vm.newNumber(identity)+ })+ expose("__phreshosClearTimeout", identity => {++ const retained = timers.get(Number(vm.dump(identity)))+ if (retained) {++ clearTimeout(retained.timer)+ retained.callback.dispose()+ timers.delete(Number(vm.dump(identity)))+ }+ })+ expose("__phreshosQueueMicrotask", callback => {++ const retained = callback.dup()+ queueMicrotask(() => {++ call(retained)+ retained.dispose()+ })+ })++ evaluate(`+ (() => {++ const messages = new Set()+ const closes = new Set()+ globalThis.__PHRESHOS_SERVER_TRANSPORT__ = Object.freeze({+ send(message) { __phreshosSend(Array.from(message)) },+ onMessage(listener) { messages.add(listener) },+ onClose(listener) { closes.add(listener) }+ })+ globalThis.__phreshosReceive = message => { for (const listener of messages) listener(message) }+ globalThis.crypto = Object.freeze({ randomUUID: () => __phreshosUUID() })+ globalThis.TextEncoder = class TextEncoder {++ encode(value = "") { return new Uint8Array(__phreshosEncode(String(value))) }+ encodeInto(value, destination) {++ if (!(destination instanceof Uint8Array)) throw new TypeError("TextEncoder.encodeInto requires a Uint8Array destination")++ const source = String(value)+ const encoded = this.encode(source)++ if (encoded.length <= destination.length) {++ destination.set(encoded)+ return { read: source.length, written: encoded.length }+ }++ let read = 0+ let written = 0++ for (const character of source) {++ const bytes = this.encode(character)++ if (written + bytes.length > destination.length) break++ destination.set(bytes, written)+ read += character.length+ written += bytes.length+ }++ return { read, written }+ }+ }+ globalThis.TextDecoder = class TextDecoder {++ decode(value = new Uint8Array()) { return __phreshosDecode(Array.from(value)) }+ }+ globalThis.URL = class URL {++ #value+ constructor(value, base = undefined) { this.#read(value, base) }+ #read(value, base, property = undefined, replacement = undefined) {++ this.#value = JSON.parse(__phreshosURL(String(value), base === undefined ? undefined : String(base), property, replacement))+ }+ #replace(property, value) { this.#read(this.href, undefined, property, String(value)) }+ get hash() { return this.#value.hash }+ set hash(value) { this.#replace("hash", value) }+ get host() { return this.#value.host }+ set host(value) { this.#replace("host", value) }+ get hostname() { return this.#value.hostname }+ set hostname(value) { this.#replace("hostname", value) }+ get href() { return this.#value.href }+ set href(value) { this.#read(value) }+ get origin() { return this.#value.origin }+ get password() { return this.#value.password }+ set password(value) { this.#replace("password", value) }+ get pathname() { return this.#value.pathname }+ set pathname(value) { this.#replace("pathname", value) }+ get port() { return this.#value.port }+ set port(value) { this.#replace("port", value) }+ get protocol() { return this.#value.protocol }+ set protocol(value) { this.#replace("protocol", value) }+ get search() { return this.#value.search }+ set search(value) { this.#replace("search", value) }+ get username() { return this.#value.username }+ set username(value) { this.#replace("username", value) }+ toJSON() { return this.href }+ toString() { return this.href }+ static canParse(value, base = undefined) {++ try { new URL(value, base); return true }+ catch { return false }+ }+ static parse(value, base = undefined) {++ try { return new URL(value, base) }+ catch { return null }+ }+ }+ globalThis.setTimeout = (callback, delay = 0) => __phreshosSetTimeout(callback, delay)+ globalThis.clearTimeout = identity => __phreshosClearTimeout(identity)+ globalThis.queueMicrotask = callback => __phreshosQueueMicrotask(callback)++ class Event {++ constructor(type) { this.type = String(type) }+ }+ class EventTarget {++ #listeners = new Map()+ addEventListener(type, listener, options) {++ const listeners = this.#listeners.get(type) ?? new Set()+ let registered = listener+ if (options?.once) {++ registered = Object.assign(event => {++ listeners.delete(registered)+ listener.call(this, event)+ }, { original: listener })+ }+ listeners.add(registered)+ this.#listeners.set(type, listeners)+ }+ removeEventListener(type, listener) {++ const listeners = this.#listeners.get(type)+ if (!listeners) return+ for (const candidate of listeners) if (candidate === listener || candidate.original === listener) listeners.delete(candidate)+ }+ dispatchEvent(event) {++ for (const listener of [...this.#listeners.get(event.type) ?? []]) listener.call(this, event)+ return true+ }+ }+ class AbortSignal extends EventTarget {++ aborted = false+ reason = undefined+ throwIfAborted() { if (this.aborted) throw this.reason }+ static any(signals) {++ const controller = new AbortController()+ for (const signal of signals) {++ if (signal.aborted) { controller.abort(signal.reason); break }+ signal.addEventListener("abort", () => controller.abort(signal.reason), { once: true })+ }+ return controller.signal+ }+ }+ class AbortController {++ signal = new AbortSignal()+ abort(reason = new Error("This operation was aborted")) {++ if (this.signal.aborted) return+ this.signal.aborted = true+ this.signal.reason = reason+ this.signal.dispatchEvent(new Event("abort"))+ }+ }+ globalThis.Event = Event+ globalThis.EventTarget = EventTarget+ globalThis.AbortSignal = AbortSignal+ globalThis.AbortController = AbortController+ globalThis.console = Object.freeze({+ log: (...values) => __phreshosPrint("out", values),+ info: (...values) => __phreshosPrint("out", values),+ warn: (...values) => __phreshosPrint("err", values),+ error: (...values) => __phreshosPrint("err", values)+ })+ })()+ `, "phreshos:environment")++ function expose(name: string, implementation: (...args: QuickJSHandle[]) => QuickJSHandle | void) {++ const fn = vm.newFunction(name, implementation)+ vm.setProp(vm.global, name, fn)+ fn.dispose()+ }++ function call(callback: QuickJSHandle) {++ if (stopped) return+ const result = vm.callFunction(callback, vm.undefined)+ if (result.error) {++ process.stderr.write(`${printable(vm.dump(result.error))}\n`)+ result.error.dispose()+ } else result.value.dispose()+ pump()+ }+}++function evaluate(code: string, filename: string, options?: { type: "module" | "global" }) {++ const result = context.evalCode(code, filename, options)+ if (result.error) {++ const error = context.dump(result.error)+ result.error.dispose()+ throw new Error(printable(error))+ }+ result.value.dispose()+}++function pump() {++ while (runtime.hasPendingJob()) {++ const result = runtime.executePendingJobs()+ if (result.error) {++ process.stderr.write(`${printable(result.error.context.dump(result.error))}\n`)+ result.error.dispose()+ break+ }+ }+}++function confined(path: string) {++ const target = realpathSync(isAbsolute(path) ? resolve(path) : resolve(root, path))+ const step = relative(root, target)+ if (step === ".." || step.startsWith(`..${sep}`) || isAbsolute(step)) throw new Error("A Sandbox module may not leave its Server directory")+ return target+}++function rejectModule(message: string) {++ return `${rejectedModule}${encodeURIComponent(message)}`+}++function bytesOf(value: unknown) {++ if (value instanceof Uint8Array) return value+ if (value instanceof ArrayBuffer) return new Uint8Array(value)+ if (ArrayBuffer.isView(value)) return new Uint8Array(value.buffer, value.byteOffset, value.byteLength)+ return null+}++function numericBytes(value: unknown) {++ if (!Array.isArray(value) || value.some(byte => !Number.isInteger(byte) || byte < 0 || byte > 255)) throw new Error("The Sandbox transport accepts bytes")+ return Uint8Array.from(value as number[])+}++function printable(value: unknown): string {+ if (typeof value === "string") return value+ try { return JSON.stringify(value) }+ catch { return String(value) }+}++function dispose() {++ if (stopped) return+ stopped = true+ for (const retained of timers.values()) {++ clearTimeout(retained.timer)+ retained.callback.dispose()+ }+ timers.clear()+ context.dispose()+ runtime.dispose()+}diff --git a/source/server/core/server-runtime/sandbox.ts b/source/server/core/server-runtime/sandbox.tsnew file mode 100644index 0000000..21ee394--- /dev/null+++ b/source/server/core/server-runtime/sandbox.ts@@ -0,0 +1,15 @@+import ThreadServerRuntime from "./thread"++/** Runs one capability-contained JavaScript Server Endpoint in QuickJS. */+export default class SandboxServerRuntime extends ThreadServerRuntime {++ public constructor(entry: string, root: string) {++ super(bootstrap("sandbox"), { entry, root })+ }+}++function bootstrap(runtime: "sandbox") {++ return new URL(`./${runtime}-bootstrap.${import.meta.url.endsWith(".ts") ? "ts" : "js"}`, import.meta.url)+}diff --git a/source/server/view/server-runtime/worker.ts b/source/server/core/server-runtime/thread.tssimilarity index 74%rename from source/server/view/server-runtime/worker.tsrename to source/server/core/server-runtime/thread.tsindex b5d7758..8e339aa 100644--- a/source/server/view/server-runtime/worker.ts+++ b/source/server/core/server-runtime/thread.ts@@ -1,4 +1,4 @@-import type { ServerRuntime, ServerRuntimeEnding, Stream } from "@server/core/server-runtime"+import type { ServerRuntime, ServerRuntimeEnding, Stream } from "../server-runtime"import messagepack from "@the-link/messagepack"import { Worker } from "node:worker_threads"import RuntimeInbox from "./inbox"@@ -7,48 +7,36 @@ type OutputListener = (stream: Stream, text: string) => voidconst maximumPendingOutput = 256-/** Represents one JavaScript Server Endpoint as an isolate inside the System process. */-export default class WorkerServerRuntime implements ServerRuntime {+/** Shared supervision for Server runtimes hosted in a System-owned thread. */+export default abstract class ThreadServerRuntime implements ServerRuntime {public readonly finished: Promise<ServerRuntimeEnding>private readonly worker: Worker+ private readonly inbox = new RuntimeInbox()+private readonly output = new Set<OutputListener>()private readonly pendingOutput: [Stream, string][] = []private clearingPendingOutput = false- private readonly inbox = new RuntimeInbox()-- public constructor(entry: string) {+ protected constructor(bootstrap: URL, workerData: object) {- this.worker = new Worker(entry, { stdout: true, stderr: true })+ this.worker = new Worker(bootstrap, { stdout: true, stderr: true, workerData })- this.finished = new Promise(resolve => {-- this.worker.once("exit", code => resolve({ code, signal: null }))- })+ this.finished = new Promise(resolve => { this.worker.once("exit", code => resolve({ code, signal: null })) })this.worker.on("message", message => this.inbox.receive(message))-this.worker.stdout?.on("data", chunk => this.print("out", String(chunk)))-this.worker.stderr?.on("data", chunk => this.print("err", String(chunk)))-this.worker.on("error", error => this.print("err", `${error instanceof Error ? error.stack ?? error.message : String(error)}\n`))}- public send(event: string, ...values: unknown[]) {-- this.worker.postMessage(messagepack.serialize([event, ...values]))- }-- public onMessage(listener: (event: string, ...values: unknown[]) => void) {+ public send(event: string, ...values: unknown[]) { this.worker.postMessage(messagepack.serialize([event, ...values])) }- this.inbox.listen(listener)- }+ public onMessage(listener: (event: string, ...values: unknown[]) => void) { this.inbox.listen(listener) }public onOutput(listener: OutputListener) {@@ -63,7 +51,6 @@ export default class WorkerServerRuntime implements ServerRuntime {queueMicrotask(() => {this.pendingOutput.splice(0)-this.clearingPendingOutput = false})}diff --git a/source/server/core/server-runtime/worker-bootstrap.ts b/source/server/core/server-runtime/worker-bootstrap.tsnew file mode 100644index 0000000..5f4488e--- /dev/null+++ b/source/server/core/server-runtime/worker-bootstrap.ts@@ -0,0 +1,23 @@+import { parentPort, workerData } from "node:worker_threads"++if (!parentPort) throw new Error("A Server Worker requires a parent port")+const port = parentPort++const listeners = new Set<(message: unknown) => void>()+const closing = new Set<() => void>()++Object.defineProperty(globalThis, "__PHRESHOS_SERVER_TRANSPORT__", {+ configurable: false,+ enumerable: false,+ writable: false,+ value: Object.freeze({+ send(message: Uint8Array) { port.postMessage(message) },+ onMessage(listener: (message: unknown) => void) { listeners.add(listener) },+ onClose(listener: () => void) { closing.add(listener) }+ })+})++port.on("message", message => { for (const listener of listeners) listener(message) })+port.once("close", () => { for (const listener of closing) listener() })++await import(String(workerData.entry))diff --git a/source/server/core/server-runtime/worker.ts b/source/server/core/server-runtime/worker.tsnew file mode 100644index 0000000..ab928a8--- /dev/null+++ b/source/server/core/server-runtime/worker.ts@@ -0,0 +1,15 @@+import ThreadServerRuntime from "./thread"++/** Runs one JavaScript Server Endpoint in a Node Worker. */+export default class WorkerServerRuntime extends ThreadServerRuntime {++ public constructor(entry: string) {++ super(bootstrap("worker"), { entry })+ }+}++function bootstrap(runtime: "worker") {++ return new URL(`./${runtime}-bootstrap.${import.meta.url.endsWith(".ts") ? "ts" : "js"}`, import.meta.url)+}diff --git a/source/server/core/system.ts b/source/server/core/system.tsindex 316c53a..17e4f60 100644--- a/source/server/core/system.ts+++ b/source/server/core/system.ts@@ -19,6 +19,7 @@ import type { Half, TrafficKind } from "./link-manager/auth-manager/process-manaimport { processReference, type ProcessReference } from "./link-manager/auth-manager/process-manager/endpoint-reference"import type { Area, Watching } from "./link-manager/auth-manager/program-manager/program-manager"import shell from "./shell"+import type FileArea from "@libs/file-area"type Endpoint = "server" | "client"type ProgramSource = Parameters<Application["linkManager"]["authManager"]["programManager"]["create"]>[0]@@ -482,6 +483,31 @@ export default class System {return this.programManager.area(program, area, "path", [])}+ public nativeStorage(operation: string, joins: string[], input?: unknown) {++ return operateArea(this.application.home, operation, joins, input)+ }++ public nativeStorageStream(joins: string[], options: { offset?: number, length?: number } = {}) {++ return this.application.home.stream(joins, [options.offset, options.length])+ }++ public nativeStorageWrite(joins: string[], content: ReadableStream<Uint8Array>, overwrite = true, signal?: AbortSignal) {++ return this.application.home.write(joins, content, signal, overwrite)+ }++ public nativeStorageAppend(joins: string[], content: ReadableStream<Uint8Array>, signal?: AbortSignal) {++ return this.application.home.append(joins, content, signal)+ }++ public nativeStorageWatch(joins: string[], recursive: boolean, signal?: AbortSignal) {++ return this.application.home.watch(joins, recursive, signal)+ }+public programStore(program: Program, operation: string, key: string, value?: unknown, ttl?: number) {return this.programManager.store(program, operation, key, value, ttl)@@ -536,6 +562,45 @@ export default class System {private get processManager() { return this.application.linkManager.authManager.processManager }}+function operateArea(place: FileArea, operation: string, joins: string[], input?: unknown) {++ if (operation === "path") return place.resolve(joins)+ if (operation === "name") return place.name(joins)+ if (operation === "create") { place.create(joins); return }+ if (operation === "clear") { place.clear(joins); return }++ if (operation === "stat-storage" || operation === "stat-file") {+ const found = place.stat(joins)+ if (!found) return null+ if (operation === "stat-storage") {+ if (found.kind !== "directory") throw new Error(`${place.resolve(joins)} is not a Storage directory`)+ return { modifiedAt: found.modifiedAt }+ }+ if (found.kind !== "file") throw new Error(`${place.resolve(joins)} is not a file`)+ return { size: found.size, modifiedAt: found.modifiedAt }+ }++ if (operation === "list") {+ const value = input as { recursive?: unknown, depth?: unknown } | undefined+ const recursive = value?.recursive === true+ const depth = value?.depth+ if (depth !== undefined && (!Number.isSafeInteger(depth) || (depth as number) < 0)) throw new Error("A Storage list depth must be a non-negative safe integer")+ if (depth !== undefined && !recursive) throw new Error("A Storage list depth requires recursive listing")+ return place.list(joins, [recursive, depth as number | undefined])+ }++ if (operation === "delete-storage" || operation === "delete-file") {+ const found = place.stat(joins)+ if (found && operation === "delete-storage" && found.kind !== "directory") throw new Error(`${place.resolve(joins)} is not a Storage directory`)+ if (found && operation === "delete-file" && found.kind !== "file") throw new Error(`${place.resolve(joins)} is not a file`)+ place.delete(joins)+ return+ }++ if (operation === "space") return place.space(joins)+ throw new Error(`The host does not know the storage operation "${operation}"`)+}+function isHandleAddress(value: unknown): value is { identity: string, reference: string } {return typeof value === "object"diff --git a/source/server/core/upload-manager.ts b/source/server/core/upload-manager.tsindex edf03a4..1ecfe2c 100644--- a/source/server/core/upload-manager.ts+++ b/source/server/core/upload-manager.ts@@ -1,4 +1,4 @@-import { createWriteStream, lstatSync, mkdirSync } from "node:fs"+import { createReadStream, createWriteStream, lstatSync, mkdirSync } from "node:fs"import FileManager from "@libs/file-manager"import { rename, rm } from "node:fs/promises"import { randomUUID } from "node:crypto"@@ -117,4 +117,9 @@ export default class UploadManager {return { size: stat.size, modifiedAt: Math.round(stat.mtimeMs) }}+ public stream(file: string) {++ return Readable.toWeb(createReadStream(this.path(file))) as ReadableStream<Uint8Array>+ }+}diff --git a/source/server/view/server-runtime/server-runtime.ts b/source/server/view/server-runtime/server-runtime.tsdeleted file mode 100644index fd6e1af..0000000--- a/source/server/view/server-runtime/server-runtime.ts+++ /dev/null@@ -1,18 +0,0 @@-import type Program from "@server/core/link-manager/auth-manager/program-manager/program"-import type { ServerRuntime } from "@server/core/server-runtime"-import CommandServerRuntime from "./command"-import WorkerServerRuntime from "./worker"--/** Creates the concrete View representation selected by a Program declaration. */-export default function serverRuntime(program: Program): ServerRuntime {-- const server = program.server-- if (!server) throw new Error("This program declared no server half")-- return server.startCommand !== undefined-- ? new CommandServerRuntime(server.startCommand, program.serverPath!)-- : new WorkerServerRuntime(program.serverEntryPath!)-}diff --git a/source/server/view/view.ts b/source/server/view/view.tsindex 16d52b6..68efe19 100644--- a/source/server/view/view.ts+++ b/source/server/view/view.ts@@ -15,7 +15,6 @@ import { Hono } from "hono"import { resolve } from "node:path"import { writeFile } from "node:fs/promises"import { styleText } from "node:util"-import serverRuntime from "./server-runtime/server-runtime"import { listenOnPorts } from "./configuration"export default async function (config: Config) {@@ -29,7 +28,7 @@ export default async function (config: Config) {font: "simple"})- const application = await Application.initialize(config.name, config.displayName, config.version, config.home, resolve("assets/default-icon.png"), serverRuntime)+ const application = await Application.initialize(config.name, config.displayName, config.version, config.home, resolve("assets/default-icon.png"))// One server, five doors, each at its own name. A program's client// is still not the API — it is files a browser reads, with no link,diff --git a/tests/authentication-domains.test.ts b/tests/authentication-domains.test.tsindex 1062e8a..8790ed3 100644--- a/tests/authentication-domains.test.ts+++ b/tests/authentication-domains.test.ts@@ -12,8 +12,7 @@ test("browser Connections and Sessions form one authoritative lifecycle", async"PhreshOS","test",home,- join(home, "icon.png"),- () => { throw new Error("The test does not launch Server Endpoints") }+ join(home, "icon.png"))const link = new TheLink()const connection = application.linkManager.addConnection(link)diff --git a/tests/client-process-boundary-lifecycle.test.ts b/tests/client-process-boundary-lifecycle.test.tsnew file mode 100644index 0000000..c5272de--- /dev/null+++ b/tests/client-process-boundary-lifecycle.test.ts@@ -0,0 +1,42 @@+import assert from "node:assert/strict"+import messagepack from "@the-link/messagepack"+import ClientProcessBoundary from "@client/view/components/desktop-host/client-process-boundary"+import type AuthManager from "@client/core/link-manager/auth-manager/auth-manager"+import type ClientTraffic from "@client/view/components/desktop-host/client-traffic"+import type { LocalWindowHost } from "@client/view/components/desktop-host/local-window"+import { test } from "vitest"++test("a Client question expectation survives initial iframe ownership", async () => {++ const sent: unknown[][] = []+ const element = {+ contentWindow: {+ postMessage(message: unknown[]) {++ sent.push(messagepack.deserialize(message[0] as Uint8Array) as unknown[])+ }+ }+ } as unknown as HTMLIFrameElement+ const authManager = {+ processManager: {+ async ownFrame() {},+ async releaseFrame() {}+ }+ } as unknown as AuthManager+ const boundary = new ClientProcessBoundary(+ "process",+ element,+ authManager,+ () => ({ size: { width: 800, height: 600 } }),+ {} as ClientTraffic,+ { release() {} } as unknown as LocalWindowHost+ )+ const question = "client:process:question"++ boundary.receive(["boundary", "expect", question])++ await boundary.own("document")+ await boundary.deliver("end-end", "answer", question, "public-question", "read", { success: true, result: 4 })++ assert.deepEqual(sent, [["end-end", "answer", question, "public-question", "read", { success: true, result: 4 }]])+})diff --git a/tests/desktop-replacements.test.tsx b/tests/desktop-replacements.test.tsxindex 798068f..9363411 100644--- a/tests/desktop-replacements.test.tsx+++ b/tests/desktop-replacements.test.tsx@@ -50,7 +50,7 @@ vi.mock("@client/view/structure/desktop/windows/process-window", () => ({}))test("Desktop replaces its default wallpaper with the running Client and restores the fallback after stop", () => {- const render = () => renderToStaticMarkup(<UIProvider preferences={{ theme: "light", animations: true }}><Workspace /></UIProvider>)+ const render = () => renderToStaticMarkup(<UIProvider preferences={{ theme: "light", animations: true, scale: 1 }}><Workspace /></UIProvider>)fixture.processes.clear()fixture.pane.mockClear()fixture.fallback.mockClear()@@ -83,7 +83,7 @@ test("Desktop replaces its default wallpaper with the running Client and restore})test("Desktop replaces the built-in Start Menu in its existing host and restores the fallback after stop", () => {- const render = () => renderToStaticMarkup(<UIProvider preferences={{ theme: "light", animations: true }}><Workspace /></UIProvider>)+ const render = () => renderToStaticMarkup(<UIProvider preferences={{ theme: "light", animations: true, scale: 1 }}><Workspace /></UIProvider>)fixture.processes.clear()fixture.pane.mockClear()fixture.startMenu.mockClear()diff --git a/tests/endpoint-services.test.ts b/tests/endpoint-services.test.tsindex c64cb12..39287cb 100644--- a/tests/endpoint-services.test.ts+++ b/tests/endpoint-services.test.ts@@ -8,12 +8,12 @@ import { test } from "vitest"test("endpoint services contract", async () => {const privateProgram = new Program({identity: "private-program",- server: { location: ".", startCommand: "true" }+ server: { location: ".", command: "true" }})const documentedProgram = new Program({identity: "documented-program",agent: "agent.md",- server: { location: ".", startCommand: "true" },+ server: { location: ".", command: "true" },client: { location: "." }})@@ -22,12 +22,12 @@ test("endpoint services contract", async () => {assert.throws(() => new Program({identity: "invalid-program",agent: "",- server: { location: ".", startCommand: "true" }+ server: { location: ".", command: "true" }}), /agent documentation/)const program = new Program({identity: "program",- server: { location: ".", startCommand: "true" },+ server: { location: ".", command: "true" },client: { location: "." }})const waits: string[] = []@@ -117,7 +117,7 @@ test("endpoint services contract", async () => {const unconfiguredProgram = new Program({identity: "unconfigured",- server: { location: ".", startCommand: "true" }+ server: { location: ".", command: "true" }})assert.equal(unconfiguredProgram.server?.service, false)diff --git a/tests/fixtures/sandbox-codec.ts b/tests/fixtures/sandbox-codec.tsnew file mode 100644index 0000000..dda5ac8--- /dev/null+++ b/tests/fixtures/sandbox-codec.ts@@ -0,0 +1,17 @@+import messagepack from "@the-link/messagepack"++const transport = (globalThis as typeof globalThis & {+ __PHRESHOS_SERVER_TRANSPORT__: {+ send(message: Uint8Array): void+ onMessage(listener: (message: unknown) => void): void+ }+}).__PHRESHOS_SERVER_TRANSPORT__++transport.send(messagepack.serialize(["codec-ready"]))++transport.onMessage(message => {++ const value = messagepack.deserialize(message as Uint8Array)++ transport.send(messagepack.serialize(["codec-result", value]))+})diff --git a/tests/panel.test.tsx b/tests/panel.test.tsxindex dd5d7f0..6fc5e41 100644--- a/tests/panel.test.tsx+++ b/tests/panel.test.tsx@@ -23,7 +23,7 @@ test("panel contract", async () => {function markup(children: ReactNode) {return renderToStaticMarkup(<ApplicationContext.Provider value={application}>- <UIProvider appearance={defaultAppearance} preferences={{ theme: "light", animations: true }}>{children}</UIProvider>+ <UIProvider appearance={defaultAppearance} preferences={{ theme: "light", animations: true, scale: 1 }}>{children}</UIProvider></ApplicationContext.Provider>)}diff --git a/tests/permission-requests.test.ts b/tests/permission-requests.test.tsindex 64d3bee..e1bfde2 100644--- a/tests/permission-requests.test.ts+++ b/tests/permission-requests.test.ts@@ -79,7 +79,7 @@ test("permission requests contract", async () => {assert(!programManager.grantsPermission(program, "network", ["https://other.example.com"]))// Permission decisions read the authoritative stored state.- const declared = new Program({ identity: "declared", storage: temporary, client: { location: ".", permissions: { programs: ["browser"] } } })+ const declared = new Program({ identity: "declared", storage: temporary, permissions: { programs: ["browser"] }, client: { location: "." } })writePermissions(declared, { services: ["editor"] })assert(!programManager.grantsPermission(declared, "services", ["browser"]))assert(programManager.grantsPermission(declared, "services", ["editor"]))diff --git a/tests/permissions.test.ts b/tests/permissions.test.tsindex ffeffdd..4cda8bf 100644--- a/tests/permissions.test.ts+++ b/tests/permissions.test.ts@@ -8,7 +8,7 @@ test("permissions contract", async () => {all: {default: [],title: "All permissions",- description: "Grant every available Client permission."+ description: "Grant every available Program permission."},services: {default: [],@@ -66,7 +66,7 @@ test("permissions contract", async () => {valueDomain: "none",default: [],title: "All permissions",- description: "Grant every available Client permission."+ description: "Grant every available Program permission."})assert.deepEqual(catalog.definition("programs"), {valueDomain: "program",diff --git a/tests/process-lifecycle.test.ts b/tests/process-lifecycle.test.tsindex 934c83c..2b40247 100644--- a/tests/process-lifecycle.test.ts+++ b/tests/process-lifecycle.test.ts@@ -18,7 +18,9 @@ test("process lifecycle contract", async () => {Object.assign(authManager, {programManager: {- permission() { return null }+ permission() { return null },+ grantsPermission() { return true },+ grantsStorage() { return true }},linkManager: {application: {@@ -45,7 +47,7 @@ test("process lifecycle contract", async () => {function program(identity: string) {- return new Program({ identity, server: { location: ".", startCommand: "true" } })+ return new Program({ identity, server: { location: ".", command: "true" } })}async function register(manager: ProcessManager, identity: string) {diff --git a/tests/program-creation.test.ts b/tests/program-creation.test.tsindex 4ea8dc0..fa7c87b 100644--- a/tests/program-creation.test.ts+++ b/tests/program-creation.test.ts@@ -3,7 +3,7 @@ import { tmpdir } from "node:os"import { join } from "node:path"import { TheLink } from "@the-link/core"import { expect, test, vi, type TestContext } from "vitest"-import type { ClientPermissionDeclarations } from "@phreshos/core"+import type { ProgramPermissionDeclarations } from "@phreshos/core"import FileManager from "@libs/file-manager"import type AuthManager from "@server/core/link-manager/auth-manager/auth-manager"import ProgramManager from "@server/core/link-manager/auth-manager/program-manager/program-manager"@@ -22,8 +22,8 @@ function fixture(context: TestContext) {processManager: { processes: new Map(), exitAll: vi.fn(), announceHost, announceSubject: vi.fn() }}) as unknown as AuthManagerconst manager = new ProgramManager(auth)- function definition(permissions?: ClientPermissionDeclarations) {- return { identity: "example", storage: join(directory, "data"), client: { location: client, permissions } }+ function definition(permissions?: ProgramPermissionDeclarations) {+ return { identity: "example", storage: join(directory, "data"), permissions, client: { location: client } }}return { directory, client, manager, announceHost, definition }}@@ -82,7 +82,7 @@ test("boot reconstruction preserves all stored settings and launches the saved sconst { manager, definition, client } = fixture(context)const directory = manager.fileManager.join("example")mkdirSync(directory)- writeFileSync(join(directory, "program.json"), JSON.stringify({ ...definition({ all: true }), startup: true, launch: true, storage: "storage", client: { location: client, permissions: { all: true } } }))+ writeFileSync(join(directory, "program.json"), JSON.stringify({ ...definition({ all: true }), startup: true, launch: true, storage: "storage", client: { location: client } }))mkdirSync(join(directory, "storage"))writeFileSync(join(directory, "storage", "permissions.json"), JSON.stringify({ network: false }))writeFileSync(join(directory, "storage", "launch.json"), JSON.stringify({ options: { document: "saved.txt" } }))@@ -269,8 +269,8 @@ for (const previous of [false, true]) test(`failed installation rolls back declaconst replacement = vi.spyOn(entry.program, "replace").mockImplementationOnce(() => { throw new Error("registration failed") })try {await expect(manager.install(new Program({- identity: "example", startup: true, launch: true,- client: { location: client, permissions: { network: true } }+ identity: "example", startup: true, launch: true, permissions: { network: true },+ client: { location: client }}))).rejects.toThrow("registration failed")}finally { replacement.mockRestore() }diff --git a/tests/program-install.test.ts b/tests/program-install.test.tsindex 1ee2147..a2d3b24 100644--- a/tests/program-install.test.ts+++ b/tests/program-install.test.ts@@ -29,12 +29,10 @@ test("program install contract", async () => {location: join(source, "server"),installCommand: `node -e "process.stdout.write('install-out'); process.stderr.write('install-err')"`,uninstallCommand: `node -e "process.stdout.write('uninstall-out'); process.stderr.write('uninstall-err')"`,- startCommand: "true"+ command: "true"},- client: {- location: join(source, "client"),- permissions: { network: ["https://api.example.test/**"] }- }+ permissions: { network: ["https://api.example.test/**"] },+ client: { location: join(source, "client") }})await program.validate()diff --git a/tests/program-installation-lifecycle.test.ts b/tests/program-installation-lifecycle.test.tsindex 1d35084..f612ece 100644--- a/tests/program-installation-lifecycle.test.ts+++ b/tests/program-installation-lifecycle.test.ts@@ -23,7 +23,7 @@ function fixture(context: TestContext) {const definition = (installCommand = `node -e "process.stdout.write('preparing')"`) => new Program({identity: "example", storage: join(directory, "source", "storage"),startup: { name: "startup" },- server: { location: server, installCommand, startCommand: "node main.js" }+ server: { location: server, installCommand, command: "node main.js" }})return { directory, manager, exitAll, definition }}diff --git a/tests/program-startup.test.ts b/tests/program-startup.test.tsindex 34ea977..bf1f067 100644--- a/tests/program-startup.test.ts+++ b/tests/program-startup.test.ts@@ -32,8 +32,8 @@ test("installation applies declared settings and launches the resulting stored s})function definition(setting?: true | Launch) {return new Program({- identity: "example", startup: setting,- client: { location: client, permissions: { network: ["https://new.example.test"] } }+ identity: "example", startup: setting, permissions: { network: ["https://new.example.test"] },+ client: { location: client }})}diff --git a/tests/server-permission-boundary.test.ts b/tests/server-permission-boundary.test.tsnew file mode 100644index 0000000..f076f93--- /dev/null+++ b/tests/server-permission-boundary.test.ts@@ -0,0 +1,91 @@+import assert from "node:assert/strict"+import { TheLink } from "@the-link/core"+import type { PermissionName, PermissionValue, Permissions } from "@phreshos/core"+import type AuthManager from "@server/core/link-manager/auth-manager/auth-manager"+import Program from "@server/core/link-manager/auth-manager/program-manager/program"+import ProcessManager from "@server/core/link-manager/auth-manager/process-manager/process-manager"+import type Process from "@server/core/link-manager/auth-manager/process-manager/process"+import type ServerProcessBoundary from "@server/core/link-manager/auth-manager/process-manager/server-process-boundary"+import { permissionCatalog } from "@server/core/permissions"+import { test } from "vitest"++test("Server Endpoints use their Program's permission scope", async () => {++ let permissions: Permissions = {}+ const authManager = new TheLink() as unknown as AuthManager+ const manager = new ProcessManager(authManager)+ const owner = program("owner")+ const outside = program("outside")+ const launch = { server: null, client: null, options: {} } as const+ const programs = new Map([[owner.identity, { program: owner }], [outside.identity, { program: outside }]])++ const system = {+ listPrograms() { return [owner, outside] },+ findProgram(identity: string) { return identity === owner.identity ? owner : identity === outside.identity ? outside : null },+ async createProgram(source: { identity: string }) {++ const created = program(source.identity)+ programs.set(created.identity, { program: created })+ return created+ },+ requireProgram(identity: string) {++ const found = programs.get(identity)?.program+ if (!found) throw new Error("The Program does not exist")+ return found+ },+ holdProgram(value: unknown, fallback: Program = owner) {++ if (value === undefined || value === null) return fallback+ if (typeof value !== "object" || value === null) throw new Error("Invalid Program handle")+ const handle = value as { identity?: string, reference?: string }+ const found = this.findProgram(String(handle.identity))+ if (!found || found.reference !== handle.reference) throw new Error("The Program represented by this handle does not exist")+ return found+ }+ }++ Object.assign(authManager, {+ programManager: {+ programs,+ permission() { return null },+ grantsPermission<Name extends PermissionName>(_program: Program, name: Name, requested: readonly PermissionValue<Name>[]) {++ return permissionCatalog.allows(name, requested, permissions)+ },+ grantsStorage() { return false }+ },+ linkManager: { application: { system } }+ })++ const current = await manager.register("current", null, owner, {}, launch, null, false, null, null)+ const hidden = await manager.register("hidden", null, outside, {}, launch, null, false, null, null)++ const boundary = manager as unknown as {+ endHost(process: Process, server: ServerProcessBoundary, args: unknown[]): Promise<unknown[]>+ }+ const answer = (...args: unknown[]) => boundary.endHost(current, {} as ServerProcessBoundary, args)++ assert.deepEqual((await answer("host-program-list") as [Program[]])[0].map(program => program.identity), [owner.identity])+ assert.deepEqual(await answer("host-program-find", outside.identity), [null])+ await assert.rejects(answer("host-program-create", { identity: "created", client: { location: "." } }), /Execution is not permitted/)+ await assert.rejects(answer("update-appearance", {}), /Execution is not permitted/)+ await assert.rejects(answer("program-create-process", owner, { client: { layer: "over" } }), /Execution is not permitted/)++ permissions = { programs: [outside.identity], appearance: [], layers: ["over"] }++ assert.deepEqual((await answer("host-program-list") as [Program[]])[0].map(program => program.identity), [owner.identity, outside.identity])+ assert.equal((await answer("host-program-find", outside.identity) as [Program])[0], outside)+ await assert.rejects(answer("host-program-create", { identity: "created", client: { location: "." } }), /Execution is not permitted/)++ permissions = { all: [] }++ assert.equal(((await answer("host-program-create", { identity: "created", client: { location: "." } })) as [Program])[0].identity, "created")++ assert.equal(manager.processes.get(hidden.identity), hidden)+})++function program(identity: string) {++ return new Program({ identity, server: { location: ".", command: "true" } })+}diff --git a/tests/server-process-boundary.test.ts b/tests/server-process-boundary.test.tsnew file mode 100644index 0000000..70a9121--- /dev/null+++ b/tests/server-process-boundary.test.ts@@ -0,0 +1,32 @@+import assert from "node:assert/strict"+import type { ServerRuntime } from "@server/core/server-runtime"+import ServerProcessBoundary from "@server/core/link-manager/auth-manager/process-manager/server-process-boundary"+import type HostTraffic from "@server/core/link-manager/auth-manager/process-manager/host-traffic"+import type { Tunnel } from "@the-link/core"+import { test } from "vitest"++test("the Server boundary receives readiness already buffered by its runtime", async () => {++ const runtime: ServerRuntime = {+ finished: new Promise(() => undefined),+ send() {},+ onOutput() {},+ stop() {},+ onMessage(listener) { listener("boundary", "ready") }+ }++ const boundary = new ServerProcessBoundary(+ runtime,+ true,+ false,+ async () => undefined,+ () => undefined,+ {} as HostTraffic,+ {} as Tunnel,+ () => true+ )++ await Promise.resolve()++ assert.equal(boundary.ready, true)+})diff --git a/tests/start-menu-search.test.tsx b/tests/start-menu-search.test.tsxindex f3f34ca..eaeda29 100644--- a/tests/start-menu-search.test.tsx+++ b/tests/start-menu-search.test.tsx@@ -38,7 +38,7 @@ test("start menu search contract", async () => {assert(!matchesProcess(null, undefined, searchTerms("notes")))assert(!matchesProcess("daily draft", program, searchTerms("missing")))- const footer = renderToStaticMarkup(<UIProvider appearance={defaultAppearance} preferences={{ theme: "light", animations: true }}><SearchBar query="notes" onChange={() => {}} /></UIProvider>)+ const footer = renderToStaticMarkup(<UIProvider appearance={defaultAppearance} preferences={{ theme: "light", animations: true, scale: 1 }}><SearchBar query="notes" onChange={() => {}} /></UIProvider>)assert.match(footer, /<div class="react-aria-TextField"/)assert.match(footer, /<input\b/)diff --git a/tests/wallpaper-source.test.tsx b/tests/wallpaper-source.test.tsxindex f576eba..c65439b 100644--- a/tests/wallpaper-source.test.tsx+++ b/tests/wallpaper-source.test.tsx@@ -18,7 +18,7 @@ test("wallpaper source contract", () => {function render(file: string) {return renderToStaticMarkup(<ApplicationContext.Provider value={application}>- <UIProvider appearance={defaultAppearance} preferences={{ theme: "dark", animations: true }}>+ <UIProvider appearance={defaultAppearance} preferences={{ theme: "dark", animations: true, scale: 1 }}><WallpaperBackground file={file} /></UIProvider></ApplicationContext.Provider>)diff --git a/tests/worker-runtime.test.ts b/tests/worker-runtime.test.tsindex f7550c1..f67d271 100644--- a/tests/worker-runtime.test.ts+++ b/tests/worker-runtime.test.ts@@ -1,37 +1,56 @@import assert from "node:assert/strict"-import { mkdtemp, rm, writeFile } from "node:fs/promises"+import { mkdtemp, rm, symlink, writeFile } from "node:fs/promises"import { createRequire } from "node:module"import { tmpdir } from "node:os"import { delimiter, join } from "node:path"import { pathToFileURL } from "node:url"-import CommandServerRuntime, { commandServerEnvironment } from "@server/view/server-runtime/command"-import WorkerServerRuntime from "@server/view/server-runtime/worker"+import messagepack from "@the-link/messagepack"+import { build } from "vite"+import CommandServerRuntime, { commandServerEnvironment } from "@server/core/server-runtime/command"+import SandboxServerRuntime from "@server/core/server-runtime/sandbox"+import WorkerServerRuntime from "@server/core/server-runtime/worker"import Program from "@server/core/link-manager/auth-manager/program-manager/program"import type { ProgramConfig } from "@server/core/link-manager/auth-manager/program-manager/config"import { test } from "vitest"-test("worker runtime contract", async () => {+test("server runtime contract", async () => {const directory = await mkdtemp(join(tmpdir(), "phresh-worker-runtime-"))const entry = join(directory, "server.mjs")+ const dependency = join(directory, "dependency.mjs")+ const bareEntry = join(directory, "bare.mjs")+ const escapedEntry = join(directory, "escaped.mjs")+ const outsideDirectory = await mkdtemp(join(tmpdir(), "phresh-sandbox-outside-"))+ const outsideModule = join(outsideDirectory, "outside.mjs")+ const linkedModule = join(directory, "linked.mjs")const commandEntry = join(directory, "command.mjs")+ const codecDirectory = join(directory, "codec")+ const codecEntry = join(codecDirectory, "sandbox-codec.js")const codec = pathToFileURL(createRequire(import.meta.url).resolve("@the-link/messagepack")).href+ const ready = [...messagepack.serialize(["boundary", "ready"])]+ const urlResult = [...messagepack.serialize(["url-result", "https://example.test/runtime"])]+ const bytesResult = [...messagepack.serialize(["bytes-result", [1, 2, 3]])]assert.equal(commandServerEnvironment(directory, { Path: "/native/bin" }).Path,`${join(directory, "node_modules", ".bin")}${delimiter}/native/bin`)+ await writeFile(dependency, `export const runtimePath = "/runtime"\n`)await writeFile(entry, `- import { parentPort } from "node:worker_threads"- import { deserialize as decode, serialize as encode } from ${JSON.stringify(codec)}-- console.log("worker output")- parentPort.postMessage(encode(["boundary", "ready"]))- parentPort.on("message", message => {- const [event, value] = decode(message)- if (event === "probe") parentPort.postMessage(encode(["probe-result", value]))- })+ import { runtimePath } from "./dependency.mjs"+ const transport = globalThis.__PHRESHOS_SERVER_TRANSPORT__+ const runtimeUrl = new URL(runtimePath, "https://example.test/root")+ console.log("runtime output")+ transport.send(new Uint8Array(${JSON.stringify(ready)}))+ transport.send(new Uint8Array(runtimeUrl.href === "https://example.test/runtime" ? ${JSON.stringify(urlResult)} : []))+ transport.send(new Uint8Array(Uint8Array.from([1, 2, 3]).join(",") === "1,2,3" ? ${JSON.stringify(bytesResult)} : []))+ transport.onMessage(message => Promise.resolve(message).then(value => transport.send(Uint8Array.from(value))))`)+ const ambientPackage = "ambient-package"+ await writeFile(bareEntry, `import ${JSON.stringify(ambientPackage)}\n`)+ await writeFile(outsideModule, `export const outside = true\n`)+ await symlink(outsideModule, linkedModule)+ await writeFile(escapedEntry, `import "./linked.mjs"\n`)await writeFile(commandEntry, `import { deserialize as decode, serialize as encode } from ${JSON.stringify(codec)}@@ -52,37 +71,47 @@ test("worker runtime contract", async () => {}`)+ await build({+ configFile: false,+ logLevel: "silent",+ ssr: { noExternal: true },+ build: {+ ssr: join(import.meta.dirname, "fixtures", "sandbox-codec.ts"),+ outDir: codecDirectory,+ emptyOutDir: false,+ rollupOptions: { output: { entryFileNames: "sandbox-codec.js" } }+ }+ })+try {- const program = new Program({ identity: "worker-verification", server: { location: directory, entryFile: "server.mjs" } })+ const program = new Program({ identity: "worker-verification", server: { location: directory, worker: "server.mjs" } })await program.validate()assert.equal(program.serverEntryPath, entry)- assert.throws(() => new Program({ identity: "worker-conflict", server: { location: directory, startCommand: "node main.js", entryFile: "server.mjs" } } as unknown as ProgramConfig))- assert.throws(() => new Program({ identity: "worker-escape", server: { location: directory, entryFile: "../server.mjs" } }))-- const runtime = new WorkerServerRuntime(entry)- const messages: unknown[][] = []- const output: ["out" | "err", string][] = []-- runtime.onMessage((event, ...values) => messages.push([event, ...values]))- runtime.onOutput((stream, text) => output.push([stream, text]))-- await until(() => messages.some(message => message[0] === "boundary" && message[1] === "ready"))-- runtime.send("probe", 42)+ assert.throws(() => new Program({ identity: "worker-conflict", server: { location: directory, command: "node main.js", worker: "server.mjs" } } as unknown as ProgramConfig))+ assert.throws(() => new Program({ identity: "worker-escape", server: { location: directory, worker: "../server.mjs" } }))- await until(() => messages.some(message => message[0] === "probe-result"))- await until(() => output.some(([stream, text]) => stream === "out" && text.includes("worker output")))+ await verifyContainedRuntime(new WorkerServerRuntime(entry))+ await verifyContainedRuntime(new SandboxServerRuntime(entry, directory))+ await verifyCodecRuntime(new SandboxServerRuntime(codecEntry, codecDirectory))- assert.deepEqual(messages.find(message => message[0] === "probe-result"), ["probe-result", 42])+ const sandbox = new Program({ identity: "sandbox-verification", server: { location: directory, sandbox: "server.mjs" } })+ await sandbox.validate()+ assert.equal(sandbox.serverEntryPath, entry)- runtime.stop()+ const bare = new SandboxServerRuntime(bareEntry, directory)+ const bareOutput: string[] = []+ bare.onOutput((_stream, text) => bareOutput.push(text))+ await bare.finished+ assert.match(bareOutput.join(""), /cannot import the package.*ambient-package.*bundle package dependencies/)- const ending = await runtime.finished-- assert.equal(ending.signal, null)+ const escaped = new SandboxServerRuntime(escapedEntry, directory)+ const escapedOutput: string[] = []+ escaped.onOutput((_stream, text) => escapedOutput.push(text))+ await escaped.finished+ assert.match(escapedOutput.join(""), /may not leave its Server directory/)const command = new CommandServerRuntime(`"${process.execPath}" "${commandEntry}"`, directory)const commandMessages: unknown[][] = []@@ -105,6 +134,86 @@ test("worker runtime contract", async () => {await command.finished} finally {await rm(directory, { recursive: true, force: true })+ await rm(outsideDirectory, { recursive: true, force: true })+ }++ async function verifyContainedRuntime(runtime: WorkerServerRuntime | SandboxServerRuntime) {+ const messages: unknown[][] = []+ const output: ["out" | "err", string][] = []++ runtime.onMessage((event, ...values) => messages.push([event, ...values]))+ runtime.onOutput((stream, text) => output.push([stream, text]))++ await until(() => messages.some(message => message[0] === "boundary" && message[1] === "ready"))+ await until(() => messages.some(message => message[0] === "url-result"))+ await until(() => messages.some(message => message[0] === "bytes-result"))++ runtime.send("probe", 42)++ await until(() => messages.some(message => message[0] === "probe"))+ await until(() => output.some(([stream, text]) => stream === "out" && text.includes("runtime output")))++ assert.deepEqual(messages.find(message => message[0] === "probe"), ["probe", 42])+ assert.deepEqual(messages.find(message => message[0] === "url-result"), ["url-result", "https://example.test/runtime"])+ assert.deepEqual(messages.find(message => message[0] === "bytes-result"), ["bytes-result", [1, 2, 3]])++ runtime.stop()++ const ending = await runtime.finished++ assert.equal(ending.signal, null)+ }++ async function verifyCodecRuntime(runtime: SandboxServerRuntime) {++ const messages: unknown[][] = []+ const output: string[] = []++ runtime.onMessage((event, ...values) => messages.push([event, ...values]))+ runtime.onOutput((_stream, text) => output.push(text))++ await until(() => messages.some(message => message[0] === "codec-ready") || output.length > 0)++ assert.deepEqual(output, [])++ const endpoint = {+ kind: "client",+ process: {+ reference: "process-reference",+ identity: "process",+ name: null,+ program: {+ reference: "program-reference",+ identity: "program",+ assetId: "asset",+ installed: false,+ name: "Program",+ version: null,+ description: null,+ categories: [],+ keywords: [],+ hasAgent: false,+ server: { location: "server", sandbox: "main.js", service: false },+ client: { location: "client", service: false }+ },+ options: {},+ startedAt: new Date("2026-01-01T00:00:00.000Z"),+ server: { service: false },+ client: { service: false }+ }+ }+ const question = `client:${"a".repeat(36)}:${"b".repeat(36)}`++ runtime.send("codec-probe", endpoint, question)++ await until(() => messages.some(message => message[0] === "codec-result") || output.length > 0)++ assert.deepEqual(output, [])+ assert.deepEqual(messages.find(message => message[0] === "codec-result"), ["codec-result", ["codec-probe", endpoint, question]])++ runtime.stop()++ await runtime.finished}async function until(condition: () => boolean, timeout = 2_000) {diff --git a/vite.config.ts b/vite.config.tsindex 32738fd..be7823c 100644--- a/vite.config.ts+++ b/vite.config.ts@@ -22,7 +22,11 @@ export default defineConfig({emptyOutDir: true,outDir: resolve(import.meta.dirname, "dist/server"),rolldownOptions: {- input: "main.ts"+ input: {+ main: "main.ts",+ "worker-bootstrap": "core/server-runtime/worker-bootstrap.ts",+ "sandbox-bootstrap": "core/server-runtime/sandbox-bootstrap.ts"+ }}}})