Skip to content

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

Expose authoritative local System control

zohayrslileh5ea4716049b2
diff --git a/scripts/verify-intake-address.mjs b/scripts/verify-intake-address.mjs
index a3b1e92..2fc60c1 100644
--- a/scripts/verify-intake-address.mjs
+++ b/scripts/verify-intake-address.mjs
@@ -1,5 +1,6 @@
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")
@@ -11,3 +12,7 @@ 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/server/core/application.ts b/source/server/core/application.ts
index ee45516..cc5329e 100644
--- a/source/server/core/application.ts
+++ b/source/server/core/application.ts
@@ -10,6 +10,7 @@ import openStore from "./open-store"
import Keyv from "keyv"
import FileArea from "@libs/file-area"
import { homedir } from "node:os"
+import SystemControl from "./system-control/system-control"
export default class Application {
@@ -44,6 +45,8 @@ export default class Application {
public readonly linkManager: LinkManager
+ public readonly systemControl: SystemControl
+
private constructor(payload: ApplicationPayload) {
this.name = payload.name
@@ -73,6 +76,8 @@ export default class Application {
this.dialogManager = new DialogManager()
this.linkManager = new LinkManager(this)
+
+ this.systemControl = new SystemControl(this)
}
public static async initialize(name: string, displayName: string, version: string, storagePath: string | undefined, defaultProgramIcon: string) {
diff --git a/source/server/core/link-manager/auth-manager/process-manager/outside-questions.ts b/source/server/core/link-manager/auth-manager/process-manager/outside-questions.ts
new file mode 100644
index 0000000..48be901
--- /dev/null
+++ b/source/server/core/link-manager/auth-manager/process-manager/outside-questions.ts
@@ -0,0 +1,80 @@
+import { randomUUID } from "node:crypto"
+import type { Outcome } from "@server/core/outcome"
+import type ServerProcessBoundary from "./server-process-boundary"
+
+/** Active questions from trusted System views that are not Program Endpoints. */
+export default class OutsideQuestions {
+
+ private readonly pending = new Map<string, Pending>()
+
+ public ask(
+ target: ServerProcessBoundary,
+ timeout: number,
+ signal: AbortSignal | undefined,
+ send: (question: string, publicQuestion: string) => Promise<unknown>
+ ) {
+
+ const question = `outside:${randomUUID()}`
+ const publicQuestion = randomUUID()
+
+ return new Promise<unknown>((resolve, reject) => {
+
+ const cancel = () => this.reject(question, signal?.reason instanceof Error ? signal.reason : new Error("The question was cancelled"))
+ const timer = setTimeout(() => this.reject(question, new Error(`Answer timeout ${timeout}ms`)), timeout)
+
+ this.pending.set(question, {
+ resolve,
+ reject,
+ timer,
+ target,
+ release: () => signal?.removeEventListener("abort", cancel)
+ })
+
+ signal?.addEventListener("abort", cancel, { once: true })
+
+ if (signal?.aborted) cancel()
+ else send(question, publicQuestion).catch(error => this.reject(question, error instanceof Error ? error : new Error(String(error))))
+ })
+ }
+
+ public answer(question: string, outcome: Outcome) {
+
+ const pending = this.take(question)
+
+ if (!pending) return
+
+ if (outcome?.success === true) pending.resolve(outcome.result)
+ else pending.reject(new Error(outcome?.success === false ? outcome.error : "The Endpoint returned an invalid answer"))
+ }
+
+ private reject(question: string, error: Error) {
+
+ const pending = this.take(question)
+
+ if (!pending) return
+
+ pending.target.forget(question)
+ pending.reject(error)
+ }
+
+ private take(question: string) {
+
+ const pending = this.pending.get(question)
+
+ if (!pending) return null
+
+ clearTimeout(pending.timer)
+ pending.release()
+ this.pending.delete(question)
+
+ return pending
+ }
+}
+
+interface Pending {
+ resolve(value: unknown): void
+ reject(error: Error): void
+ timer: NodeJS.Timeout
+ target: ServerProcessBoundary
+ release(): void
+}
diff --git a/source/server/core/link-manager/auth-manager/process-manager/process-manager.ts b/source/server/core/link-manager/auth-manager/process-manager/process-manager.ts
index b378fe1..59c8fa1 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
@@ -18,6 +18,7 @@ import { failed, succeeded, type Outcome } from "@server/core/outcome"
import { endpointReference, processReference } from "./endpoint-reference"
import EndpointEvents from "./endpoint-events"
import EndpointServices from "./endpoint-services"
+import OutsideQuestions from "./outside-questions"
import { isPermissionName, isServiceKey, type PermissionName, type WindowGeometry, type WindowLayer } from "@phreshos/core"
/**
@@ -65,6 +66,8 @@ export default class ProcessManager extends TheLink {
private readonly stoppingServers = new Set<ServerProcessBoundary>()
+ private readonly outsideQuestions = new OutsideQuestions()
+
private highest = 0
// Questions name their waiting endpoint in their correlation address.
@@ -157,6 +160,68 @@ export default class ProcessManager extends TheLink {
return window
}
+ /** Complete public Window state, shared by every representation. */
+ public windowSnapshot(identity: string) {
+
+ const process = this.find(identity)
+ const window = this.windowOf(identity)
+
+ return Object.freeze({
+ title: window.title,
+ position: window.position,
+ size: window.size,
+ minimized: window.minimized,
+ front: this.front(window.layer) === process.identity,
+ layer: window.layer,
+ location: window.location
+ })
+ }
+
+ /** Observe one authoritative host fact without creating a Program boundary. */
+ public observeHost(domain: "program" | "process" | "window", event: string, subject: string | null, subscriber: (event: string, ...values: unknown[]) => void) {
+
+ return this.hostTraffic.observe(domain, event, subject, (_delivery, word, ...values) => subscriber(word, ...values))
+ }
+
+ /** Observe destinationless events from one exact live Endpoint. */
+ public observeEndpoint(identity: string, half: Half, event: string, subscriber: (payload: unknown) => void, impossible?: (reason: string) => void) {
+
+ const process = this.find(identity)
+
+ if (half === "server" ? !process.server : !process.client) throw new Error(`This process has no live ${half} endpoint`)
+
+ return this.endpointEvents.follow(process.reference, half, event, (_word, payload) => subscriber(payload), impossible)
+ }
+
+ /** Publish from a trusted execution boundary whose identity is not a Program Endpoint. */
+ public async publishFromOutside(identity: string, half: Half, event: string, payload: unknown) {
+
+ const process = this.find(identity)
+
+ if (half === "server" ? !process.server : !process.client) throw new Error(`This process has no live ${half} endpoint`)
+
+ await this.deliver(identity, half, [event, { from: null, payload }])
+ }
+
+ /** Ask a Server from a trusted execution boundary whose identity is intentionally hidden. */
+ public askFromOutside(identity: string, event: string, payload: unknown, timeout = 10_000, signal?: AbortSignal) {
+
+ const process = this.find(identity)
+ const target = process.server
+
+ if (!target) return Promise.reject(new Error("This process has no live server endpoint"))
+
+ return this.outsideQuestions.ask(target, timeout, signal, (question, publicQuestion) => (
+ this.deliver(identity, "server", [
+ "wait",
+ question,
+ publicQuestion,
+ event,
+ { from: null, payload }
+ ])
+ ))
+ }
+
// A server runtime is a ProcessLink. Speaking through its outbound
// tunnel keeps IPC as a transport detail and leaves a stopped child as
// fire-and-forget: there is no receiver to promise once it has gone.
@@ -486,6 +551,13 @@ export default class ProcessManager extends TheLink {
if (!back) return false
+ if (back.half === "outside") {
+
+ this.outsideQuestions.answer(values[1], values[4] as Outcome)
+
+ return true
+ }
+
const process = this.processes.get(back.identity)
const outcome = values[4] as Outcome
@@ -1637,32 +1709,9 @@ export default class ProcessManager extends TheLink {
// depth was being used to ask.
if (word === "window") {
- const { process: target, window } = this.heldWindow(rest[0], process)
-
- return [{
-
- title: window.title,
-
- position: window.position,
-
- size: window.size,
-
- minimized: window.minimized,
-
- // At the front of its own layer — which is ordering, and
- // is not the keyboard. There is no word here for the
- // keyboard at all.
- front: this.front(window.layer) === target.identity,
-
- // Which layer it lives in, and which of its own pages it
- // was opened at. A launch may say either, so a program
- // cannot read them off its own description — and `front`
- // is a weaker claim than it reads as unless you know
- // which layer it is the front of.
- layer: window.layer,
+ const target = this.heldWindow(rest[0], process).process
- location: window.location
- }]
+ return [this.windowSnapshot(target.identity)]
}
if (word === "move") {
@@ -2362,11 +2411,11 @@ export default class ProcessManager extends TheLink {
// memory at all. The address is in the message, which is the one place
// it cannot go stale, and the only place that does not require the
// middle to be trusted.
-function addressed(question: string): { half: Half, identity: string } | null {
+function addressed(question: string): { half: Half | "outside", identity: string } | null {
const [half, identity] = question.split(":")
- if (half !== "server" && half !== "client") return null
+ if (half !== "server" && half !== "client" && half !== "outside") return null
return { half, identity }
}
diff --git a/source/server/core/link-manager/auth-manager/process-manager/process.ts b/source/server/core/link-manager/auth-manager/process-manager/process.ts
index b28c709..1a781fb 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
@@ -211,11 +211,15 @@ export default class Process {
public onServerStop(listener: (code: number | null, signal: NodeJS.Signals | null) => void) {
this.serverStops.push(listener)
+
+ return () => removeListener(this.serverStops, listener)
}
public onClientStop(listener: () => void) {
this.clientStops.push(listener)
+
+ return () => removeListener(this.clientStops, listener)
}
// Every aggregate ending, one word. Endpoint stops are separate lifecycle
@@ -315,6 +319,13 @@ export default class Process {
}
}
+function removeListener<Listener>(listeners: Listener[], listener: Listener) {
+
+ const index = listeners.indexOf(listener)
+
+ if (index >= 0) listeners.splice(index, 1)
+}
+
export type HostedProcess = ReturnType<Process["hosted"]>
/** Public Process data from which an endpoint SDK reconstructs a handle. */
diff --git a/source/server/core/system-control/system-control.ts b/source/server/core/system-control/system-control.ts
new file mode 100644
index 0000000..74f83cd
--- /dev/null
+++ b/source/server/core/system-control/system-control.ts
@@ -0,0 +1,477 @@
+import {
+ systemControlInputIssue,
+ systemControlOperation,
+ type EndpointAskInput,
+ type EndpointInput,
+ type EndpointPublishInput,
+ type EndpointWaitInput,
+ type EndpointWaitReadyInput,
+ type ProcessCreateInput,
+ type ProcessFindOrCreateInput,
+ type ProcessInput,
+ type ProcessListInput,
+ type ProcessWaitInput,
+ type ProgramInput,
+ type ProgramListInput,
+ type ProgramWaitInput,
+ type SystemControlRequest,
+ type SystemControlOperation,
+ type WindowInput,
+ type WindowWaitInput
+} from "@phreshos/core"
+import { z } from "zod"
+import type Application from "../application"
+import type Entry from "../link-manager/auth-manager/program-manager/entry"
+import type Process from "../link-manager/auth-manager/process-manager/process"
+
+const envelope = z.object({
+ capability: z.string(),
+ operation: z.string(),
+ input: z.unknown()
+}).strict()
+
+const inputs = new WeakMap<SystemControlOperation, z.ZodType>()
+
+/** Executes the shared System-control contract against authoritative Core state. */
+export default class SystemControl {
+
+ public constructor(private readonly application: Application) {}
+
+ public async execute(value: unknown, signal?: AbortSignal) {
+
+ const request = envelope.parse(value)
+ const operation = systemControlOperation(request.capability, request.operation)
+
+ if (!operation) throw new Error(`Unknown System control operation "${request.capability}.${request.operation}"`)
+
+ let validator = inputs.get(operation)
+
+ if (!validator) {
+
+ validator = z.fromJSONSchema(operation.input as Parameters<typeof z.fromJSONSchema>[0])
+ inputs.set(operation, validator)
+ }
+
+ const input = validator.parse(request.input)
+ const issue = systemControlInputIssue(request.capability, request.operation, input)
+
+ if (issue) throw new Error(issue)
+
+ const normalized = { capability: request.capability, operation: request.operation, input } as SystemControlRequest
+
+ if (normalized.capability === "program") return this.program(normalized.operation, normalized.input, signal)
+ if (normalized.capability === "process") return this.process(normalized.operation, normalized.input, signal)
+ if (normalized.capability === "endpoint") return this.endpoint(normalized.operation, normalized.input, signal)
+ return this.window(normalized.operation, normalized.input, signal)
+ }
+
+ private async program(operation: string, input: ProgramListInput | ProgramInput | ProgramWaitInput, signal?: AbortSignal) {
+
+ const manager = this.programs
+
+ if (operation === "list") {
+
+ const request = input as ProgramListInput
+ const installedOnly = request.installedOnly ?? true
+ const query = request.search?.toLocaleLowerCase()
+ const found = [...manager.programs.values()].filter(entry => (
+ (!installedOnly || entry.installed)
+ && (!query || [entry.identity, entry.program.name, entry.program.config.description]
+ .some(value => value?.toLocaleLowerCase().includes(query)))
+ ))
+ const selected = found
+ .sort((left, right) => left.identity.localeCompare(right.identity))
+ .slice(0, request.limit ?? 30)
+
+ return Object.freeze({
+ data: Object.freeze(selected.map(programSnapshot)),
+ total: found.length,
+ truncated: found.length > selected.length
+ })
+ }
+
+ if (operation === "wait") return this.waitProgram(input as ProgramWaitInput, signal)
+
+ const entry = requiredProgram(manager.programs, (input as ProgramInput).program)
+
+ if (operation === "inspect") return programSnapshot(entry)
+
+ const content = entry.program.agent()
+
+ if (content === null) throw new Error(`Program "${entry.identity}" has no agent documentation`)
+
+ return Object.freeze({ program: entry.identity, content })
+ }
+
+ private async process(operation: string, input: ProcessListInput | ProcessInput | ProcessCreateInput | ProcessFindOrCreateInput | ProcessWaitInput, signal?: AbortSignal) {
+
+ if (operation === "list") {
+
+ const request = input as ProcessListInput
+ const owner = request.program ? requiredProgram(this.programs.programs, request.program).program : null
+ const query = request.search?.toLocaleLowerCase()
+ const found = [...this.processes.processes.values()].filter(process => (
+ (!owner || process.program === owner)
+ && (!query || [process.identity, process.name, process.program.identity]
+ .some(value => value?.toLocaleLowerCase().includes(query)))
+ ))
+ const selected = found
+ .sort((left, right) => right.startedAt.getTime() - left.startedAt.getTime())
+ .slice(0, request.limit ?? 30)
+
+ return Object.freeze({
+ data: Object.freeze(selected.map(processSnapshot)),
+ total: found.length,
+ truncated: found.length > selected.length
+ })
+ }
+
+ if (operation === "wait") return this.waitProcess(input as ProcessWaitInput, signal)
+
+ if (operation === "create" || operation === "findOrCreate") {
+
+ const request = input as ProcessCreateInput | ProcessFindOrCreateInput
+ const identity = operation === "create"
+ ? await this.programs.createProcess(request.program, request.launch)
+ : await this.programs.findOrCreateProcess(
+ request.program,
+ (request as ProcessFindOrCreateInput).launch
+ )
+
+ return processSnapshot(requiredProcess(this.processes.processes, identity))
+ }
+
+ const request = input as ProcessInput
+ const process = resolveProcess(this.processes.processes, this.programs.programs, request)
+ const snapshot = processSnapshot(process)
+
+ if (operation === "exit") {
+
+ await this.processes.exit(process.identity)
+
+ return Object.freeze({ ...snapshot, exited: true })
+ }
+
+ return snapshot
+ }
+
+ private async endpoint(operation: string, input: EndpointInput | EndpointWaitReadyInput | EndpointAskInput | EndpointPublishInput | EndpointWaitInput, signal?: AbortSignal) {
+
+ const process = resolveProcess(this.processes.processes, this.programs.programs, input)
+ const declaration = process.program[input.endpoint]
+
+ if (!declaration) throw new Error(`Program "${process.program.identity}" does not declare a ${input.endpoint} Endpoint`)
+
+ if (operation === "inspect") return endpointSnapshot(process, input.endpoint)
+
+ if (operation === "start" || operation === "stop") {
+
+ if (operation === "start") {
+ if (input.endpoint === "server") await this.processes.startServer(process.identity)
+ else await this.processes.startClient(process.identity)
+ } else {
+ if (input.endpoint === "server") await this.processes.stopServer(process.identity)
+ else await this.processes.stopClient(process.identity)
+ }
+
+ return endpointSnapshot(process, input.endpoint)
+ }
+
+ if (operation === "waitReady") {
+
+ await waitReady(process, (input as EndpointWaitReadyInput).timeout, signal)
+
+ return endpointSnapshot(process, "server")
+ }
+
+ if (operation === "ask") {
+
+ const request = input as EndpointAskInput
+
+ return this.processes.askFromOutside(
+ process.identity,
+ request.event,
+ request.payload,
+ request.timeout,
+ signal
+ )
+ }
+
+ if (operation === "publish") {
+
+ const request = input as EndpointPublishInput
+
+ await this.processes.publishFromOutside(process.identity, request.endpoint, request.event, request.payload)
+
+ return Object.freeze({ ...endpointSnapshot(process, request.endpoint), event: request.event, published: true })
+ }
+
+ const request = input as EndpointWaitInput
+ const payload = await waitFor(
+ (resolve, reject) => this.processes.observeEndpoint(
+ process.identity,
+ request.endpoint,
+ request.event,
+ resolve,
+ reason => reject(new Error(reason))
+ ),
+ request.timeout,
+ signal
+ )
+
+ return Object.freeze({
+ scope: "endpoint",
+ process: process.identity,
+ endpoint: request.endpoint,
+ event: request.event,
+ payload
+ })
+ }
+
+ private async window(operation: string, input: WindowInput | WindowWaitInput | (WindowInput & Record<string, unknown>), signal?: AbortSignal) {
+
+ const process = resolveProcess(this.processes.processes, this.programs.programs, input)
+ const request = input as WindowInput & Record<string, unknown>
+
+ if (!process.client) throw new Error(`Process "${process.identity}" has no running Client Endpoint`)
+
+ if (operation === "wait") {
+
+ const waiting = input as WindowWaitInput
+ const payload = await waitFor(
+ (resolve, reject) => {
+
+ const stopObservation = this.processes.observeHost("window", waiting.event, process.reference, (_event, _subject, value) => resolve(value))
+ const stopProcess = process.onExit(() => reject(new Error(`Process "${process.identity}" exited while waiting for its Window`)))
+ const stopClient = process.onClientStop(() => reject(new Error(`The Client Endpoint stopped while waiting for Process "${process.identity}" Window`)))
+
+ return () => { stopObservation(); stopProcess(); stopClient() }
+ },
+ waiting.timeout,
+ signal
+ )
+
+ return Object.freeze({ scope: "window", process: process.identity, event: waiting.event, payload })
+ }
+
+ if (operation === "move") await this.processes.move(process.identity, request.position as never)
+ else if (operation === "resize") await this.processes.resize(process.identity, request.size as never)
+ else if (operation === "setGeometry") await this.processes.setGeometry(process.identity, {
+ position: request.position as never,
+ size: request.size as never
+ })
+ else if (operation === "minimize") await this.processes.minimize(process.identity, request.minimized !== false)
+ else if (operation === "changeTitle") await this.processes.changeTitle(process.identity, String(request.title))
+ else if (operation === "raise") await this.processes.raise(process.identity)
+
+ return Object.freeze({ process: process.identity, ...this.processes.windowSnapshot(process.identity) })
+ }
+
+ private async waitProgram(request: ProgramWaitInput, signal?: AbortSignal) {
+
+ const entry = request.program ? requiredProgram(this.programs.programs, request.program) : null
+ const subject = entry?.program.reference ?? null
+ const values = await waitFor<unknown[]>(
+ resolve => this.processes.observeHost("program", request.event, subject, (_event, ...payload) => resolve(payload)),
+ request.timeout,
+ signal
+ )
+
+ const affected = entry ?? values.find(value => value && typeof value === "object" && "program" in value) as Entry | undefined
+ ?? values.find(value => value && typeof value === "object" && "installed" in value) as Entry | undefined
+
+ return Object.freeze({
+ scope: entry ? "program" : "host",
+ ...(entry ? { program: programSnapshot(entry) } : {}),
+ event: request.event,
+ payload: request.event === "uninstall"
+ ? Object.freeze({
+ ...(affected ? { program: programSnapshot(affected) } : {}),
+ everythingRemoved: values.at(-1) === true
+ })
+ : affected ? programSnapshot(affected) : values
+ })
+ }
+
+ private async waitProcess(request: ProcessWaitInput, signal?: AbortSignal) {
+
+ const process = request.process
+ ? resolveProcess(this.processes.processes, this.programs.programs, request as ProcessInput)
+ : null
+ const program = !process && request.program
+ ? requiredProgram(this.programs.programs, request.program)
+ : null
+ const subject = process?.reference ?? program?.program.reference ?? null
+ const values = await waitFor<unknown[]>(
+ resolve => this.processes.observeHost("process", request.event, subject, (_event, ...payload) => resolve(payload)),
+ request.timeout,
+ signal
+ )
+ const record = values.find(value => value && typeof value === "object" && "identity" in value) as ReturnType<Process["record"]> | undefined
+
+ return Object.freeze({
+ scope: process ? "process" : program ? "program" : "host",
+ ...(process ? { process: process.identity } : {}),
+ ...(program ? { program: program.identity } : {}),
+ event: request.event,
+ payload: request.event === "exit"
+ ? Object.freeze({
+ process: record?.identity ?? process?.identity ?? null,
+ status: values.at(-1) ? "signaled" : "exited",
+ code: values.at(-2) ?? null,
+ signal: values.at(-1) ?? null
+ })
+ : request.event === "endpointStart" || request.event === "endpointStop"
+ ? Object.freeze({ process: record?.identity ?? process?.identity ?? null, endpoint: values.at(-1) })
+ : record ? processRecordSnapshot(record) : values
+ })
+ }
+
+ private get programs() { return this.application.linkManager.authManager.programManager }
+ private get processes() { return this.application.linkManager.authManager.processManager }
+}
+
+function requiredProgram(programs: ReadonlyMap<string, Entry>, identity: string) {
+
+ const program = programs.get(identity)
+
+ if (!program) throw new Error(`Unknown Program "${identity}"`)
+
+ return program
+}
+
+function requiredProcess(processes: ReadonlyMap<string, Process>, identity: string) {
+
+ const process = processes.get(identity)
+
+ if (!process) throw new Error(`Unknown Process "${identity}"`)
+
+ return process
+}
+
+function resolveProcess(processes: ReadonlyMap<string, Process>, programs: ReadonlyMap<string, Entry>, input: ProcessInput) {
+
+ if (!input.program) return requiredProcess(processes, input.process)
+
+ const owner = requiredProgram(programs, input.program).program
+ const process = [...processes.values()].find(candidate => (
+ candidate.program === owner
+ && (candidate.identity === input.process || candidate.name === input.process)
+ ))
+
+ if (!process) throw new Error(`Unknown Process "${input.process}" in Program "${input.program}"`)
+
+ return process
+}
+
+function programSnapshot(entry: Entry) {
+
+ const program = entry.program
+
+ return Object.freeze({
+ identity: program.identity,
+ name: program.name,
+ version: program.config.version ?? null,
+ description: program.config.description ?? null,
+ installed: entry.installed,
+ hasAgent: program.agentPath !== null,
+ server: program.server ? Object.freeze({ start: program.server.start }) : null,
+ client: program.client ? Object.freeze({
+ start: program.client.start,
+ title: program.client.title ?? null,
+ size: program.client.size ?? null,
+ position: program.client.position ?? null,
+ layer: program.client.layer ?? null,
+ minimize: program.client.minimize ?? null
+ }) : null
+ })
+}
+
+function processSnapshot(process: Process) {
+
+ return Object.freeze({
+ identity: process.identity,
+ name: process.name,
+ program: process.program.identity,
+ startedAt: process.startedAt.toISOString(),
+ server: Object.freeze({ declared: process.program.server !== null, running: process.server !== null }),
+ client: Object.freeze({ declared: process.program.client !== null, running: process.client !== null })
+ })
+}
+
+function processRecordSnapshot(process: ReturnType<Process["record"]>) {
+
+ const record = process as unknown as {
+ identity: string
+ name: string | null
+ program: { identity: string, server: unknown, client: unknown }
+ startedAt: Date | string
+ server: unknown
+ client: unknown
+ }
+
+ return Object.freeze({
+ identity: record.identity,
+ name: record.name,
+ program: record.program.identity,
+ startedAt: new Date(record.startedAt).toISOString(),
+ server: Object.freeze({ declared: record.program.server !== null, running: record.server !== null }),
+ client: Object.freeze({ declared: record.program.client !== null, running: record.client !== null })
+ })
+}
+
+function endpointSnapshot(process: Process, endpoint: "server" | "client") {
+
+ return Object.freeze({
+ process: process.identity,
+ program: process.program.identity,
+ endpoint,
+ declared: process.program[endpoint] !== null,
+ running: process[endpoint] !== null
+ })
+}
+
+function waitReady(process: Process, timeout = 10_000, signal?: AbortSignal) {
+
+ return waitFor<void>((resolve, reject) => {
+
+ const stopReady = process.waitReady(resolve)
+ const stopExit = process.onExit(() => reject(new Error(`Process "${process.identity}" exited before its Server became ready`)))
+ const stopServer = process.onServerStop(() => reject(new Error(`The Server Endpoint stopped before Process "${process.identity}" became ready`)))
+
+ return () => { stopReady(); stopExit(); stopServer() }
+ }, timeout, signal)
+}
+
+function waitFor<Value>(subscribe: (resolve: (value: Value) => void, reject: (error: Error) => void) => () => void, timeout = 10_000, signal?: AbortSignal) {
+
+ return new Promise<Value>((resolve, reject) => {
+
+ let done = false
+ let cleanup: () => void = () => undefined
+ const finish = (work: () => void) => {
+
+ if (done) return
+
+ done = true
+ clearTimeout(timer)
+ signal?.removeEventListener("abort", cancel)
+ cleanup()
+ work()
+ }
+ const cancel = () => finish(() => reject(signal?.reason instanceof Error ? signal.reason : new Error("The wait was cancelled")))
+ const timer = setTimeout(() => finish(() => reject(new Error(`Event promise timeout ${timeout}ms`))), timeout)
+
+ const subscribed = subscribe(
+ value => finish(() => resolve(value)),
+ error => finish(() => reject(error))
+ )
+
+ cleanup = subscribed
+
+ if (done) cleanup()
+
+ if (signal?.aborted) cancel()
+ else signal?.addEventListener("abort", cancel, { once: true })
+ })
+}
diff --git a/source/server/view/control-address.ts b/source/server/view/control-address.ts
new file mode 100644
index 0000000..903f676
--- /dev/null
+++ b/source/server/view/control-address.ts
@@ -0,0 +1,7 @@
+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
new file mode 100644
index 0000000..c0f63da
--- /dev/null
+++ b/source/server/view/control.ts
@@ -0,0 +1,51 @@
+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/intake-address.ts b/source/server/view/intake-address.ts
index 5ea5981..cb997b9 100644
--- a/source/server/view/intake-address.ts
+++ b/source/server/view/intake-address.ts
@@ -1,14 +1,19 @@
import { createHash } from "node:crypto"
import { join } from "node:path"
-/** Resolve the owner-local address shared by this System and its local CLI. */
-export default function intakeAddress(storage: string, platform = process.platform) {
+/** 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, "intake.sock")
+ 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}-intake`
+ 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
index ffbcb46..15e3888 100644
--- a/source/server/view/intake.ts
+++ b/source/server/view/intake.ts
@@ -1,88 +1,26 @@
-import { chmodSync, mkdirSync, rmSync } from "node:fs"
import Application from "@server/core/application"
-import { connect, createServer, type Socket } from "node:net"
-import { dirname } from "node:path"
+import { type Socket } from "node:net"
+import localServer from "./local-server"
/**
- * The local program intake: programs entering from this machine.
+ * Owner-local intake for one Program project.
*
- * One narrow local interface beside the web view a person lives in. The
- * two views are the two audiences, and this one accepts exactly one subject:
- * the Program a local project declares: attached, installed, or uninstalled.
+ * 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.
*
- * It was called *control* while it had two words and no stated limit,
- * and the name invited every next word: anything about the machine could
- * be called controlling it, so the surface had no edge. The role is
- * named instead. The boundary is the lifecycle of one locally identified
- * Program project: laid out, run attached, or removed from its installed
- * place. Words about arbitrary Processes, Windows, stores, or application
- * state remain outside it because this is not the machine's control panel.
- *
- * The link is how a person somewhere else reaches the system, and it has
- * to prove who it is because it arrived over a network. This is how a
- * local project standing on the same machine reaches it, and it is already
- * proven by being able to open the socket.
- *
- * **That is the whole authorization model, and it is the operating
- * system's rather than ours.** The socket is a filesystem entry at mode
- * 0600, so only the account that owns this machine may speak here — and
- * that account is exactly who may run programs on it. Nothing is checked
- * in this file because there is nothing left to check.
- *
- * A port would have had the opposite property. Every process on the
- * machine can reach a port, a browser page can `fetch` one, and stopping
- * that means inventing a token — a mechanism the transport made
- * necessary rather than one anything needed.
- *
- * On POSIX, the socket file's 0600 mode is the authorization. On Windows,
- * the equivalent address is a named pipe created without `readableAll` or
- * `writableAll`. Windows grants the creator owner full control while other
- * accounts do not receive the duplex access required by this protocol. The
- * pipe name is derived from the storage root so users and isolated instances
- * do not collide in Windows' machine-wide pipe namespace.
- *
- * **One system per storage root.** The socket lives in the root, so it
- * follows wherever the root is — which is how the lab runs a throwaway
- * system beside a real one, by moving `HOME`. Two systems sharing a root
- * were already colliding over its persistent state and its programs before this
- * existed; the socket is where that finally gets said out loud.
- *
- * **Three words, and the list is closed.** `install` lays a Program out,
- * `uninstall` removes that same project's installed form, and `run` starts it
- * attached. None was ever a session's business —
- * install had a button on the desktop until it was noticed that a person
- * at a browser somewhere else installing software onto this machine is
- * exactly what the remote and local split says should not happen.
- *
- * What is refused is inheriting a vocabulary wholesale: running The Link
- * over this would hand intake the whole remote surface, and the two views
- * do not have the same trust to spend. Nor does a word earn a
- * place here by being about the machine — that test admits everything.
- * It earns one by being a way the local project enters the system, and
- * nothing else is.
- *
- * **The connection is the lifetime.** A program launched here is attached
- * to the connection that asked for it: when that connection goes, the
- * process is stopped. Not a pid, not a heartbeat, not a timeout — the
- * operating system closes an ended process's descriptors whatever killed
- * it, so a terminal closed, an ssh session dropped and a `kill -9` all
- * arrive here as the same event, and none of them can be missed.
- *
- * That makes a launched program's life its launcher's, which is the line
- * between the two ways in: **attached means not installed, installed
- * means persistent.** Something meant to outlive a terminal is installed.
+ * 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) {
- const namedPipe = process.platform === "win32"
-
// 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.
- const server = createServer(function (socket) {
+ return localServer(path, function (socket) {
let said = ""
@@ -115,61 +53,6 @@ export default function intake(application: Application, path: string) {
socket.on("error", () => undefined)
})
-
- if (!namedPipe) mkdirSync(dirname(path), { recursive: true })
-
- return new Promise<string>(function (settle, refuse) {
-
- server.once("error", function (error: NodeJS.ErrnoException) {
-
- if (error.code !== "EADDRINUSE") return refuse(error)
-
- // Two meanings, and only one of them is safe to act on. A
- // socket file outlives the process that made it, so this is
- // either a system that is running or the litter of one that
- // is not — and the only way to tell is to knock.
- //
- // The first version unlinked before listening, which never
- // asked. A second system took the path, the first kept
- // running and was reachable by nobody, and every launch
- // afterwards spoke to the newcomer. Proved by running two.
- alive(path).then(function (running) {
-
- if (running) return refuse(new Error(`A system is already running here — ${dirname(path)} holds one system, and two would share its programs and persistent state`))
-
- if (namedPipe) return refuse(error)
-
- rmSync(path, { force: true })
-
- server.listen(path, () => settle(secured(path, namedPipe)))
- }, refuse)
- })
-
- server.listen({ path, readableAll: false, writableAll: false }, () => settle(secured(path, namedPipe)))
- })
-}
-
-// The mode is the authorization, so it is set before anything is
-// answered rather than left to whatever umask was in force.
-function secured(path: string, namedPipe: boolean) {
-
- if (!namedPipe) chmodSync(path, 0o600)
-
- return path
-}
-
-// Whether anything is listening there. Connecting is the only honest
-// test: the file's existence says only that a socket was made once.
-function alive(path: string) {
-
- return new Promise<boolean>(function (settle) {
-
- const knock = connect(path)
-
- knock.on("connect", () => { knock.destroy(); settle(true) })
-
- knock.on("error", () => settle(false))
- })
}
// One question in, many events out. A launch is not a thing with an
diff --git a/source/server/view/local-server.ts b/source/server/view/local-server.ts
new file mode 100644
index 0000000..19eb219
--- /dev/null
+++ b/source/server/view/local-server.ts
@@ -0,0 +1,55 @@
+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. */
+export default function localServer(path: string, receive: (socket: Socket) => void) {
+
+ const namedPipe = process.platform === "win32"
+ const server = createServer(receive)
+
+ if (!namedPipe) mkdirSync(dirname(path), { recursive: true })
+
+ return new Promise<string>(function (resolve, reject) {
+
+ const listen = (recovered: boolean) => {
+
+ server.once("error", function (error: NodeJS.ErrnoException) {
+
+ if (error.code !== "EADDRINUSE" || recovered) return reject(error)
+
+ alive(path).then(function (running) {
+
+ if (running) return reject(new Error(`A system is already running here — ${dirname(path)} holds one system, and two would share its programs and persistent state`))
+
+ if (namedPipe) return reject(error)
+
+ rmSync(path, { force: true })
+ listen(true)
+ }, reject)
+ })
+
+ server.listen({ path, readableAll: false, writableAll: false }, () => resolve(secured(path, namedPipe)))
+ }
+
+ listen(false)
+ })
+}
+
+function secured(path: string, namedPipe: boolean) {
+
+ if (!namedPipe) chmodSync(path, 0o600)
+
+ return path
+}
+
+function alive(path: string) {
+
+ return new Promise<boolean>(function (resolve) {
+
+ const socket = connect(path)
+
+ socket.on("connect", () => { socket.destroy(); resolve(true) })
+ socket.on("error", () => resolve(false))
+ })
+}
diff --git a/source/server/view/view.ts b/source/server/view/view.ts
index 6aa4871..d77f477 100644
--- a/source/server/view/view.ts
+++ b/source/server/view/view.ts
@@ -5,6 +5,8 @@ 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 program from "./program"
import proxy from "./proxy"
import storage from "./storage"
@@ -73,13 +75,18 @@ export default async function (config: Config) {
// 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 socket = await intake(application, intakeAddress(application.storage.path))
+ const [intakeSocket, controlSocket] = await Promise.all([
+ intake(application, intakeAddress(application.storage.path)),
+ control(application, controlAddress(application.storage.path))
+ ])
const origin = `http://localhost:${port}`
if (config.assets) console.log(` ➜ ${styleText("bold", "Desktop:")} ${origin}`)
- console.log(` ➜ ${styleText("bold", "Intake:")} ${socket}`)
+ console.log(` ➜ ${styleText("bold", "Intake:")} ${intakeSocket}`)
+
+ console.log(` ➜ ${styleText("bold", "Control:")} ${controlSocket}`)
return { origin }
}