An open-source, self-hosted system for apps built with web technologies.
Add authoritative shell execution
zohayrslileh10aea0713bed
diff --git a/scripts/contracts/gateway.ts b/scripts/contracts/gateway.tsindex f7ecc65..e17ad9a 100644--- a/scripts/contracts/gateway.ts+++ b/scripts/contracts/gateway.ts@@ -44,6 +44,14 @@ const process = {const application = {system: {listPrograms() { return [] },+ async *shell(command: string) {++ assert.equal(command, "printf hello")++ yield { event: "started", pid: 42 }+ yield { event: "output", stream: "stdout", text: "hello" }+ yield { event: "exited", exit: { status: "exited", code: 0, signal: null } }+ },async forceCreateProgram() { return entry.program },requireProgram(identity: string) { return identity === forkedEntry.program.identity ? forkedEntry : entry },programSnapshot(selected: typeof entry) { return { ...programSnapshot, identity: selected.program.identity } },@@ -85,6 +93,17 @@ try {assert.deepEqual(system, [{ success: true, result: { data: [], total: 0, truncated: false } }])+ const shell = await exchange(path, {+ target: "shell",+ request: { command: "printf hello", options: {} }+ })++ assert.deepEqual(shell, [+ { event: "started", pid: 42 },+ { event: "output", stream: "stdout", text: "hello" },+ { event: "exited", exit: { status: "exited", code: 0, signal: null } }+ ])+const ready = await exchange(path, {target: "system",request: {diff --git a/scripts/contracts/shell.ts b/scripts/contracts/shell.tsnew file mode 100644index 0000000..0c1487d--- /dev/null+++ b/scripts/contracts/shell.ts@@ -0,0 +1,36 @@+import assert from "node:assert/strict"+import shell from "@server/core/shell"++const executable = JSON.stringify(process.execPath)+const script = JSON.stringify("process.stdout.write(process.env.PHRESHOS_SHELL_TEST); process.stderr.write('error'); process.exit(7)")+const events = []++for await (const event of shell(`${executable} -e ${script}`, { env: { PHRESHOS_SHELL_TEST: "output" } })) events.push(event)++assert.equal(events[0]?.event, "started")+assert(events.some(event => event.event === "output" && event.stream === "stdout" && event.text === "output"))+assert(events.some(event => event.event === "output" && event.stream === "stderr" && event.text === "error"))+assert.deepEqual(events.at(-1), {+ event: "exited",+ exit: { status: "exited", code: 7, signal: null }+})++const running = shell(`${executable} -e ${JSON.stringify("setInterval(() => {}, 1_000)")}`)+const started = await running.next()+const startedEvent = started.value++assert.equal(startedEvent?.event, "started")+await running.return(undefined)++if (startedEvent?.event === "started") assert.throws(() => process.kill(startedEvent.pid, 0), { code: "ESRCH" })++const controller = new AbortController()+const aborted = shell(`${executable} -e ${JSON.stringify("setInterval(() => {}, 1_000)")}`, { signal: controller.signal })+const abortedStart = (await aborted.next()).value+const reason = new Error("test cancellation")++controller.abort(reason)++await assert.rejects(aborted.next(), error => error === reason)++if (abortedStart?.event === "started") assert.throws(() => process.kill(abortedStart.pid, 0), { code: "ESRCH" })diff --git a/source/client/core/link-manager/auth-manager/auth-manager.ts b/source/client/core/link-manager/auth-manager/auth-manager.tsindex 758ecb4..d96a18d 100644--- a/source/client/core/link-manager/auth-manager/auth-manager.ts+++ b/source/client/core/link-manager/auth-manager/auth-manager.ts@@ -6,6 +6,7 @@ import DialogManager from "./dialog-manager"import { TheLink } from "@the-link/core"import LinkManager from "../link-manager"import { type PermissionChange, type PermissionRequest } from "@phreshos/core"+import ShellManager from "./shell-manager"export default class AuthManager extends TheLink {@@ -19,6 +20,8 @@ export default class AuthManager extends TheLink {public readonly dialogManager: DialogManager+ public readonly shellManager: ShellManager+public constructor(linkManager: LinkManager, authorization: string, payload: TransmittedAuthManager) {super()@@ -34,6 +37,8 @@ export default class AuthManager extends TheLink {this.processManager = new ProcessManager(this, payload.processManager)this.dialogManager = new DialogManager(this, payload.dialogManager)++ this.shellManager = new ShellManager(this)}@Intercept("outbound")diff --git a/source/client/core/link-manager/auth-manager/program-manager/program-manager.ts b/source/client/core/link-manager/auth-manager/program-manager/program-manager.tsindex 7843df0..8cf3c3f 100644--- a/source/client/core/link-manager/auth-manager/program-manager/program-manager.ts+++ b/source/client/core/link-manager/auth-manager/program-manager/program-manager.ts@@ -5,6 +5,7 @@ import { TheLink } from "@the-link/core"import AuthManager from "../auth-manager"import Program from "./program"import { type Launch, type PermissionInput, type ProgramCommandChunk, type ProgramIconSize } from "@phreshos/core"+import StreamRelay from "@client/core/link-manager/stream-relay"/*** The peer of the core's programs: born holding them from the@@ -24,7 +25,7 @@ export default class ProgramManager extends TheLink {public readonly programs = new Map<string, Program>()- private readonly commands = new Map<string, PendingCommand>()+ private readonly commands = new StreamRelay("Program command output", programCommandChunk)public constructor(authManager: AuthManager, payload: TransmittedProgramManager) {@@ -86,45 +87,11 @@ export default class ProgramManager extends TheLink {/** Streams one authoritative Program command to its requesting View. */public command(subject: unknown, operation: "install" | "uninstall" | "run", value: unknown, asker: string) {- const manager = this- return (async function* (): AsyncGenerator<ProgramCommandChunk, void, void> {- const stream = crypto.randomUUID()- const state: PendingCommand = { queue: [], settled: false, failure: null, wake: null }-- manager.commands.set(stream, state)-- const pending = manager.$outbound.publishFirst("/client-command", stream, operation, subject, value, asker).then(- () => { state.settled = true },- error => { state.failure = error instanceof Error ? error : new Error(String(error)) }- ).finally(() => {- state.wake?.()- state.wake = null- })-- try {- while (!state.settled || state.queue.length) {- const next = state.queue.shift()-- if (next) {- yield next- continue- }-- if (state.failure) throw state.failure-- await new Promise<void>(resolve => { state.wake = resolve })- }-- await pending-- if (state.failure) throw state.failure- }- finally {- manager.commands.delete(stream)- manager.$outbound.publish("/client-command-cancel", stream).catch(() => undefined)- }- })()+ return this.commands.open(+ stream => this.$outbound.publishFirst("/client-command", stream, operation, subject, value, asker),+ stream => this.$outbound.publish("/client-command-cancel", stream)+ )}public async forget(subject: unknown, asker: string) {@@ -196,22 +163,8 @@ export default class ProgramManager extends TheLink {@Subscribe("/client-command-output")protected commandOutput(stream: string, value: unknown) {- const state = this.commands.get(stream)-- if (!state || state.failure) return- const chunk = value as Partial<ProgramCommandChunk> | null-- if (!chunk || (chunk.stream !== "stdout" && chunk.stream !== "stderr") || typeof chunk.text !== "string") {- state.failure = new Error("The System returned an invalid Program command output chunk")- }- else if (state.queue.length >= maximumCommandQueue) {- state.failure = new Error(`Program command output exceeded its queue capacity of ${maximumCommandQueue}`)- }- else state.queue.push(Object.freeze({ stream: chunk.stream, text: chunk.text }))-- state.wake?.()- state.wake = null+ this.commands.receive(stream, value)}@Subscribe("/forget")@@ -230,11 +183,14 @@ export default class ProgramManager extends TheLink {}}-interface PendingCommand {- queue: ProgramCommandChunk[]- settled: boolean- failure: Error | null- wake: (() => void) | null-}+function programCommandChunk(value: unknown): ProgramCommandChunk {++ const chunk = value as Partial<ProgramCommandChunk> | null-const maximumCommandQueue = 256+ if (!chunk || (chunk.stream !== "stdout" && chunk.stream !== "stderr") || typeof chunk.text !== "string") {++ throw new Error("The System returned an invalid Program command output chunk")+ }++ return Object.freeze({ stream: chunk.stream, text: chunk.text })+}diff --git a/source/client/core/link-manager/auth-manager/shell-manager.ts b/source/client/core/link-manager/auth-manager/shell-manager.tsnew file mode 100644index 0000000..c7b9570--- /dev/null+++ b/source/client/core/link-manager/auth-manager/shell-manager.ts@@ -0,0 +1,32 @@+import { TheLink } from "@the-link/core"+import { Subscribe } from "@the-link/core/decorators"+import { parseShellEvent, type ShellOptions } from "@phreshos/core"+import type AuthManager from "./auth-manager"+import StreamRelay from "@client/core/link-manager/stream-relay"++/** Client-side adapter for authoritative System shell streams. */+export default class ShellManager extends TheLink {++ private readonly streams = new StreamRelay("Shell output", parseShellEvent)++ public constructor(authManager: AuthManager) {++ super()++ this.connectTo(authManager, "/frame/shell")+ }++ public run(command: string, options: Omit<ShellOptions, "signal">, asker: string) {++ return this.streams.open(+ stream => this.$outbound.publishFirst("/run", stream, command, options, asker),+ stream => this.$outbound.publish("/cancel", stream)+ )+ }++ @Subscribe("/event")+ protected event(stream: string, value: unknown) {++ this.streams.receive(stream, value)+ }+}diff --git a/source/client/core/link-manager/stream-relay.ts b/source/client/core/link-manager/stream-relay.tsnew file mode 100644index 0000000..204ef1e--- /dev/null+++ b/source/client/core/link-manager/stream-relay.ts@@ -0,0 +1,81 @@+const maximumQueue = 256++/** Owns the lifecycle and backpressure queue for remotely produced streams. */+export default class StreamRelay<Value> {++ private readonly streams = new Map<string, PendingStream<Value>>()++ public constructor(private readonly name: string, private readonly parse: (value: unknown) => Value) { }++ public open(start: (stream: string) => Promise<unknown>, cancel: (stream: string) => Promise<unknown>) {++ const relay = this++ return (async function* (): AsyncGenerator<Value, void, void> {++ const stream = crypto.randomUUID()+ const state: PendingStream<Value> = { queue: [], settled: false, failure: null, wake: null }++ relay.streams.set(stream, state)++ const pending = Promise.resolve().then(() => start(stream)).then(+ () => { state.settled = true },+ error => { state.failure = error instanceof Error ? error : new Error(String(error)) }+ ).finally(() => {++ state.wake?.()+ state.wake = null+ })++ try {++ while (!state.settled || state.queue.length) {++ if (state.queue.length) {++ yield state.queue.shift()!+ continue+ }++ if (state.failure) throw state.failure++ await new Promise<void>(resolve => { state.wake = resolve })+ }++ await pending++ if (state.failure) throw state.failure+ }+ finally {++ relay.streams.delete(stream)+ cancel(stream).catch(() => undefined)+ }+ })()+ }++ public receive(stream: string, value: unknown) {++ const state = this.streams.get(stream)++ if (!state || state.failure) return++ try {++ if (state.queue.length >= maximumQueue) throw new Error(`${this.name} exceeded its queue capacity of ${maximumQueue}`)++ state.queue.push(this.parse(value))+ }+ catch (error) { state.failure = error instanceof Error ? error : new Error(String(error)) }++ state.wake?.()+ state.wake = null+ }+}++interface PendingStream<Value> {+ queue: Value[]+ settled: boolean+ failure: Error | null+ wake: (() => void) | null+}diff --git a/source/client/view/components/desktop-host/client-process-boundary.ts b/source/client/view/components/desktop-host/client-process-boundary.tsindex c50cb84..83fe9b8 100644--- a/source/client/view/components/desktop-host/client-process-boundary.ts+++ b/source/client/view/components/desktop-host/client-process-boundary.ts@@ -4,7 +4,7 @@ import host, { TransferredAnswer } from "./host"import ClientTraffic from "./client-traffic"import { failed, succeeded } from "@server/core/outcome"import { type TrafficKind } from "@server/core/link-manager/auth-manager/process-manager/process-traffic"-import { type DesktopSurfaceSnapshot } from "@phreshos/core"+import { type DesktopSurfaceSnapshot, type ShellOptions } from "@phreshos/core"import { type LocalWindowHost } from "./local-window"import messagepack from "@libs/messagepack"import { sdkProcess, type SdkProcessSource } from "./sdk-records"@@ -600,19 +600,35 @@ export default class ClientProcessBoundary extends TheLink {const run = async () => {await this.deliver("host-end", "stream", question, "open")- if (args[0] !== "install" && args[0] !== "uninstall" && args[0] !== "run") throw new Error(`The desktop does not know the stream operation "${String(args[0])}"`)+ if (args[0] === "shell") {- if (!isHandleAddress(args[1])) throw new Error("A Program handle is required")+ await this.systemAccess.requireAll()+ if (typeof args[1] !== "string") throw new Error("A shell command must be text")- const program = this.authManager.programManager.programs.get(args[1].identity)+ const operation = this.authManager.shellManager.run(+ args[1],+ shellOptions(args[2]),+ this.pane+ )- if (!program || program.reference !== args[1].reference) throw new Error("The Program represented by this handle does not exist")+ iterator = operation[Symbol.asyncIterator]()+ }+ else {++ if (args[0] !== "install" && args[0] !== "uninstall" && args[0] !== "run") throw new Error(`The desktop does not know the stream operation "${String(args[0])}"`)++ if (!isHandleAddress(args[1])) throw new Error("A Program handle is required")++ const program = this.authManager.programManager.programs.get(args[1].identity)- await this.systemAccess.program(program)+ if (!program || program.reference !== args[1].reference) throw new Error("The Program represented by this handle does not exist")- const operation = this.authManager.programManager.command(args[1], args[0], args[2], this.pane)+ await this.systemAccess.program(program)- iterator = operation[Symbol.asyncIterator]()+ const operation = this.authManager.programManager.command(args[1], args[0], args[2], this.pane)++ iterator = operation[Symbol.asyncIterator]()+ }while (active) {const next = await iterator.next()@@ -941,6 +957,23 @@ function runEvent(authManager: AuthManager, value: unknown) {return { ...event, process: sdkProcess(event.process, program) }}+function shellOptions(value: unknown): Omit<ShellOptions, "signal"> {++ if (value === undefined) return {}+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Shell options must be an object")++ const options = value as Record<string, unknown>++ if (Object.keys(options).some(key => key !== "cwd" && key !== "env")) throw new Error("Shell options contain an unknown field")+ if (options.cwd !== undefined && (typeof options.cwd !== "string" || !options.cwd)) throw new Error("A shell working directory must be non-empty text")+ if (options.env !== undefined && (!options.env || typeof options.env !== "object" || Array.isArray(options.env) || Object.values(options.env).some(entry => typeof entry !== "string"))) {++ throw new Error("Shell environment values must be text")+ }++ return options as Omit<ShellOptions, "signal">+}+const nativeAttachments = (value: unknown, transfer: readonly Transferable[]) => {const attachments: object[] = [...transfer]diff --git a/source/server/core/link-manager/auth-manager/auth-manager.ts b/source/server/core/link-manager/auth-manager/auth-manager.tsindex c572877..687bda1 100644--- a/source/server/core/link-manager/auth-manager/auth-manager.ts+++ b/source/server/core/link-manager/auth-manager/auth-manager.ts@@ -7,6 +7,7 @@ import { Transmitted } from "@libs/messagepack"import { TheLink } from "@the-link/core"import LinkManager from "../link-manager"import { type PermissionRequest } from "@phreshos/core"+import ShellManager from "./shell-manager"export default class AuthManager extends TheLink {@@ -18,6 +19,8 @@ export default class AuthManager extends TheLink {public readonly dialogManager: DialogManager+ public readonly shellManager: ShellManager+public constructor(linkManager: LinkManager) {super()@@ -30,6 +33,8 @@ export default class AuthManager extends TheLink {this.dialogManager = this.linkManager.application.dialogManager+ this.shellManager = new ShellManager(this)+this.dialogManager.connectTo(this, "/dialog")this.subscribeTo(this.linkManager, "/auth")diff --git a/source/server/core/link-manager/auth-manager/process-manager/client-process-forwarder.ts b/source/server/core/link-manager/auth-manager/process-manager/client-process-forwarder.tsindex 4455b2a..e1b3d6c 100644--- a/source/server/core/link-manager/auth-manager/process-manager/client-process-forwarder.ts+++ b/source/server/core/link-manager/auth-manager/process-manager/client-process-forwarder.ts@@ -176,6 +176,11 @@ export default class ClientProcessForwarder {this.requests.delete(question)}+ public forget(question: string) {++ this.requests.delete(question)+ }+public release() {for (const stop of this.observations.values()) stop()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 81a318b..57b1de7 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@@ -17,7 +17,7 @@ import { endpointReference, processReference } from "./endpoint-reference"import EndpointEvents from "./endpoint-events"import EndpointServices from "./endpoint-services"import OutsideQuestions from "./outside-questions"-import { isServiceKey, type ClientLaunch, type Launch, type Permission, type PermissionChange, type PermissionRequest, type ServerLaunch, type ServiceKey, type WindowGeometry, type WindowLayer } from "@phreshos/core"+import { isServiceKey, type ClientLaunch, type Launch, type Permission, type PermissionChange, type PermissionRequest, type ServerLaunch, type ServiceKey, type ShellOptions, type WindowGeometry, type WindowLayer } from "@phreshos/core"import type { ServerRuntime } from "./server-runtime"import { permissionCatalog } from "@server/core/permissions"@@ -490,6 +490,17 @@ export default class ProcessManager extends TheLink {}}+ public retainClientOperation(connection: string, pane: string, operation: string, cancel: () => void) {++ const boundary = this.clientForwarders.get(this.clientOwnerKey(connection, pane))++ if (!boundary) return null++ boundary.retain(operation, cancel)++ return () => boundary.forget(operation)+ }+// Raw boundary delivery. Application publications and questions are// shaped before they reach this point so the receiving SDK sees the// source Endpoint supplied by the host rather than by Program code.@@ -2219,6 +2230,31 @@ export default class ProcessManager extends TheLink {try {const operation = args[0]++ if (operation === "shell") {++ if (typeof args[1] !== "string") throw new Error("A shell command must be text")++ const command = this.system.shell(args[1], args[2] as ShellOptions ?? {})++ cancel = () => {++ active = false+ void command.return(undefined)+ }++ for await (const event of command) {++ 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+ }+const program = this.system.holdProgram(args[1])if (operation === "run") {diff --git a/source/server/core/link-manager/auth-manager/shell-manager.ts b/source/server/core/link-manager/auth-manager/shell-manager.tsnew file mode 100644index 0000000..768e935--- /dev/null+++ b/source/server/core/link-manager/auth-manager/shell-manager.ts@@ -0,0 +1,64 @@+import { TheLink } from "@the-link/core"+import { Connect, Subscribe } from "@the-link/core/decorators"+import type { ShellOptions } from "@phreshos/core"+import type AuthManager from "./auth-manager"++/** Authenticated bridge from one Client shell stream to the authoritative System. */+export default class ShellManager extends TheLink {++ private readonly commands = new Map<string, RunningShell>()++ public constructor(private readonly authManager: AuthManager) {++ super()++ this.connectTo(authManager, "/frame/shell")+ }++ @Connect("/run")+ protected async run(connection: string, stream: string, command: string, options: Omit<ShellOptions, "signal">, asker: string) {++ if (typeof connection !== "string" || typeof asker !== "string" || !asker) throw new Error("A Client shell command needs a requesting Process")+ if (typeof stream !== "string" || !stream || this.commands.has(stream)) throw new Error("A Client shell command needs a unique stream")+ if (!this.authManager.processManager.grants(asker, "all", [])) throw new Error("Execution is not permitted")++ const controller = new AbortController()+ const release = this.authManager.processManager.retainClientOperation(+ connection,+ asker,+ stream,+ () => controller.abort(new Error("The requester disconnected"))+ )++ if (!release) throw new Error("Execution is not permitted")++ this.commands.set(stream, { connection, controller })++ try {++ for await (const event of this.authManager.linkManager.application.system.shell(command, { ...options, signal: controller.signal })) {++ await this.authManager.publishToConnection(connection, "/frame/shell/event", stream, event)+ }+ }+ finally {++ release()+ this.commands.delete(stream)+ }+ }++ @Subscribe("/cancel")+ protected cancel(connection: unknown, stream: unknown) {++ const command = typeof stream === "string" ? this.commands.get(stream) : null++ if (command && command.connection === connection) command.controller.abort(new Error("The shell command was cancelled"))+ }++}++interface RunningShell {+ connection: string+ controller: AbortController+}diff --git a/source/server/core/shell.ts b/source/server/core/shell.tsnew file mode 100644index 0000000..133af44--- /dev/null+++ b/source/server/core/shell.ts@@ -0,0 +1,154 @@+import { spawn } from "node:child_process"+import { homedir } from "node:os"+import type { ShellEvent, ShellOptions } from "@phreshos/core"+import ProcessTree from "@libs/process-tree"++type Queued = Readonly<{+ event: ShellEvent+ resume?: () => void+}>++/** Run one shell command while its iterator owns the complete process tree. */+export default function shell(command: string, options: ShellOptions = {}): AsyncGenerator<ShellEvent, void, void> {++ return (async function* () {++ const input = validate(command, options)+ const queue: Queued[] = []+ let wake: (() => void) | null = null+ let failure: Error | null = null+ let closed = false+ let treeEnded = false+ let ending: Readonly<{ code: number | null, signal: NodeJS.Signals | null }> | null = null+ let settle!: () => void+ const stopped = new Promise<void>(resolve => { settle = resolve })+ const notify = () => {++ wake?.()+ wake = null+ }+ const finish = () => {++ if (!closed || !treeEnded || !ending) return++ queue.push({+ event: {+ event: "exited",+ exit: {+ status: ending.signal ? "signaled" : "exited",+ code: ending.code,+ signal: ending.signal+ }+ }+ })+ settle()+ notify()+ }+ const child = spawn(input.command, {+ shell: true,+ detached: true,+ cwd: input.cwd,+ env: { ...process.env, ...input.env },+ stdio: ["ignore", "pipe", "pipe"]+ })+ const tree = new ProcessTree(child, (code, signal) => {++ ending = { code, signal }+ treeEnded = true+ finish()+ })+ const output = (stream: NodeJS.ReadableStream, name: "stdout" | "stderr") => {++ stream.on("data", chunk => {++ stream.pause()+ queue.push({ event: { event: "output", stream: name, text: String(chunk) }, resume: () => stream.resume() })+ notify()+ })+ }+ const abort = () => {++ failure = options.signal?.reason instanceof Error ? options.signal.reason : new Error("The shell command was cancelled")+ tree.stop()+ notify()+ }++ child.once("spawn", () => {++ if (typeof child.pid !== "number") {++ failure = new Error("The shell command started without a process identity")+ tree.stop()+ }+ else queue.push({ event: { event: "started", pid: child.pid } })++ notify()+ })+ child.once("error", error => {++ failure = error+ settle()+ notify()+ })+ child.once("close", () => {++ closed = true+ finish()+ })++ output(child.stdout!, "stdout")+ output(child.stderr!, "stderr")++ if (options.signal?.aborted) abort()+ else options.signal?.addEventListener("abort", abort, { once: true })++ try {++ while (true) {++ if (failure) throw failure++ const next = queue.shift()++ if (next) {++ yield next.event+ next.resume?.()++ if (next.event.event === "exited") return++ continue+ }++ await new Promise<void>(resolve => { wake = resolve })+ }+ }+ finally {++ options.signal?.removeEventListener("abort", abort)++ if (!closed || !treeEnded) tree.stop()++ await stopped+ }+ })()+}++function validate(command: string, options: ShellOptions) {++ if (typeof command !== "string" || !command.trim()) throw new Error("A shell command must be non-empty text")+ if (!options || typeof options !== "object" || Array.isArray(options)) throw new Error("Shell options must be an object")+ if (Object.keys(options).some(key => key !== "cwd" && key !== "env" && key !== "signal")) throw new Error("Shell options contain an unknown field")+ if (options.signal !== undefined && !(options.signal instanceof AbortSignal)) throw new Error("A shell signal must be an AbortSignal")++ const cwd = options.cwd ?? homedir()+ const env = options.env ?? {}++ if (typeof cwd !== "string" || !cwd) throw new Error("A shell working directory must be non-empty text")+ if (!env || typeof env !== "object" || Array.isArray(env) || Object.values(env).some(value => typeof value !== "string")) {++ throw new Error("Shell environment values must be text")+ }++ return { command, cwd, env }+}diff --git a/source/server/core/system.ts b/source/server/core/system.tsindex f93d2e6..8ac169c 100644--- a/source/server/core/system.ts+++ b/source/server/core/system.ts@@ -2,10 +2,11 @@ import type Application from "./application"import type Entry from "./link-manager/auth-manager/program-manager/entry"import type Program from "./link-manager/auth-manager/program-manager/program"import type Process from "./link-manager/auth-manager/process-manager/process"-import type { ClientLaunch, Launch, PermissionInput, Position, ServerLaunch, Size, WindowGeometry } from "@phreshos/core"+import type { ClientLaunch, Launch, PermissionInput, Position, ServerLaunch, ShellOptions, Size, WindowGeometry } from "@phreshos/core"import type { Half, TrafficKind } from "./link-manager/auth-manager/process-manager/process-traffic"import { 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"type Endpoint = "server" | "client"type ProgramSource = Parameters<Application["linkManager"]["authManager"]["programManager"]["create"]>[0]@@ -21,6 +22,11 @@ export default class System {public constructor(private readonly application: Application) {}+ public shell(command: string, options: ShellOptions = {}) {++ return shell(command, options)+ }+public listPrograms(onlyInstalled = false) {return [...this.programManager.programs.values()].filter(entry => !onlyInstalled || entry.installed)diff --git a/source/server/view/gateway/gateway.ts b/source/server/view/gateway/gateway.tsindex 1af4140..d12b666 100644--- a/source/server/view/gateway/gateway.ts+++ b/source/server/view/gateway/gateway.ts@@ -2,6 +2,7 @@ import type Application from "@server/core/application"import localServer from "./local-server"import apiRequest from "./api-request"import programRequest from "./program-request"+import shellRequest from "./shell-request"import systemRequest from "./system-request"const maximumRequestSize = 16 * 1024 * 1024@@ -44,6 +45,12 @@ export default function gateway(application: Application, path: string) {return}+ if (envelope.target === "shell") {++ shellRequest(application, socket, envelope.request, controller.signal).catch(error => fail(socket, error))+ return+ }+if (envelope.target === "api") {apiRequest(application, envelope.request, controller.signal).then(@@ -77,7 +84,7 @@ function parseEnvelope(line: string): GatewayEnvelope {if (Object.keys(envelope).some(key => key !== "target" && key !== "request")) throw new Error("The gateway request contains an unknown field")- if (envelope.target !== "api" && envelope.target !== "program" && envelope.target !== "system") throw new Error("The Gateway target must be api, program, or system")+ if (envelope.target !== "api" && envelope.target !== "program" && envelope.target !== "shell" && envelope.target !== "system") throw new Error("The Gateway target must be api, program, shell, or system")if (!("request" in envelope)) throw new Error("The gateway request is missing")return { target: envelope.target, request: envelope.request }@@ -100,6 +107,6 @@ function reason(error: unknown) {interface GatewayEnvelope {- target: "api" | "program" | "system"+ target: "api" | "program" | "shell" | "system"request: unknown}diff --git a/source/server/view/gateway/shell-request.ts b/source/server/view/gateway/shell-request.tsnew file mode 100644index 0000000..327d4b3--- /dev/null+++ b/source/server/view/gateway/shell-request.ts@@ -0,0 +1,47 @@+import type Application from "@server/core/application"+import type { ShellOptions } from "@phreshos/core"+import type { Socket } from "node:net"++/** Stream one owner-local shell command through the System gateway. */+export default async function shellRequest(application: Application, socket: Socket, value: unknown, signal: AbortSignal) {++ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("The shell request must be an object")++ const request = value as Record<string, unknown>++ if (Object.keys(request).some(key => key !== "command" && key !== "options")) throw new Error("The shell request contains an unknown field")+ if (typeof request.command !== "string") throw new Error("A shell command must be text")++ const options = request.options === undefined ? {} : request.options++ if (!options || typeof options !== "object" || Array.isArray(options)) throw new Error("Shell options must be an object")+ if (Object.keys(options).some(key => key !== "cwd" && key !== "env")) throw new Error("Shell options contain an unknown field")++ for await (const event of application.system.shell(request.command, { ...(options as ShellOptions), signal })) {++ if (!await write(socket, `${JSON.stringify(event)}\n`)) return+ }++ if (socket.writable) socket.end()+}++async function write(socket: Socket, value: string) {++ if (!socket.writable) return false+ if (socket.write(value)) return true++ await new Promise<void>(resolve => {++ const settled = () => {++ socket.off("drain", settled)+ socket.off("close", settled)+ resolve()+ }++ socket.once("drain", settled)+ socket.once("close", settled)+ })++ return socket.writable+}diff --git a/source/server/view/link.ts b/source/server/view/link.tsindex 44a15ba..0f901fb 100644--- a/source/server/view/link.ts+++ b/source/server/view/link.ts@@ -24,7 +24,7 @@ export default function (application: Application, debugging: boolean) {// envelope. Route it once and do not manufacture an acknowledgement.if (responseUuid === null) {- const routed = event.startsWith("/auth/process/frame/") ? [values[0], connectionIdentity, ...values.slice(1)] : values+ const routed = connectionOwned(event) ? [values[0], connectionIdentity, ...values.slice(1)] : valuesapplication.linkManager.$inbound.publish(event, ...routed).catch(() => undefined)@@ -33,10 +33,10 @@ export default function (application: Application, debugging: boolean) {try {- // Every client Process-boundary operation is owned by this- // socket. Insert the connection here, where it comes from the- // connection itself and cannot be supplied by an iframe.- const routed = event.startsWith("/auth/process/frame/") ? [values[0], connectionIdentity, ...values.slice(1)] : values+ // Every Client-frame operation is owned by this socket. Insert+ // the connection here, where it comes from the connection+ // itself and cannot be supplied by an iframe.+ const routed = connectionOwned(event) ? [values[0], connectionIdentity, ...values.slice(1)] : valuesconst results = await application.linkManager.$inbound.publish(event, ...routed)@@ -63,3 +63,8 @@ export default function (application: Application, debugging: boolean) {return serverLink.app}++function connectionOwned(event: string) {++ return event.startsWith("/auth/frame/") || event.startsWith("/auth/process/frame/")+}