An open-source, self-hosted system for apps built with web technologies.
Release System 0.1.66 with unified Program permissions and saved launches
zohayrslilehecac4c686605
diff --git a/bun.lock b/bun.lockindex 7a386cf..8fcb44a 100644--- a/bun.lock+++ b/bun.lock@@ -7,7 +7,7 @@"dependencies": {"@fontsource/roboto": "^5.3.0","@hono/node-server": "^2.1.1",- "@phreshos/core": "^0.1.44",+ "@phreshos/core": "^0.1.45","@phreshos/react-ui": "^0.1.19","@the-link/core": "^0.3.0","@the-link/http": "^0.1.1",@@ -235,7 +235,7 @@"@oxc-project/types": ["@oxc-project/[email protected]", "", {}, "sha512-nuhZIOLuI6TFQ32I/WnUx+SCPY7SdSKwgnFHydAuoS1+Z4BRcaP+RRJmGzl9lw+0OFF7UmaESf7KQRXaNLHypg=="],- "@phreshos/core": ["@phreshos/[email protected]", "", {}, "sha512-0Qo4SlNg9fi2xfpDMbMucHQrDhzE8hhzOy7n5rQPjpj4UIWPUU5ZuEGEON6bfQM6nKJ4ogNJF7KFp4RhMxf5PA=="],+ "@phreshos/core": ["@phreshos/[email protected]", "", {}, "sha512-u/P6GJynoC8IaOjIHGCzsA1a2Mhwkg5qstuAKN70PsiHQ/ioE2inOUpEuL2JPhmvjcQslZnbLpZhfwMYIUW0+A=="],"@phreshos/react-ui": ["@phreshos/[email protected]", "", { "dependencies": { "@phreshos/core": "^0.1.43", "colorjs.io": "^0.7.1", "motion": "^13.2.0", "react-aria-components": "^1.20.0" }, "peerDependencies": { "react": "^19.2.0", "react-dom": "^19.2.0" } }, "sha512-F4xiDGvOrgEomSSy3HwieFOI3eiyhDQAbJeQNWHVXXVekT1lUonr86z0crEQigXEIqdFWBQg+GKf9mkcjlYKOw=="],@@ -559,6 +559,8 @@"yallist": ["[email protected]", "", {}, "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g=="],+ "@phreshos/react-ui/@phreshos/core": ["@phreshos/[email protected]", "", {}, "sha512-0Qo4SlNg9fi2xfpDMbMucHQrDhzE8hhzOy7n5rQPjpj4UIWPUU5ZuEGEON6bfQM6nKJ4ogNJF7KFp4RhMxf5PA=="],+"@tailwindcss/node/lightningcss": ["[email protected]", "", { "dependencies": { "detect-libc": "^2.0.3" }, "optionalDependencies": { "lightningcss-android-arm64": "1.32.0", "lightningcss-darwin-arm64": "1.32.0", "lightningcss-darwin-x64": "1.32.0", "lightningcss-freebsd-x64": "1.32.0", "lightningcss-linux-arm-gnueabihf": "1.32.0", "lightningcss-linux-arm64-gnu": "1.32.0", "lightningcss-linux-arm64-musl": "1.32.0", "lightningcss-linux-x64-gnu": "1.32.0", "lightningcss-linux-x64-musl": "1.32.0", "lightningcss-win32-arm64-msvc": "1.32.0", "lightningcss-win32-x64-msvc": "1.32.0" } }, "sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ=="],"@tailwindcss/oxide-wasm32-wasi/@emnapi/core": ["@emnapi/[email protected]", "", { "dependencies": { "@emnapi/wasi-threads": "1.2.3", "tslib": "^2.4.0" }, "bundled": true }, "sha512-zLpS5asjEb7lq8jYLq37N6XKaE41DIexlY1rF/z4/tIl3wo13Sqm28fRyfIsKZD+NZ8mM5RoKkpW/rBcuoSZSg=="],diff --git a/package.json b/package.jsonindex 8ead76a..b2b8a9e 100644--- a/package.json+++ b/package.json@@ -1,7 +1,7 @@{"name": "phreshos","displayName": "PhreshOS",- "version": "0.1.65",+ "version": "0.1.66","description": "The PhreshOS server, desktop, and authoritative system runtime.","type": "module","private": true,@@ -36,7 +36,7 @@"dependencies": {"@fontsource/roboto": "^5.3.0","@hono/node-server": "^2.1.1",- "@phreshos/core": "^0.1.44",+ "@phreshos/core": "^0.1.45","@phreshos/react-ui": "^0.1.19","@the-link/core": "^0.3.0","@the-link/http": "^0.1.1",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 4d87574..848aee9 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@@ -70,14 +70,14 @@ export default class ProgramManager extends TheLink {return await this.$outbound.publishFirst("/force-create-program", source, asker) as string}- public async fork(subject: unknown, identity: string) {+ public async startup(subject: unknown, operation: string, value?: unknown) {- return await this.$outbound.publishFirst("/fork-program", subject, identity) as string+ return await this.$outbound.publishFirst("/startup", subject, operation, value)}- public async startup(subject: unknown, operation: string, value?: unknown) {+ public async launch(subject: unknown, operation: string, value?: unknown) {- return await this.$outbound.publishFirst("/startup", subject, operation, value)+ return await this.$outbound.publishFirst("/launch", subject, operation, value)}public async permissions<Name extends PermissionName>(diff --git a/source/client/core/link-manager/auth-manager/program-manager/program.ts b/source/client/core/link-manager/auth-manager/program-manager/program.tsindex 0a0b239..b50ab52 100644--- a/source/client/core/link-manager/auth-manager/program-manager/program.ts+++ b/source/client/core/link-manager/auth-manager/program-manager/program.ts@@ -73,6 +73,13 @@ export default class Program {await this.programManager.$outbound.publish("/create-process", this.address, launch)}+ public async open() {++ const launch = await this.programManager.launch(this.address, "get")++ await this.createProcess(launch ?? {})+ }+public install(asker: string) {return this.programManager.command(this.address, "install", undefined, asker)diff --git a/source/client/view/components/desktop-host/client-process-boundary.ts b/source/client/view/components/desktop-host/client-process-boundary.tsindex fc3f8d3..e8d50b7 100644--- a/source/client/view/components/desktop-host/client-process-boundary.ts+++ b/source/client/view/components/desktop-host/client-process-boundary.ts@@ -667,7 +667,8 @@ export default class ClientProcessBoundary extends TheLink {await this.systemAccess.program(program)- const operation = this.authManager.programManager.command(args[1], args[0], args[2], this.pane)+ const value = args[0] === "run" ? await this.systemAccess.launch(args[2]) : args[2]+ const operation = this.authManager.programManager.command(args[1], args[0], value, this.pane)iterator = operation[Symbol.asyncIterator]()}diff --git a/source/client/view/components/desktop-host/host.ts b/source/client/view/components/desktop-host/host.tsindex 2fafbfd..8ed5ef1 100644--- a/source/client/view/components/desktop-host/host.ts+++ b/source/client/view/components/desktop-host/host.ts@@ -183,7 +183,7 @@ export default function host(authManager: AuthManager, pane: string, viewport: (if (word === "host-program-create" || word === "host-program-force-create") {- await access.requirePrograms()+ await access.requireAll()const identity = word === "host-program-create"? await programManager.create(args[0])@@ -252,7 +252,9 @@ export default function host(authManager: AuthManager, pane: string, viewport: (if (args[1] !== "server" && args[1] !== "client") throw new Error("A Process endpoint is server or client")- await processManager.startEndpoint(target.identity, args[1], args[2] as never)+ const launch = args[1] === "client" ? await access.clientLaunch(args[2]) : args[2]++ await processManager.startEndpoint(target.identity, args[1], launch as never)return [target.identity]}@@ -400,7 +402,8 @@ export default function host(authManager: AuthManager, pane: string, viewport: (if (word === "program-process-create") {const program = await permittedProgram(args[0])- const started = await programManager.createProcess(address(program), args[1] as Launch, process().identity)+ const launch = await access.launch(args[1])+ const started = await programManager.createProcess(address(program), launch, process().identity)return [record(requireProcess(started))]}@@ -408,7 +411,7 @@ export default function host(authManager: AuthManager, pane: string, viewport: (if (word === "program-process-find-or-create") {const program = await permittedProgram(args[0])- const launch = args[1] as Launch & { name: string }+ const launch = await access.launch(args[1]) as Launch & { name: string }const found = await programManager.findOrCreateProcess(address(program), launch, process().identity)@@ -626,23 +629,26 @@ export default function host(authManager: AuthManager, pane: string, viewport: (return []}- if (word === "startup") {+ if (word === "launch") {const program = await permittedProgram(args[0])+ const operation = String(args[1])- return [await programManager.startup(address(program), String(args[1]), args[2])]- }+ if (operation === "set" && args[2] === undefined) throw new Error("A Launch is required")- if (word === "fork") {+ const launch = operation === "set" ? await access.launch(args[2]) : args[2]- await access.requirePrograms()+ return [await programManager.launch(address(program), operation, launch)]+ }- const identity = await programManager.fork(args[0], String(args[1]))- const program = programManager.programs.get(identity)+ if (word === "startup") {- if (!program) throw new Error("The forked Program was not synchronized")+ const program = await permittedProgram(args[0])- return [sdkProgram(program)]+ const operation = String(args[1])+ const launch = operation === "enable" ? await access.launch(args[2]) : args[2]++ return [await programManager.startup(address(program), operation, launch)]}if (word === "program-agent") return [await programManager.agent(address(await permittedProgram(args[0])))]diff --git a/source/client/view/components/desktop-host/system-access.ts b/source/client/view/components/desktop-host/system-access.tsindex 225e4c4..86bbe71 100644--- a/source/client/view/components/desktop-host/system-access.ts+++ b/source/client/view/components/desktop-host/system-access.ts@@ -1,7 +1,7 @@import type AuthManager from "@client/core/link-manager/auth-manager/auth-manager"import type Program from "@client/core/link-manager/auth-manager/program-manager/program"import type Process from "@client/core/link-manager/auth-manager/process-manager/process"-import type { PermissionName, PermissionValue, ServiceKey } from "@phreshos/core"+import { parseLaunch, type ClientLaunch, type PermissionName, type PermissionValue, type ServiceKey } from "@phreshos/core"const denied = "Execution is not permitted"@@ -25,11 +25,6 @@ export default class SystemAccess {return service.program ?? this.authManager.processManager.processes.get(service.process)?.program ?? null}- public ownsService(service: ServiceKey) {-- return this.serviceProgram(service) === this.owner().program- }-public async all() {return await this.authManager.grantsPermission(this.pane, "all", [])@@ -51,10 +46,7 @@ export default class SystemAccess {const program = this.serviceProgram(service)- if (program === null) return await this.all()- if (program === this.owner().program) return true-- return await this.authManager.grantsPermission(this.pane, "services", [program])+ return await this.authManager.grantsPermission(this.pane, "services", program === null ? [] : [program])}public async program(program: Program) {@@ -83,9 +75,31 @@ export default class SystemAccess {if (!await this.all()) throw new Error(denied)}- public async requirePrograms() {+ /** Authorize the layer explicitly selected by this Client's Process request. */+ public async launch(value: unknown = {}) {++ const launch = parseLaunch(value)++ if (typeof launch.client === "object") await this.clientLayer(launch.client)++ return launch+ }++ /** Authorize one fresh Client Endpoint incarnation in an existing Process. */+ public async clientLaunch(value: unknown = {}) {++ const launch = parseLaunch({ client: value }).client++ if (!launch || typeof launch !== "object") throw new Error("A Client launch must be an object")++ await this.clientLayer(launch)++ return launch+ }++ private async clientLayer(launch: ClientLaunch) {- await this.require("programs", [])+ if (launch.layer === "under" || launch.layer === "over") await this.require("layers", [launch.layer])}public async requireNetwork(scope: string) {diff --git a/source/client/view/structure/desktop/taskbar/launcher/programs/programs.tsx b/source/client/view/structure/desktop/taskbar/launcher/programs/programs.tsxindex 6268329..fbd1da0 100644--- a/source/client/view/structure/desktop/taskbar/launcher/programs/programs.tsx+++ b/source/client/view/structure/desktop/taskbar/launcher/programs/programs.tsx@@ -50,7 +50,7 @@ function ProgramItem({ icon, record, onChoose }: { icon: string, record: ProgramonChoose()- await record.createProcess()+ await record.open()})return <>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 f133526..ffd9ac6 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@@ -1670,6 +1670,13 @@ export default class ProcessManager extends TheLink {return [await this.system.programIcon(this.system.holdProgram(rest[0], process.program), rest[1])]}+ if (word === "launch") {++ const program = this.system.holdProgram(rest[0], process.program)++ return [await this.system.programLaunch(program, String(rest[1]), rest[2])]+ }+if (word === "startup") {const program = this.system.holdProgram(rest[0], process.program)@@ -1723,15 +1730,6 @@ export default class ProcessManager extends TheLink {return []}- if (word === "fork") {-- const program = this.system.holdProgram(rest[0])-- const forked = await this.system.forkProgram(program, String(rest[1]))-- return [this.system.requireProgram(forked.identity)]- }-if (word === "installed") {return [this.system.programInstalled(this.system.holdProgram(rest[0]))]diff --git a/source/server/core/link-manager/auth-manager/program-manager/launch-storage.ts b/source/server/core/link-manager/auth-manager/program-manager/launch-storage.tsnew file mode 100644index 0000000..16490a5--- /dev/null+++ b/source/server/core/link-manager/auth-manager/program-manager/launch-storage.ts@@ -0,0 +1,47 @@+import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs"+import { randomUUID } from "node:crypto"+import { join } from "node:path"+import { parseLaunch, type Launch } from "@phreshos/core"+import type Program from "./program"++/** Persistent launch intent, without resolving Program defaults or executing it. */+export default class LaunchStorage {+ public constructor(private readonly program: Program, private readonly name: "startup" | "launch") {}++ public get(): Launch | null {+ if (!existsSync(this.path)) return null+ return parseLaunch(JSON.parse(readFileSync(this.path, "utf8")))+ }++ public set(launch: Launch) {+ this.write(`${JSON.stringify(parseLaunch(launch), null, 2)}\n`)+ }++ /** Replace one declaration, retaining exact bytes for operation rollback. */+ public replace(launch: Launch) {+ const previous = existsSync(this.path) ? readFileSync(this.path) : null+ this.set(launch)+ return () => {+ if (previous === null) this.remove()+ else this.write(previous)+ }+ }++ public remove() {+ rmSync(this.path, { force: true })+ }++ private get path() {+ return join(this.program.storagePath, `${this.name}.json`)+ }++ private write(content: string | Uint8Array) {+ mkdirSync(this.program.storagePath, { recursive: true })+ const temporary = join(this.program.storagePath, `.${this.name}.json.${randomUUID()}`)+ try {+ writeFileSync(temporary, content)+ renameSync(temporary, this.path)+ }+ finally { rmSync(temporary, { force: true }) }+ }+}diff --git a/source/server/core/link-manager/auth-manager/program-manager/permissions.ts b/source/server/core/link-manager/auth-manager/program-manager/permissions.tsindex 0cf8616..1bb55d1 100644--- a/source/server/core/link-manager/auth-manager/program-manager/permissions.ts+++ b/source/server/core/link-manager/auth-manager/program-manager/permissions.ts@@ -1,4 +1,4 @@-import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from "node:fs"+import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs"import { randomUUID } from "node:crypto"import { join } from "node:path"import type Program from "./program"@@ -7,27 +7,6 @@ import type { Permissions } from "@phreshos/core"const file = "permissions.json"-/** Replaces runtime permission state with this installation's declaration. */-export function installPermissions(program: Program) {-- const directory = program.storagePath- const path = join(directory, file)- const directoryExisted = existsSync(directory)- const previous = existsSync(path) ? readFileSync(path) : null-- writePermissions(program, program.installationPermissions)-- return function rollbackPermissionInstallation() {-- if (previous === null) rmSync(path, { force: true })- else atomicWrite(directory, path, previous)-- if (!directoryExisted && existsSync(directory) && readdirSync(directory).length === 0) {- rmSync(directory, { recursive: true, force: true })- }- }-}-/** Reads one Program's authoritative permission state. */export function readPermissions(program: Program): Permissions {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.tsindex 0f3669d..cfb22f7 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@@ -18,9 +18,9 @@ import Program, { type CommandOutput, type InstallOutput } from "./program"import Entry, { type ProgramRecord } from "./entry"import Keyv from "keyv"import { isIconSize, ProgramIcons } from "./icon"-import { installStartup, readStartup, removeStartup, writeStartup } from "./startup"+import LaunchStorage from "./launch-storage"import { permissionCatalog } from "@server/core/permissions"-import { installPermissions, readPermissions, writePermissions } from "./permissions"+import { readPermissions, writePermissions } from "./permissions"import {parsePermissionName,type Permission,@@ -33,6 +33,13 @@ import {const maximumProcessesPerProgram = 20+type Registration = {+ origin: "creation" | "reconstruction"+ installed: boolean+ transitionOwnsIdentity?: boolean+ restoreInstalled?: boolean+}+function clonePermission<Name extends PermissionName>(permission: Permission<Name>): Permission<Name> {return Array.isArray(permission) ? [...permission] : permission@@ -114,7 +121,7 @@ export default class ProgramManager extends TheLink {try {- await this.register(new Program(declaration), true, true)+ await this.register(new Program(declaration), { origin: "reconstruction", installed: true, transitionOwnsIdentity: true })}catch (exception) { console.log(`programs: ${found.name} was not read — ${exception instanceof Error ? exception.message : "unreadable"}`) }@@ -291,18 +298,18 @@ export default class ProgramManager extends TheLink {return (await this.forceCreate(source, asker)).identity}- @Connect("/fork-program")- protected async forkProgram(subject: unknown, identity: string) {-- return (await this.fork(this.held(subject), identity)).identity- }-@Connect("/startup")protected async startupProgram(subject: unknown, operation: string, value?: unknown) {return await this.startup(this.held(subject), operation, value)}+ @Connect("/launch")+ protected async savedProgramLaunch(subject: unknown, operation: string, value?: unknown) {++ return await this.launch(this.held(subject), operation, value)+ }+public reach(identity: string) {return this.programs.get(identity)?.program ?? null@@ -341,7 +348,7 @@ export default class ProgramManager extends TheLink {// absolute itself.public async create(source: ProgramDefinition | string) {- const entry = await this.register(this.runtimeProgram(source), false)+ const entry = await this.register(this.runtimeProgram(source), { origin: "creation", installed: false })await this.created(entry)@@ -359,6 +366,8 @@ export default class ProgramManager extends TheLink {// that currently owns this public identity.await program.validate()+ this.declaredLaunch(program)+return await this.change(program.identity, async () => {const existing = this.programs.get(program.identity)@@ -370,7 +379,7 @@ export default class ProgramManager extends TheLink {await this.forgetEntry(existing, false)}- const entry = this.remember(program, false, true, restoreInstalled)+ const entry = this.remember(program, { origin: "creation", installed: false, transitionOwnsIdentity: true, restoreInstalled })try {@@ -422,35 +431,38 @@ export default class ProgramManager extends TheLink {return new Program(definition)}- public async fork(program: Program, identity: string) {-- const entry = await this.register(program.fork(identity), false)-- await this.created(entry)-- return entry.program- }-- private async register(program: Program, installed: boolean, transitionOwnsIdentity = false) {+ private async register(program: Program, registration: Registration) {await program.validate()- return this.remember(program, installed, transitionOwnsIdentity)+ return this.remember(program, registration)}/** Commit one already validated Program to the authoritative registry. */- private remember(program: Program, installed: boolean, transitionOwnsIdentity = false, restoreInstalled = false) {+ private remember(program: Program, { origin, installed, transitionOwnsIdentity = false, restoreInstalled = false }: Registration) {// The runtime map is the live registry, while an installed// declaration is the durable reservation reconstructed on boot.// Forgetting an installed Program removes the former but cannot- // make its identity available to an ordinary create or fork while the+ // make its identity available to ordinary creation while the// latter still exists. Attached replacement is the one transition// that deliberately owns this identity across both representations.if (this.programs.has(program.identity) || (!transitionOwnsIdentity && (this.changing.has(program.identity) || existsSync(this.fileManager.join(program.identity, "program.json"))))) throw new Error("The system already knows this program identity")const entry = new Entry(program, installed, restoreInstalled)+ // Publish a new Program only after its complete permission state exists.+ // Reconstructing an existing Program reads its authoritative stored state.+ if (origin === "creation") {+ const launch = this.declaredLaunch(program)+ const rollback = launch === null ? null : new LaunchStorage(program, "launch").replace(launch)+ try { writePermissions(program, program.declaredPermissions) }+ catch (error) {+ rollback?.()+ throw error+ }+ }+this.programs.set(entry.identity, entry)return entry@@ -610,12 +622,39 @@ export default class ProgramManager extends TheLink {return this.held(subject).agent()}+ private declaredLaunch(program: Program) {+ const value = program.config.launch+ if (value === undefined) return null+ const launch = parseLaunch(value === true ? {} : value)+ this.resolveLaunch(program, launch)+ return launch+ }++ /** Read or replace the saved icon launch without executing it. */+ public async launch(program: Program, operation: string, value?: unknown): Promise<Launch | null | void> {+ const storage = new LaunchStorage(program, "launch")+ if (operation === "get") {+ const launch = storage.get()+ if (launch !== null) this.resolveLaunch(program, launch)+ return launch+ }+ if (operation === "set") {+ const launch = parseLaunch(value)+ this.resolveLaunch(program, launch)+ storage.set(launch)+ return+ }+ throw new Error(`The host does not know the launch operation "${operation}"`)+ }+/** Read or change the system-managed startup launch for one Program. */public async startup(program: Program, operation: string, value?: unknown): Promise<Launch | null | void> {+ const storage = new LaunchStorage(program, "startup")+if (operation === "get") {- const launch = readStartup(program)+ const launch = storage.get()if (launch === null) return null@@ -633,14 +672,14 @@ export default class ProgramManager extends TheLink {const launch = parseLaunch(value === undefined ? {} : value)this.resolveLaunch(program, launch)- writeStartup(program, launch)+ storage.set(launch)return}if (operation === "disable") {- removeStartup(program)+ storage.remove()return}@@ -997,7 +1036,6 @@ export default class ProgramManager extends TheLink {let createdHere = false- let restorePermissions: (() => void) | null = nulllet restoreStartup: (() => void) | null = nulltry {@@ -1040,10 +1078,7 @@ export default class ProgramManager extends TheLink {// the registry claims the install succeeded.await installed.installServer(output)- // Installation establishes the only permission source of- // truth. Reinstalling deliberately replaces prior owner edits.- restorePermissions = installPermissions(installed)- restoreStartup = installStartup(installed, startupLaunch)+ if (startupLaunch !== null) restoreStartup = new LaunchStorage(installed, "startup").replace(startupLaunch)let entry = this.programs.get(source.identity)@@ -1058,14 +1093,13 @@ export default class ProgramManager extends TheLink {else {- entry = await this.register(installed, true, true)+ entry = await this.register(installed, { origin: "creation", installed: true, transitionOwnsIdentity: true })createdHere = true}committed = true- restorePermissions = nullrestoreStartup = nullif (createdHere) await this.created(entry)@@ -1079,11 +1113,12 @@ export default class ProgramManager extends TheLink {// yesterday's list.await this.$outbound.publish("/install", entry.record())- if (startupLaunch !== null) {- try { await this.start(entry.program, startupLaunch, undefined, null, true) }- catch (exception) {- await output({ stream: "stderr", text: `Program installed, but startup failed: ${exception instanceof Error ? exception.message : String(exception)}\n` })- }+ try {+ const launch = await this.startup(entry.program, "get")+ if (launch) await this.start(entry.program, launch, undefined, null, true)+ }+ catch (exception) {+ await output({ stream: "stderr", text: `Program installed, but startup failed: ${exception instanceof Error ? exception.message : String(exception)}\n` })}return entry@@ -1091,13 +1126,12 @@ export default class ProgramManager extends TheLink {catch (exception) {- // Restore the prior program files and permission source after+ // Restore the prior program files and startup configuration after// any failure in the swap or install command. Other storage// never enters the transaction and is neither copied nor moved.if (swapping && !committed) {restoreStartup?.()- restorePermissions?.()for (const what of installedParts) rmSync(join(home, what), { recursive: true, force: true })@@ -1201,7 +1235,7 @@ export default class ProgramManager extends TheLink {if (existsSync(declaration)) {- const installed = await this.register(new Program(declaration), true, true)+ const installed = await this.register(new Program(declaration), { origin: "reconstruction", installed: true, transitionOwnsIdentity: true })await this.created(installed)}diff --git a/source/server/core/link-manager/auth-manager/program-manager/program.ts b/source/server/core/link-manager/auth-manager/program-manager/program.tsindex d3f7005..6113c75 100644--- a/source/server/core/link-manager/auth-manager/program-manager/program.ts+++ b/source/server/core/link-manager/auth-manager/program-manager/program.ts@@ -4,7 +4,7 @@ import { dirname, isAbsolute, normalize, relative, resolve, sep } from "node:patimport { spawn } from "node:child_process"import { randomUUID } from "node:crypto"import { validateIcon } from "./icon"-import { parseProgramDefinition, type ProgramCommandChunk, type ProgramSnapshot } from "@phreshos/core"+import { parseLaunch, parseProgramDefinition, type ProgramCommandChunk, type ProgramSnapshot } from "@phreshos/core"import { permissionCatalog, type DeclaredPermissions } from "@server/core/permissions"/**@@ -53,20 +53,10 @@ export default class Program {this.identity = this.config.identity- // Given only when a program is made from another: the same- // description standing in the same place, which an object alone- // cannot say because an object's relative paths resolve against- // whatever directory the system was started in.+ // An explicit root keeps relative declaration paths anchored to their source.this.root = root ?? where}- // The same description and place under an explicitly different- // identity. A fork is another program, never an alias for this one.- public fork(identity: string) {-- return new Program({ ...this.config, identity }, this.root)- }-// Installation lays the same logical program out in the system's// canonical place. Its identity does not change; only the description// and root it runs from do.@@ -113,8 +103,8 @@ export default class Program {} : null}- /** Canonical permissions copied into authoritative storage when installed. */- public get installationPermissions(): DeclaredPermissions {+ /** Canonical permissions written into authoritative storage at creation. */+ public get declaredPermissions(): DeclaredPermissions {return permissionCatalog.declarations(this.config.client?.permissions)}@@ -324,6 +314,8 @@ function storedDefinition(value: unknown): ProgramConfig {// not whether they are true.function coherent(config: ProgramConfig) {+ if (config?.launch !== undefined && config.launch !== true) parseLaunch(config.launch)+// A name is also the name of a directory, so it is checked as a path// component before it is anything else — a program calling itself// "../../etc" would otherwise be laid out in the system's own files.diff --git a/source/server/core/link-manager/auth-manager/program-manager/startup.ts b/source/server/core/link-manager/auth-manager/program-manager/startup.tsdeleted file mode 100644index e46d506..0000000--- a/source/server/core/link-manager/auth-manager/program-manager/startup.ts+++ /dev/null@@ -1,62 +0,0 @@-import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs"-import { randomUUID } from "node:crypto"-import { join } from "node:path"-import type Program from "./program"-import { parseLaunch, type Launch } from "@phreshos/core"--const file = "startup.json"--/** Read and validate the stored launch without resolving Program defaults. */-export function readStartup(program: Program): Launch | null {-- const path = join(program.storagePath, file)-- if (!existsSync(path)) return null-- return parseLaunch(JSON.parse(readFileSync(path, "utf8")))-}--/** Atomically replace one Program's system-managed startup declaration. */-export function writeStartup(program: Program, launch: Launch) {-- write(program, `${JSON.stringify(launch, null, 2)}\n`)-}--function write(program: Program, content: string | Uint8Array) {-- mkdirSync(program.storagePath, { recursive: true })-- const path = join(program.storagePath, file)-- const temporary = join(program.storagePath, `.${file}.${randomUUID()}`)-- try {-- writeFileSync(temporary, content)-- renameSync(temporary, path)- }-- finally { rmSync(temporary, { force: true }) }-}--/** Installation replaces startup, including an omitted or disabled declaration. */-export function installStartup(program: Program, launch: Launch | null) {-- const path = join(program.storagePath, file)- const previous = existsSync(path) ? readFileSync(path) : null-- if (launch === null) removeStartup(program)- else writeStartup(program, launch)-- return function rollbackStartupInstallation() {- if (previous === null) removeStartup(program)- else write(program, previous)- }-}--/** Disable startup without touching any other Program storage. */-export function removeStartup(program: Program) {-- rmSync(join(program.storagePath, file), { force: true })-}diff --git a/source/server/core/permissions.ts b/source/server/core/permissions.tsindex 617e5e0..f5415fb 100644--- a/source/server/core/permissions.ts+++ b/source/server/core/permissions.ts@@ -169,10 +169,6 @@ export class PermissionCatalog {// permission. Broader fallback grants must never undo a restriction.if (assigned !== undefined && assigned !== null) return this.grants(name, assigned, requested)- if (name === "services" && Array.isArray(permissions.programs)) {- return this.grants(name, permissions.programs, requested)- }-if (name !== "all" && this.granted(permissions.all ?? null)) return truereturn false@@ -253,7 +249,7 @@ function unique(values: readonly string[]) {function valued(domain: PermissionValueDomain) {- if (domain === "program" || domain === "network" || domain === "storage") return true+ if (domain === "program" || domain === "layer" || domain === "network" || domain === "storage") return trueif (domain === "none") return falsedomain satisfies never@@ -263,7 +259,7 @@ function valued(domain: PermissionValueDomain) {function valueCovers(domain: PermissionValueDomain, grant: string, requested: string) {- if (domain === "program") return grant === requested+ if (domain === "program" || domain === "layer") return grant === requestedif (domain === "network") return networkScopeCovers(grant, requested)if (domain === "storage") return nativeStorageScopeCovers(grant, requested)if (domain === "none") return false@@ -288,7 +284,12 @@ export const permissionCatalog = new PermissionCatalog({programs: {default: [],title: "Programs",- description: "Access every Program or selected Programs and their Services."+ description: "Access every Program or selected Programs."+ },+ layers: {+ default: [],+ title: "Window layers",+ description: "Select the under and over layers in Client Endpoint launches."},network: {default: [],diff --git a/source/server/core/system.ts b/source/server/core/system.tsindex b1e8820..238b8c4 100644--- a/source/server/core/system.ts+++ b/source/server/core/system.ts@@ -85,11 +85,6 @@ export default class System {return this.programManager.forceCreate(source, asker)}- public forkProgram(program: Program, identity: string) {-- return this.programManager.fork(program, identity)- }-public programPermissions(program: Program) {return this.programManager.permissions(program)@@ -380,6 +375,11 @@ export default class System {return this.programManager.startup(program, operation, value)}+ public programLaunch(program: Program, operation: string, value?: unknown) {++ return this.programManager.launch(program, operation, value)+ }+public programInstalled(program: Program) {return this.programManager.installed(program)diff --git a/tests/client-layer-permissions.test.ts b/tests/client-layer-permissions.test.tsnew file mode 100644index 0000000..7129b62--- /dev/null+++ b/tests/client-layer-permissions.test.ts@@ -0,0 +1,105 @@+import { expect, test, vi } from "vitest"+import type { Layer, PermissionName, Permissions, PermissionValue, ProgramSnapshot } from "@phreshos/core"+import type AuthManager from "@client/core/link-manager/auth-manager/auth-manager"+import ClientProcessBoundary from "@client/view/components/desktop-host/client-process-boundary"+import SystemAccess from "@client/view/components/desktop-host/system-access"+import host from "@client/view/components/desktop-host/host"+import { permissionCatalog } from "@server/core/permissions"++function fixture() {+ let permissions: Permissions = {}+ const program: ProgramSnapshot = {+ identity: "owner", reference: "program-reference", assetId: "assets", name: "Owner",+ version: null, description: null, hasAgent: false, server: null,+ client: { start: true, service: false, title: null, size: null, position: null, layer: "over", minimize: null, maximize: null }+ }+ const process = { identity: "caller", reference: "process-reference", program: program.identity, name: null, startedAt: 0, options: {}, server: null, client: null }+ const createProcess = vi.fn(async () => process.identity)+ const findOrCreateProcess = vi.fn(async () => process.identity)+ const startup = vi.fn()+ const savedLaunch = vi.fn()+ const startEndpoint = vi.fn()+ const command = vi.fn(async function* () {})+ const auth = {+ programManager: { programs: new Map([[program.identity, program]]), createProcess, findOrCreateProcess, startup, launch: savedLaunch, command },+ processManager: { processes: new Map([[process.identity, process]]), startEndpoint, ownFrame: vi.fn(), releaseFrame: vi.fn() },+ grantsPermission: async <Name extends PermissionName>(_pane: string, name: Name, values: readonly PermissionValue<Name>[]) => permissionCatalog.allows(name, values, permissions)+ } as unknown as AuthManager+ const answer = host(auth, process.identity, () => ({ size: { width: 100, height: 100 } }), () => "frame", {} as never)+ return {+ auth, program, process, answer, createProcess, findOrCreateProcess, startup, savedLaunch, startEndpoint, command,+ permissions(value: Permissions) { permissions = value }+ }+}++test.each(["under", "over"] as const)("Client launch routes check %s before delegation", async layer => {+ const f = fixture()+ const program = { identity: f.program.identity, reference: f.program.reference }+ const process = { identity: f.process.identity, reference: f.process.reference }+ const launch = { name: "main", client: { layer } }+ const operations = [+ ["program-process-create", program, launch],+ ["program-process-find-or-create", program, launch],+ ["startup", program, "enable", launch],+ ["launch", program, "set", launch],+ ["start-endpoint", process, "client", { layer }]+ ] as const+ for (const denied of [{}, { programs: [] }, { layers: [layer === "under" ? "over" : "under"] }, { all: [], layers: false }] satisfies Permissions[]) {+ f.permissions(denied)+ for (const [operation, ...args] of operations) await expect(f.answer(operation, ...args)).rejects.toThrow("Execution is not permitted")+ }+ const delegates = [f.createProcess, f.findOrCreateProcess, f.startup, f.savedLaunch, f.startEndpoint]+ for (const delegate of delegates) expect(delegate).not.toHaveBeenCalled()+ for (const granted of [{ layers: [layer] }, { layers: [] }, { all: [] }] satisfies Permissions[]) {+ f.permissions(granted)+ for (const [operation, ...args] of operations) await f.answer(operation, ...args)+ }+ for (const delegate of delegates) expect(delegate).toHaveBeenCalledTimes(3)+})++test("Client layer authorization validates explicit choices without reinterpreting defaults", async () => {+ const f = fixture()+ const access = new SystemAccess(f.auth, f.process.identity)+ for (const launch of [{}, { client: true }, { client: false }, { client: { layer: "window" as Layer } }]) {+ expect(await access.launch(launch)).toEqual(launch)+ }+ expect(await access.clientLaunch()).toEqual({})+ await expect(access.launch({ client: { layer: "invalid" } })).rejects.toThrow("layer")+ await expect(access.clientLaunch(false)).rejects.toThrow("object")+ await f.answer("startup", null, "get")+ await f.answer("startup", null, "disable")+ await f.answer("start-endpoint", null, "server")+ await f.answer("program-process-create", null, {})+ expect(f.createProcess).toHaveBeenCalledOnce()+})++test.each(["under", "over"] as const)("Client run streams authorize %s before creating an iterator", async layer => {+ const f = fixture()+ const boundary = new ClientProcessBoundary(f.process.identity, { contentWindow: null } as HTMLIFrameElement, f.auth,+ () => ({ size: { width: 100, height: 100 } }), {} as never, { release: vi.fn() } as never)+ const deliver = vi.spyOn(boundary, "deliver").mockResolvedValue()+ await boundary.own("frame")+ const program = { identity: f.program.identity, reference: f.program.reference }+ const launch = { client: { layer } }+ boundary.receive(["boundary", "expect", "denied"])+ boundary.receive(["end-host", "stream", "denied", "run", program, launch])+ await vi.waitFor(() => expect(deliver).toHaveBeenCalledWith("host-end", "stream", "denied", "answer", { success: false, error: "Execution is not permitted" }))+ expect(f.command).not.toHaveBeenCalled()+ f.permissions({ layers: [layer] })+ boundary.receive(["boundary", "expect", "allowed"])+ boundary.receive(["end-host", "stream", "allowed", "run", program, launch])+ await vi.waitFor(() => expect(deliver).toHaveBeenCalledWith("host-end", "stream", "allowed", "answer", { success: true, result: undefined }))+ expect(f.command).toHaveBeenCalledExactlyOnceWith(program, "run", launch, f.process.identity)+ await boundary.release()+})++test("the layer catalog uses exact assignments before all", () => {+ expect(permissionCatalog.declarations({ layers: true })).toEqual({ layers: [] })+ expect(permissionCatalog.allows("layers", ["over"], { layers: ["under"] })).toBe(false)+ expect(permissionCatalog.allows("layers", ["under"], { layers: ["under"] })).toBe(true)+ expect(permissionCatalog.allows("layers", ["under", "over"], { layers: [] })).toBe(true)+ expect(permissionCatalog.allows("layers", ["over"], { all: [], layers: false })).toBe(false)+ expect(permissionCatalog.allows("layers", ["over"], { all: [] })).toBe(true)+ expect(() => permissionCatalog.declarations({ layers: false })).toThrow()+ expect(() => permissionCatalog.resolve("layers", ["window"])).toThrow()+})diff --git a/tests/client-permission-boundary.test.ts b/tests/client-permission-boundary.test.tsnew file mode 100644index 0000000..78887b5--- /dev/null+++ b/tests/client-permission-boundary.test.ts@@ -0,0 +1,75 @@+import { expect, test, vi } from "vitest"+import type { PermissionName, Permissions, ProgramSnapshot } from "@phreshos/core"+import type AuthManager from "@client/core/link-manager/auth-manager/auth-manager"+import host from "@client/view/components/desktop-host/host"+import { permissionCatalog } from "@server/core/permissions"++test("Client Program creation requires all before reaching the creation boundary", async () => {+ let permissions: Permissions = { programs: [] }+ const program: ProgramSnapshot = {+ identity: "created", reference: "created-reference", assetId: "created-assets",+ name: "Created", version: null, description: null, hasAgent: false,+ server: null, client: null+ }+ const create = vi.fn(async () => program.identity)+ const forceCreate = vi.fn(async () => program.identity)+ const auth = {+ programManager: { programs: new Map([[program.identity, program]]), create, forceCreate },+ processManager: { processes: new Map() },+ grantsPermission: async (_pane: string, name: PermissionName, values: never[]) => permissionCatalog.allows(name, values, permissions)+ } as unknown as AuthManager+ const answer = host(auth, "caller", () => { throw new Error("unused viewport") }, () => null, {} as never)+ const source = { identity: "created" }+ for (const operation of ["host-program-create", "host-program-force-create"]) {+ await expect(answer(operation, source)).rejects.toThrow("Execution is not permitted")+ }+ expect(create).not.toHaveBeenCalled()+ expect(forceCreate).not.toHaveBeenCalled()+ permissions = { all: [] }+ expect(await answer("host-program-create", source)).toEqual([program])+ expect(await answer("host-program-force-create", source)).toEqual([program])+ expect(create).toHaveBeenCalledWith(source)+ expect(forceCreate).toHaveBeenCalledWith(source, "caller")+})++test.each(["owner", "outside"])("Service operations require permission for Services belonging to %s", async owningProgram => {+ const destination = "6d138083-7a51-44ec-9abe-ff0194ad1e5b"+ let permissions: Permissions = { programs: [] }+ const serviceExists = vi.fn(async () => true)+ const waitServiceReady = vi.fn()+ const followService = vi.fn()+ const sendService = vi.fn()+ const askService = vi.fn()+ const auth = {+ programManager: { programs: new Map() },+ processManager: {+ processes: new Map([+ ["caller", { program: "owner" }],+ [destination, { program: owningProgram }]+ ]),+ serviceExists, waitServiceReady, followService, sendService, askService+ },+ grantsPermission: async (_pane: string, name: PermissionName, values: never[]) => permissionCatalog.allows(name, values, permissions)+ } as unknown as AuthManager+ const answer = host(auth, "caller", () => { throw new Error("unused viewport") }, () => "frame", {} as never)+ for (const key of [{ program: owningProgram, process: "main", endpoint: "server" }, { process: destination, endpoint: "server" }]) {+ const operations = [+ ["service-exists", key],+ ["service-wait-ready", key],+ ["service-follow", "subscription", key, "events", "change"],+ ["service-send", key, "change", {}],+ ["service-ask", key, "read", {}]+ ] as const+ for (const denied of [{}, { programs: [] }, { all: [], services: false }, { services: ["unrelated"] }] satisfies Permissions[]) {+ permissions = denied+ for (const [operation, ...args] of operations) {+ await expect(answer(operation, ...args)).rejects.toThrow("Execution is not permitted")+ }+ }+ for (const granted of [{ services: [owningProgram] }, { services: [] }, { all: [] }] satisfies Permissions[]) {+ permissions = granted+ for (const [operation, ...args] of operations) await answer(operation, ...args)+ }+ }+ for (const call of [serviceExists, waitServiceReady, followService, sendService, askService]) expect(call).toHaveBeenCalledTimes(6)+})diff --git a/tests/client-system-access.test.ts b/tests/client-system-access.test.tsindex da17f75..1c9b9f4 100644--- a/tests/client-system-access.test.ts+++ b/tests/client-system-access.test.ts@@ -44,16 +44,13 @@ test("client system access contract", async () => {assert(!access.ownsProgram(outsideProgram))assert(access.ownsProcess(sibling))assert(!access.ownsProcess(outside))- assert(access.ownsService(ownService))- assert(access.ownsService(ownExactService))- assert(!access.ownsService(outsideService))assert.equal(await access.program(ownProgram as never), ownProgram)- assert.equal(await access.service(ownService), ownService)- assert.equal(await access.service(ownExactService), ownExactService)+ await assert.rejects(access.service(ownService), /Execution is not permitted/)+ await assert.rejects(access.service(ownExactService), /Execution is not permitted/)await assert.rejects(access.program(outsideProgram as never), /Execution is not permitted/)await assert.rejects(access.process(outside), /Execution is not permitted/)await assert.rejects(access.service(outsideService), /Execution is not permitted/)- await assert.rejects(access.requirePrograms(), /Execution is not permitted/)+ await assert.rejects(access.requireAll(), /Execution is not permitted/)await assert.rejects(access.requireNetwork("https://api.example.com/v1/users"), /Execution is not permitted/)await assert.rejects(access.requireStorage("/Users/person/Documents/report.txt", "read"), /Execution is not permitted/)await assert.rejects(access.require("uploads", []), /Execution is not permitted/)@@ -65,26 +62,29 @@ test("client system access contract", async () => {assert.equal(await access.service(outsideService), outsideService)await assert.rejects(access.program(outsideProgram as never), /Execution is not permitted/)await assert.rejects(access.process(outside), /Execution is not permitted/)- await assert.rejects(access.requirePrograms(), /Execution is not permitted/)+ await assert.rejects(access.requireAll(), /Execution is not permitted/)permissions = { services: [] }assert.equal(await access.service(outsideService), outsideService)+ assert.equal(await access.service(ownService), ownService)+ assert.equal(await access.service(ownExactService), ownExactService)await assert.rejects(access.program(outsideProgram as never), /Execution is not permitted/)- await assert.rejects(access.requirePrograms(), /Execution is not permitted/)+ await assert.rejects(access.requireAll(), /Execution is not permitted/)permissions = { programs: ["outside"] }assert.equal(await access.program(outsideProgram as never), outsideProgram)assert.equal(await access.process(outside), outside)- assert.equal(await access.service(outsideService), outsideService)- await assert.rejects(access.requirePrograms(), /Execution is not permitted/)+ await assert.rejects(access.service(outsideService), /Execution is not permitted/)+ await assert.rejects(access.service({ process: outside.identity, endpoint: "server" }), /Execution is not permitted/)+ await assert.rejects(access.requireAll(), /Execution is not permitted/)permissions = { programs: [] }- await access.requirePrograms()+ await assert.rejects(access.requireAll(), /Execution is not permitted/)assert.equal(await access.program(outsideProgram as never), outsideProgram)- assert.equal(await access.service(outsideService), outsideService)+ await assert.rejects(access.service(outsideService), /Execution is not permitted/)permissions = { appearance: [], desktopPreferences: [] }@@ -121,11 +121,23 @@ test("client system access contract", async () => {assert.equal((await access.program(outsideProgram as never)).identity, "outside")assert.equal((await access.process(outside)).identity, outside.identity)assert.equal(await access.service(outsideService), outsideService)- await access.requirePrograms()await access.require("appearance", [])await access.require("desktopPreferences", [])await access.requireNetwork("wss://events.example.com/socket")await access.requireStorage("/any/native/path", "delete")await access.require("uploads", [])await access.requireAll()++ const unresolvedService = { process: "ec99e1e8-d13b-4fc8-89ed-eaa3f394a42f", endpoint: "server" } as const+ permissions = { all: [], services: false }+ await assert.rejects(access.service(ownService), /Execution is not permitted/)+ await assert.rejects(access.service(ownExactService), /Execution is not permitted/)+ await assert.rejects(access.service(unresolvedService), /Execution is not permitted/)+ permissions = { services: [] }+ assert.equal(await access.service(unresolvedService), unresolvedService)+ permissions = { services: ["owner"] }+ assert.equal(await access.service(ownService), ownService)+ assert.equal(await access.service(ownExactService), ownExactService)+ await assert.rejects(access.service(outsideService), /Execution is not permitted/)+ await assert.rejects(access.service(unresolvedService), /Execution is not permitted/)}, 120_000)diff --git a/tests/permission-requests.test.ts b/tests/permission-requests.test.tsindex 5890c18..64d3bee 100644--- a/tests/permission-requests.test.ts+++ b/tests/permission-requests.test.ts@@ -78,7 +78,7 @@ test("permission requests contract", async () => {assert(programManager.grantsPermission(program, "network", ["https://api.example.com/v1"]))assert(!programManager.grantsPermission(program, "network", ["https://other.example.com"]))- // Program declarations are installation input, never a second live source.+ // Permission decisions read the authoritative stored state.const declared = new Program({ identity: "declared", storage: temporary, client: { location: ".", permissions: { programs: ["browser"] } } })writePermissions(declared, { services: ["editor"] })assert(!programManager.grantsPermission(declared, "services", ["browser"]))diff --git a/tests/permissions.test.ts b/tests/permissions.test.tsindex d0ed771..593e4a5 100644--- a/tests/permissions.test.ts+++ b/tests/permissions.test.ts@@ -18,7 +18,12 @@ test("permissions contract", async () => {programs: {default: [],title: "Programs",- description: "Access every Program or selected Programs and their Services."+ description: "Access every Program or selected Programs."+ },+ layers: {+ default: [],+ title: "Window layers",+ description: "Select the under and over layers in Client Endpoint launches."},network: {default: [],@@ -57,7 +62,7 @@ test("permissions contract", async () => {valueDomain: "program",default: [],title: "Programs",- description: "Access every Program or selected Programs and their Services."+ description: "Access every Program or selected Programs."})assert.deepEqual(catalog.definition("network"), {valueDomain: "network",@@ -111,9 +116,9 @@ test("permissions contract", async () => {assert(!catalog.allows("all", [], {}))assert(catalog.allows("services", ["browser"], { all: [] }))assert(catalog.allows("services", ["browser"], { services: ["browser"] }))- assert(catalog.allows("services", ["browser"], { programs: [] }))- assert(catalog.allows("services", [], { programs: [] }))- assert(catalog.allows("services", ["browser"], { programs: ["browser"] }))+ assert(!catalog.allows("services", ["browser"], { programs: [] }))+ assert(!catalog.allows("services", [], { programs: [] }))+ assert(!catalog.allows("services", ["browser"], { programs: ["browser"] }))assert(!catalog.allows("services", ["browser", "editor"], { programs: ["browser"], services: ["editor"] }))assert(catalog.allows("services", ["editor"], { programs: ["browser"], services: ["editor"] }))assert(!catalog.allows("services", ["editor"], { programs: ["browser"] }))diff --git a/tests/process-find-or-create.test.ts b/tests/process-find-or-create.test.tsindex 215f535..4dd9c94 100644--- a/tests/process-find-or-create.test.ts+++ b/tests/process-find-or-create.test.ts@@ -20,7 +20,7 @@ test("process find or create contract", async () => {const processes = new Map<string, FixtureProcess>()const program = {identity: "example",- config: { options: { language: "en", document: "default.txt" } },+ config: { options: { language: "en", document: "default.txt" }, launch: { options: { document: "icon.txt" } } },reference: "example-reference",server: { start: true },client: {diff --git a/tests/program-creation.test.ts b/tests/program-creation.test.tsnew file mode 100644index 0000000..6e37ad7--- /dev/null+++ b/tests/program-creation.test.ts@@ -0,0 +1,147 @@+import { existsSync, mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"+import { tmpdir } from "node:os"+import { join } from "node:path"+import { TheLink } from "@the-link/core"+import { expect, test, vi, type TestContext } from "vitest"+import type { ClientPermissionDeclarations } from "@phreshos/core"+import FileManager from "@libs/file-manager"+import type AuthManager from "@server/core/link-manager/auth-manager/auth-manager"+import ProgramManager from "@server/core/link-manager/auth-manager/program-manager/program-manager"+import { readPermissions, writePermissions } from "@server/core/link-manager/auth-manager/program-manager/permissions"+import Program from "@server/core/link-manager/auth-manager/program-manager/program"++function fixture(context: TestContext) {+ const directory = mkdtempSync(join(tmpdir(), "phresh-program-creation-"))+ context.onTestFinished(() => rmSync(directory, { recursive: true, force: true }))+ const client = join(directory, "client")+ mkdirSync(client)+ writeFileSync(join(client, "index.html"), "<!doctype html>")+ const announceHost = vi.fn()+ const auth = Object.assign(new TheLink(), {+ linkManager: { application: { storage: new FileManager(directory, "system"), defaultProgramIcon: "" } },+ processManager: { processes: new Map(), exitAll: vi.fn(), announceHost, announceSubject: vi.fn() }+ }) as unknown as AuthManager+ const manager = new ProgramManager(auth)+ function definition(permissions?: ClientPermissionDeclarations) {+ return { identity: "example", storage: join(directory, "data"), client: { location: client, permissions } }+ }+ return { directory, client, manager, announceHost, definition }+}++test("creation establishes declared permissions before announcing the Program", async context => {+ const { manager, definition, announceHost } = fixture(context)+ announceHost.mockImplementation((_domain, event, _identity, entry) => {+ if (event === "create") expect(readPermissions(entry.program)).toEqual({ network: ["https://api.example.test"], uploads: [] })+ })+ const program = await manager.create(definition({ network: ["https://api.example.test/**"], uploads: true }))+ expect(manager.find(program.identity).installed).toBe(false)+ expect(JSON.parse(readFileSync(join(program.storagePath, "permissions.json"), "utf8"))).toEqual({ network: ["https://api.example.test"], uploads: [] })+ expect(announceHost).toHaveBeenCalledOnce()+})++test("creation and force-create replace the complete permission set", async context => {+ const { manager, definition } = fixture(context)+ const first = await manager.create(definition({ all: true }))+ writePermissions(first, { appearance: [] })+ const replacement = await manager.forceCreate(definition({ services: ["example"] }))+ expect(readPermissions(replacement)).toEqual({ services: ["example"] })+ await manager.forget(replacement)+ const empty = await manager.create(definition())+ expect(readPermissions(empty)).toEqual({})+ expect(existsSync(join(empty.storagePath, "permissions.json"))).toBe(true)+})++test("invalid and duplicate creation leave stored authority and registry unchanged", async context => {+ const { manager, definition, directory } = fixture(context)+ const program = await manager.create(definition({ network: true }))+ await expect(manager.create(definition({ all: true }))).rejects.toThrow("identity")+ expect(readPermissions(program)).toEqual({ network: [] })+ await expect(manager.forceCreate({ ...definition({ all: true }), client: { location: join(directory, "missing") } })).rejects.toThrow()+ expect(manager.find(program.identity).program).toBe(program)+ expect(readPermissions(program)).toEqual({ network: [] })+})++test("a permission write failure never publishes a new Program", async context => {+ const { manager, definition, directory, announceHost } = fixture(context)+ const storage = join(directory, "not-a-directory")+ writeFileSync(storage, "keep this")+ await expect(manager.create({ ...definition(), storage })).rejects.toThrow()+ expect(manager.programs.size).toBe(0)+ expect(announceHost).not.toHaveBeenCalled()+ expect(readFileSync(storage, "utf8")).toBe("keep this")+})++test("boot reconstruction preserves stored permission decisions", async context => {+ const { manager, definition, client } = fixture(context)+ const directory = manager.fileManager.join("example")+ mkdirSync(directory)+ writeFileSync(join(directory, "program.json"), JSON.stringify({ ...definition({ all: true }), launch: true, storage: "storage", client: { location: client, permissions: { all: true } } }))+ mkdirSync(join(directory, "storage"))+ writeFileSync(join(directory, "storage", "permissions.json"), JSON.stringify({ network: false }))+ writeFileSync(join(directory, "storage", "launch.json"), JSON.stringify({ options: { document: "saved.txt" } }))+ await manager.initialize()+ expect(readPermissions(manager.find("example").program)).toEqual({ network: false })+ expect(await manager.launch(manager.find("example").program, "get")).toEqual({ options: { document: "saved.txt" } })+})++test("creation writes saved launch intent; omission preserves it and true resets it", async context => {+ const { manager, definition } = fixture(context)+ const intent = { client: { layer: "over" as const }, options: { document: "icon.txt" } }+ let program = await manager.create({ ...definition(), options: { language: "en" }, launch: intent })+ expect(await manager.launch(program, "get")).toEqual(intent)+ expect(manager.authManager.processManager.processes.size).toBe(0)+ program = await manager.forceCreate(definition())+ expect(await manager.launch(program, "get")).toEqual(intent)+ await manager.launch(program, "set", { name: "saved" })+ expect(await manager.launch(program, "get")).toEqual({ name: "saved" })+ program = await manager.forceCreate({ ...definition(), launch: true })+ expect(await manager.launch(program, "get")).toEqual({})+})++test("saved launch operations preserve defaults and reject invalid intent before mutation", async context => {+ const { manager, definition } = fixture(context)+ const program = await manager.create(definition())+ expect(await manager.launch(program, "get")).toBeNull()+ expect(existsSync(join(program.storagePath, "launch.json"))).toBe(false)+ await manager.launch(program, "set", { options: { document: "saved.txt" } })+ for (const value of [undefined, false, { server: true }, { client: false }]) {+ await expect(manager.launch(program, "set", value)).rejects.toThrow()+ }+ await expect(manager.forceCreate({ ...definition(), launch: { server: true } })).rejects.toThrow("no server")+ expect(manager.find("example").program).toBe(program)+ expect(await manager.launch(program, "get")).toEqual({ options: { document: "saved.txt" } })+})++test("installation keeps saved launch settings when updating an existing Program", async context => {+ const { manager, client } = fixture(context)+ let entry = await manager.install(new Program({ identity: "example", client: { location: client }, launch: true }))+ expect(await manager.launch(entry.program, "get")).toEqual({})+ await manager.launch(entry.program, "set", { options: { document: "saved.txt" } })+ entry = await manager.install(new Program({ identity: "example", client: { location: client }, launch: { name: "declaration" } }))+ expect(await manager.launch(entry.program, "get")).toEqual({ options: { document: "saved.txt" } })+})++test("failed creation restores the exact previous saved launch", async context => {+ const { manager, definition } = fixture(context)+ const storage = definition().storage+ mkdirSync(join(storage, "permissions.json"), { recursive: true })+ const previous = '{ "options": { "document": "previous.txt" } }\n'+ writeFileSync(join(storage, "launch.json"), previous)+ await expect(manager.create({ ...definition(), launch: true })).rejects.toThrow()+ expect(manager.programs.size).toBe(0)+ expect(readFileSync(join(storage, "launch.json"), "utf8")).toBe(previous)+})++test("installing an attached Program uses the destination's stored permissions", async context => {+ const { manager, definition } = fixture(context)+ const program = await manager.create(definition({ all: true }))+ const sourceFile = join(program.storagePath, "permissions.json")+ const installedStorage = manager.fileManager.join("example", "storage")+ mkdirSync(installedStorage, { recursive: true })+ writeFileSync(join(installedStorage, "permissions.json"), JSON.stringify({ appearance: [] }))++ const installed = await manager.install(program)+ expect(installed.program.storagePath).toBe(installedStorage)+ expect(readPermissions(installed.program)).toEqual({ appearance: [] })+ expect(JSON.parse(readFileSync(sourceFile, "utf8"))).toEqual({ all: [] })+})diff --git a/tests/program-icon-launch.test.ts b/tests/program-icon-launch.test.tsnew file mode 100644index 0000000..58d6afa--- /dev/null+++ b/tests/program-icon-launch.test.ts@@ -0,0 +1,28 @@+import { expect, test, vi } from "vitest"+import Program from "@client/core/link-manager/auth-manager/program-manager/program"+import type ProgramManager from "@client/core/link-manager/auth-manager/program-manager/program-manager"+import RuntimeProgram from "@server/core/link-manager/auth-manager/program-manager/program"+import Entry from "@server/core/link-manager/auth-manager/program-manager/entry"++test("opening a Program reads saved intent while direct creation uses its explicit request", async () => {+ const intent = { options: { document: "icon.txt" }, client: { layer: "over" } }+ const launch = vi.fn().mockResolvedValue(intent)+ const publish = vi.fn()+ const manager = { launch, $outbound: { publish } } as unknown as ProgramManager+ const record = new Entry(new RuntimeProgram({ identity: "example", client: { location: "." } })).record()+ const program = new Program(manager, record)+ const address = { identity: record.identity, reference: record.reference }++ await program.open()+ expect(launch).toHaveBeenCalledExactlyOnceWith(address, "get")+ expect(publish).toHaveBeenLastCalledWith("/create-process", address, intent)+ await program.createProcess()+ expect(launch).toHaveBeenCalledOnce()+ expect(publish).toHaveBeenLastCalledWith("/create-process", address, {})+ launch.mockResolvedValueOnce(null)+ await program.open()+ expect(publish).toHaveBeenLastCalledWith("/create-process", address, {})+ launch.mockRejectedValueOnce(new Error("invalid stored launch"))+ await expect(program.open()).rejects.toThrow("invalid stored launch")+ expect(publish).toHaveBeenCalledTimes(3)+})diff --git a/tests/program-install.test.ts b/tests/program-install.test.tsindex 43f8f69..1ee2147 100644--- a/tests/program-install.test.ts+++ b/tests/program-install.test.ts@@ -4,7 +4,6 @@ import { tmpdir } from "node:os"import { join } from "node:path"import Program from "@server/core/link-manager/auth-manager/program-manager/program"import { copyProgram } from "@server/core/link-manager/auth-manager/program-manager/program-manager"-import { installPermissions, readPermissions, writePermissions } from "@server/core/link-manager/auth-manager/program-manager/permissions"import type { ProgramCommandChunk } from "@phreshos/core"import { test } from "vitest"@@ -52,15 +51,6 @@ test("program install contract", async () => {assert.equal(readFileSync(join(installed, "agent.md"), "utf8"), "Program operating knowledge")const installedProgram = new Program(join(installed, "program.json"))- writePermissions(installedProgram, { network: ["https://old.example.test/**"], appearance: [] })- const rollbackPermissions = installPermissions(installedProgram)- assert.deepEqual(readPermissions(installedProgram), { network: ["https://api.example.test"] })- rollbackPermissions()- assert.deepEqual(readPermissions(installedProgram), { network: ["https://old.example.test"], appearance: [] })- installPermissions(installedProgram)- const withoutPermissions = new Program({ ...installedProgram.config, client: { location: "client" } }, installedProgram.root)- installPermissions(withoutPermissions)- assert.deepEqual(readPermissions(installedProgram), {})const installation: ProgramCommandChunk[] = []const uninstallation: ProgramCommandChunk[] = []diff --git a/tests/program-startup.test.ts b/tests/program-startup.test.tsindex 0864428..2c1a7ac 100644--- a/tests/program-startup.test.ts+++ b/tests/program-startup.test.ts@@ -1,4 +1,4 @@-import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"+import { existsSync, mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"import { tmpdir } from "node:os"import { join } from "node:path"import { TheLink } from "@the-link/core"@@ -9,9 +9,9 @@ import type AuthManager from "@server/core/link-manager/auth-manager/auth-manageimport Program from "@server/core/link-manager/auth-manager/program-manager/program"import ProgramManager from "@server/core/link-manager/auth-manager/program-manager/program-manager"import { readPermissions, writePermissions } from "@server/core/link-manager/auth-manager/program-manager/permissions"-import * as startup from "@server/core/link-manager/auth-manager/program-manager/startup"+import LaunchStorage from "@server/core/link-manager/auth-manager/program-manager/launch-storage"-test("installation replaces startup and permissions before launching exactly once", async context => {+test("installation applies active declarations and launches the stored startup", async context => {const directory = mkdtempSync(join(tmpdir(), "phresh-startup-"))context.onTestFinished(() => { vi.restoreAllMocks(); rmSync(directory, { recursive: true, force: true }) })const client = join(directory, "client")@@ -26,8 +26,7 @@ test("installation replaces startup and permissions before launching exactly oncconst launches: Launch[] = []const start = vi.spyOn(manager as unknown as { start(program: Program, launch: Launch): Promise<string> }, "start").mockImplementation(async (program, launch) => {- expect(startup.readStartup(program)).toEqual(launch)- expect(readPermissions(program)).toEqual({ network: ["https://new.example.test"] })+ expect(new LaunchStorage(program, "startup").get()).toEqual(launch)launches.push(launch)return "process-identity"})@@ -38,33 +37,43 @@ test("installation replaces startup and permissions before launching exactly onc})}- let entry = await manager.install(definition(true))+ let entry = await manager.install(definition())+ expect(existsSync(join(entry.program.storagePath, "startup.json"))).toBe(false)+ expect(start).not.toHaveBeenCalled()+ entry = await manager.install(definition(false))+ expect(existsSync(join(entry.program.storagePath, "startup.json"))).toBe(false)+ expect(start).not.toHaveBeenCalled()++ entry = await manager.install(definition(true))expect(launches).toEqual([{}])+ expect(readPermissions(entry.program)).toEqual({ network: ["https://new.example.test"] })const note = join(entry.program.storagePath, "note.txt")writeFileSync(note, "keep this")writePermissions(entry.program, { network: [], appearance: [] })- startup.writeStartup(entry.program, { name: "owner-edit" })+ new LaunchStorage(entry.program, "startup").set({ name: "owner-edit" })const configured = { name: "welcome", options: { language: "fr" } }entry = await manager.install(definition(configured))expect(launches).toEqual([{}, configured])expect(JSON.parse(readFileSync(join(entry.program.root, "program.json"), "utf8")).options).toEqual({ language: "en" })expect(readFileSync(note, "utf8")).toBe("keep this")+ expect(readPermissions(entry.program)).toEqual({ network: [], appearance: [] })- for (const disabled of [false, undefined]) {- startup.writeStartup(entry.program, configured)- entry = await manager.install(definition(disabled))- expect(startup.readStartup(entry.program)).toBeNull()- expect(start).toHaveBeenCalledTimes(2)+ for (const inactive of [false, undefined]) {+ new LaunchStorage(entry.program, "startup").set(configured)+ entry = await manager.install(definition(inactive))+ expect(new LaunchStorage(entry.program, "startup").get()).toEqual(configured)+ expect(launches.at(-1)).toEqual(configured)}+ expect(start).toHaveBeenCalledTimes(4)- // A settings write failure restores permissions and leaves the old startup intact.+ // A settings write failure leaves the authoritative stored state intact.writePermissions(entry.program, { appearance: [] })- startup.writeStartup(entry.program, configured)- const writing = vi.spyOn(startup, "installStartup").mockImplementationOnce(() => { throw new Error("write failed") })+ new LaunchStorage(entry.program, "startup").set(configured)+ const writing = vi.spyOn(LaunchStorage.prototype, "replace").mockImplementationOnce(() => { throw new Error("write failed") })await expect(manager.install(definition(true))).rejects.toThrow("write failed")expect(readPermissions(entry.program)).toEqual({ appearance: [] })- expect(startup.readStartup(entry.program)).toEqual(configured)+ expect(new LaunchStorage(entry.program, "startup").get()).toEqual(configured)writing.mockRestore()// Startup failure is reported without undoing a valid installation.@@ -72,11 +81,11 @@ test("installation replaces startup and permissions before launching exactly oncconst warnings: string[] = []entry = await manager.install(definition(true), null, chunk => { warnings.push(chunk.text) })expect(entry.installed).toBe(true)- expect(startup.readStartup(entry.program)).toEqual({})+ expect(new LaunchStorage(entry.program, "startup").get()).toEqual({})expect(warnings.join("")).toContain("Program installed, but startup failed: cannot start")await expect(manager.install(definition({ server: true }))).rejects.toThrow("no server")- expect(startup.readStartup(entry.program)).toEqual({})+ expect(new LaunchStorage(entry.program, "startup").get()).toEqual({})})test("startup rollback preserves the exact previous file", context => {@@ -85,8 +94,8 @@ test("startup rollback preserves the exact previous file", context => {const program = new Program({ identity: "example", storage: directory, client: { location: "." } })const file = join(directory, "startup.json")writeFileSync(file, "invalid prior content")- const rollback = startup.installStartup(program, {})- expect(startup.readStartup(program)).toEqual({})+ const rollback = new LaunchStorage(program, "startup").replace({})+ expect(new LaunchStorage(program, "startup").get()).toEqual({})rollback()expect(readFileSync(file, "utf8")).toBe("invalid prior content")})