Skip to content

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

Unify the owner-local gateway

zohayrslilehbc93d4e7c434
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 04231c0..122f7f4 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -1,7 +1,7 @@
# Contributing
The system repository owns the authoritative PhreshOS runtime: server state,
-the desktop that represents it, local Program intake, persistence boundaries,
+the desktop that represents it, owner-local gateway, persistence boundaries,
and Process management.
## Development
diff --git a/README.md b/README.md
index d8fa799..b8f7faa 100644
--- a/README.md
+++ b/README.md
@@ -18,7 +18,7 @@ Host operating system
├── Server runtime
│ ├── Programs → Processes → Endpoints
│ ├── Authentication and persistence
- │ └── Local Program intake
+ │ └── Owner-local gateway
└── Web desktop
└── Browser representation of server truth
```
@@ -43,13 +43,13 @@ representation: windows, focus, layering, taskbar, and interaction. Programs
remain isolated from one another and reach shared system capabilities only
through the contracts exposed to their Endpoints.
-Local Program operations enter through an owner-restricted intake address. On
+Local Program operations enter through an owner-restricted gateway address. On
POSIX systems this is a Unix domain socket with mode `0600`; on Windows it is an
owner-created named pipe. It opens no network port and requires no token beyond
the operating-system account that owns it.
`phresh dev` and `phresh start` run an attached Program whose lifetime follows
-the intake connection. `phresh install` creates the persistent installed form,
+the gateway connection. `phresh install` creates the persistent installed form,
and `phresh uninstall` removes it through the same local boundary.
## Install and operate
@@ -89,12 +89,13 @@ the first stable release.
Production keeps System state beneath the owner's `~/.phreshos` directory.
This includes credentials and private material, the System database, installed
-Programs and their storage, uploaded files, and the local intake address while
+Programs and their storage, uploaded files, and the local gateway address while
the service is running.
-Development uses the repository's `storage/` directory by default.
-`PHRESHOS_HOME` may name another absolute directory for an isolated development
-instance; production does not consume this development override.
+Direct project execution uses the repository's `storage/` directory by default.
+`PHRESHOS_HOME` may select another absolute state root in either direct or
+CLI-launched execution. The CLI otherwise selects `~/.phreshos` and passes that
+absolute home to the System it launches.
`PHRESHOS_PORT` optionally selects the public desktop port. Production defaults
to `4300`. Neither environment variable is required.
diff --git a/package.json b/package.json
index 619f1dd..2db041d 100644
--- a/package.json
+++ b/package.json
@@ -30,7 +30,7 @@
"build": "vite-node scripts/build.ts",
"start": "node --run build && node dist/server/main.js",
"pack": "node --run build && vite-node scripts/pack.ts",
- "verify:contracts": "vite-node scripts/verify-client-launch.mjs && vite-node scripts/verify-process-find-or-create.mjs && vite-node scripts/verify-client-surface.mjs && vite-node scripts/verify-window-geometry.mjs && vite-node scripts/verify-readiness.mjs && vite-node scripts/verify-storage.mjs && vite-node scripts/verify-endpoint-services.mjs && vite-node scripts/verify-program-install.mjs && vite-node scripts/verify-host-traffic.mjs && vite-node scripts/verify-intake-address.mjs && vite-node scripts/verify-appearance.mjs",
+ "verify:contracts": "vite-node scripts/verify-client-launch.mjs && vite-node scripts/verify-process-find-or-create.mjs && vite-node scripts/verify-client-surface.mjs && vite-node scripts/verify-window-geometry.mjs && vite-node scripts/verify-readiness.mjs && vite-node scripts/verify-storage.mjs && vite-node scripts/verify-endpoint-services.mjs && vite-node scripts/verify-program-install.mjs && vite-node scripts/verify-host-traffic.mjs && vite-node scripts/verify-gateway-address.mjs && vite-node scripts/verify-gateway.mjs && vite-node scripts/verify-appearance.mjs",
"verify:distribution": "node scripts/verify-distribution.mjs",
"verify": "node --run check && node --run verify:contracts && node --run verify:distribution"
},
diff --git a/scripts/dev.ts b/scripts/dev.ts
index 9642617..1f8f39b 100644
--- a/scripts/dev.ts
+++ b/scripts/dev.ts
@@ -4,9 +4,9 @@ import view, { environmentHome, environmentPort } from "@server/view/view"
import { createServer } from "vite"
import { fileURLToPath } from "node:url"
-const storage = environmentHome(name, process.env) ?? fileURLToPath(new URL("../storage", import.meta.url))
+const home = environmentHome(name, process.env) ?? fileURLToPath(new URL("../storage", import.meta.url))
-const host = await view({ name, displayName, version, mode: "development", hostname: "localhost", storage })
+const host = await view({ name, displayName, version, mode: "development", hostname: "localhost", home })
const port = environmentPort(name, process.env)
diff --git a/scripts/verify-gateway-address.mjs b/scripts/verify-gateway-address.mjs
new file mode 100644
index 0000000..f25699a
--- /dev/null
+++ b/scripts/verify-gateway-address.mjs
@@ -0,0 +1,12 @@
+import assert from "node:assert/strict"
+import { join } from "node:path"
+import gatewayAddress from "../source/server/view/gateway/address.ts"
+
+const first = gatewayAddress("C:\\Users\\Person\\.phreshos", "win32")
+
+assert.match(first, /^\\\\\.\\pipe\\phreshos-[a-f0-9]{32}-gateway$/)
+assert.equal(first, gatewayAddress("c:/users/person/.phreshos/", "win32"))
+assert.notEqual(first, gatewayAddress("C:\\Users\\Other\\.phreshos", "win32"))
+assert.equal(gatewayAddress("/home/person/.phreshos", "linux"), join("/home/person/.phreshos", "gateway.sock"))
+
+console.log("gateway address verified")
diff --git a/scripts/verify-gateway.mjs b/scripts/verify-gateway.mjs
new file mode 100644
index 0000000..b01ad6a
--- /dev/null
+++ b/scripts/verify-gateway.mjs
@@ -0,0 +1,69 @@
+import assert from "node:assert/strict"
+import { mkdtemp, rm } from "node:fs/promises"
+import { connect } from "node:net"
+import { join, resolve } from "node:path"
+import gateway from "../source/server/view/gateway/gateway.ts"
+
+const directory = await mkdtemp(resolve(".verify-gateway-"))
+const path = join(directory, "gateway.sock")
+const application = {
+ systemControl: {
+ async execute(request) { return { received: request } }
+ },
+ linkManager: {
+ authManager: {
+ processManager: {
+ processes: new Map(),
+ async exit() {}
+ },
+ programManager: {
+ async *installSource(program) {
+ yield {
+ stage: "installed",
+ replaced: false,
+ entry: {
+ identity: program.identity,
+ program: { name: program.name, config: { version: program.version } }
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+const server = await gateway(application, path)
+
+try {
+ const system = await exchange(path, { target: "system", request: { capability: "program", operation: "list", input: {} } })
+
+ assert.deepEqual(system, [{ success: true, result: { received: { capability: "program", operation: "list", input: {} } } }])
+
+ const program = await exchange(path, {
+ target: "program",
+ request: { word: "install", program: { identity: "example", name: "Example", version: "1.0.0" } }
+ })
+
+ assert.deepEqual(program, [{
+ event: "installed",
+ replaced: false,
+ program: { identity: "example", name: "Example", version: "1.0.0" }
+ }])
+} finally {
+ await server.close()
+ await rm(directory, { recursive: true, force: true })
+}
+
+async function exchange(path, request) {
+ return await new Promise((resolve, reject) => {
+ const socket = connect(path)
+ let buffer = ""
+
+ socket.on("connect", () => socket.write(`${JSON.stringify(request)}\n`))
+ socket.on("data", chunk => { buffer += String(chunk) })
+ socket.on("error", reject)
+ socket.on("close", () => resolve(buffer.trim().split("\n").filter(Boolean).map(line => JSON.parse(line))))
+ })
+}
+
+console.log("shared gateway verified")
diff --git a/scripts/verify-intake-address.mjs b/scripts/verify-intake-address.mjs
deleted file mode 100644
index 2fc60c1..0000000
--- a/scripts/verify-intake-address.mjs
+++ /dev/null
@@ -1,18 +0,0 @@
-import assert from "node:assert/strict"
-import intakeAddress from "../source/server/view/intake-address.ts"
-import controlAddress from "../source/server/view/control-address.ts"
-import { join } from "node:path"
-
-const first = intakeAddress("C:\\Users\\Person\\.phreshos", "win32")
-
-assert.match(first, /^\\\\\.\\pipe\\phreshos-[a-f0-9]{32}-intake$/)
-
-assert.equal(first, intakeAddress("c:/users/person/.phreshos/", "win32"))
-
-assert.notEqual(first, intakeAddress("C:\\Users\\Other\\.phreshos", "win32"))
-
-assert.equal(intakeAddress("/home/person/.phreshos", "linux"), join("/home/person/.phreshos", "intake.sock"))
-
-assert.match(controlAddress("C:\\Users\\Person\\.phreshos", "win32"), /^\\\\\.\\pipe\\phreshos-[a-f0-9]{32}-control$/)
-
-assert.equal(controlAddress("/home/person/.phreshos", "linux"), join("/home/person/.phreshos", "control.sock"))
diff --git a/source/libs/file-manager.ts b/source/libs/file-manager.ts
index 6bba702..72ffb0d 100644
--- a/source/libs/file-manager.ts
+++ b/source/libs/file-manager.ts
@@ -29,9 +29,9 @@
* const configPath = appManager.join("config", "settings.json");
* ```
*/
-import { existsSync, mkdirSync, rmSync } from "node:fs"
+import { existsSync, mkdirSync, realpathSync, rmSync } from "node:fs"
import { homedir } from "node:os"
-import { join } from "node:path"
+import { join, resolve } from "node:path"
/**
* Application directory management system providing automatic directory creation
@@ -70,12 +70,14 @@ export default class FileManager {
/**
* Combine all path segments into normalized absolute path.
*/
- this.path = join(...paths)
+ const path = resolve(join(...paths))
/**
* Ensure target directory exists with recursive creation.
*/
- if (!existsSync(this.path)) mkdirSync(this.path, { recursive: true })
+ if (!existsSync(path)) mkdirSync(path, { recursive: true })
+
+ this.path = realpathSync(path)
}
/**
@@ -230,4 +232,4 @@ export default class FileManager {
*/
return new FileManager(this.path, ...paths)
}
-}
\ No newline at end of file
+}
diff --git a/source/server/core/application.ts b/source/server/core/application.ts
index 66c2667..44ee283 100644
--- a/source/server/core/application.ts
+++ b/source/server/core/application.ts
@@ -75,9 +75,9 @@ export default class Application {
this.systemControl = new SystemControl(this)
}
- public static async initialize(name: string, displayName: string, version: string, storagePath: string | undefined, defaultProgramIcon: string) {
+ public static async initialize(name: string, displayName: string, version: string, homePath: string, defaultProgramIcon: string) {
- const storage = storagePath ? new FileManager(storagePath) : FileManager.forApp(name)
+ const storage = new FileManager(homePath)
const home = new FileArea(homedir(), "the native home directory")
diff --git a/source/server/core/link-manager/auth-manager/program-manager/program-manager.ts b/source/server/core/link-manager/auth-manager/program-manager/program-manager.ts
index 62b0a81..318f746 100644
--- a/source/server/core/link-manager/auth-manager/program-manager/program-manager.ts
+++ b/source/server/core/link-manager/auth-manager/program-manager/program-manager.ts
@@ -682,7 +682,7 @@ export default class ProgramManager extends TheLink {
}
}
- /** Run a durable Program independently of the local intake connection. */
+ /** Run a durable Program independently of a local gateway connection. */
public async runInstalled(program: Program, launch: Launch = {}) {
if (!this.installed(program)) throw new Error("Only an installed program can run independently")
diff --git a/source/server/main.ts b/source/server/main.ts
index c35da71..36e7883 100644
--- a/source/server/main.ts
+++ b/source/server/main.ts
@@ -1,6 +1,14 @@
import { displayName, name, version } from "@/package.json"
-import view, { environmentPort } from "./view/view"
+import view, { environmentHome, environmentPort } from "./view/view"
import { fileURLToPath } from "node:url"
+import { isAbsolute, normalize } from "node:path"
+import { readFile, rm } from "node:fs/promises"
+
+const requested = await requestedHome(process.argv)
+const home = environmentHome(name, process.env)
+ ?? requested
+ ?? defaultHome(process.argv)
+ ?? fileURLToPath(new URL("../../storage", import.meta.url))
await view({
@@ -12,7 +20,50 @@ await view({
mode: "production",
+ home,
+
port: environmentPort(name, process.env) ?? 4300,
assets: fileURLToPath(new URL("../client", import.meta.url))
})
+
+function defaultHome(arguments_: string[]) {
+
+ const positions = arguments_.flatMap((value, index) => value === "--default-home" ? [index] : [])
+
+ if (positions.length === 0) return undefined
+ if (positions.length !== 1) throw new Error("--default-home can be supplied only once")
+
+ const value = arguments_[positions[0]! + 1]
+
+ if (!value || !isAbsolute(value)) throw new Error("--default-home must be followed by an absolute filesystem path")
+
+ return normalize(value)
+}
+
+async function requestedHome(arguments_: string[]) {
+
+ const positions = arguments_.flatMap((value, index) => value === "--home-request" ? [index] : [])
+
+ if (positions.length === 0) return undefined
+ if (positions.length !== 1) throw new Error("--home-request can be supplied only once")
+
+ const path = arguments_[positions[0]! + 1]
+
+ if (!path || !isAbsolute(path)) throw new Error("--home-request must be followed by an absolute filesystem path")
+
+ let value: string
+
+ try { value = (await readFile(path, "utf8")).trim() }
+ catch (error) {
+
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined
+ throw error
+ }
+
+ await rm(path, { force: true })
+
+ if (!isAbsolute(value)) throw new Error("The requested PhreshOS home must be an absolute filesystem path")
+
+ return normalize(value)
+}
diff --git a/source/server/view/control-address.ts b/source/server/view/control-address.ts
deleted file mode 100644
index 903f676..0000000
--- a/source/server/view/control-address.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-import { localAddress } from "./intake-address"
-
-/** Address the owner-local System control interface. */
-export default function controlAddress(storage: string, platform = process.platform) {
-
- return localAddress(storage, "control", platform)
-}
diff --git a/source/server/view/control.ts b/source/server/view/control.ts
deleted file mode 100644
index c0f63da..0000000
--- a/source/server/view/control.ts
+++ /dev/null
@@ -1,51 +0,0 @@
-import type Application from "@server/core/application"
-import localServer from "./local-server"
-
-/** Serve the complete Core-owned System control contract to the local owner. */
-export default function control(application: Application, path: string) {
-
- return localServer(path, function (socket) {
-
- const controller = new AbortController()
- let buffer = ""
- let handled = false
-
- socket.on("data", function (chunk) {
-
- if (handled) return
-
- buffer += String(chunk)
-
- const boundary = buffer.indexOf("\n")
-
- if (boundary < 0) return
-
- handled = true
-
- answer(application, buffer.slice(0, boundary), controller.signal).then(
- result => respond(socket, { success: true, result }),
- error => respond(socket, { success: false, error: error instanceof Error ? error.message : String(error) })
- )
- })
-
- socket.on("close", () => controller.abort(new Error("The requester disconnected")))
- socket.on("error", () => undefined)
- })
-}
-
-async function answer(application: Application, line: string, signal: AbortSignal) {
-
- let request: unknown
-
- try { request = JSON.parse(line) }
- catch { throw new Error("What arrived is not JSON") }
-
- return application.systemControl.execute(request, signal)
-}
-
-function respond(socket: import("node:net").Socket, outcome: object) {
-
- if (!socket.writable) return
-
- socket.end(`${JSON.stringify(outcome)}\n`)
-}
diff --git a/source/server/view/gateway/address.ts b/source/server/view/gateway/address.ts
new file mode 100644
index 0000000..1e1d218
--- /dev/null
+++ b/source/server/view/gateway/address.ts
@@ -0,0 +1,13 @@
+import { createHash } from "node:crypto"
+import { join } from "node:path"
+
+/** Resolve the owner-local gateway address for one System home. */
+export default function gatewayAddress(home: string, platform = process.platform) {
+
+ if (platform !== "win32") return join(home, "gateway.sock")
+
+ const owner = home.replaceAll("\\", "/").replace(/\/+$/, "").toLowerCase()
+ const identity = createHash("sha256").update(owner).digest("hex").slice(0, 32)
+
+ return `\\\\.\\pipe\\phreshos-${identity}-gateway`
+}
diff --git a/source/server/view/gateway/gateway.ts b/source/server/view/gateway/gateway.ts
new file mode 100644
index 0000000..943a0c5
--- /dev/null
+++ b/source/server/view/gateway/gateway.ts
@@ -0,0 +1,95 @@
+import type Application from "@server/core/application"
+import localServer from "./local-server"
+import programRequest from "./program-request"
+import systemRequest from "./system-request"
+
+const maximumRequestSize = 16 * 1024 * 1024
+
+/** Open the one owner-local gateway and route each connection internally. */
+export default function gateway(application: Application, path: string) {
+
+ return localServer(path, function (socket) {
+
+ const controller = new AbortController()
+ let buffer = ""
+ let handled = false
+
+ socket.on("data", function (chunk) {
+
+ if (handled) return
+
+ buffer += String(chunk)
+
+ if (buffer.length > maximumRequestSize) {
+
+ handled = true
+ return fail(socket, new Error("The gateway request is too large"))
+ }
+
+ const boundary = buffer.indexOf("\n")
+
+ if (boundary < 0) return
+
+ handled = true
+
+ let envelope: GatewayEnvelope
+
+ try { envelope = parseEnvelope(buffer.slice(0, boundary)) }
+ catch (error) { return fail(socket, error) }
+
+ if (envelope.target === "program") {
+
+ programRequest(application, socket, envelope.request).catch(error => fail(socket, error))
+ return
+ }
+
+ systemRequest(application, envelope.request, controller.signal).then(
+ result => finish(socket, { success: true, result }),
+ error => finish(socket, { success: false, error: reason(error) })
+ )
+ })
+
+ socket.on("close", () => controller.abort(new Error("The requester disconnected")))
+ socket.on("error", () => undefined)
+ })
+}
+
+function parseEnvelope(line: string): GatewayEnvelope {
+
+ let value: unknown
+
+ try { value = JSON.parse(line) }
+ catch { throw new Error("What arrived is not JSON") }
+
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("The gateway request must be an object")
+
+ const envelope = value as Record<string, unknown>
+
+ if (Object.keys(envelope).some(key => key !== "target" && key !== "request")) throw new Error("The gateway request contains an unknown field")
+
+ if (envelope.target !== "program" && envelope.target !== "system") throw new Error("The gateway target must be program or system")
+ if (!("request" in envelope)) throw new Error("The gateway request is missing")
+
+ return { target: envelope.target, request: envelope.request }
+}
+
+function fail(socket: import("node:net").Socket, error: unknown) {
+
+ if (socket.writable) socket.end(`${JSON.stringify({ event: "error", message: reason(error) })}\n`)
+}
+
+function finish(socket: import("node:net").Socket, outcome: object) {
+
+ if (socket.writable) socket.end(`${JSON.stringify(outcome)}\n`)
+}
+
+function reason(error: unknown) {
+
+ return error instanceof Error ? error.message : String(error)
+}
+
+interface GatewayEnvelope {
+
+ target: "program" | "system"
+ request: unknown
+}
diff --git a/source/server/view/local-server.ts b/source/server/view/gateway/local-server.ts
similarity index 77%
rename from source/server/view/local-server.ts
rename to source/server/view/gateway/local-server.ts
index 19eb219..1e86048 100644
--- a/source/server/view/local-server.ts
+++ b/source/server/view/gateway/local-server.ts
@@ -2,7 +2,7 @@ import { chmodSync, mkdirSync, rmSync } from "node:fs"
import { connect, createServer, type Socket } from "node:net"
import { dirname } from "node:path"
-/** Open an owner-only local socket and safely recover a stale POSIX address. */
+/** Open Gateway's owner-only local socket and safely recover a stale POSIX address. */
export default function localServer(path: string, receive: (socket: Socket) => void) {
const namedPipe = process.platform === "win32"
@@ -10,7 +10,7 @@ export default function localServer(path: string, receive: (socket: Socket) => v
if (!namedPipe) mkdirSync(dirname(path), { recursive: true })
- return new Promise<string>(function (resolve, reject) {
+ return new Promise<LocalServer>(function (resolve, reject) {
const listen = (recovered: boolean) => {
@@ -29,13 +29,22 @@ export default function localServer(path: string, receive: (socket: Socket) => v
}, reject)
})
- server.listen({ path, readableAll: false, writableAll: false }, () => resolve(secured(path, namedPipe)))
+ server.listen({ path, readableAll: false, writableAll: false }, () => resolve({
+ path: secured(path, namedPipe),
+ close: () => new Promise<void>((resolve, reject) => server.close(error => error ? reject(error) : resolve()))
+ }))
}
listen(false)
})
}
+export interface LocalServer {
+
+ path: string
+ close(): Promise<void>
+}
+
function secured(path: string, namedPipe: boolean) {
if (!namedPipe) chmodSync(path, 0o600)
diff --git a/source/server/view/gateway/program-request.ts b/source/server/view/gateway/program-request.ts
new file mode 100644
index 0000000..8c30eea
--- /dev/null
+++ b/source/server/view/gateway/program-request.ts
@@ -0,0 +1,114 @@
+import type Application from "@server/core/application"
+import type { Socket } from "node:net"
+
+/** Execute a streamed owner-local Program lifecycle request. */
+export default async function programRequest(application: Application, socket: Socket, value: unknown) {
+
+ if (!record(value)) throw new Error("The Program request must be an object")
+
+ const asked = value as Asked
+ const attached = new Set<string>()
+ const say = (event: Record<string, unknown>) => {
+
+ if (socket.writable) socket.write(`${JSON.stringify(event)}\n`)
+ }
+ const done = () => socket.end()
+
+ socket.on("close", function () {
+
+ for (const identity of attached) {
+
+ application.linkManager.authManager.processManager.exit(identity).catch(() => undefined)
+ }
+
+ attached.clear()
+ })
+
+ const programManager = application.linkManager.authManager.programManager
+
+ if (asked.word === "uninstall") {
+
+ if (typeof asked.identity !== "string" || !asked.identity) throw new Error("Uninstalling needs a Program identity")
+ if (asked.everything !== undefined && typeof asked.everything !== "boolean") throw new Error("Uninstalling everything must be true or false")
+
+ for await (const chunk of programManager.uninstallInstalledStreaming(asked.identity, asked.everything === true)) {
+
+ say({ event: "output", ...chunk })
+ }
+
+ say({ event: "uninstalled", identity: asked.identity, everything: asked.everything === true })
+ return done()
+ }
+
+ if (asked.word === "install") {
+
+ if (!asked.program) throw new Error("Installing needs a Program description")
+ if (asked.run !== undefined && typeof asked.run !== "boolean") throw new Error("Running after installation must be true or false")
+ if (asked.startup !== undefined && typeof asked.startup !== "boolean") throw new Error("Enabling startup during installation must be true or false")
+
+ for await (const stage of programManager.installSource(asked.program, { run: asked.run, startup: asked.startup })) {
+
+ if (stage.stage === "output") say({ event: "output", ...stage.chunk })
+ else if (stage.stage === "installed") say({
+ event: "installed",
+ replaced: stage.replaced,
+ program: {
+ identity: stage.entry.identity,
+ name: stage.entry.program.name,
+ version: stage.entry.program.config.version ?? null
+ }
+ })
+ else if (stage.stage === "startup-enabled") say({ event: "startupEnabled" })
+ else say({ event: "running", process: stage.process })
+ }
+
+ return done()
+ }
+
+ if (asked.word !== "run") throw new Error(`The Program gateway does not know the word "${String(asked.word)}"`)
+ if (!asked.program) throw new Error("Running needs a Program description")
+
+ let identity: string | null = null
+ let ended = false
+
+ identity = await programManager.launchAttached(asked.program, asked.options ?? {}, {
+ output: (stream, text) => say({ event: "output", stream, text }),
+ exited: function (code, signal) {
+
+ ended = true
+ if (identity) attached.delete(identity)
+ say({ event: "exited", code, signal })
+ done()
+ }
+ })
+
+ if (ended) return
+
+ if (socket.destroyed) {
+
+ if (application.linkManager.authManager.processManager.processes.has(identity)) {
+ await application.linkManager.authManager.processManager.exit(identity)
+ }
+
+ return
+ }
+
+ attached.add(identity)
+ say({ event: "started", process: identity })
+}
+
+function record(value: unknown): value is Record<string, unknown> {
+
+ return typeof value === "object" && value !== null && !Array.isArray(value)
+}
+
+interface Asked {
+
+ word?: string
+ identity?: string
+ everything?: boolean
+ run?: boolean
+ startup?: boolean
+ program?: Parameters<Application["linkManager"]["authManager"]["programManager"]["launchAttached"]>[0]
+ options?: Record<string, string>
+}
diff --git a/source/server/view/gateway/system-request.ts b/source/server/view/gateway/system-request.ts
new file mode 100644
index 0000000..7ed6b02
--- /dev/null
+++ b/source/server/view/gateway/system-request.ts
@@ -0,0 +1,7 @@
+import type Application from "@server/core/application"
+
+/** Execute a short owner-local System request. */
+export default async function systemRequest(application: Application, request: unknown, signal: AbortSignal) {
+
+ return application.systemControl.execute(request, signal)
+}
diff --git a/source/server/view/intake-address.ts b/source/server/view/intake-address.ts
deleted file mode 100644
index cb997b9..0000000
--- a/source/server/view/intake-address.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-import { createHash } from "node:crypto"
-import { join } from "node:path"
-
-/** Resolve one owner-local address shared by this System and its local CLI. */
-export function localAddress(storage: string, channel: string, platform = process.platform) {
-
- if (platform !== "win32") return join(storage, `${channel}.sock`)
-
- const owner = storage.replaceAll("\\", "/").replace(/\/+$/, "").toLowerCase()
-
- const identity = createHash("sha256").update(owner).digest("hex").slice(0, 32)
-
- return `\\\\.\\pipe\\phreshos-${identity}-${channel}`
-}
-
-export default function intakeAddress(storage: string, platform = process.platform) {
-
- return localAddress(storage, "intake", platform)
-}
diff --git a/source/server/view/intake.ts b/source/server/view/intake.ts
deleted file mode 100644
index 15e3888..0000000
--- a/source/server/view/intake.ts
+++ /dev/null
@@ -1,200 +0,0 @@
-import Application from "@server/core/application"
-import { type Socket } from "node:net"
-import localServer from "./local-server"
-
-/**
- * Owner-local intake for one Program project.
- *
- * Its closed vocabulary is install, uninstall, and attached run. General
- * System control uses a separate boundary. An attached Process lives exactly
- * as long as this connection; installed Programs are persistent.
- *
- * Authorization belongs to `localServer`: a mode-0600 POSIX socket or an
- * owner-only Windows named pipe, scoped by the System storage root.
- */
-export default function intake(application: Application, path: string) {
-
- // A message is a line. The first version had no framing at all — a
- // question was whatever arrived before the asker closed its own side
- // — which is elegant and needs half-close to work, and bun's `net`
- // does not half-close: `end(data)` there closes the socket, so the
- // answer was written into nothing. A line costs one delimiter and
- // depends on no runtime agreeing about anything.
- return localServer(path, function (socket) {
-
- let said = ""
-
- // What this connection launched, ended when it goes.
- const attached = new Set<string>()
-
- socket.on("data", function (chunk) {
-
- said += String(chunk)
-
- const lines = said.split("\n")
-
- said = lines.pop() ?? ""
-
- for (const line of lines) if (line.trim()) reply(application, socket, attached, line)
- })
-
- // Both directions of the tether meet here. The asker going is
- // what ends the process; the process ending is what ends the
- // socket, and either arriving first makes the other a no-op.
- socket.on("close", function () {
-
- for (const identity of attached) {
-
- application.linkManager.authManager.processManager.exit(identity).catch(() => undefined)
- }
-
- attached.clear()
- })
-
- socket.on("error", () => undefined)
- })
-}
-
-// One question in, many events out. A launch is not a thing with an
-// answer — it is a thing with a beginning, a middle of whatever the
-// program says, and an end.
-function reply(application: Application, socket: Socket, attached: Set<string>, line: string) {
-
- const say = (event: Record<string, unknown>) => { if (socket.writable) socket.write(JSON.stringify(event) + "\n") }
-
- const done = () => socket.end()
-
- const alive = () => !socket.destroyed
-
- answer(application, attached, say, done, alive, line).catch((error: Error) => {
-
- say({ event: "error", message: error.message })
-
- done()
- })
-}
-
-async function answer(application: Application, attached: Set<string>, say: (event: Record<string, unknown>) => void, done: () => void, alive: () => boolean, said: string) {
-
- let asked: Asked
-
- try { asked = JSON.parse(said) as Asked }
-
- catch { throw new Error("What arrived is not JSON") }
-
- // Direct launch and installation both enter the same runtime registry
- // under the Program's declared identity. Installation sets its installed
- // flag; launch atomically forgets the prior runtime occupant, if any, and
- // tethers the resulting uninstalled Program to its root process.
- const programManager = application.linkManager.authManager.programManager
-
- if (asked.word === "uninstall") {
-
- if (typeof asked.identity !== "string" || !asked.identity) throw new Error("Uninstalling needs a Program identity")
-
- if (asked.everything !== undefined && typeof asked.everything !== "boolean") throw new Error("Uninstalling everything must be true or false")
-
- for await (const chunk of programManager.uninstallInstalledStreaming(asked.identity, asked.everything === true)) {
-
- say({ event: "output", ...chunk })
- }
-
- say({ event: "uninstalled", identity: asked.identity, everything: asked.everything === true })
-
- return done()
- }
-
- // Laid out: a description, and only ever a description.
- //
- // The system does not know what an archive is. A package carries a
- // Program to this machine, so the CLI that acquired it verifies and opens
- // it. Intake receives the same concrete description whether its source
- // was an official package or the local project beside the caller. From
- // here onward the System alone validates, lays out, and launches it.
- if (asked.word === "install") {
-
- if (!asked.program) throw new Error("Installing needs a program description")
-
- if (asked.run !== undefined && typeof asked.run !== "boolean") throw new Error("Running after installation must be true or false")
-
- if (asked.startup !== undefined && typeof asked.startup !== "boolean") throw new Error("Enabling startup during installation must be true or false")
-
- for await (const stage of programManager.installSource(asked.program, { run: asked.run, startup: asked.startup })) {
-
- if (stage.stage === "output") say({ event: "output", ...stage.chunk })
-
- else if (stage.stage === "installed") {
-
- // Whether it replaced one. Installation has already ended every
- // process that could have retained one of the previous paths.
- say({ event: "installed", replaced: stage.replaced, program: { identity: stage.entry.identity, name: stage.entry.program.name, version: stage.entry.program.config.version ?? null } })
- }
-
- else if (stage.stage === "startup-enabled") say({ event: "startupEnabled" })
-
- else say({ event: "running", process: stage.process })
- }
-
- return done()
- }
-
- if (asked.word !== "run") throw new Error(`This machine's intake does not know the word "${String(asked.word)}"`)
-
- if (!asked.program) throw new Error("Running needs a program description")
-
- let identity: string | null = null
-
- let ended = false
-
- identity = await programManager.launchAttached(asked.program, asked.options ?? {}, {
-
- output: (stream, text) => say({ event: "output", stream, text }),
-
- exited: function (code, signal) {
-
- ended = true
-
- if (identity) attached.delete(identity)
-
- say({ event: "exited", code, signal })
-
- // Nothing more will be said on this connection: one question
- // per connection, and its subject has ended.
- done()
- }
- })
-
- // A child may end before launch finishes announcing its creation, and
- // the launcher may itself disappear during that same interval. Neither
- // event may leave a process attached to a connection that is already
- // finished.
- if (ended) return
-
- if (!alive()) {
-
- if (application.linkManager.authManager.processManager.processes.has(identity)) await application.linkManager.authManager.processManager.exit(identity)
-
- return
- }
-
- attached.add(identity)
-
- say({ event: "started", process: identity })
-}
-
-interface Asked {
-
- word?: string
-
- identity?: string
-
- everything?: boolean
-
- run?: boolean
-
- startup?: boolean
-
- program?: Parameters<Application["linkManager"]["authManager"]["programManager"]["launchAttached"]>[0]
-
- options?: Record<string, string>
-}
diff --git a/source/server/view/view.ts b/source/server/view/view.ts
index d77f477..1386276 100644
--- a/source/server/view/view.ts
+++ b/source/server/view/view.ts
@@ -3,10 +3,8 @@ import { serveStatic } from "@hono/node-server/serve-static"
import { serve } from "@hono/node-server"
import { WebSocketServer } from "ws"
import doors from "./doors"
-import intake from "./intake"
-import intakeAddress from "./intake-address"
-import control from "./control"
-import controlAddress from "./control-address"
+import gateway from "./gateway/gateway"
+import gatewayAddress from "./gateway/address"
import program from "./program"
import proxy from "./proxy"
import storage from "./storage"
@@ -30,7 +28,7 @@ export default async function (config: Config) {
font: "simple"
})
- const application = await Application.initialize(config.name, config.displayName, config.version, config.storage, resolve("assets/default-icon.png"))
+ 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,
@@ -72,21 +70,13 @@ export default async function (config: Config) {
}, resolve)
})
- // Local program intake beside the way the network reaches the system.
- // Not HTTP: it is a filesystem socket reachable only from this machine,
- // for installing or running the one program a local project declares.
- const [intakeSocket, controlSocket] = await Promise.all([
- intake(application, intakeAddress(application.storage.path)),
- control(application, controlAddress(application.storage.path))
- ])
+ const localGateway = await gateway(application, gatewayAddress(application.storage.path))
const origin = `http://localhost:${port}`
if (config.assets) console.log(` ➜ ${styleText("bold", "Desktop:")} ${origin}`)
- console.log(` ➜ ${styleText("bold", "Intake:")} ${intakeSocket}`)
-
- console.log(` ➜ ${styleText("bold", "Control:")} ${controlSocket}`)
+ console.log(` ➜ ${styleText("bold", "Gateway:")} ${localGateway.path}`)
return { origin }
}
@@ -101,8 +91,8 @@ export interface Config {
mode: "development" | "production"
- /** Explicit instance storage. Omission selects the real user installation. */
- storage?: string
+ /** Absolute authoritative state root selected by Main. */
+ home: string
assets?: string
@@ -129,7 +119,7 @@ export function environmentPort(name: string, variables: NodeJS.ProcessEnv) {
return port
}
-/** Read an optional absolute home for an isolated development instance. */
+/** Read the optional absolute authoritative home selected by Main's environment. */
export function environmentHome(name: string, variables: NodeJS.ProcessEnv) {
const selected = environment(name, "HOME", variables)
@@ -140,5 +130,5 @@ export function environmentHome(name: string, variables: NodeJS.ProcessEnv) {
if (!isAbsolute(value)) throw new Error(`${selected.key} must be an absolute filesystem path`)
- return value
+ return resolve(value)
}