Skip to content

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

Implement unified client domains and permissions

zohayrslileh5724455c8d4c
diff --git a/scripts/contracts/client-surface.ts b/scripts/contracts/client-surface.ts
index e356e64..83113f9 100644
--- a/scripts/contracts/client-surface.ts
+++ b/scripts/contracts/client-surface.ts
@@ -1,7 +1,7 @@
import assert from "node:assert/strict"
import ClientProcessBoundary from "@client/view/components/desktop-host/client-process-boundary"
import ClientProcessManager from "@client/core/link-manager/auth-manager/process-manager/process-manager"
-import { visibilityTransition, visualTransaction } from "@client/view/components/desktop-host/local-window"
+import { visualTransaction } from "@client/view/components/desktop-host/local-window"
import host from "@client/view/components/desktop-host/host"
import LocalWindows from "@client/view/components/window-manager/local-windows"
import type { LocalWindowEntry } from "@client/view/components/window-manager/local-windows"
@@ -21,13 +21,12 @@ assert.equal("surface" in authoritativeWindow, false)
assert.equal("surface" in authoritativeWindow.toJSON(), false)
const transaction = visualTransaction({ duration: 240, easing: "ease-out", wait: true })
-const visibility = visibilityTransition({ duration: 240, easing: "ease-out", wait: true })
+const visibility = visualTransaction({ duration: 240, easing: "ease-out", wait: true })!
assert.throws(() => visualTransaction({}), /must provide duration or easing/)
assert.throws(() => visualTransaction({ wait: true }), /must provide duration or easing/)
assert.throws(() => visualTransaction({ duration: 60_001 }), /0 to 60000/)
-assert.throws(() => visibilityTransition(undefined), /required/)
-assert.throws(() => visibilityTransition({ unknown: true }), /no "unknown" field/)
+assert.throws(() => visualTransaction({ unknown: true }), /no "unknown" field/)
const ordinary = client("window")
const bare = client("over")
@@ -93,7 +92,7 @@ const interrupted = first.move("bare", { x: 100, y: 110 }, { duration: 200, wait
await first.move("bare", { x: 120, y: 130 })
await assert.rejects(interrupted, /interrupted/)
-const surfaceWaiting = first.setSurface("bare", visibility)
+const surfaceWaiting = first.addSurface("bare", visibility)
const surfaceRevision = surface(first, "bare:0").transition!.revision
first.complete("bare", "surface", surfaceRevision)
await surfaceWaiting
@@ -107,7 +106,6 @@ first.complete("bare", "surface", removalRevision)
await surfaceRemoval
assert.equal(represented(first, "bare:0").surface, null)
-assert.throws(() => first.setSurface("ordinary", visibility), /window-layer/)
assert.equal(represented(second, "bare:0").surface, null)
first.release("bare")
@@ -137,13 +135,12 @@ const calls: unknown[][] = []
const localWindow = {
state(identity: string) { return { position: identity === "target" ? { x: 70, y: 80 } : { x: 0, y: 0 } } },
move(identity: string, value: unknown, motion: Transaction | undefined) { calls.push(["move", identity, value, motion]) },
- setSurface(identity: string, motion: Transaction) { calls.push(["set", identity, motion]) },
+ addSurface(identity: string, motion: Transaction) { calls.push(["add", identity, motion]) },
removeSurface(identity: string, motion: Transaction) { calls.push(["remove", identity, motion]) }
}
const processManager = {
processes,
front: ClientProcessManager.prototype.front,
- scope: ClientProcessManager.prototype.scope,
async ownFrame() {},
async releaseFrame() {},
async unsubscribeFrame() {}
@@ -151,27 +148,28 @@ const processManager = {
const authManager = {
processManager,
programManager: { programs: new Map() },
- async permissionGranted() { return true }
}
-const pointer = { snapshot: () => ({ position: { x: 12, y: 24 } }) }
-const request = host(authManager as never, requester.identity, () => ({ size: { width: 1, height: 1 } }), () => "owner", pointer as never, localWindow as never)
+const request = host(authManager as never, requester.identity, () => ({ size: { width: 1, height: 1 } }), () => "owner", localWindow as never)
assert.deepEqual(await request("desktopSurface"), [{ size: { width: 1, height: 1 } }])
-assert.deepEqual(await request("desktopPointer"), [{ position: { x: 12, y: 24 } }])
const targetAddress = { identity: target.identity, reference: target.reference }
-assert.deepEqual(await request("windowLocal", targetAddress), [{ position: { x: 70, y: 80 } }])
-await request("windowLocalMove", targetAddress, { x: 70, y: 80 })
-await request("windowLocalSurfaceSet", targetAddress, visibility)
-await request("windowLocalSurfaceRemove", targetAddress, visibility)
+const requesterAddress = { identity: requester.identity, reference: requester.reference }
+await request("windowLocalMove", requesterAddress, { x: 70, y: 80 })
+await request("windowLocalSurfaceAdd", requesterAddress, undefined, visibility)
+await request("windowLocalSurfaceRemove", requesterAddress, undefined, visibility)
assert.deepEqual(calls, [
- ["move", "target", { x: 70, y: 80 }, undefined],
- ["set", "target", visibility],
- ["remove", "target", visibility]
+ ["move", "requester", { x: 70, y: 80 }, undefined],
+ ["add", "requester", visibility],
+ ["remove", "requester", visibility]
])
assert.deepEqual(target.client.window.position, { x: 10, y: 20 })
-await assert.rejects(request("windowLocalSurfaceSet", targetAddress, { identity: "unexpected" }), /no "identity" field/)
-await assert.rejects(request("windowLocalSurfaceSet", { ...targetAddress, reference: "wrong" }, visibility), /does not know this process/)
+await assert.rejects(request("windowLocalSurfaceAdd", requesterAddress, undefined, { identity: "unexpected" }), /no "identity" field/)
+await assert.rejects(request("windowLocalSurfaceAdd", targetAddress), /current Client Context/)
+await assert.rejects(request("windowLocalSurfaceAdd", { ...requesterAddress, reference: "wrong" }), /represented by this handle does not exist/)
+requester.client.window.layer = "window"
+await assert.rejects(request("windowLocalMove", requesterAddress, { x: 0, y: 0 }), /window-layer Process/)
+requester.client.window.layer = "over"
const lifecycle: string[] = []
const boundary = new ClientProcessBoundary(
@@ -180,7 +178,6 @@ const boundary = new ClientProcessBoundary(
authManager as never,
() => ({ size: { width: 1, height: 1 } }),
{} as never,
- {} as never,
{ release(identity: string) { lifecycle.push(identity) } } as never
)
diff --git a/scripts/contracts/gateway-api.ts b/scripts/contracts/gateway-api.ts
index e3c2c5a..96713bd 100644
--- a/scripts/contracts/gateway-api.ts
+++ b/scripts/contracts/gateway-api.ts
@@ -43,28 +43,6 @@ const system = {
calls.push(["query", database])
return [{ statement, values }]
},
- programPermissions(owner: unknown) {
-
- assert.equal(owner, program)
- calls.push(["permission", "getAll"])
- return { pointer: true }
- },
- programPermission(owner: unknown, name: string) {
-
- assert.equal(owner, program)
- calls.push(["permission", "get", name])
- return true
- },
- setProgramPermission(owner: unknown, name: string, value: boolean) {
-
- assert.equal(owner, program)
- calls.push(["permission", "set", name, value])
- },
- deleteProgramPermission(owner: unknown, name: string) {
-
- assert.equal(owner, program)
- calls.push(["permission", "delete", name])
- },
listProcesses(owner: unknown) {
assert.equal(owner, program)
@@ -150,38 +128,6 @@ assert.deepEqual(await apiRequest(application, {
values: [1]
}, signal), [{ statement: "select ?", values: [1] }])
-assert.deepEqual(await apiRequest(application, {
- capability: "program",
- operation: "permission",
- handle,
- permissionOperation: "getAll"
-}, signal), { pointer: true })
-
-assert.equal(await apiRequest(application, {
- capability: "program",
- operation: "permission",
- handle,
- permissionOperation: "get",
- name: "pointer"
-}, signal), true)
-
-await apiRequest(application, {
- capability: "program",
- operation: "permission",
- handle,
- permissionOperation: "set",
- name: "pointer",
- value: false
-}, signal)
-
-await apiRequest(application, {
- capability: "program",
- operation: "permission",
- handle,
- permissionOperation: "delete",
- name: "pointer"
-}, signal)
-
assert.equal(await apiRequest(application, {
capability: "program",
operation: "wait",
@@ -239,10 +185,6 @@ assert.deepEqual(calls, [
["agent"],
["store", "get", "state", undefined, undefined],
["query", "logs"],
- ["permission", "getAll"],
- ["permission", "get", "pointer"],
- ["permission", "set", "pointer", false],
- ["permission", "delete", "pointer"],
["observe", "program", "uninstall"],
["observe", "program", "forget"],
["process", "list"],
diff --git a/scripts/contracts/permissions.ts b/scripts/contracts/permissions.ts
new file mode 100644
index 0000000..0729f6c
--- /dev/null
+++ b/scripts/contracts/permissions.ts
@@ -0,0 +1,63 @@
+import assert from "node:assert/strict"
+import { PermissionCatalog, permissionCatalog } from "@server/core/permissions"
+
+const catalog = new PermissionCatalog({
+ files: {
+ values: ["read", "write"],
+ default: ["read"],
+ activation: "live",
+ title: "Files",
+ description: "Access selected files."
+ },
+ environment: {
+ values: [],
+ default: [],
+ activation: "reload",
+ title: "Environment",
+ description: "Access the Client environment."
+ }
+})
+
+assert.deepEqual(catalog.resolve("files", true), ["read"])
+assert.deepEqual(catalog.resolve("files", ["write", "read"]), ["read", "write"])
+assert.deepEqual(catalog.resolve("environment", true), [])
+assert.equal(catalog.resolve("files", false), false)
+assert.equal(catalog.resolve("files", null), null)
+
+assert.deepEqual(catalog.declarations({ files: true, environment: [] }), {
+ files: ["read"],
+ environment: []
+})
+assert(Object.isFrozen(catalog.declarations({})))
+assert(Object.isFrozen(catalog.declarations({ files: true }).files))
+
+assert(catalog.grants(["read", "write"], ["write"]))
+assert(!catalog.grants(false, ["read"]))
+assert(!catalog.grants(null, []))
+assert(catalog.grants([], []))
+assert.equal(catalog.combine("files", null, false), null)
+assert.deepEqual(catalog.combine("files", ["write"], ["read"]), ["read", "write"])
+assert.equal(catalog.effective("files", null, false), false)
+assert.deepEqual(catalog.effective("files", ["read"], false), ["read"])
+assert.deepEqual(catalog.effective("environment", []), [])
+assert.deepEqual(catalog.merge("files", ["read"], ["write"]), ["read", "write"])
+
+assert(!catalog.needReload("files", true))
+assert(!catalog.needReload("environment", false))
+assert(catalog.needReload("environment", true))
+
+assert.throws(() => catalog.resolve("unknown", true), /does not know/)
+assert.throws(() => catalog.resolve("files", ["delete"]), /unknown value/)
+assert.throws(() => catalog.resolve("files", ["read", "read"]), /unknown value/)
+assert.throws(() => catalog.stored({ files: true }), /unresolved shorthand/)
+assert.throws(() => new PermissionCatalog({
+ invalid: {
+ values: ["read"],
+ default: ["write"],
+ activation: "live",
+ title: "Invalid",
+ description: "Invalid default."
+ }
+}), /invalid default/)
+
+assert.throws(() => permissionCatalog.definition("files"), /does not know/)
diff --git a/scripts/contracts/process-find-or-create.ts b/scripts/contracts/process-find-or-create.ts
index 31825c4..dbedbbd 100644
--- a/scripts/contracts/process-find-or-create.ts
+++ b/scripts/contracts/process-find-or-create.ts
@@ -18,6 +18,7 @@ interface FixtureManager {
const processes = new Map<string, FixtureProcess>()
const program = {
identity: "example",
+ reference: "example-reference",
server: { start: true },
client: {
start: true,
@@ -65,8 +66,8 @@ const launch = {
}
const [first, second] = await Promise.all([
- manager.findOrCreateProcess(program.identity, launch),
- manager.findOrCreateProcess(program.identity, {
+ manager.findOrCreateProcess(program, launch),
+ manager.findOrCreateProcess(program, {
name: "shared",
server: true,
client: false,
@@ -78,7 +79,7 @@ assert.equal(first, second)
assert.equal(starts, 1)
await assert.rejects(
- manager.findOrCreateProcess(program.identity, {
+ manager.findOrCreateProcess(program, {
name: "shared",
server: false,
client: true,
@@ -109,3 +110,8 @@ const activated = fixture.resolveLaunch(program, {
assert.equal(activated.server?.service, true)
assert.equal(activated.client?.service, true)
+
+const stale = { identity: program.identity, reference: "replaced-program-reference" } as unknown as Program
+
+await assert.rejects(manager.createProcess(stale), /represented by this handle does not exist/)
+await assert.rejects(manager.findOrCreateProcess(stale, { name: "stale" }), /represented by this handle does not exist/)
diff --git a/scripts/contracts/program-frame.tsx b/scripts/contracts/program-frame.tsx
index 8c83bce..5bbd46e 100644
--- a/scripts/contracts/program-frame.tsx
+++ b/scripts/contracts/program-frame.tsx
@@ -11,7 +11,6 @@ const common = {
client,
title: "Program",
door: "/program",
- access: "available" as const,
onFrame() {},
onLoad() {}
}
@@ -21,3 +20,4 @@ const light = renderToStaticMarkup(<ProgramFrame {...common} theme="light" />)
assert.match(dark, /style="color-scheme:dark"/)
assert.match(light, /style="color-scheme:light"/)
+assert.doesNotMatch(dark, /sandbox=/)
diff --git a/scripts/contracts/storage.ts b/scripts/contracts/storage.ts
index 9252c39..1b62040 100644
--- a/scripts/contracts/storage.ts
+++ b/scripts/contracts/storage.ts
@@ -3,6 +3,7 @@ import { mkdirSync, mkdtempSync, readdirSync, rmSync, symlinkSync, writeFileSync
import { tmpdir } from "node:os"
import { join } from "node:path"
import FileArea from "@libs/file-area"
+import AuthManager from "@server/core/link-manager/auth-manager/auth-manager"
const fixture = mkdtempSync(join(tmpdir(), "phreshos-storage-"))
const root = join(fixture, "configured")
@@ -10,6 +11,16 @@ const outside = join(fixture, "outside")
try {
const storage = new FileArea(root)
+ const home = new FileArea(join(fixture, "home"))
+ const authManager = Object.assign(Object.create(AuthManager.prototype), {
+ linkManager: { application: { home, storage: { path: root } } },
+ $outbound: { async publish() {} }
+ }) as AuthManager
+ const systemStorage = (AuthManager.prototype as unknown as {
+ storage(operation: unknown, values: unknown): Promise<unknown>
+ }).storage
+
+ assert.equal(await systemStorage.call(authManager, "path", []), home.path)
mkdirSync(join(root, "kept"), { recursive: true })
mkdirSync(join(root, "nested"), { recursive: true })
diff --git a/source/client/core/application.ts b/source/client/core/application.ts
index 4c98566..98eb3e2 100644
--- a/source/client/core/application.ts
+++ b/source/client/core/application.ts
@@ -120,7 +120,7 @@ export default class Application {
}
}
- public async storageStream(request: Omit<StorageRequest, "operation">, authorization: string, signal?: AbortSignal) {
+ public async storageStream(request: StorageTarget, authorization: string, signal?: AbortSignal) {
const response = await this.storage({ ...request, operation: "stream" }, null, authorization, signal)
@@ -129,7 +129,7 @@ export default class Application {
return response.body
}
- public async storageWrite(request: Omit<StorageRequest, "operation">, body: ClientBody, authorization: string, signal?: AbortSignal) {
+ public async storageWrite(request: StorageTarget, body: ClientBody, authorization: string, signal?: AbortSignal) {
await this.storage({ ...request, operation: "write" }, body, authorization, signal)
}
@@ -170,6 +170,10 @@ export default class Application {
}
}
+type StorageTarget = StorageRequest extends infer Request
+ ? Request extends StorageRequest ? Omit<Request, "operation"> : never
+ : never
+
function framedBody<Metadata>(metadata: Metadata, body: ClientBody | null) {
return body instanceof ReadableStream ? frame(metadata, body) : frameBlob(metadata, body)
diff --git a/source/client/core/link-manager/auth-manager/auth-manager.ts b/source/client/core/link-manager/auth-manager/auth-manager.ts
index 2f0584d..2bf6788 100644
--- a/source/client/core/link-manager/auth-manager/auth-manager.ts
+++ b/source/client/core/link-manager/auth-manager/auth-manager.ts
@@ -5,7 +5,7 @@ import ProgramManager from "./program-manager/program-manager"
import DialogManager from "./dialog-manager"
import { TheLink } from "@the-link/core"
import LinkManager from "../link-manager"
-import { type PermissionDecision, type PermissionName } from "@phreshos/core"
+import { type PermissionChange, type PermissionRequest } from "@phreshos/core"
export default class AuthManager extends TheLink {
@@ -48,26 +48,29 @@ export default class AuthManager extends TheLink {
this.linkManager.emitToSession(`/auth${event}`, this.authorization, ...values)
}
- /** Reads one effective permission for the structurally identified Process. */
- public async permissionGranted(process: string, permission: PermissionName): Promise<PermissionDecision> {
+ public async storage(operation: string, values: string[]) {
- return await this.$outbound.publishFirst("/permission/granted", process, permission) as PermissionDecision
+ return await this.$outbound.publishFirst("/storage", operation, values)
}
- /** Requests one permission until the iframe boundary cancels or authority decides. */
- public async requestPermission(process: string, permission: PermissionName, signal: AbortSignal): Promise<PermissionDecision> {
+ public async updateAppearance(value: unknown) {
- const request = crypto.randomUUID()
+ return await this.$outbound.publishFirst("/appearance/update", value)
+ }
+
+ public async permission(process: string, name: string) {
- const cancel = () => { this.$outbound.publish("/permission/cancel", request, process).catch(() => undefined) }
+ return await this.$outbound.publishFirst("/permission/get", process, name)
+ }
- if (signal.aborted) return null
+ public async requestPermission(process: string, request: string, name: string, permission: PermissionRequest) {
- signal.addEventListener("abort", cancel, { once: true })
+ return await this.$outbound.publishFirst("/permission/request", request, process, name, permission) as PermissionChange
+ }
- try { return await this.$outbound.publishFirst("/permission/request", request, process, permission) as PermissionDecision }
+ public async cancelPermission(process: string, request: string) {
- finally { signal.removeEventListener("abort", cancel) }
+ await this.$outbound.publish("/permission/cancel", request, process)
}
public disconnect() {
diff --git a/source/client/core/link-manager/auth-manager/process-manager/process-manager.ts b/source/client/core/link-manager/auth-manager/process-manager/process-manager.ts
index 1489f52..e253d22 100644
--- a/source/client/core/link-manager/auth-manager/process-manager/process-manager.ts
+++ b/source/client/core/link-manager/auth-manager/process-manager/process-manager.ts
@@ -5,10 +5,9 @@ import { Publish, Subscribe } from "@the-link/core/decorators"
import { TheLink } from "@the-link/core"
import AuthManager from "../auth-manager"
import Process from "./process"
-import ProcessScope from "./process-scope"
import { type ClientLaunch, type ServerLaunch } from "@phreshos/core"
import { type TrafficKind } from "@server/core/link-manager/auth-manager/process-manager/process-traffic"
-import { isPermissionName, type ServiceKey, type WindowLayer } from "@phreshos/core"
+import { type ServiceKey, type WindowLayer } from "@phreshos/core"
import { type ServiceScope } from "@server/core/link-manager/auth-manager/process-manager/endpoint-services"
/**
@@ -43,12 +42,6 @@ export default class ProcessManager extends TheLink {
return [...this.processes.values()]
}
- /** Bind application operations and visibility policy to one framed Process. */
- public scope(pane: string) {
-
- return new ProcessScope(this, pane)
- }
-
/** The shown authoritative Window at the front of one projected layer. */
public front(layer: WindowLayer) {
@@ -199,14 +192,6 @@ export default class ProcessManager extends TheLink {
await this.$outbound.publish("/endpoint/stop", identity, which)
}
- @Subscribe("/permission")
- protected async permissionChanged(identity: unknown, permission: unknown, decision: unknown) {
-
- if (typeof identity !== "string" || !isPermissionName(permission) || (decision !== true && decision !== false && decision !== null)) return
-
- await this.$inbound.publish("/permission-changed", identity, permission, decision)
- }
-
/** Announces a locally changed counterpart to desktop representations. */
public async changed() {
diff --git a/source/client/core/link-manager/auth-manager/process-manager/process-scope.ts b/source/client/core/link-manager/auth-manager/process-manager/process-scope.ts
deleted file mode 100644
index bb3f0a7..0000000
--- a/source/client/core/link-manager/auth-manager/process-manager/process-scope.ts
+++ /dev/null
@@ -1,155 +0,0 @@
-import { type WindowLayer } from "@phreshos/core"
-import { type default as Process } from "./process"
-import { type default as ProcessManager } from "./process-manager"
-
-/**
- * The Core capability scope of one framed Client Process.
- *
- * View supplies only the pane that received a request. This scope resolves
- * every domain subject from that structural fact, so presentation never owns
- * cross-Program visibility or Window mutability policy.
- */
-export default class ProcessScope {
-
- public constructor(public readonly processManager: ProcessManager, public readonly pane: string) { }
-
- public current() {
-
- const found = this.processManager.processes.get(this.pane)
-
- if (!found) throw new Error("The desktop does not know this process")
-
- return found
- }
-
- public related(named: unknown) {
-
- if (!isHandleAddress(named)) return null
-
- const found = this.processManager.processes.get(named.identity)
-
- return found?.reference === named.reference && found.program === this.current().program ? found : null
- }
-
- public sibling(named: unknown) {
-
- const found = this.related(named)
-
- if (!found) throw new Error("The desktop does not know this process")
-
- return found
- }
-
- public window(named: unknown) {
-
- const found = this.sibling(named).client?.window
-
- if (!found) throw new Error("This process has no live client endpoint")
-
- return found
- }
-
- public mutableWindow(named: unknown) {
-
- const found = this.window(named)
-
- return found
- }
-
- public localProcess(named: unknown) {
-
- const found = this.sibling(named)
-
- if (!found.client) throw new Error("This process has no live client endpoint")
-
- return found
- }
-
- public declared(found: Process, half: "server" | "client") {
-
- return (this.processManager.authManager.programManager.programs.get(found.program)?.[half] ?? null) !== null
- }
-
- public programOf(found: Pick<Process, "program">) {
-
- const program = this.processManager.authManager.programManager.programs.get(found.program)
-
- if (!program) throw new Error("The desktop does not know this program")
-
- return program
- }
-
- /** Resolve the current Process's live, same-Program parent. */
- public parent(found: Process) {
-
- const address = found.parent
-
- if (!address) return null
-
- const parent = this.processManager.processes.get(address.identity)
-
- if (!parent || parent.reference !== address.reference) throw new Error("The parent Process no longer exists")
-
- return parent.program === this.current().program ? parent : null
- }
-
- /** Whether a handle has ended or is outside this pane's Program scope. */
- public exited(address: HandleAddress) {
-
- const found = this.processManager.processes.get(address.identity)
-
- return !found || found.reference !== address.reference || found.program !== this.current().program
- }
-
- /** Every live Process belonging to this pane's Program. */
- public processes() {
-
- return [...this.processManager.processes.values()].filter(entry => entry.program === this.current().program)
- }
-
- /** Resolve one same-Program Process by identity first, then by local name. */
- public findProcess(wanted: string) {
-
- const program = this.current().program
-
- const identified = this.processManager.processes.get(wanted)
-
- if (identified?.program === program) return identified
-
- return [...this.processManager.processes.values()].find(entry => entry.program === program && entry.name === wanted) ?? null
- }
-
- /** Resolve a trusted Process identity returned by an application operation. */
- public requireProcess(identity: string) {
-
- const found = this.processManager.processes.get(identity)
-
- if (!found) throw new Error("The desktop does not know this process")
-
- return found
- }
-
- /** The Program that owns this pane. */
- public program() {
-
- return this.programOf(this.current())
- }
-
- public front(layer: WindowLayer) {
-
- return this.processManager.front(layer)
- }
-}
-
-function isHandleAddress(value: unknown): value is HandleAddress {
-
- return typeof value === "object" && value !== null && "identity" in value && "reference" in value
- && typeof value.identity === "string" && typeof value.reference === "string"
-}
-
-interface HandleAddress {
-
- identity: string
-
- reference: string
-}
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.ts
index 86f00a2..d601f11 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
@@ -4,7 +4,7 @@ import { Publish, Subscribe } from "@the-link/core/decorators"
import { TheLink } from "@the-link/core"
import AuthManager from "../auth-manager"
import Program from "./program"
-import { type Launch, type ProgramCommandChunk, type ProgramIconSize } from "@phreshos/core"
+import { type Launch, type PermissionInput, type ProgramCommandChunk, type ProgramIconSize } from "@phreshos/core"
/**
* The peer of the core's programs: born holding them from the
@@ -14,9 +14,9 @@ import { type Launch, type ProgramCommandChunk, type ProgramIconSize } from "@ph
* Keyed by the program's public identity. A display name addresses
* nothing and may be shared.
*
- * The trusted desktop may install, uninstall, or forget a Program only
- * after deriving that Program from a frame. These methods take the
- * already-resolved subject; no client-provided identity is forwarded.
+ * Operations forward exact handles rather than reusable identities. Core
+ * validates the handle again, so a retained Program can never retarget a
+ * replacement that later claims the same public identity.
*/
export default class ProgramManager extends TheLink {
@@ -41,32 +41,51 @@ export default class ProgramManager extends TheLink {
// pane's store words with this, so a client half means the same
// thing by them as a server half does — one implementation, two
// roads to it.
- public async store(identity: string, operation: string, key: string, value?: unknown, ttl?: number) {
+ public async store(subject: unknown, operation: string, key: string, value?: unknown, ttl?: number) {
- return await this.$outbound.publishFirst("/store", identity, operation, key, value, ttl)
+ return await this.$outbound.publishFirst("/store", subject, operation, key, value, ttl)
}
- // Another instance of a program. Which program is the desktop's to
- // decide before it asks — from the frame, for a pane; from the list,
- // for its own controls.
- public async createProcess(identity: string, launch: Launch = {}, parent?: string) {
+ // Another instance of the exact Program represented by the supplied
+ // handle.
+ public async createProcess(subject: unknown, launch: Launch = {}, parent?: string) {
- return await this.$outbound.publishFirst("/create-process", identity, launch, parent) as string
+ return await this.$outbound.publishFirst("/create-process", subject, launch, parent) as string
}
- /** Atomically resolves one named Process at the authoritative host. */
- public async findOrCreateProcess(identity: string, launch: Launch & { name: string }, parent?: string) {
+ public async create(source: unknown) {
+
+ return await this.$outbound.publishFirst("/create-program", source) as string
+ }
+
+ public async forceCreate(source: unknown, asker: string) {
+
+ return await this.$outbound.publishFirst("/force-create-program", source, asker) as string
+ }
+
+ public async fork(subject: unknown, identity: string) {
+
+ return await this.$outbound.publishFirst("/fork-program", subject, identity) as string
+ }
+
+ public async startup(subject: unknown, operation: string, value?: unknown) {
+
+ return await this.$outbound.publishFirst("/startup", subject, operation, value)
+ }
- return await this.$outbound.publishFirst("/find-or-create-process", identity, launch, parent) as string
+ public async permissions(subject: unknown, operation: "all" | "get" | "set" | "delete", name?: string, value?: Exclude<PermissionInput, null>) {
+
+ return await this.$outbound.publishFirst("/permissions", subject, operation, name, value)
}
- public async install(identity: string, asker: string) {
+ /** Atomically resolves one named Process at the authoritative host. */
+ public async findOrCreateProcess(subject: unknown, launch: Launch & { name: string }, parent?: string) {
- return await this.$outbound.publishFirst("/install-program", identity, asker)
+ return await this.$outbound.publishFirst("/find-or-create-process", subject, launch, parent) as string
}
- /** Streams one authoritative uninstall operation to its requesting View. */
- public uninstallStreaming(identity: string, everything: boolean, asker: string) {
+ /** 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> {
@@ -75,7 +94,7 @@ export default class ProgramManager extends TheLink {
manager.commands.set(stream, state)
- const operation = manager.$outbound.publishFirst("/uninstall-program-stream", identity, everything, asker, stream).then(
+ 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(() => {
@@ -97,51 +116,52 @@ export default class ProgramManager extends TheLink {
await new Promise<void>(resolve => { state.wake = resolve })
}
- await operation
+ await pending
if (state.failure) throw state.failure
}
finally {
manager.commands.delete(stream)
+ manager.$outbound.publish("/client-command-cancel", stream).catch(() => undefined)
}
})()
}
- public async forget(identity: string, asker: string) {
+ public async forget(subject: unknown, asker: string) {
- return await this.$outbound.publishFirst("/forget-program", identity, asker)
+ return await this.$outbound.publishFirst("/forget-program", subject, asker)
}
// One of a Program's metadata operations, asked of the core. Byte
// content takes the storage door instead of the serialized link.
- public async area(identity: string, area: "data" | "cache", operation: string, args: unknown[]) {
+ public async area(subject: unknown, area: "data" | "cache", operation: string, args: unknown[]) {
- return await this.$outbound.publishFirst("/area", identity, area, operation, args)
+ return await this.$outbound.publishFirst("/area", subject, area, operation, args)
}
// What a program has said, asked of the core. Read-only there, so
// nothing on this side has to decide what a query means.
- public async logs(identity: string, sql: string, values: unknown[]) {
+ public async logs(subject: unknown, sql: string, values: unknown[]) {
- return await this.$outbound.publishFirst("/logs", identity, sql, values)
+ return await this.$outbound.publishFirst("/logs", subject, sql, values)
}
// A program's own database, asked of the core.
- public async database(identity: string, sql: string, values: unknown[]) {
+ public async database(subject: unknown, sql: string, values: unknown[]) {
- return await this.$outbound.publishFirst("/database", identity, sql, values)
+ return await this.$outbound.publishFirst("/database", subject, sql, values)
}
/** Request one rendered icon from the authoritative server Program. */
- public async icon(identity: string, size: ProgramIconSize) {
+ public async icon(subject: unknown, size: ProgramIconSize) {
- return await this.$outbound.publishFirst("/icon", identity, size) as number[]
+ return await this.$outbound.publishFirst("/icon", subject, size) as number[]
}
/** Reads Program-specific operating knowledge from authoritative Core. */
- public async agent(identity: string) {
+ public async agent(subject: unknown) {
- return await this.$outbound.publishFirst("/agent", identity) as string | null
+ return await this.$outbound.publishFirst("/agent", subject) as string | null
}
@Subscribe("/install")
@@ -174,7 +194,7 @@ export default class ProgramManager extends TheLink {
return this.arrived(payload)
}
- @Subscribe("/uninstall-program-output")
+ @Subscribe("/client-command-output")
protected commandOutput(stream: string, value: unknown) {
const state = this.commands.get(stream)
@@ -200,8 +220,12 @@ export default class ProgramManager extends TheLink {
if (!identity) return
+ const program = this.programs.get(identity)
+
this.programs.delete(identity)
+ if (program) await this.$inbound.publish("/forgotten", program)
+
return [...this.programs.values()]
}
}
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.ts
index feb12e9..f97c13c 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
@@ -1,6 +1,7 @@
import { HostedEntry } from "@server/core/link-manager/auth-manager/program-manager/entry"
import { type Launch } from "@phreshos/core"
import ProgramManager from "./program-manager"
+import type { Transmitted } from "@libs/messagepack"
/**
* A program this session knows about, rebuilt from what the core
@@ -31,11 +32,11 @@ export default class Program {
public readonly hasAgent: boolean
- public readonly server: HostedEntry["server"]
+ public readonly server: Transmitted<HostedEntry>["server"]
- public readonly client: HostedEntry["client"]
+ public readonly client: Transmitted<HostedEntry>["client"]
- public constructor(programManager: ProgramManager, payload: HostedEntry) {
+ public constructor(programManager: ProgramManager, payload: Transmitted<HostedEntry>) {
this.programManager = programManager
@@ -62,23 +63,28 @@ export default class Program {
public async createProcess(launch: Launch = {}) {
- await this.programManager.$outbound.publish("/create-process", this.identity, launch)
+ await this.programManager.$outbound.publish("/create-process", this.address, launch)
}
- public async install(asker: string) {
+ public install(asker: string) {
- await this.programManager.install(this.identity, asker)
+ return this.programManager.command(this.address, "install", undefined, asker)
}
// False removes only installed program files. True removes everything
// owned by the system and forgets the runtime Program.
public uninstall(everything = false, asker = "") {
- return this.programManager.uninstallStreaming(this.identity, everything, asker)
+ return this.programManager.command(this.address, "uninstall", everything, asker)
}
public async forget(asker: string) {
- await this.programManager.forget(this.identity, asker)
+ await this.programManager.forget(this.address, asker)
+ }
+
+ private get address() {
+
+ return { identity: this.identity, reference: this.reference }
}
}
diff --git a/source/client/view/components/desktop-host/announcements.ts b/source/client/view/components/desktop-host/announcements.ts
index 2e23d49..c8f4814 100644
--- a/source/client/view/components/desktop-host/announcements.ts
+++ b/source/client/view/components/desktop-host/announcements.ts
@@ -4,203 +4,104 @@ import { ReactTunnel } from "@the-link/react"
import { useCallback } from "react"
import ClientProcessBoundary from "./client-process-boundary"
import ClientTraffic from "./client-traffic"
-import { sdkProcess } from "./sdk-records"
-
-/**
- * Host facts routed to the client Process boundaries that may represent them.
- *
- * Structural isolation is decided here: a pane can be offered only facts about
- * itself and its own Program. The boundary joins a desktop-local `the-link`
- * route only after its endpoint subscribes, so an uninterested boundary is not
- * entered at all. Eligibility and interest are separate decisions, and neither
- * is inferred by application code.
- *
- * Three kinds are eligible. A pane's **own Program's windows** — relayed
- * exactly as the system said them, because the system is what decided a
- * window moved or took focus and a second opinion here would be a second
- * answer. Its **own Program's** processes coming and going,
- * so a client half that can list its instances can also know when the
- * list changed without polling for it. And a **process ending**, to the
- * panes that could be holding that process — which is every pane of its
- * program, since a pane can hold no other.
- *
- * Nothing about another program is routed to anyone, at any point.
- *
- * A server half reaches the same facts through its own subscribed host routes;
- * the desktop does not reinterpret them.
- */
+import { sdkProcess, sdkProgram } from "./sdk-records"
+
+/** Projects authoritative System announcements into every Client frame. */
export default function useAnnouncements(authManager: AuthManager, panes: Map<string, ClientProcessBoundary>, traffic: ClientTraffic) {
- // Two tunnels, because there are two managers and each carries its
- // own words. A subscription put on the wrong one is silent forever
- // and looks exactly like a subscription that is simply never
- // triggered — which is what happened to `/uninstall`, added next to
- // its neighbours without checking they travelled the same road.
const processes = ReactTunnel.useFactory(authManager.processManager.$inbound)
-
const programs = ReactTunnel.useFactory(authManager.programManager.$inbound)
- const announce = useCallback(function (identity: string, route: string, ...args: unknown[]) {
-
- traffic.emit(identity, route, ...args).catch(() => undefined)
-
- }, [traffic])
-
- const post = useCallback(function (offers: Offer[]) {
-
- for (const [pane, ...message] of offers) announce(pane, ...message)
-
- }, [announce])
-
- processes.useSubscribe("/created", useCallback((...results: unknown[]) => {
+ const post = useCallback(function (route: string, ...message: unknown[]) {
- const [payload] = results as [ExitedProcess | null]
+ for (const pane of panes.keys()) traffic.emit(pane, route, ...message).catch(() => undefined)
- if (payload) post(created(authManager, whose(authManager, panes), payload))
+ }, [panes, traffic])
- }, [post, authManager, panes]))
+ processes.useSubscribe("/created", useCallback((payload: ProcessRecord | null) => {
- processes.useSubscribe("/exited", useCallback((...results: unknown[]) => {
+ if (!payload) return
- const [process, code, signal] = results as [ExitedProcess | null, number | null, string | null]
+ const record = processRecord(authManager, payload)
- if (process) post(exited(authManager, whose(authManager, panes), process, code, signal))
+ post("host-process", "create", payload.program, record)
+ post("program-process", "create", program(authManager, payload.program).reference, record)
- }, [post, authManager, panes]))
+ }, [authManager, post]))
- const changed = useCallback((event: EndpointEvent, endpointKind: EndpointKind, results: unknown[]) => {
+ processes.useSubscribe("/exited", useCallback((payload: ProcessRecord | null, code: number | null, signal: string | null) => {
- const [identity, payload] = results as [string | null, ExitedProcess | null]
+ if (!payload) return
- if (identity && payload) post(endpoint(authManager, whose(authManager, panes), event, endpointKind, payload))
+ const record = processRecord(authManager, payload)
- }, [post, authManager, panes])
+ post("host-process", "exit", payload.program, record, code, signal)
+ post("program-process", "exit", program(authManager, payload.program).reference, record, code, signal)
+ post("process-host", "exit", payload.reference, code, signal)
- processes.useSubscribe("/server-start", useCallback((...results: unknown[]) => changed("endpointStart", "server", results), [changed]))
+ }, [authManager, post]))
- processes.useSubscribe("/server-stop", useCallback((...results: unknown[]) => changed("endpointStop", "server", results), [changed]))
+ const endpoint = useCallback((event: "endpointStart" | "endpointStop", endpoint: "server" | "client", payload: ProcessRecord | null) => {
- processes.useSubscribe("/client-start", useCallback((...results: unknown[]) => changed("endpointStart", "client", results), [changed]))
+ if (!payload) return
- processes.useSubscribe("/client-stop", useCallback((...results: unknown[]) => changed("endpointStop", "client", results), [changed]))
+ post("process-host", event, payload.reference, processRecord(authManager, payload), endpoint)
- // A program leaving the list, said to the windows of that program.
- //
- // A pane outlives its own program's removal — uninstalling ends
- // nothing that is running — so there is something left to hear it,
- // and this is the only way one could learn that what it is a face of
- // is no longer on the machine.
- programs.useSubscribe("/uninstall", useCallback((...results: unknown[]) => {
+ }, [authManager, post])
- const [program, everything] = results as [HostedEntry, boolean]
+ processes.useSubscribe("/server-start", useCallback((_identity: unknown, payload: ProcessRecord | null) => endpoint("endpointStart", "server", payload), [endpoint]))
+ processes.useSubscribe("/server-stop", useCallback((_identity: unknown, payload: ProcessRecord | null) => endpoint("endpointStop", "server", payload), [endpoint]))
+ processes.useSubscribe("/client-start", useCallback((_identity: unknown, payload: ProcessRecord | null) => endpoint("endpointStart", "client", payload), [endpoint]))
+ processes.useSubscribe("/client-stop", useCallback((_identity: unknown, payload: ProcessRecord | null) => endpoint("endpointStop", "client", payload), [endpoint]))
- post(uninstalled(whose(authManager, panes), program, everything === true))
-
- }, [post, authManager, panes]))
-
- // Everything a window says, relayed whole to subscribed panes allowed to
- // hold that Client: every pane of its Program, and no pane outside it.
- // The system decided what happened and to which Client; this decides
- // neither again.
- processes.useSubscribe("/said", useCallback((...results: unknown[]) => {
-
- const [identity, event, value] = results as [string, string, unknown]
+ processes.useSubscribe("/said", useCallback((identity: string, event: string, value: unknown) => {
const target = authManager.processManager.processes.get(identity)
- if (!target) return
-
- const eligible = whose(authManager, panes)
- .filter(([, program]) => program === target.program)
- .map(([pane]) => [pane, "host-end", event, target.reference, value] as Offer)
-
- post(eligible)
-
- }, [post, authManager, panes]))
-}
-
-// ── What is routed, and to whom ──────────────────────────────────────
-//
-// Kept out of the hook because this is the part with a rule in it. The
-// hook posts what these decide; these decide it from what the desktop
-// already holds, and from nothing any pane said. A pane cannot ask to be
-// in one of these lists, which is the isolation as a structure rather
-// than as a check.
-
-// Each pane, and the program it is a face of.
-export function whose(authManager: AuthManager, panes: Map<string, unknown>) {
-
- return [...panes.keys()].map(pane => [pane, authManager.processManager.processes.get(pane)?.program] as const)
-}
-
-// The subject leads, exactly as it does on the core's own announcement,
-// so a kit's `Program` filters on it without either side agreeing to
-// anything extra.
-export function created(authManager: AuthManager, panes: readonly (readonly [string, string | undefined])[], process: ExitedProcess): Offer[] {
+ if (target) post("host-end", event, target.reference, value)
- const program = authManager.programManager.programs.get(process.program)
+ }, [authManager, post]))
- if (!program) return []
+ const programEvent = useCallback((event: "create" | "install" | "uninstall" | "forget", entry: HostedEntry | null, everything?: boolean) => {
- return panes.filter(([, identity]) => identity === process.program).map(([pane]) => [pane, "program-process", "create", program.reference, record(authManager, process)])
-}
+ if (!entry) return
-// One ending, said to two subjects. A program watching its instances
-// wants the first; whoever holds this one process wants the second.
-export function exited(authManager: AuthManager, panes: readonly (readonly [string, string | undefined])[], process: ExitedProcess, code: number | null, signal: string | null): Offer[] {
+ const record = sdkProgram(entry)
- // The subject leads both, and what follows is the thing the event is
- // about — the process itself rather than an identity a listener would
- // have to look up. It is already gone, which is what `exited()`
- // answers and why holding it is legitimate.
- //
- // Built here from what the ending carried, because the record was
- // dropped before this was sent — which is why the ending carries
- // when it started at all. A listener handed a process must be handed
- // the whole of one.
- return panes.filter(([, shown]) => shown === process.program).flatMap(([pane]) => [
+ post("host-program", event, entry.identity, record, everything === true)
- [pane, "program-process", "exit", owner(authManager, process).reference, record(authManager, process), code, signal],
+ if (event === "uninstall") post("program-host", event, entry.reference, everything === true)
+ if (event === "forget") post("program-host", event, entry.reference)
- [pane, "process-host", "exit", process.reference, code, signal]
+ }, [post])
- ] as Offer[])
+ programs.useSubscribe("/create", useCallback((entry: HostedEntry | null) => programEvent("create", entry), [programEvent]))
+ programs.useSubscribe("/install", useCallback((entry: HostedEntry | null) => programEvent("install", entry), [programEvent]))
+ programs.useSubscribe("/uninstall", useCallback((entry: HostedEntry | null, everything: boolean) => programEvent("uninstall", entry, everything), [programEvent]))
+ programs.useSubscribe("/forgotten", useCallback((entry: HostedEntry | null) => programEvent("forget", entry), [programEvent]))
}
-export function endpoint(authManager: AuthManager, panes: readonly (readonly [string, string | undefined])[], event: EndpointEvent, endpointKind: EndpointKind, process: ExitedProcess): Offer[] {
+function processRecord(authManager: AuthManager, process: ProcessRecord) {
- const processRecord = record(authManager, process)
-
- return panes
- .filter(([, shown]) => shown === process.program)
- .map(([pane]) => [pane, "process-host", event, process.reference, processRecord, endpointKind])
+ return sdkProcess(process, program(authManager, process.program))
}
-function record(authManager: AuthManager, process: ExitedProcess) {
+function program(authManager: AuthManager, identity: string) {
- return sdkProcess(process, owner(authManager, process))
-}
+ const found = authManager.programManager.programs.get(identity)
-function owner(authManager: AuthManager, process: ExitedProcess) {
+ if (!found) throw new Error("The desktop does not know this program")
- const program = authManager.programManager.programs.get(process.program)
-
- if (!program) throw new Error("The desktop does not know this program")
-
- return program
+ return found
}
-// A program left the installed state, routed to its panes and no others.
-// What comes with it is whether everything the system owned went too.
-export function uninstalled(panes: readonly (readonly [string, string | undefined])[], program: { identity: string, reference: string }, everything: boolean): Offer[] {
-
- return panes.filter(([, shown]) => shown === program.identity).map(([pane]) => [pane, "program-host", "uninstall", program.reference, everything])
+type ProcessRecord = {
+ reference: string
+ identity: string
+ program: string
+ startedAt: Date
+ name: string | null
+ options: Record<string, string>
+ server: { ready: boolean, service: boolean } | null
+ client: { window: unknown, service: boolean } | null
}
-
-type ExitedProcess = { reference: string, identity: string, program: string, startedAt: Date, name: string | null, options: Record<string, string>, server: { ready: boolean, service: boolean } | null, client: { window: unknown, service: boolean } | null }
-
-type EndpointEvent = "endpointStart" | "endpointStop"
-
-type EndpointKind = "server" | "client"
-
-export type Offer = [pane: string, route: string, ...message: unknown[]]
diff --git a/source/client/view/components/desktop-host/client-host.ts b/source/client/view/components/desktop-host/client-host.ts
index 87b25af..3c8c454 100644
--- a/source/client/view/components/desktop-host/client-host.ts
+++ b/source/client/view/components/desktop-host/client-host.ts
@@ -1,10 +1,9 @@
import { ReactTunnel } from "@the-link/react"
-import { isPermissionName, type DesktopSize, type DesktopSurfaceSnapshot } from "@phreshos/core"
+import { type DesktopSize, type DesktopSurfaceSnapshot } from "@phreshos/core"
import useAnnouncements from "./announcements"
-import DesktopPointer from "./pointer"
import ClientProcessBoundary from "./client-process-boundary"
import ClientTraffic from "./client-traffic"
-import { type RefObject, useCallback, useEffect, useLayoutEffect, useRef, useState } from "react"
+import { type RefObject, useCallback, useLayoutEffect, useRef, useState } from "react"
import { type default as AuthManager } from "@client/core/link-manager/auth-manager/auth-manager"
import { type LocalWindowHost } from "./local-window"
import messagepack from "@libs/messagepack"
@@ -24,8 +23,6 @@ export default function useClientHost(authManager: AuthManager, desktop: RefObje
const boundaries = useRef(new Map<string, ClientProcessBoundary>())
- const [pointer] = useState(() => new DesktopPointer(desktop))
-
const [traffic] = useState(() => new ClientTraffic())
const [windowSurfaceSize, setWindowSurfaceSize] = useState<SurfaceSize>({ width: 0, height: 0 })
@@ -110,8 +107,6 @@ export default function useClientHost(authManager: AuthManager, desktop: RefObje
useAnnouncements(authManager, boundaries.current, traffic)
- useEffect(() => pointer.listen(), [pointer])
-
// The process-to-interface leg rides the same tunnel the echoes land on:
// an end-end arrives as (identity, values) and is posted into its pane in
// its envelope. The op's own echo shares the event name with a null
@@ -200,16 +195,6 @@ export default function useClientHost(authManager: AuthManager, desktop: RefObje
}, [sources]))
- inbound.useSubscribe("/permission-changed", useCallback((...results: unknown[]) => {
-
- const [identity, permission, decision] = results
-
- if (typeof identity !== "string" || !isPermissionName(permission) || (decision !== true && decision !== false && decision !== null)) return
-
- boundaries.current.get(identity)?.permissionChanged(permission, decision)
-
- }, []))
-
const frame = useCallback(function (identity: string, element: HTMLIFrameElement | null) {
if (element) {
@@ -218,7 +203,7 @@ export default function useClientHost(authManager: AuthManager, desktop: RefObje
boundaries.current.get(identity)?.release().catch(() => undefined)
- boundaries.current.set(identity, new ClientProcessBoundary(identity, element, authManager, desktopSurface, pointer, traffic, localWindow))
+ boundaries.current.set(identity, new ClientProcessBoundary(identity, element, authManager, desktopSurface, traffic, localWindow))
return
}
@@ -233,7 +218,7 @@ export default function useClientHost(authManager: AuthManager, desktop: RefObje
boundary?.release().catch(() => undefined)
- }, [authManager, desktopSurface, localWindow, pointer, sources, traffic])
+ }, [authManager, desktopSurface, localWindow, sources, traffic])
const frameLoaded = useCallback(function (identity: string, element: HTMLIFrameElement) {
@@ -271,7 +256,7 @@ export default function useClientHost(authManager: AuthManager, desktop: RefObje
task.finally(() => { if (frameTasks.current.get(identity) === task) frameTasks.current.delete(identity) }).catch(() => undefined)
- }, [authManager, pointer, sources])
+ }, [authManager, sources])
// The interface wall: an iframe's end-end relays to its process's
// other end; its end-host terminates here, handled by the desktop —
@@ -314,7 +299,7 @@ export default function useClientHost(authManager: AuthManager, desktop: RefObje
return () => window.removeEventListener("message", onMessage)
- }, [authManager, pointer, sources])
+ }, [authManager, sources])
return { windowSurfaceRef, windowSurfaceSize, frame, frameLoaded }
}
diff --git a/source/client/view/components/desktop-host/client-process-boundary.ts b/source/client/view/components/desktop-host/client-process-boundary.ts
index 839432f..099a8eb 100644
--- a/source/client/view/components/desktop-host/client-process-boundary.ts
+++ b/source/client/view/components/desktop-host/client-process-boundary.ts
@@ -1,18 +1,13 @@
import AuthManager from "@client/core/link-manager/auth-manager/auth-manager"
import { TheLink } from "@the-link/core"
import host, { TransferredAnswer } from "./host"
-import { type PointerHost } from "./pointer"
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 {
- isPermissionName,
- type DesktopPointerPosition,
- type DesktopSurfaceSnapshot,
- type PermissionName
-} from "@phreshos/core"
+import { type DesktopSurfaceSnapshot } from "@phreshos/core"
import { type LocalWindowHost } from "./local-window"
import messagepack from "@libs/messagepack"
+import { sdkProcess, type SdkProcessSource } from "./sdk-records"
/** The desktop boundary around one iframe execution endpoint. */
export default class ClientProcessBoundary extends TheLink {
@@ -25,16 +20,12 @@ export default class ClientProcessBoundary extends TheLink {
private readonly desktop: () => DesktopSurfaceSnapshot
- private readonly pointer: PointerHost
-
private readonly traffic: ClientTraffic
private readonly localWindow: LocalWindowHost
private readonly subscriptions = new Map<string, EndpointSubscription>()
- private readonly blockedSubscriptions = new Map<string, EndpointSubscription>()
-
private readonly expected = new Set<string>()
private readonly requests = new Map<string, () => void>()
@@ -59,15 +50,11 @@ export default class ClientProcessBoundary extends TheLink {
// as later ones.
private readonly pending = new Array<unknown[]>()
- private pointerStop: (() => void) | null = null
-
- private pointerPosition: DesktopPointerPosition | null = null
-
private owner: string | null = null
private leased: string | null = null
- public constructor(pane: string, element: HTMLIFrameElement, authManager: AuthManager, desktop: () => DesktopSurfaceSnapshot, pointer: PointerHost, traffic: ClientTraffic, localWindow: LocalWindowHost) {
+ public constructor(pane: string, element: HTMLIFrameElement, authManager: AuthManager, desktop: () => DesktopSurfaceSnapshot, traffic: ClientTraffic, localWindow: LocalWindowHost) {
super()
@@ -79,8 +66,6 @@ export default class ClientProcessBoundary extends TheLink {
this.desktop = desktop
- this.pointer = pointer
-
this.traffic = traffic
this.localWindow = localWindow
@@ -238,14 +223,7 @@ export default class ClientProcessBoundary extends TheLink {
})
}
- if (values[0] === "pointerSample") {
-
- this.samplePointer(values[1], values[2])
-
- return
- }
-
- host(this.authManager, this.pane, this.desktop, () => this.owner, this.pointer, this.localWindow)(values[0], ...values.slice(1)).catch((error: Error) => {
+ host(this.authManager, this.pane, this.desktop, () => this.owner, this.localWindow)(values[0], ...values.slice(1)).catch((error: Error) => {
if (values[0] === "observe" && typeof values[1] === "string" && values[6] === true) {
@@ -373,18 +351,6 @@ export default class ClientProcessBoundary extends TheLink {
const description = { kind, route, event, subject }
- if (pointerSubscription(description)) {
-
- this.blockedSubscriptions.set(subscription, description)
-
- this.authManager.permissionGranted(this.pane, "pointer").then(decision => {
-
- if (decision === true) this.allowSubscription(subscription)
- }).catch(() => undefined)
-
- return
- }
-
this.subscriptions.set(subscription, description)
if (!localPropertySubscription(description)) this.addTraffic(kind, route, event)
@@ -415,8 +381,6 @@ export default class ClientProcessBoundary extends TheLink {
if (kind === "ask") this.releaseWaiting(route, event)
- this.updatePointer()
-
return
}
@@ -424,8 +388,6 @@ export default class ClientProcessBoundary extends TheLink {
if (typeof args[0] === "string") this.removeSubscription(args[0])
- this.updatePointer()
-
return
}
@@ -465,30 +427,18 @@ export default class ClientProcessBoundary extends TheLink {
return
}
- if (args[0] === "permission-request") {
-
- if (!isPermissionName(args[1])) {
-
- this.deliver("host-end", "answer", question, failed(new Error(`The system does not know the permission "${String(args[1])}"`))).catch(() => undefined)
-
- return
- }
-
- const controller = new AbortController()
+ if (args[0] === "context-permission-request" && typeof args[1] === "string") {
this.answerRequest(
-
question,
-
- this.authManager.requestPermission(this.pane, args[1], controller.signal).then(decision => [decision]),
-
- () => controller.abort()
+ host(this.authManager, this.pane, this.desktop, () => this.owner, this.localWindow)(args[0], ...args.slice(1)),
+ () => { this.authManager.cancelPermission(this.pane, args[1] as string).catch(() => undefined) }
)
return
}
- this.answerRequest(question, host(this.authManager, this.pane, this.desktop, () => this.owner, this.pointer, this.localWindow)(args[0], ...args.slice(1)))
+ this.answerRequest(question, host(this.authManager, this.pane, this.desktop, () => this.owner, this.localWindow)(args[0], ...args.slice(1)))
}
private answerRequest(question: string, operation: Promise<unknown[] | TransferredAnswer>, cancel: () => void = () => undefined) {
@@ -543,9 +493,9 @@ export default class ClientProcessBoundary extends TheLink {
const run = async () => {
await this.deliver("host-end", "stream", question, "open")
- if (args[0] !== "uninstall") throw new Error(`The desktop does not know the stream operation "${String(args[0])}"`)
+ if (args[0] !== "install" && args[0] !== "uninstall" && args[0] !== "run") throw new Error(`The desktop does not know the stream operation "${String(args[0])}"`)
- const operation = this.authManager.processManager.scope(this.pane).program().uninstall(args[2] === true, this.pane)
+ const operation = this.authManager.programManager.command(args[1], args[0], args[2], this.pane)
iterator = operation[Symbol.asyncIterator]()
@@ -554,7 +504,7 @@ export default class ClientProcessBoundary extends TheLink {
if (next.done) break
- await this.deliver("host-end", "stream", question, "data", next.value)
+ await this.deliver("host-end", "stream", question, "data", args[0] === "run" ? runEvent(this.authManager, next.value) : next.value)
}
if (active && this.expected.has(question)) {
@@ -574,15 +524,13 @@ export default class ClientProcessBoundary extends TheLink {
private waitReady(question: string, target: unknown, endpoint: unknown, requireCurrentIncarnation: boolean) {
- const mine = this.authManager.processManager.processes.get(this.pane)
-
const process = target === undefined || target === null
- ? mine
+ ? this.authManager.processManager.processes.get(this.pane)
: isHandleAddress(target)
? this.authManager.processManager.processes.get(target.identity)
: undefined
- if (!mine || !process || mine.program !== process.program || (isHandleAddress(target) && process.reference !== target.reference)) {
+ if (!process || (isHandleAddress(target) && process.reference !== target.reference)) {
this.deliver("host-end", "answer", question, failed(new Error("The desktop does not know this process"))).catch(() => undefined)
@@ -720,8 +668,6 @@ export default class ClientProcessBoundary extends TheLink {
private removeSubscription(subscription: string) {
- this.blockedSubscriptions.delete(subscription)
-
const existing = this.subscriptions.get(subscription)
if (!existing) return
@@ -759,43 +705,6 @@ export default class ClientProcessBoundary extends TheLink {
this.trafficSubscriptions.delete(key)
}
- private allowSubscription(subscription: string) {
-
- const description = this.blockedSubscriptions.get(subscription)
-
- if (!description) return
-
- this.blockedSubscriptions.delete(subscription)
-
- this.subscriptions.set(subscription, description)
-
- this.updatePointer()
- }
-
- /** Applies an authoritative effective-decision change to guarded subscriptions. */
- public permissionChanged(permission: PermissionName, decision: boolean | null) {
-
- if (permission !== "pointer") return
-
- if (decision === true) {
-
- for (const subscription of [...this.blockedSubscriptions.keys()]) this.allowSubscription(subscription)
-
- return
- }
-
- for (const [subscription, description] of [...this.subscriptions]) {
-
- if (!pointerSubscription(description)) continue
-
- this.removeSubscription(subscription)
-
- this.blockedSubscriptions.set(subscription, description)
- }
-
- this.updatePointer()
- }
-
private releaseWaiting(route: string, event: string | null) {
for (const [key, waiting] of this.waiting) {
@@ -859,14 +768,8 @@ export default class ClientProcessBoundary extends TheLink {
for (const stop of this.requests.values()) stop()
- this.pointerStop?.()
-
this.requests.clear()
- this.pointerStop = null
-
- this.pointerPosition = null
-
if (this.owner) for (const [subscription, description] of this.subscriptions) {
if (directSubscription(description)) this.authManager.processManager.unsubscribeFrame(this.pane, this.owner, subscription).catch(() => undefined)
@@ -874,8 +777,6 @@ export default class ClientProcessBoundary extends TheLink {
this.subscriptions.clear()
- this.blockedSubscriptions.clear()
-
this.desktopPreferencesSubscriptions.clear()
this.appearanceSubscriptions.clear()
@@ -899,50 +800,19 @@ export default class ClientProcessBoundary extends TheLink {
this.pending.length = 0
}
- private updatePointer() {
-
- const wanted = [...this.subscriptions.values()].some(pointerSubscription)
-
- if (!wanted) {
-
- this.pointerStop?.()
-
- this.pointerStop = null
-
- this.pointerPosition = null
-
- return
- }
-
- if (this.pointerStop) return
-
- this.pointerPosition = this.pointer.snapshot().position
-
- this.pointerStop = this.pointer.$inbound.subscribe("move", (position: unknown) => {
-
- if (!isPointerPosition(position)) return
-
- this.pointerPosition = position
-
- this.deliver("host-desktop-pointer", "move", { position }).catch(() => undefined)
- })
- }
+}
- // Pointer movement inside a sandboxed iframe does not bubble into the
- // desktop document. Advance the last desktop-space position retained by
- // this boundary, never a frame-relative coordinate.
- private samplePointer(movementX: unknown, movementY: unknown) {
+function runEvent(authManager: AuthManager, value: unknown) {
- const position = this.pointerPosition
+ const event = value as { event?: unknown, process?: SdkProcessSource } | null
- if (!position || typeof movementX !== "number" || typeof movementY !== "number" || !Number.isFinite(movementX) || !Number.isFinite(movementY)) return
+ if ((event?.event !== "started" && event?.event !== "exited") || !event.process) return value
- const next = { x: position.x + Number(movementX), y: position.y + Number(movementY) }
+ const program = authManager.programManager.programs.get(event.process.program)
- this.pointerPosition = next
+ if (!program) throw new Error("The desktop does not know the Process Program")
- this.deliver("host-desktop-pointer", "move", { position: next }).catch(() => undefined)
- }
+ return { ...event, process: sdkProcess(event.process, program) }
}
const nativeAttachments = (value: unknown, transfer: readonly Transferable[]) => {
@@ -993,15 +863,6 @@ const nativeAttachments = (value: unknown, transfer: readonly Transferable[]) =>
return attachments
}
-function isPointerPosition(value: unknown): value is { x: number, y: number } {
-
- if (!value || typeof value !== "object") return false
-
- const position = value as { x?: unknown, y?: unknown }
-
- return typeof position.x === "number" && typeof position.y === "number"
-}
-
interface EndpointSubscription {
kind: TrafficKind
@@ -1013,11 +874,6 @@ interface EndpointSubscription {
subject: string | null
}
-function pointerSubscription(subscription: EndpointSubscription) {
-
- return subscription.kind === "publish" && subscription.route === "host-desktop-pointer" && (subscription.event === null || subscription.event === "move")
-}
-
function desktopPreferencesSubscription(subscription: EndpointSubscription) {
return subscription.kind === "publish" && subscription.route === "host-desktop-preferences" && (subscription.event === null || subscription.event === "change")
diff --git a/source/client/view/components/desktop-host/host.ts b/source/client/view/components/desktop-host/host.ts
index 67f66e0..eb9f8b3 100644
--- a/source/client/view/components/desktop-host/host.ts
+++ b/source/client/view/components/desktop-host/host.ts
@@ -5,15 +5,16 @@ import {
import { type ProxyRequest } from "@server/core/protocol/proxy"
import AuthManager from "@client/core/link-manager/auth-manager/auth-manager"
import { type ClientBody, type ProxiedResponse, type UploadValue } from "@client/core/application"
-import { type PointerHost } from "./pointer"
import { type TrafficKind } from "@server/core/link-manager/auth-manager/process-manager/process-traffic"
import { sdkProcess, sdkProgram } from "./sdk-records"
-import { isPermissionName, isServiceKey, isUploadFile, type DesktopPreferencesUpdate, type ProgramIconSize } from "@phreshos/core"
+import { type default as ClientProgram } from "@client/core/link-manager/auth-manager/program-manager/program"
+import { type default as ClientProcess } from "@client/core/link-manager/auth-manager/process-manager/process"
+import { isServiceKey, isUploadFile, type DesktopPreferencesUpdate, type PermissionRequest, type ProgramIconSize } from "@phreshos/core"
import {
localGeometry,
localPosition,
localSize,
- visibilityTransition,
+ requireLocalWindowLayer,
visualTransaction,
type LocalWindowHost
} from "./local-window"
@@ -24,66 +25,150 @@ export class TransferredAnswer {
public constructor(public readonly result: unknown[], public readonly transfer: Transferable[]) { }
}
-/**
- * The desktop's vocabulary: what a client half may ask of the interface
- * that frames it.
- *
- * A client half has the capabilities a server half has, narrowed to a
- * world containing exactly one program — its own. Public services are the
- * deliberate exception: a complete service key may name another Program, but
- * it reveals no topology and resolves only through the authoritative service
- * registry. It is not a claim of network confinement — `fetch` deliberately
- * reaches arbitrary URLs, but carries neither a Program subject nor the
- * desktop's authorization.
- *
- * Program operations take no subject at all: the frame a message arrived
- * in decides which program is meant, and what was asked is discarded.
- * Operations on a Process handle name a sibling and all go through
- * `sibling`, the one place a process identity from a pane is measured.
- *
- * A server half is the other thing and deliberately so: it runs
- * arbitrary code already, so vocabulary costs it nothing.
- *
- * Answers cross to a sandboxed frame inside MessagePack envelopes. Native
- * browser capabilities travel only as explicit attachments, so every ordinary
- * word answers with data built here, never with an instance the desktop holds.
- */
-export default function host(authManager: AuthManager, pane: string, desktop: () => DesktopSurfaceSnapshot, frameOwner: () => string | null, pointer: PointerHost, localWindow: LocalWindowHost) {
+/** Adapts the complete System contract and contextual Desktop capabilities to one Client frame. */
+export default function host(authManager: AuthManager, pane: string, desktop: () => DesktopSurfaceSnapshot, frameOwner: () => string | null, localWindow: LocalWindowHost) {
const { processManager, programManager } = authManager
- const scope = processManager.scope(pane)
-
function process() {
- return scope.current()
+ const found = processManager.processes.get(pane)
+
+ if (!found) throw new Error("The desktop does not know this process")
+
+ return found
+ }
+
+ function programOf(found: Pick<ClientProcess, "program">) {
+
+ const program = programManager.programs.get(found.program)
+
+ if (!program) throw new Error("The desktop does not know this program")
+
+ return program
+ }
+
+ function requireProgram(identity: string) {
+
+ const program = programManager.programs.get(identity)
+
+ if (!program) throw new Error("The desktop does not know this program")
+
+ return program
+ }
+
+ function holdProgram(value: unknown, fallback: ClientProgram = programOf(process())) {
+
+ if (value === undefined || value === null) return fallback
+ if (!isHandleAddress(value)) throw new Error("A Program handle is required")
+
+ const found = programManager.programs.get(value.identity)
+
+ if (!found || found.reference !== value.reference) throw new Error("The Program represented by this handle does not exist")
+
+ return found
+ }
+
+ function holdProcess(value: unknown, fallback: ClientProcess = process()) {
+
+ if (value === undefined || value === null) return fallback
+ if (!isHandleAddress(value)) throw new Error("A Process handle is required")
+
+ const found = processManager.processes.get(value.identity)
+
+ if (!found || found.reference !== value.reference) throw new Error("The Process represented by this handle does not exist")
+
+ return found
+ }
+
+ function resolveProcess(value: unknown) {
+
+ if (!isHandleAddress(value)) return null
+
+ const found = processManager.processes.get(value.identity)
+
+ return found?.reference === value.reference ? found : null
+ }
+
+ function requireProcess(identity: string) {
+
+ const found = processManager.processes.get(identity)
+
+ if (!found) throw new Error("The desktop does not know this process")
+
+ return found
+ }
+
+ function clientOf(found: ClientProcess) {
+
+ if (!found.client) throw new Error("This process has no live client endpoint")
+
+ return found.client
+ }
+
+ function localProcess(value: unknown) {
+
+ const found = holdProcess(value)
+
+ if (found !== process()) throw new Error("Local Window operations belong to the current Client Context")
+
+ clientOf(found)
+
+ return found
}
// One process record on every road. Nullable values carry the resolved
// shape as data; the SDK turns them into permanent addressed ends whose
// exists() reads the latest fact. A frame receives MessagePack data, never
// the desktop's mutable record.
- function record(found: ReturnType<typeof process> | NonNullable<ReturnType<typeof process>["parent"]>) {
+ function record(found: ClientProcess) {
- return sdkProcess(found, scope.programOf(found))
+ return sdkProcess(found, programOf(found))
}
return async function answer(word: unknown, ...args: unknown[]) {
- if (word === "permission-granted") {
-
- if (!isPermissionName(args[0])) throw new Error(`The system does not know the permission "${String(args[0])}"`)
-
- return [await authManager.permissionGranted(pane, args[0])]
- }
-
// When it started is a fact about this process, which a pane may
// already ask everything else about — it was missing on this side
// only because it was added on the other.
if (word === "current-process") return [record(process())]
+ if (word === "host-program-list") return [[...programManager.programs.values()].filter(program => args[0] !== true || program.installed).map(sdkProgram)]
+
+ if (word === "host-program-find") {
+
+ const program = programManager.programs.get(String(args[0]))
+
+ return [program ? sdkProgram(program) : null]
+ }
+
+ if (word === "host-program-create" || word === "host-program-force-create") {
+
+ const identity = word === "host-program-create"
+ ? await programManager.create(args[0])
+ : await programManager.forceCreate(args[0], pane)
+
+ return [sdkProgram(requireProgram(identity))]
+ }
+
+ if (word === "host-process-list") return [[...processManager.processes.values()].map(record)]
+
+ if (word === "host-process-find") {
+
+ const found = processManager.processes.get(String(args[0]))
+
+ return [found ? record(found) : null]
+ }
+
if (word === "appearance") return [authManager.linkManager.appearance.value]
+ if (word === "updateAppearance") {
+
+ await authManager.updateAppearance(args[0])
+
+ return []
+ }
+
if (word === "desktopPreferences") return [authManager.linkManager.desktopPreferences.value]
if (word === "updateDesktopPreferences") {
@@ -97,7 +182,7 @@ export default function host(authManager: AuthManager, pane: string, desktop: ()
if (word === "exists") {
- const target = args[1] === undefined ? process() : scope.sibling(args[1])
+ const target = holdProcess(args[1])
if (args[0] === "server") return [target.server !== null]
@@ -108,7 +193,7 @@ export default function host(authManager: AuthManager, pane: string, desktop: ()
if (word === "start-endpoint") {
- const target = args[0] === undefined ? process() : scope.sibling(args[0])
+ const target = holdProcess(args[0])
if (args[1] !== "server" && args[1] !== "client") throw new Error("A Process endpoint is server or client")
@@ -119,7 +204,7 @@ export default function host(authManager: AuthManager, pane: string, desktop: ()
if (word === "stop-endpoint") {
- const target = args[0] === undefined ? process() : scope.sibling(args[0])
+ const target = holdProcess(args[0])
if (args[1] !== "server" && args[1] !== "client") throw new Error("A Process endpoint is server or client")
@@ -137,7 +222,7 @@ export default function host(authManager: AuthManager, pane: string, desktop: ()
if (word === "is-service") {
- const target = args[1] === undefined ? process() : scope.sibling(args[1])
+ const target = holdProcess(args[1])
const endpoint = args[0] ?? "client"
if (endpoint !== "server" && endpoint !== "client") throw new Error("A Process endpoint is server or client")
@@ -203,78 +288,71 @@ export default function host(authManager: AuthManager, pane: string, desktop: ()
return []
}
- // A pane may receive a parent only inside the one program it is
- // already a face of. No parent and a cross-program parent are
- // the same `null`, so the relationship cannot reveal a stranger.
+ // A Process parent is resolved by its exact retained address.
if (word === "parent") {
- const target = args[0] === undefined ? process() : scope.sibling(args[0])
+ const target = holdProcess(args[0])
+ const parent = target.parent ? resolveProcess(target.parent) : null
- const parent = scope.parent(target)
+ if (target.parent && !parent) throw new Error("The parent Process no longer exists")
return [parent ? record(parent) : null]
}
- // Whether a process a pane holds has ended.
- //
- // The one word here that answers about a process the desktop
- // does not know, because that absence is its subject — and the
- // one that does not go through `sibling`, because refusing would
- // answer the question it exists for. It stays inside the same
- // boundary by giving a stranger the same answer as a ghost: a
- // pane may not learn that another program's process exists, so
- // as far as one is concerned, it does not.
+ // A retained Process handle remains able to report its own ending.
if (word === "exited") {
if (!isHandleAddress(args[0])) throw new Error("The boundary returned an invalid Process handle")
- return [scope.exited(args[0])]
+ if (!isHandleAddress(args[0])) throw new Error("A Process handle is required")
+
+ return [resolveProcess(args[0]) === null]
}
- // Every instance of this pane's program, this one among them: a
- // program's two halves must not disagree about how many of it
- // are running. Nothing is named — the program is the frame's.
+ // Every live Process belonging to one exact Program handle.
if (word === "program-process-list") {
- return [scope.processes().map(record)]
+ const program = holdProgram(args[0])
+
+ return [[...processManager.processes.values()].filter(entry => entry.program === program.identity).map(record)]
}
// One process of this program by immutable identity or by its
// living program-local name. An exact identity always wins.
if (word === "program-process-find") {
- const wanted = String(args[0])
-
- const found = scope.findProcess(wanted)
+ const program = holdProgram(args[0])
+ const wanted = String(args[1])
+ const exact = processManager.processes.get(wanted)
+ const found = exact?.program === program.identity
+ ? exact
+ : [...processManager.processes.values()].find(entry => entry.program === program.identity && entry.name === wanted)
return [found ? record(found) : null]
}
- // Another instance of this pane's own program. The identity comes
- // from the frame, so this word can start nothing else.
- // The whole record, not the identity alone: a record invented at the
- // kit's end knows only what the caller could already have
- // guessed, which is how the process a program starts was the one
- // process that did not know when it started.
+ // Create another Process from one exact Program handle.
if (word === "program-process-create") {
- const started = await programManager.createProcess(process().program, args[0] as Launch, process().identity)
+ const program = holdProgram(args[0])
+ const started = await programManager.createProcess(address(program), args[1] as Launch, process().identity)
- return [record(scope.requireProcess(started))]
+ return [record(requireProcess(started))]
}
if (word === "program-process-find-or-create") {
- const launch = args[0] as Launch & { name: string }
+ const program = holdProgram(args[0])
+ const launch = args[1] as Launch & { name: string }
- const found = await programManager.findOrCreateProcess(process().program, launch, process().identity)
+ const found = await programManager.findOrCreateProcess(address(program), launch, process().identity)
- return [record(scope.requireProcess(found))]
+ return [record(requireProcess(found))]
}
// Every instance ended, the asker last. One implementation on the
// core serves this and a server half both.
- if (word === "program-process-exit-all") return [await processManager.exitAll(process().program, pane)]
+ if (word === "program-process-exit-all") return [await processManager.exitAll(holdProgram(args[0]).identity, pane)]
if (word === "observe") {
@@ -290,7 +368,7 @@ export default function host(authManager: AuthManager, pane: string, desktop: ()
const owner = frameOwner()
- const target = args[1] === null ? process() : scope.related(args[1])
+ const target = args[1] === null ? process() : resolveProcess(args[1])
// Callback subscriptions are synchronous and remain silent when
// their source is unavailable. waitFor() and events() identify
@@ -303,7 +381,7 @@ export default function host(authManager: AuthManager, pane: string, desktop: ()
return []
}
- if (!scope.declared(target, half)) {
+ if (!programOf(target)[half]) {
if (reportImpossible) throw new Error(`This program declared no ${half} half`)
@@ -338,7 +416,7 @@ export default function host(authManager: AuthManager, pane: string, desktop: ()
const frame = frameOwner()
- const target = args[1] === null ? process() : scope.related(args[1])
+ const target = args[1] === null ? process() : resolveProcess(args[1])
if (!frame || !target) {
@@ -347,7 +425,7 @@ export default function host(authManager: AuthManager, pane: string, desktop: ()
return []
}
- if (!scope.declared(target, half)) {
+ if (!programOf(target)[half]) {
if (reportImpossible) throw new Error(`This program declared no ${half} half`)
@@ -372,8 +450,7 @@ export default function host(authManager: AuthManager, pane: string, desktop: ()
return []
}
- // Destinationless emission. The source comes from the frame boundary,
- // so Program code cannot speak as a sibling or another Program.
+ // Destinationless emission. The source comes from the frame boundary.
if (word === "emit") {
if (typeof args[0] !== "string") return []
@@ -383,14 +460,12 @@ export default function host(authManager: AuthManager, pane: string, desktop: ()
return []
}
- // Into one end of a sibling's channel, and asking its server end.
- // `sibling` is what makes the name safe; everything after it is
- // the same act a server half performs.
+ // Into one addressed Endpoint, with the current Client as source.
if (word === "send") {
if (args[1] !== "server" && args[1] !== "client") throw new Error(`A process has no "${String(args[1])}" end`)
- await processManager.publish(pane, scope.sibling(args[0]).identity, args[1], args.slice(2))
+ await processManager.publish(pane, holdProcess(args[0]).identity, args[1], args.slice(2))
return []
}
@@ -402,29 +477,23 @@ export default function host(authManager: AuthManager, pane: string, desktop: ()
if (args[1] !== "server") throw new Error("Only a server end can be asked — a client end has no one answerer")
- await processManager.askOf(pane, scope.sibling(args[0]).identity, args.slice(2))
+ await processManager.askOf(pane, holdProcess(args[0]).identity, args.slice(2))
return []
}
- // What a launch said. An explicit subject is a held sibling; the
- // empty subject used by `context.option()` is this frame's Process.
- // The latter is resolved here rather than named by program code,
- // exactly like every other `context` operation on this side.
+ // What a launch said. An empty subject is this frame's Process.
if (word === "option") {
- const found = args[0] === undefined ? process() : scope.sibling(args[0])
+ const found = holdProcess(args[0])
return [found.options[String(args[1])]]
}
- // What this pane's program says it is. Never a path: a client
- // half has no disk, and where the machine put things is not a
- // program's own word about itself.
-
+ // The Program belonging to the current Client Context.
if (word === "current-program") {
- const program = scope.program()
+ const program = programOf(process())
// What it declared about its window comes too — the same
// kind of fact as its name, and what a window needs to know
@@ -432,26 +501,50 @@ export default function host(authManager: AuthManager, pane: string, desktop: ()
return [sdkProgram(program)]
}
- if (word === "program-agent") return [await programManager.agent(process().program)]
+ if (word === "context-permission-get") return [await authManager.permission(pane, String(args[0]))]
+
+ if (word === "context-permission-request") {
+
+ if (typeof args[0] !== "string") throw new Error("A permission request needs an identity")
+
+ return [await authManager.requestPermission(pane, args[0], String(args[1]), args[2] as PermissionRequest)]
+ }
+
+ if (word === "program-permissions") {
+
+ const operation = args[1]
+
+ if (operation !== "all" && operation !== "get" && operation !== "set" && operation !== "delete") throw new Error(`The System does not know the Program permission operation "${String(operation)}"`)
+
+ return [await programManager.permissions(address(holdProgram(args[0])), operation, typeof args[2] === "string" ? args[2] : undefined, args[3] as never)]
+ }
+
+ if (word === "startup") return [await programManager.startup(args[0], String(args[1]), args[2])]
+
+ if (word === "fork") {
- // Icon bytes are requested only when this frame asks. The frame cannot
- // provide an identity; its owning Process determines the Program.
- if (word === "icon") return [await programManager.icon(process().program, args[0] as ProgramIconSize)]
+ const identity = await programManager.fork(args[0], String(args[1]))
+ const program = programManager.programs.get(identity)
- // Whether this pane's Program is installed, and the operations
- // that remove or forget it. Every subject is derived from the
- // frame; no identity supplied by the pane crosses this gate.
- //
- // **No `fork` or `install`.** Both lay out a Program and belong to
- // the server side; neither is a capability of a client face.
+ if (!program) throw new Error("The forked Program was not synchronized")
+
+ return [sdkProgram(program)]
+ }
+
+ if (word === "program-agent") return [await programManager.agent(address(holdProgram(args[0])))]
+
+ // Icon bytes are requested only when a concrete Program handle asks.
+ if (word === "icon") return [await programManager.icon(address(holdProgram(args[0])), args[1] as ProgramIconSize)]
+
+ // Installation state and lifecycle operations of one held Program.
if (word === "installed") {
- return [scope.program().installed === true]
+ return [holdProgram(args[0]).installed === true]
}
if (word === "forget") {
- const program = scope.program()
+ const program = holdProgram(args[0])
return [await program.forget(pane)]
}
@@ -463,7 +556,8 @@ export default function host(authManager: AuthManager, pane: string, desktop: ()
// was being used to ask.
if (word === "window") {
- const shown = scope.window(args[0] ?? address(process()))
+ const target = holdProcess(args[0])
+ const shown = clientOf(target).window
return [{
@@ -475,7 +569,7 @@ export default function host(authManager: AuthManager, pane: string, desktop: ()
minimized: shown.minimized,
- front: scope.front(shown.layer) === pane,
+ front: processManager.front(shown.layer) === target.identity,
// Which layer it lives in, and which of its own pages it
// was opened at. Both are the system's answers about
@@ -490,134 +584,116 @@ export default function host(authManager: AuthManager, pane: string, desktop: ()
if (word === "move") {
- await scope.mutableWindow(args[0]).move(args[1] as never)
+ await clientOf(holdProcess(args[0])).window.move(args[1] as never)
return [pane]
}
if (word === "resize") {
- await scope.mutableWindow(args[0]).resize(args[1] as never)
+ await clientOf(holdProcess(args[0])).window.resize(args[1] as never)
return [pane]
}
if (word === "setGeometry") {
- await scope.mutableWindow(args[0]).setGeometry(args[1] as never)
+ await clientOf(holdProcess(args[0])).window.setGeometry(args[1] as never)
return [pane]
}
- if (word === "windowLocal") return [localWindow.state(scope.localProcess(args[0]).identity)]
-
if (word === "windowLocalMove") {
- await localWindow.move(scope.localProcess(args[0]).identity, localPosition(args[1]), visualTransaction(args[2]))
+ const target = localProcess(args[0])
+ requireLocalWindowLayer(target.client!.window.layer)
+ await localWindow.move(target.identity, localPosition(args[1]), visualTransaction(args[2]))
return []
}
if (word === "windowLocalResize") {
- await localWindow.resize(scope.localProcess(args[0]).identity, localSize(args[1]), visualTransaction(args[2]))
+ const target = localProcess(args[0])
+ requireLocalWindowLayer(target.client!.window.layer)
+ await localWindow.resize(target.identity, localSize(args[1]), visualTransaction(args[2]))
return []
}
if (word === "windowLocalGeometry") {
- await localWindow.geometry(scope.localProcess(args[0]).identity, localGeometry(args[1]), visualTransaction(args[2]))
-
- return []
- }
-
- if (word === "windowLocalMinimize") {
-
- localWindow.minimize(scope.localProcess(args[0]).identity, args[1] !== false)
-
- return []
- }
-
- if (word === "windowLocalTitle") {
-
- localWindow.title(scope.localProcess(args[0]).identity, String(args[1] ?? ""))
+ const target = localProcess(args[0])
+ requireLocalWindowLayer(target.client!.window.layer)
+ await localWindow.geometry(target.identity, localGeometry(args[1]), visualTransaction(args[2]))
return []
}
- if (word === "windowLocalRaise") {
+ if (word === "windowLocalSurfaceAdd") {
- localWindow.raise(scope.localProcess(args[0]).identity)
-
- return []
- }
-
- if (word === "windowLocalSurfaceSet") {
-
- await localWindow.setSurface(scope.localProcess(args[0]).identity, visibilityTransition(args[1]))
+ const target = localProcess(args[0])
+ requireLocalWindowLayer(target.client!.window.layer)
+ await localWindow.addSurface(target.identity, visualTransaction(args[2]))
return []
}
if (word === "windowLocalSurfaceRemove") {
- await localWindow.removeSurface(scope.localProcess(args[0]).identity, visibilityTransition(args[1]))
+ const target = localProcess(args[0])
+ requireLocalWindowLayer(target.client!.window.layer)
+ await localWindow.removeSurface(target.identity, visualTransaction(args[2]))
return []
}
if (word === "changeTitle") {
- await scope.mutableWindow(args[0]).changeTitle(String(args[1] ?? ""))
+ await clientOf(holdProcess(args[0])).window.changeTitle(String(args[1] ?? ""))
return [pane]
}
if (word === "raise") {
- await scope.mutableWindow(args[0]).raise()
+ await clientOf(holdProcess(args[0])).window.raise()
return [pane]
}
if (word === "minimize") {
- await scope.mutableWindow(args[0]).minimize(args[1] !== false)
+ await clientOf(holdProcess(args[0])).window.minimize(args[1] !== false)
return [pane]
}
if (word === "exit") {
- await scope.sibling(args[0]).exit()
+ await holdProcess(args[0]).exit()
return [pane]
}
- // This program's own store. The question names whose, as it does
- // on the other side, and the answer ignores it: whose is resolved
- // from the frame, never from what was asked. The application store
- // has no generic host road at all.
if (word === "store") {
- const [, operation, key, value, ttl] = args as [unknown, string, string, unknown, number | undefined]
+ const [subject, operation, key, value, ttl] = args as [unknown, string, string, unknown, number | undefined]
- return [await programManager.store(process().program, operation, key, value, ttl)]
+ return [await programManager.store(address(holdProgram(subject)), operation, key, value, ttl)]
}
// This program's places. Metadata operations remain ordinary values;
// file content takes the storage door so its bytes never enter The
- // Link's serialization. The pane names neither a Program nor an
- // authorization: this frame resolves to a Process, and that Process
- // resolves to the Program whose area is opened.
+ // Link's serialization. The exact Program handle crosses with the
+ // request and is validated again by the authoritative Core.
if (word === "data" || word === "cache") {
const area: "data" | "cache" = word === "data" ? "data" : "cache"
const operation = String(args[1])
- if (operation === "path" || operation === "resolve") throw new Error(`A client half is not told where its ${word} is`)
+ const program = holdProgram(args[0])
if (operation === "stream" || operation === "write") {
@@ -627,7 +703,7 @@ export default function host(authManager: AuthManager, pane: string, desktop: ()
const { control, controller } = cancellation(args[4], operation)
- const request = { program: process().program, area, path: joins }
+ const request = { scope: "program" as const, program: address(program), area, path: joins }
try {
@@ -662,44 +738,66 @@ export default function host(authManager: AuthManager, pane: string, desktop: ()
}
}
- return [await programManager.area(process().program, word, operation, args.slice(2))]
+ return [await programManager.area(address(program), word, operation, args.slice(2))]
}
- // What this program has said. Whose, as everywhere here, is the
- // frame's rather than the question's — so a window reads its own
- // program's output and has no way to name another's.
- //
- // Nothing refuses a query that would write, because the
- // connection behind it cannot: a pane's SQL reaches a read-only
- // database, which is the same thing a server half's reaches.
+ // Read-only logs belonging to one exact Program.
if (word === "logs") {
- return [await programManager.logs(process().program, String(args[1]), Array.isArray(args[2]) ? args[2] : [])]
+ return [await programManager.logs(address(holdProgram(args[0])), String(args[1]), Array.isArray(args[2]) ? args[2] : [])]
}
- // This program's own database. Whose is the frame's, as
- // everywhere here, so a window reads and writes its own and has
- // no way to name another's.
+ // Read and write one exact Program database.
if (word === "database") {
- return [await programManager.database(process().program, String(args[1]), Array.isArray(args[2]) ? args[2] : [])]
+ return [await programManager.database(address(holdProgram(args[0])), String(args[1]), Array.isArray(args[2]) ? args[2] : [])]
}
- // One desktop can frame many Client layers, but its complete area is
- // one host fact. It is this desktop's answer rather than a machine
- // fact, and the gutter remains private desktop layout state.
- if (word === "desktopSurface") return [desktop()]
+ if (word === "host-storage") {
+
+ return [await authManager.storage(String(args[0]), args.slice(1).map(String))]
+ }
+
+ if (word === "host-storage-stream" || word === "host-storage-write") {
- // Coordinates use the same desktop display core as window geometry.
- // Before this session has observed a pointer movement there is no
- // position to invent, so the initial answer is null.
- if (word === "desktopPointer") {
+ const path = args[0]
+
+ if (!Array.isArray(path) || path.some(part => typeof part !== "string")) throw new Error("A storage path is a list of names")
+
+ const writing = word === "host-storage-write"
+ const { control, controller } = cancellation(args[2], word)
+ const request = { scope: "system" as const, path }
+
+ try {
- if (await authManager.permissionGranted(pane, "pointer") !== true) throw new Error("Permission \"pointer\" is not granted")
+ if (writing) {
- return [pointer.snapshot()]
+ if (!clientBody(args[1])) throw new Error("Writing takes bytes")
+ await authManager.linkManager.application.storageWrite(request, args[1], authManager.authorization, controller.signal)
+ control.close()
+ return []
+ }
+
+ const body = controlled(
+ await authManager.linkManager.application.storageStream(request, authManager.authorization, controller.signal),
+ controller,
+ control
+ )
+
+ return new TransferredAnswer([body], [body])
+ }
+ catch (exception) {
+
+ control.close()
+ throw exception
+ }
}
+ // One desktop can frame many Client layers, but its complete area is
+ // one host fact. It is this desktop's answer rather than a machine
+ // fact, and the gutter remains private desktop layout state.
+ if (word === "desktopSurface") return [desktop()]
+
// Uploads are one flat public collection. A pane may provide bytes or
// one opaque file key; it never receives a filesystem path or route.
if (word === "uploads") {
diff --git a/source/client/view/components/desktop-host/local-window.ts b/source/client/view/components/desktop-host/local-window.ts
index 1d43eb7..c113ca4 100644
--- a/source/client/view/components/desktop-host/local-window.ts
+++ b/source/client/view/components/desktop-host/local-window.ts
@@ -4,7 +4,6 @@ import {
type Position,
type Size,
type Transaction,
- type VisibilityTransition,
type WindowGeometry,
type WindowLayer,
type WindowState
@@ -36,8 +35,8 @@ export interface LocalWindowHost {
minimize(identity: string, minimized: boolean): void
title(identity: string, title: string): void
raise(identity: string): void
- setSurface(identity: string, transition: VisibilityTransition): Promise<void>
- removeSurface(identity: string, transition: VisibilityTransition): Promise<void>
+ addSurface(identity: string, transaction?: Transaction): Promise<void>
+ removeSurface(identity: string, transaction?: Transaction): Promise<void>
complete(identity: string, kind: "geometry" | "surface", revision: number): void
release(identity: string): void
}
@@ -91,15 +90,9 @@ export function visualTransaction(value: unknown): Transaction | undefined {
return Object.freeze(result) as Transaction
}
-export function visibilityTransition(value: unknown): VisibilityTransition {
- const transition = visualTransaction(value)
- if (!transition) throw new Error("A VisibilityTransition is required")
- return transition
-}
-
-export function layerAllowsSurface(layer: WindowLayer) {
+export function requireLocalWindowLayer(layer: WindowLayer) {
- if (layer === "window") throw new Error("A window-layer representation cannot own a Surface")
+ if (layer === "window") throw new Error("A window-layer Process cannot change its local Window representation")
}
function easing(value: unknown): Easing {
diff --git a/source/client/view/components/desktop-host/pointer.ts b/source/client/view/components/desktop-host/pointer.ts
deleted file mode 100644
index 6f8a03b..0000000
--- a/source/client/view/components/desktop-host/pointer.ts
+++ /dev/null
@@ -1,60 +0,0 @@
-import { type RefObject } from "react"
-import { TheLink } from "@the-link/core"
-import { type DesktopPointerPosition, type DesktopPointerSnapshot } from "@phreshos/core"
-
-/**
- * Pointer state belongs to one desktop session. Programs may observe it,
- * but they neither own the listener nor receive another frame's lease.
- */
-export default class DesktopPointer extends TheLink implements PointerHost {
-
- private latest: DesktopPointerPosition | null = null
-
- public constructor(private readonly desktop: RefObject<HTMLDivElement | null>) {
-
- super()
- }
-
- public listen() {
-
- const desktop = this.desktop.current
-
- if (!desktop) return () => undefined
-
- const move = (event: PointerEvent) => {
-
- const bounds = desktop.getBoundingClientRect()
-
- const position = {
-
- x: event.clientX - bounds.left,
-
- y: event.clientY - bounds.top
- }
-
- this.latest = position
-
- this.$inbound.publish("move", position).catch(() => undefined)
- }
-
- desktop.addEventListener("pointermove", move)
-
- return () => {
-
- desktop.removeEventListener("pointermove", move)
- }
- }
-
- public snapshot(): DesktopPointerSnapshot {
-
- return { position: this.latest }
- }
-
-}
-
-export interface PointerHost {
-
- snapshot(): DesktopPointerSnapshot
-
- readonly $inbound: TheLink["$inbound"]
-}
diff --git a/source/client/view/components/desktop-host/sdk-records.ts b/source/client/view/components/desktop-host/sdk-records.ts
index 9234f97..e85c603 100644
--- a/source/client/view/components/desktop-host/sdk-records.ts
+++ b/source/client/view/components/desktop-host/sdk-records.ts
@@ -1,4 +1,15 @@
-import type Program from "@client/core/link-manager/auth-manager/program-manager/program"
+export interface SdkProgramSource {
+
+ reference: string
+ identity: string
+ installed: boolean
+ name: string
+ version: string | null
+ description: string | null
+ hasAgent: boolean
+ server: unknown | null
+ client: unknown | null
+}
export interface SdkProcessSource {
@@ -20,7 +31,7 @@ export interface SdkProcessSource {
}
/** Plain SDK Program state carried across the iframe boundary. */
-export function sdkProgram(program: Program) {
+export function sdkProgram(program: SdkProgramSource) {
return {
@@ -45,7 +56,7 @@ export function sdkProgram(program: Program) {
}
/** Plain Process state with its ownership chain embedded for synchronous navigation. */
-export function sdkProcess(process: SdkProcessSource, program: Program) {
+export function sdkProcess(process: SdkProcessSource, program: SdkProgramSource) {
return {
diff --git a/source/client/view/components/program-access.tsx b/source/client/view/components/program-access.tsx
deleted file mode 100644
index 8dbc0a7..0000000
--- a/source/client/view/components/program-access.tsx
+++ /dev/null
@@ -1,117 +0,0 @@
-import { type Dispatch, type SetStateAction, useLayoutEffect, useMemo, useRef } from "react"
-
-export type ProgramAccess = "checking" | "available" | "blocked"
-
-const programAccessRequest = "program-access-request"
-
-const programAccessMessage = "program-access"
-
-const timeout = 10_000
-
-/**
- * Exercise the Program asset door from the same opaque origin as a real
- * Program. A normal desktop fetch would be same-origin and would therefore
- * prove nothing about the boundary that Program frames cross.
- */
-export default function ({ door, setAccess }: ProgramAccessProbeProps) {
-
- const frame = useRef<HTMLIFrameElement>(null)
-
- const source = useMemo(function () {
-
- const url = new URL(`${door}/ping`, window.location.href).href
-
- return `<!doctype html><meta charset="utf-8"><script>
-let requested = false;
-let result;
-function report() {
-
- if (requested && typeof result === "boolean") parent.postMessage([${JSON.stringify(programAccessMessage)}, result], "*");
-}
-addEventListener("message", event => {
-
- if (event.data !== ${JSON.stringify(programAccessRequest)}) return;
- requested = true;
- report();
-});
-fetch(${JSON.stringify(url)}, { cache: "no-store" })
- .then(response => { result = response.ok; report(); })
- .catch(() => { result = false; report(); });
-</script>`
-
- }, [door])
-
- useLayoutEffect(function () {
-
- const timer = window.setTimeout(() => setAccess("blocked"), timeout)
-
- function receive(event: MessageEvent) {
-
- if (event.source !== frame.current?.contentWindow) return
-
- if (!Array.isArray(event.data) || event.data[0] !== programAccessMessage || typeof event.data[1] !== "boolean") return
-
- window.clearTimeout(timer)
-
- setAccess(event.data[1] ? "available" : "blocked")
- }
-
- window.addEventListener("message", receive)
-
- return function () {
-
- window.clearTimeout(timer)
-
- window.removeEventListener("message", receive)
- }
-
- }, [setAccess])
-
- return <iframe
-
- ref={frame}
-
- srcDoc={source}
-
- title="Program asset compatibility check"
-
- sandbox="allow-scripts"
-
- onLoad={event => event.currentTarget.contentWindow?.postMessage(programAccessRequest, "*")}
-
- hidden
-
- />
-}
-
-interface ProgramAccessProbeProps {
-
- door: string
-
- setAccess: Dispatch<SetStateAction<ProgramAccess>>
-}
-
-export const blockedProgramDocument = `<!doctype html>
-<html lang="en">
-<head>
-<meta charset="utf-8">
-<meta name="viewport" content="width=device-width, initial-scale=1">
-<title>Program unavailable</title>
-<style>
- :root { color-scheme: light; font-family: system-ui, sans-serif; color: #233548; background: #eef8ff; }
- * { box-sizing: border-box; }
- body { min-height: 100vh; margin: 0; display: grid; place-items: center; padding: 2rem; background: radial-gradient(circle at top left, #ffffff 0, #eef8ff 48%, #dff4ff 100%); }
- .message { width: min(34rem, 100%); padding: 1.5rem; border: 1px solid rgba(89, 151, 191, .28); border-radius: 1.25rem; background: rgba(255, 255, 255, .82); box-shadow: 0 1.25rem 3rem rgba(47, 104, 145, .15); }
- h1 { margin: 0 0 .75rem; font-size: 1.35rem; }
- p { margin: 0; line-height: 1.6; }
- p + p { margin-top: .8rem; color: #526b7f; font-size: .92rem; }
-</style>
-</head>
-<body>
-<div class="message">
- <h1>This Program cannot load</h1>
- <p>The desktop is connected, but this hosting server blocks requests made by isolated Program frames.</p>
- <p>Configure the server or reverse proxy to preserve the CORS headers on <code>/program/*</code>, including requests whose origin is <code>null</code>, then reload the desktop.</p>
-</div>
-</body>
-</html>`
diff --git a/source/client/view/components/program-frame.tsx b/source/client/view/components/program-frame.tsx
index b4c49a7..9ae1108 100644
--- a/source/client/view/components/program-frame.tsx
+++ b/source/client/view/components/program-frame.tsx
@@ -1,6 +1,5 @@
import Process from "@client/core/link-manager/auth-manager/process-manager/process"
import ClientState from "@client/core/link-manager/auth-manager/process-manager/client-state"
-import { blockedProgramDocument, type ProgramAccess } from "./program-access"
import { type Theme } from "@phreshos/core"
import { type ReactEventHandler, useCallback } from "react"
@@ -15,25 +14,11 @@ export function programFrameSource(record: Process, client: ClientState, door: s
: `${door}/${record.assetId}/assets/${window.location.slice(1)}`
}
-/** The one sandboxed document representation shared by every Client role. */
-export default function ProgramFrame({ record, client, title, door, access, theme, className = "size-full border-0", onFrame, onLoad }: ProgramFrameProps) {
+/** The document representation shared by every Client role. */
+export default function ProgramFrame({ record, client, title, door, theme, className = "size-full border-0", onFrame, onLoad }: ProgramFrameProps) {
const source = useCallback((element: HTMLIFrameElement | null) => onFrame(record.identity, element), [onFrame, record.identity])
- if (access === "checking") return null
-
- if (access === "blocked") return <iframe
-
- srcDoc={blockedProgramDocument}
-
- title={`${title}: Program unavailable`}
-
- sandbox=""
-
- className={className}
-
- />
-
return <iframe
style={{ colorScheme: theme }}
@@ -42,8 +27,6 @@ export default function ProgramFrame({ record, client, title, door, access, them
title={title}
- sandbox="allow-scripts allow-forms"
-
className={className}
ref={source}
@@ -63,8 +46,6 @@ interface ProgramFrameProps {
door: string
- access: ProgramAccess
-
theme: Theme
className?: string
diff --git a/source/client/view/components/window-manager/local-windows.ts b/source/client/view/components/window-manager/local-windows.ts
index fa77b70..3635ed2 100644
--- a/source/client/view/components/window-manager/local-windows.ts
+++ b/source/client/view/components/window-manager/local-windows.ts
@@ -1,6 +1,6 @@
import ClientState from "@client/core/link-manager/auth-manager/process-manager/client-state"
import { type Transaction, type WindowGeometry, type WindowState } from "@phreshos/core"
-import { layerAllowsSurface, type LocalWindowHost, type LocalWindowState } from "../desktop-host/local-window"
+import { type LocalWindowHost, type LocalWindowState } from "../desktop-host/local-window"
export interface LocalWindowEntry {
identity: string
@@ -142,26 +142,24 @@ export default class LocalWindows implements LocalWindowHost {
this.replace(identity, { ...state, depth: depth + 1 })
}
- public setSurface(process: string, transaction: Transaction) {
+ public addSurface(process: string, transaction?: Transaction) {
const { identity, state } = this.existing(process)
- layerAllowsSurface(state.layer)
if (state.surface?.visible) return Promise.resolve()
this.cancel(identity, "surface")
- const transition = { revision: ++this.revision, transaction }
+ const transition = transaction ? { revision: ++this.revision, transaction } : null
this.replace(identity, { ...state, surface: { visible: true, transition } })
return this.waitFor(identity, "surface", transition)
}
- public removeSurface(process: string, transaction: Transaction) {
+ public removeSurface(process: string, transaction?: Transaction) {
const { identity, state } = this.existing(process)
- layerAllowsSurface(state.layer)
if (!state.surface || !state.surface.visible) return Promise.resolve()
this.cancel(identity, "surface")
- const transition = { revision: ++this.revision, transaction }
+ const transition = transaction ? { revision: ++this.revision, transaction } : null
this.replace(identity, { ...state, surface: { visible: false, transition } })
return this.waitFor(identity, "surface", transition)
}
diff --git a/source/client/view/structure/desktop/desktop.tsx b/source/client/view/structure/desktop/desktop.tsx
index f467612..de8bedd 100644
--- a/source/client/view/structure/desktop/desktop.tsx
+++ b/source/client/view/structure/desktop/desktop.tsx
@@ -5,7 +5,6 @@ import useClientHost from "../../components/desktop-host/client-host"
import DesktopDisplay from "./desktop-display"
import useDesktopFocus from "./desktop-focus"
import programIcon from "./programs/program-icon"
-import ProgramAccessProbe, { type ProgramAccess } from "../../components/program-access"
import StartMenu from "./taskbar/launcher/start-menu"
import OverflowRow from "./taskbar/programs/overflow-row"
import SignOut from "./taskbar/system/sign-out"
@@ -49,11 +48,9 @@ export default function Workspace() {
const desktop = useRef<HTMLDivElement>(null)
- const [programAccess, setProgramAccess] = useState<ProgramAccess>("checking")
-
const currentPrograms = new Set(windows.records.map(record => record.identity))
- const initialProgramsReady = programAccess === "blocked" || [...initialPrograms.current].every(identity => readyPrograms.has(identity) || !currentPrograms.has(identity))
+ const initialProgramsReady = [...initialPrograms.current].every(identity => readyPrograms.has(identity) || !currentPrograms.has(identity))
useEffect(function () {
@@ -144,8 +141,6 @@ export default function Workspace() {
door={application.doors.program}
- programAccess={programAccess}
-
theme={theme}
onFrame={frame}
@@ -220,8 +215,6 @@ export default function Workspace() {
return <div ref={desktop} tabIndex={-1} aria-label="Desktop" onFocusCapture={focus.remember} className="relative isolate grid min-h-0 grid-cols-1 grid-rows-1 outline-none" style={{ color: foreground }}>
- <ProgramAccessProbe door={application.doors.program} setAccess={setProgramAccess} />
-
<DesktopDisplay
wallpaper={wallpaper}
diff --git a/source/client/view/structure/desktop/geometry.ts b/source/client/view/structure/desktop/geometry.ts
index 1549a76..9ee3989 100644
--- a/source/client/view/structure/desktop/geometry.ts
+++ b/source/client/view/structure/desktop/geometry.ts
@@ -4,7 +4,7 @@ import { type CSSProperties } from "react"
* The gap between adjacent painted windows, in pixels. Each window uses
* half inside its own box; the ordinary workspace uses the other half
* at its boundary. The gutter remains private desktop layout state and never
- * enters the layer-independent `system.desktop.surface` snapshot.
+ * enters the layer-independent Desktop surface snapshot.
*
* The visible window edge, taskbar edge and Start Menu geometry derive from
* this value rather than restating its pixel or rem equivalent.
diff --git a/source/client/view/structure/desktop/taskbar/system/system-dialogs.tsx b/source/client/view/structure/desktop/taskbar/system/system-dialogs.tsx
index d1c4c3a..29ffbf9 100644
--- a/source/client/view/structure/desktop/taskbar/system/system-dialogs.tsx
+++ b/source/client/view/structure/desktop/taskbar/system/system-dialogs.tsx
@@ -101,9 +101,11 @@ function PermissionRequest({ dialog, description, decide }: PermissionRequestPro
<div className="grid gap-1">
- <h3 className="text-base font-medium">{dialog.program.name} needs permission</h3>
+ <h3 className="text-base font-medium">{dialog.program.name} needs {dialog.title}</h3>
- <p id={description} className="text-sm leading-6 opacity-60">{permissionDescription(dialog)}</p>
+ <p id={description} className="text-sm leading-6 opacity-60">{dialog.description}</p>
+
+ {dialog.values.length > 0 && <p className="text-xs leading-5 opacity-50">{dialog.values.join(", ")}</p>}
</div>
@@ -163,18 +165,6 @@ function CrashReport({ dialog, description, acknowledge }: CrashReportProps) {
</div>
}
-function permissionDescription(dialog: PermissionDialog) {
-
- if (dialog.permission === "pointer") return "Allow this Program to read and listen to pointer movement across the desktop."
-
- return unknownPermission(dialog.permission)
-}
-
-function unknownPermission(permission: never): never {
-
- throw new Error(`The system has no description for permission "${permission}"`)
-}
-
function crashDescription(dialog: ServerCrashDialog) {
const endpoint = dialog.process.name ? `the “${dialog.process.name}” Process’s server endpoint` : "its server endpoint"
@@ -186,20 +176,18 @@ function crashDescription(dialog: ServerCrashDialog) {
return `${dialog.program.name} stopped because ${endpoint} ended unexpectedly.`
}
-interface PermissionRequestProps {
+interface CrashReportProps {
- dialog: PermissionDialog
+ dialog: ServerCrashDialog
description: string
- decide(choice: PermissionChoice): Promise<void>
+ acknowledge(): Promise<void>
}
-interface CrashReportProps {
-
- dialog: ServerCrashDialog
+interface PermissionRequestProps {
+ dialog: PermissionDialog
description: string
-
- acknowledge(): Promise<void>
+ decide(choice: PermissionChoice): Promise<void>
}
diff --git a/source/client/view/structure/desktop/windows/process-window.tsx b/source/client/view/structure/desktop/windows/process-window.tsx
index 9a527b1..a49d0c2 100644
--- a/source/client/view/structure/desktop/windows/process-window.tsx
+++ b/source/client/view/structure/desktop/windows/process-window.tsx
@@ -3,7 +3,6 @@ import ClientState from "@client/core/link-manager/auth-manager/process-manager/
import { type WindowSurfaceSize } from "@client/view/components/window-manager/window-geometry"
import { type LocalAnimation, type LocalSurfaceState } from "@client/view/components/desktop-host/local-window"
import { type LocalGeometryReader } from "@client/view/components/window-manager/local-windows"
-import { type ProgramAccess } from "@client/view/components/program-access"
import { type Position, type Size, type Theme } from "@phreshos/core"
import Spinner from "@client/view/components/spinner"
import Window from "./window"
@@ -17,7 +16,7 @@ const settleDelay = 80
* props so memoization can see which process actually changed even though
* the peer deliberately keeps each Process instance alive and mutates it.
*/
-export default memo(function ({ identity, record, client, title, icon, position, size, localSurface, geometryAnimation, onLocalAnimationComplete, onLocalRepresentation, paintSurfaceSize, depth, active, minimized, closing, stopping, entering, bare, door, programAccess, theme, onFrame, onFrameLoad, onReady, onRaise, onMinimize, onFill, onClose, onClosed, onUnavailable, onMove, onResize, onSnap }: ProcessWindowProps) {
+export default memo(function ({ identity, record, client, title, icon, position, size, localSurface, geometryAnimation, onLocalAnimationComplete, onLocalRepresentation, paintSurfaceSize, depth, active, minimized, closing, stopping, entering, bare, door, theme, onFrame, onFrameLoad, onReady, onRaise, onMinimize, onFill, onClose, onClosed, onUnavailable, onMove, onResize, onSnap }: ProcessWindowProps) {
const activate = useCallback(() => onRaise(record), [onRaise, record])
@@ -84,7 +83,7 @@ export default memo(function ({ identity, record, client, title, icon, position,
}, [frameSource, loading, onReady, record.identity])
- const frameLoading = programAccess === "available" && (loading.source !== frameSource || loading.phase !== "ready")
+ const frameLoading = loading.source !== frameSource || loading.phase !== "ready"
const progress = !bare && (stopping || closing ? "Closing" : frameLoading ? "Loading" : null)
@@ -145,12 +144,7 @@ export default memo(function ({ identity, record, client, title, icon, position,
>
{/* A launch names one of its client half's own pages; joining it
- to the program asset route remains the view's responsibility.
-
- Without allow-same-origin, the pane has an opaque origin and
- cannot reach the desktop document or its authorization. Its
- channel crosses through postMessage and resolves identity from
- this frame, so isolation does not weaken communication. */}
+ to the program asset route remains the view's responsibility. */}
{!stopping && !closing && <ProgramFrame
record={record}
@@ -161,8 +155,6 @@ export default memo(function ({ identity, record, client, title, icon, position,
door={door}
- access={programAccess}
-
theme={theme}
className={`size-full border-0 ${frameLoading ? "opacity-0" : ""}`}
@@ -235,8 +227,6 @@ interface ProcessWindowProps {
door: string
- programAccess: ProgramAccess
-
theme: Theme
onFrame: (identity: string, element: HTMLIFrameElement | null) => void
diff --git a/source/server/core/dialog-manager.ts b/source/server/core/dialog-manager.ts
index af33999..3e18a9a 100644
--- a/source/server/core/dialog-manager.ts
+++ b/source/server/core/dialog-manager.ts
@@ -3,7 +3,7 @@ import { Transmitted } from "@libs/messagepack"
import { TheLink } from "@the-link/core"
import { randomUUID } from "node:crypto"
import { type default as Process } from "./link-manager/auth-manager/process-manager/process"
-import { type PermissionName } from "@phreshos/core"
+import { permissionCatalog } from "./permissions"
/** Authoritative runtime queue of system messages awaiting acknowledgment. */
export default class DialogManager extends TheLink {
@@ -57,46 +57,32 @@ export default class DialogManager extends TheLink {
await this.$outbound.publish("/created", dialog).catch(() => undefined)
}
- /** Waits for one authoritative user decision for a Client Process. */
- public async requestPermission(process: Process, request: string, permission: PermissionName): Promise<PermissionChoice> {
+ /** Waits for one authoritative owner decision for a Client Process. */
+ public async requestPermission(process: Process, request: string, permission: string, values: string[]): Promise<PermissionChoice> {
+ if (!request || this.permissionRequests.has(request)) throw new Error("A permission request needs a unique identity")
if (this.permissionProcesses.has(process.reference)) throw new Error("This Client Process already has a pending permission request")
+ const definition = permissionCatalog.definition(permission)
const dialog: PermissionDialog = {
identity: randomUUID(),
-
kind: "permission",
-
createdAt: new Date(),
-
permission,
-
- program: {
-
- identity: process.program.identity,
-
- name: process.program.name
- },
-
- process: {
-
- identity: process.identity,
-
- name: process.name
- }
+ values: [...values],
+ title: definition.title,
+ description: definition.description,
+ program: { identity: process.program.identity, name: process.program.name },
+ process: { identity: process.identity, name: process.name }
}
let settle: (choice: PermissionChoice) => void = () => undefined
-
const answer = new Promise<PermissionChoice>(resolve => { settle = resolve })
-
const stopExit = process.onExit(() => { this.cancelPermission(request, process.reference).catch(() => undefined) })
this.permissionRequests.set(request, { request, dialog, process: process.reference, settle, stopExit })
-
this.permissionProcesses.set(process.reference, request)
-
this.dialogs.set(dialog.identity, dialog)
await this.$outbound.publish("/created", dialog).catch(() => undefined)
@@ -104,7 +90,7 @@ export default class DialogManager extends TheLink {
return await answer
}
- /** Resolves one permission prompt from any synchronized desktop. */
+ /** Resolves one permission prompt from any synchronized Desktop. */
@Subscribe("/resolve-permission")
protected async resolvePermission(identity: unknown, choice: unknown) {
@@ -112,9 +98,7 @@ export default class DialogManager extends TheLink {
const pending = [...this.permissionRequests.values()].find(entry => entry.dialog.identity === identity)
- if (!pending) return
-
- await this.finishPermission(pending, choice)
+ if (pending) await this.finishPermission(pending, choice)
}
/** Cancels one boundary-owned prompt without creating a decision. */
@@ -122,9 +106,7 @@ export default class DialogManager extends TheLink {
const pending = this.permissionRequests.get(request)
- if (!pending || pending.process !== process) return
-
- await this.finishPermission(pending, null)
+ if (pending?.process === process) await this.finishPermission(pending, null)
}
private async finishPermission(pending: PendingPermission, choice: PermissionChoice) {
@@ -132,11 +114,8 @@ export default class DialogManager extends TheLink {
if (!this.permissionRequests.delete(pending.request)) return
this.permissionProcesses.delete(pending.process)
-
this.dialogs.delete(pending.dialog.identity)
-
pending.stopExit()
-
pending.settle(choice)
await this.$outbound.publish("/removed", pending.dialog.identity).catch(() => undefined)
@@ -187,26 +166,14 @@ export interface ServerCrashDialog {
export interface PermissionDialog {
readonly identity: string
-
readonly kind: "permission"
-
readonly createdAt: Date
-
- readonly permission: PermissionName
-
- readonly program: Readonly<{
-
- identity: string
-
- name: string
- }>
-
- readonly process: Readonly<{
-
- identity: string
-
- name: string | null
- }>
+ readonly permission: string
+ readonly values: string[]
+ readonly title: string
+ readonly description: string
+ readonly program: Readonly<{ identity: string, name: string }>
+ readonly process: Readonly<{ identity: string, name: string | null }>
}
export type PermissionChoice = "process" | "always" | false | null
@@ -216,13 +183,9 @@ export type SystemDialog = ServerCrashDialog | PermissionDialog
interface PendingPermission {
readonly request: string
-
readonly dialog: PermissionDialog
-
readonly process: string
-
readonly settle: (choice: PermissionChoice) => void
-
readonly stopExit: () => void
}
diff --git a/source/server/core/link-manager/auth-manager/auth-manager.ts b/source/server/core/link-manager/auth-manager/auth-manager.ts
index 875c741..80c8574 100644
--- a/source/server/core/link-manager/auth-manager/auth-manager.ts
+++ b/source/server/core/link-manager/auth-manager/auth-manager.ts
@@ -6,7 +6,7 @@ import ProgramManager from "./program-manager/program-manager"
import { Transmitted } from "@libs/messagepack"
import { TheLink } from "@the-link/core"
import LinkManager from "../link-manager"
-import { isPermissionName } from "@phreshos/core"
+import { type PermissionRequest } from "@phreshos/core"
export default class AuthManager extends TheLink {
@@ -77,11 +77,34 @@ export default class AuthManager extends TheLink {
return fetch(input, init)
}
- public streamArea(authorization: unknown, identity: string, area: "data" | "cache", path: string[]) {
+ public streamArea(authorization: unknown, program: unknown, area: "data" | "cache", path: string[]) {
this.verify(authorization)
- return this.programManager.streamArea(identity, area, path)
+ return this.programManager.streamArea(program, area, path)
+ }
+
+ @Connect("/storage")
+ protected async storage(operation: unknown, values: unknown) {
+
+ if (typeof operation !== "string" || !Array.isArray(values) || values.some(value => typeof value !== "string")) throw new Error("A System storage operation is invalid")
+
+ const area = this.linkManager.application.home
+
+ if (operation === "path") return area.path
+ if (operation === "resolve") return area.resolve(values)
+ if (operation === "stat") return area.stat(values)
+ if (operation === "list") return area.list(values)
+ if (operation === "delete") return area.delete(values)
+ if (operation === "clear") return area.clear(values)
+
+ throw new Error(`System storage does not know "${operation}"`)
+ }
+
+ @Connect("/appearance/update")
+ protected async changeAppearance(value: unknown) {
+
+ return await this.updateAppearance(value)
}
/** Replace System Appearance through the authenticated boundary. */
@@ -90,35 +113,33 @@ export default class AuthManager extends TheLink {
return await this.linkManager.updateAppearance(value)
}
- @Connect("/permission/granted")
- protected async permissionGranted(process: unknown, permission: unknown) {
+ @Connect("/permission/get")
+ protected async permission(process: unknown, name: unknown) {
- if (typeof process !== "string" || !isPermissionName(permission)) throw new Error("A permission request is invalid")
+ if (typeof process !== "string" || typeof name !== "string") throw new Error("A permission read is invalid")
- return this.processManager.permissionGranted(process, permission)
+ return this.processManager.permission(process, name)
}
@Connect("/permission/request")
- protected async requestPermission(request: unknown, process: unknown, permission: unknown) {
+ protected async requestPermission(request: unknown, process: unknown, name: unknown, permission: unknown) {
- if (typeof request !== "string" || typeof process !== "string" || !isPermissionName(permission)) throw new Error("A permission request is invalid")
+ if (typeof request !== "string" || typeof process !== "string" || typeof name !== "string") throw new Error("A permission request is invalid")
- return await this.processManager.requestPermission(process, request, permission)
+ return this.processManager.requestPermission(process, request, name, permission as PermissionRequest)
}
@Subscribe("/permission/cancel")
protected async cancelPermission(request: unknown, process: unknown) {
- if (typeof request !== "string" || typeof process !== "string") return
-
- await this.processManager.cancelPermission(process, request)
+ if (typeof request === "string" && typeof process === "string") await this.processManager.cancelPermission(process, request)
}
- public async writeArea(authorization: unknown, identity: string, area: "data" | "cache", path: string[], content: ReadableStream<Uint8Array> | null, signal?: AbortSignal) {
+ public async writeArea(authorization: unknown, program: unknown, area: "data" | "cache", path: string[], content: ReadableStream<Uint8Array> | null, signal?: AbortSignal) {
this.verify(authorization)
- await this.programManager.writeArea(identity, area, path, content, signal)
+ await this.programManager.writeArea(program, area, path, content, signal)
}
// A targeted client observation belongs to one authorized desktop
diff --git a/source/server/core/link-manager/auth-manager/process-manager/process-manager.ts b/source/server/core/link-manager/auth-manager/process-manager/process-manager.ts
index 5d4eb04..3210d81 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,8 +17,9 @@ import { endpointReference, processReference } from "./endpoint-reference"
import EndpointEvents from "./endpoint-events"
import EndpointServices from "./endpoint-services"
import OutsideQuestions from "./outside-questions"
-import { isPermissionName, isServiceKey, type ClientLaunch, type Launch, type PermissionName, type ServerLaunch, type ServiceKey, type WindowGeometry, type WindowLayer } from "@phreshos/core"
+import { isServiceKey, type ClientLaunch, type Launch, type PermissionChange, type PermissionRequest, type ServerLaunch, type ServiceKey, type WindowGeometry, type WindowLayer } from "@phreshos/core"
import type { ServerRuntime } from "./server-runtime"
+import { permissionCatalog } from "@server/core/permissions"
/**
* The core's processes: the wire and the collection. Each process owns
@@ -355,8 +356,6 @@ export default class ProcessManager extends TheLink {
try {
observed = this.system.holdProcess(target)
-
- if (observed.program !== this.find(pane).program) throw new Error("The desktop does not know this process")
}
catch (error) {
@@ -378,30 +377,9 @@ export default class ProcessManager extends TheLink {
boundary.observe(subscription, observed.reference, observation.half, kind, event, reportImpossible)
}
- /** Remove foreign Endpoint identities before observed traffic reaches a Client boundary. */
- private clientVisibleTraffic(pane: string, values: unknown[]) {
-
- const viewer = this.processes.get(pane)
-
- const index = values.length - 1
-
- const message = values[index]
-
- if (!viewer || index < 0 || typeof message !== "object" || message === null || !("to" in message)) return values
-
- const to = message.to
-
- if (typeof to !== "object" || to === null || !("process" in to)) return values
-
- const reference = to as ReturnType<typeof endpointReference>
+ private clientVisibleTraffic(_pane: string, values: unknown[]) {
- if (reference.process.program.identity === viewer.program.identity) return values
-
- const masked = [...values]
-
- masked[index] = { ...message, to: null }
-
- return masked
+ return values
}
private removeClientObservation(connection: string, pane: string, owner: string, subscription: string) {
@@ -422,8 +400,6 @@ export default class ProcessManager extends TheLink {
try {
observed = this.system.holdProcess(target)
-
- if (observed.program !== this.find(pane).program) throw new Error("The desktop does not know this process")
}
catch (error) {
@@ -553,9 +529,7 @@ export default class ProcessManager extends TheLink {
const received = {
- from: targetHalf === "client" && sourceProcess.program !== targetProcess.program
- ? null
- : endpointReference(sourceProcess, sourceHalf),
+ from: endpointReference(sourceProcess, sourceHalf),
payload
}
@@ -1376,72 +1350,66 @@ export default class ProcessManager extends TheLink {
await this.hostTraffic.emitSubject(domain, event, subject, ...values)
}
- /** Reads the effective permission decision for one live Client Process. */
- public permissionGranted(identity: string, permission: PermissionName): boolean | null {
-
- const process = this.find(identity)
-
- if (!process.client) throw new Error("This process has no live client endpoint")
+ /** Reads only the persistent user grant belonging to this Process's Program. */
+ public permission(identity: string, name: string) {
- if (process.permissions.has(permission)) return true
-
- return this.authManager.programManager.permission(process.program, permission) ?? null
+ return this.authManager.programManager.permission(this.find(identity).program, name)
}
- /** Creates at most one user-facing permission request for a Client Process. */
- public async requestPermission(identity: string, request: string, permission: PermissionName) {
+ /** Resolves one permission request through declarations, grants, then the owner. */
+ public async requestPermission(identity: string, request: string, name: string, input: PermissionRequest): Promise<PermissionChange> {
const process = this.find(identity)
- if (!process.client) throw new Error("This process has no live client endpoint")
+ if (!process.client) throw new Error("A permission request requires a live Client endpoint")
- const known = this.permissionGranted(identity, permission)
+ const requested = permissionCatalog.resolve(name, input)
- if (known !== null) return known
+ if (!Array.isArray(requested)) throw new Error("A permission request must be true or a list of values")
- const choice = await this.authManager.dialogManager.requestPermission(process, request, permission)
+ const declared = process.program.clientPermissions[name] ?? null
+ const temporary = process.permissions.get(name) ?? null
+ const stored = this.authManager.programManager.permission(process.program, name)
+ const effective = permissionCatalog.effective(name, declared, temporary, stored)
- if (choice === "process") {
+ if (permissionCatalog.grants(effective, requested)) return Object.freeze({ permission: requested, needReload: false })
+ if (effective === false) return Object.freeze({ permission: false, needReload: false })
- if (this.processes.get(identity) !== process || !process.client) return null
+ const choice = await this.authManager.dialogManager.requestPermission(process, request, name, requested)
- process.permissions.add(permission)
+ if (choice === "process") {
- await this.permissionChanged(process.program, permission)
+ const permission = permissionCatalog.merge(name, temporary, requested)
+ const changed = permissionCatalog.changed(
+ effective,
+ permissionCatalog.effective(name, declared, permission, stored)
+ )
- return true
+ process.permissions.set(name, permission)
+
+ return Object.freeze({
+ permission: [...permission],
+ needReload: permissionCatalog.needReload(name, changed)
+ })
}
if (choice === "always") {
- if (this.processes.get(identity) !== process || !process.client) return null
-
- this.authManager.programManager.setPermission(process.program, permission, true)
-
- return true
+ return this.authManager.programManager.setPermission(
+ process.program,
+ name,
+ permissionCatalog.merge(name, stored, requested)
+ )
}
- return choice
+ return Object.freeze({ permission: choice, needReload: false })
}
- public async cancelPermission(identity: string, request: string) {
+ public cancelPermission(identity: string, request: string) {
const process = this.processes.get(identity)
- if (!process) return
-
- await this.authManager.dialogManager.cancelPermission(request, process.reference)
- }
-
- /** Publishes one effective-decision change to every desktop counterpart. */
- public async permissionChanged(program: Program, permission: PermissionName) {
-
- for (const process of this.processes.values()) {
-
- if (process.program !== program || !process.client) continue
-
- await this.$outbound.publish("/permission", process.identity, permission, this.permissionGranted(process.identity, permission))
- }
+ return process ? this.authManager.dialogManager.cancelPermission(request, process.reference) : Promise.resolve()
}
// A window's news, said once and heard by both kinds of half.
@@ -1480,6 +1448,19 @@ export default class ProcessManager extends TheLink {
if (word === "current-program") return [this.system.requireProgram(process.program.identity)]
+ if (word === "program-permissions") {
+
+ const program = this.system.holdProgram(rest[0], process.program)
+ const operation = rest[1]
+
+ if (operation === "all") return [this.authManager.programManager.permissions(program)]
+ if (operation === "get") return [this.authManager.programManager.permission(program, String(rest[2]))]
+ if (operation === "set") return [this.authManager.programManager.setPermission(program, String(rest[2]), rest[3] as never)]
+ if (operation === "delete") return [this.authManager.programManager.deletePermission(program, String(rest[2]))]
+
+ throw new Error(`The System does not know the Program permission operation "${String(operation)}"`)
+ }
+
if (word === "program-agent") {
const program = this.system.holdProgram(rest[0], process.program)
@@ -1501,37 +1482,6 @@ export default class ProcessManager extends TheLink {
return [await this.system.programStartup(program, String(rest[1]), rest[2])]
}
- if (word === "program-permission") {
-
- const program = this.system.holdProgram(rest[0], process.program)
- const operation = rest[1]
- const name = rest[2]
-
- if (operation === "getAll") return [this.system.programPermissions(program)]
-
- if (!isPermissionName(name)) throw new Error(`The system does not know the permission "${String(name)}"`)
-
- if (operation === "get") return [this.system.programPermission(program, name)]
-
- if (operation === "set") {
-
- if (typeof rest[3] !== "boolean") throw new Error("A permission decision must be boolean")
-
- this.system.setProgramPermission(program, name, rest[3])
-
- return []
- }
-
- if (operation === "delete") {
-
- this.system.deleteProgramPermission(program, name)
-
- return []
- }
-
- throw new Error(`The host does not know the permission operation "${String(operation)}"`)
- }
-
// Which live process made this one through `program.process.create()`.
// The child retains a handle, but the registry remains authoritative:
// once the parent disappears that retained handle no longer resolves.
diff --git a/source/server/core/link-manager/auth-manager/process-manager/process.ts b/source/server/core/link-manager/auth-manager/process-manager/process.ts
index 9d6da50..99d84db 100644
--- a/source/server/core/link-manager/auth-manager/process-manager/process.ts
+++ b/source/server/core/link-manager/auth-manager/process-manager/process.ts
@@ -6,9 +6,10 @@ import ServerProcessBoundary from "./server-process-boundary"
import HostTraffic from "./host-traffic"
import ClientState from "./client-state"
import { randomUUID } from "node:crypto"
-import { type Layer, type PermissionName } from "@phreshos/core"
+import { type Layer } from "@phreshos/core"
import { Tunnel } from "@the-link/core"
import type { ServerRuntime } from "./server-runtime"
+import type { Permission } from "@phreshos/core"
/**
* One live execution of a Program.
@@ -50,9 +51,6 @@ export default class Process {
/** Immutable normalized intent used only to converge named creation. */
public readonly launch: ProcessLaunch
- /** Permission grants that live exactly as long as this Process. */
- public readonly permissions = new Set<PermissionName>()
-
// When this instance began. A process's birth is its construction,
// so nothing hands this over — there is no earlier moment to mean.
//
@@ -79,6 +77,9 @@ export default class Process {
// either life.
public readonly parent: Process | null
+ /** User grants retained only for this Process lifetime. */
+ public readonly permissions = new Map<string, Exclude<Permission, false | null>>()
+
private readonly hostTraffic: HostTraffic
private readonly serverStarts: ((server: ServerProcessBoundary) => void)[] = []
diff --git a/source/server/core/link-manager/auth-manager/program-manager/config.ts b/source/server/core/link-manager/auth-manager/program-manager/config.ts
index 188a51f..99ede80 100644
--- a/source/server/core/link-manager/auth-manager/program-manager/config.ts
+++ b/source/server/core/link-manager/auth-manager/program-manager/config.ts
@@ -1,4 +1,4 @@
-import { type Layer, type Position, type Size } from "@phreshos/core"
+import { type ClientPermissionDeclarations, type Layer, type Position, type Size } from "@phreshos/core"
/**
* What a program says it is.
@@ -136,6 +136,10 @@ export interface ClientConfig {
// nothing to undo, where one that opens shown and hides itself has
// already been seen.
minimize?: boolean
+
+ // Initial grants fixed for this Program entity. Process launches cannot
+ // add to or replace them.
+ permissions?: ClientPermissionDeclarations
}
export { layers, type Layer, type Position, type Size, type Value } from "@phreshos/core"
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.ts
index 6368bad..a4d55bf 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
@@ -2,36 +2,30 @@ import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync
import { randomUUID } from "node:crypto"
import { join } from "node:path"
import type Program from "./program"
-import { isPermissionName, type PermissionDecisions } from "@phreshos/core"
+import { permissionCatalog } from "@server/core/permissions"
+import type { Permissions } from "@phreshos/core"
const file = "permissions.json"
-/** Reads one Program's system-managed persistent permission decisions. */
-export function readPermissions(program: Program): PermissionDecisions {
+/** Reads one Program's system-managed persistent user grants. */
+export function readPermissions(program: Program): Permissions {
+
const path = join(program.storagePath, file)
if (!existsSync(path)) return {}
- const parsed = JSON.parse(readFileSync(path, "utf8")) as unknown
-
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("The Program permissions file is invalid")
-
- const entries = Object.entries(parsed)
+ try { return permissionCatalog.stored(JSON.parse(readFileSync(path, "utf8"))) }
- const permissions: PermissionDecisions = {}
+ catch (exception) {
- for (const [name, value] of entries) {
+ if (exception instanceof SyntaxError) throw new Error("The Program permissions file is invalid")
- if (!isPermissionName(name) || typeof value !== "boolean") throw new Error("The Program permissions file is invalid")
-
- permissions[name] = value
+ throw exception
}
-
- return permissions
}
-/** Atomically replaces one Program's persistent permission decisions. */
-export function writePermissions(program: Program, permissions: PermissionDecisions) {
+/** Atomically replaces one Program's persistent user grants. */
+export function writePermissions(program: Program, permissions: Permissions) {
mkdirSync(program.storagePath, { recursive: true })
@@ -39,6 +33,7 @@ export function writePermissions(program: Program, permissions: PermissionDecisi
const temporary = join(program.storagePath, `.${file}.${randomUUID()}`)
try {
+
writeFileSync(temporary, `${JSON.stringify(permissions, null, 2)}\n`)
renameSync(temporary, path)
}
diff --git a/source/server/core/link-manager/auth-manager/program-manager/program-manager.ts b/source/server/core/link-manager/auth-manager/program-manager/program-manager.ts
index 7187f8d..29b1527 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
@@ -1,5 +1,5 @@
import { copyFileSync, cpSync, existsSync, mkdirSync, mkdtempSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs"
-import { Connect } from "@the-link/core/decorators"
+import { Connect, Subscribe } from "@the-link/core/decorators"
import { randomUUID } from "node:crypto"
import { TheLink } from "@the-link/core"
import SqliteDatabase from "@libs/sqlite-database"
@@ -12,7 +12,7 @@ import { dirname, isAbsolute, join } from "node:path"
import { isDeepStrictEqual } from "node:util"
import Logs, { type LogSource } from "./logs"
import { isValue, layers, type ProgramConfig } from "./config"
-import { type ClientLaunch, type Launch, type PermissionName, type ProgramCommandChunk } from "@phreshos/core"
+import { type ClientLaunch, type Launch, type ProgramCommandChunk } from "@phreshos/core"
import { type default as Process, type ProcessLaunch, type Stream } from "../process-manager/process"
import { type StandardShape } from "../process-manager/process-manager"
import Program, { type CommandOutput, type InstallOutput } from "./program"
@@ -20,11 +20,23 @@ import Entry, { type HostedEntry } from "./entry"
import Keyv from "keyv"
import { isIconSize, ProgramIcons } from "./icon"
import { readStartup, removeStartup, writeStartup } from "./startup"
-import { readPermissions, writePermissions } from "./permissions"
import { CommandServerRuntime, WorkerServerRuntime } from "../process-manager/server-runtime"
+import { permissionCatalog } from "@server/core/permissions"
+import { readPermissions, writePermissions } from "./permissions"
+import { type Permission, type PermissionChange, type PermissionInput, type Permissions } from "@phreshos/core"
const maximumProcessesPerProgram = 20
+function clonePermission(permission: Permission): Permission {
+
+ return Array.isArray(permission) ? [...permission] : permission
+}
+
+function clonePermissions(permissions: Permissions): Permissions {
+
+ return Object.fromEntries(Object.entries(permissions).map(([name, permission]) => [name, clonePermission(permission)]))
+}
+
/**
* Every program this runtime knows, in one map keyed by its public
* identity. Installation is a flag on the record; it changes persistence,
@@ -49,6 +61,8 @@ export default class ProgramManager extends TheLink {
// This keeps find-or-create atomic even when another caller uses create.
private readonly creating = new Map<string, Promise<void>>()
+ private readonly clientCommands = new Map<string, () => void>()
+
// What each program remembers about itself, opened on first use and
// kept by the identity of the program that asked.
private readonly opened = new Map<string, Keyv>()
@@ -138,42 +152,112 @@ export default class ProgramManager extends TheLink {
return entry
}
- /** Reads one persistent permission decision without creating storage. */
- public permission(program: Program, name: PermissionName) {
+ /** Reads one Program's stored user grant without deriving effective access. */
+ public permission(program: Program, name: string): Permission {
- return readPermissions(program)[name]
+ permissionCatalog.definition(name)
+
+ return clonePermission(readPermissions(program)[name] ?? null)
}
- /** Returns an independent snapshot of one Program's persistent decisions. */
- public permissions(program: Program) {
+ /** Returns an independent snapshot of one Program's stored user grants. */
+ public permissions(program: Program): Permissions {
- return readPermissions(program)
+ return clonePermissions(readPermissions(program))
}
- /** Stores one persistent permission decision. */
- public setPermission(program: Program, name: PermissionName, value: boolean) {
+ /** Stores one canonical user grant and reports its Client activation need. */
+ public setPermission(program: Program, name: string, value: Exclude<PermissionInput, null>): PermissionChange {
+
+ if (value === null) throw new Error("A stored Program permission cannot be null")
const permissions = readPermissions(program)
+ const before = permissions[name] ?? null
+ const permission = permissionCatalog.resolve(name, value)
+ const change = this.permissionChange(program, name, before, permission)
- Object.defineProperty(permissions, name, { configurable: true, enumerable: true, value, writable: true })
+ if (permissionCatalog.changed(before, permission)) {
- writePermissions(program, permissions)
+ permissions[name] = permission
+ writePermissions(program, permissions)
+ }
- this.authManager.processManager.permissionChanged(program, name).catch(() => undefined)
+ return change
}
- /** Removes one persistent permission decision. */
- public deletePermission(program: Program, name: PermissionName) {
+ /** Removes one stored user grant without changing Program declarations. */
+ public deletePermission(program: Program, name: string): PermissionChange {
+
+ permissionCatalog.definition(name)
const permissions = readPermissions(program)
+ const before = permissions[name] ?? null
+
+ if (Object.hasOwn(permissions, name)) {
+
+ delete permissions[name]
+ writePermissions(program, permissions)
+ }
+
+ return this.permissionChange(program, name, before, null)
+ }
- if (!Object.hasOwn(permissions, name)) return
+ @Connect("/permissions")
+ protected async programPermissions(subject: unknown, operation: unknown, name?: unknown, value?: unknown) {
- delete permissions[name]
+ const program = this.held(subject)
- writePermissions(program, permissions)
+ if (operation === "all") return this.permissions(program)
+ if (operation === "get") return this.permission(program, String(name))
+ if (operation === "set") return this.setPermission(program, String(name), value as Exclude<PermissionInput, null>)
+ if (operation === "delete") return this.deletePermission(program, String(name))
- this.authManager.processManager.permissionChanged(program, name).catch(() => undefined)
+ throw new Error(`The System does not know the Program permission operation "${String(operation)}"`)
+ }
+
+ private permissionChange(program: Program, name: string, before: Permission, permission: Permission): PermissionChange {
+
+ const changed = [...this.authManager.processManager.processes.values()].some(process => {
+
+ if (process.program !== program || process.client === null) return false
+
+ const declared = program.clientPermissions[name] ?? null
+ const temporary = process.permissions.get(name) ?? null
+
+ return permissionCatalog.changed(
+ permissionCatalog.effective(name, declared, temporary, before),
+ permissionCatalog.effective(name, declared, temporary, permission)
+ )
+ })
+
+ return Object.freeze({
+ permission: clonePermission(permission),
+ needReload: permissionCatalog.needReload(name, changed)
+ })
+ }
+
+ @Connect("/create-program")
+ protected async createProgram(source: ProgramConfig | string) {
+
+ return (await this.create(source)).identity
+ }
+
+ @Connect("/force-create-program")
+ protected async forceCreateProgram(source: ProgramConfig | string, asker: string) {
+
+ 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)
}
public reach(identity: string) {
@@ -436,9 +520,9 @@ export default class ProgramManager extends TheLink {
// channel and a pane says over the link, because the two roads must
// mean the same thing.
@Connect("/logs")
- public async logs(identity: string, sql: string, values: unknown[]) {
+ public async logs(subject: unknown, sql: string, values: unknown[]) {
- return this.logsOf(this.reachOrRefuse(identity)).query(sql, values)
+ return this.logsOf(this.held(subject)).query(sql, values)
}
// A program's own database, opened on first use like the managed files
@@ -462,25 +546,25 @@ export default class ProgramManager extends TheLink {
// Read and written both: this file is the program's own, which is
// the whole of why it is a file of its own.
@Connect("/database")
- public async database(identity: string, sql: string, values: unknown[]) {
+ public async database(subject: unknown, sql: string, values: unknown[]) {
- return this.databaseOf(this.reachOrRefuse(identity)).query(sql, values)
+ return this.databaseOf(this.held(subject)).query(sql, values)
}
/** One authoritative icon operation shared by SDKs and HTTP hosting. */
@Connect("/icon")
- public async icon(identity: string, size: unknown) {
+ public async icon(subject: unknown, size: unknown) {
if (!isIconSize(size)) throw new Error("A Program icon size is small, medium, or large")
- return [...await this.icons.render(this.reachOrRefuse(identity), size)]
+ return [...await this.icons.render(this.held(subject), size)]
}
/** Reads Program-specific operating knowledge for agents. */
@Connect("/agent")
- public async agent(identity: string) {
+ public async agent(subject: unknown) {
- return this.reachOrRefuse(identity).agent()
+ return this.held(subject).agent()
}
/** Read or change the system-managed startup launch for one Program. */
@@ -522,12 +606,12 @@ export default class ProgramManager extends TheLink {
// A store's five controls, in one place. Reached from a process
// over its own channel and from a session over the link, and both
- // must mean the same thing. The identity always names a Program;
+ // must mean the same thing. The exact handle always names a Program;
// application persistence has no generic route through this manager.
@Connect("/store")
- public async store(identity: string, operation: string, key: string, value?: unknown, ttl?: number) {
+ public async store(subject: unknown, operation: string, key: string, value?: unknown, ttl?: number) {
- const store = this.storeOf(this.reachOrRefuse(identity))
+ const store = this.storeOf(this.held(subject))
if (operation === "get") return await store.get(key) as unknown
@@ -545,11 +629,11 @@ export default class ProgramManager extends TheLink {
// Area metadata reached from a session over the link. Content stays
// a byte stream at the storage door; locations remain server-only.
@Connect("/area")
- public async area(identity: string, area: string, operation: string, args: unknown[]) {
+ public async area(subject: unknown, area: string, operation: string, args: unknown[]) {
if (area !== "data" && area !== "cache") throw new Error(`The host does not know the place "${String(area)}"`)
- return this.operate(this.reachOrRefuse(identity), area, operation, args)
+ return this.operate(this.held(subject), area, operation, args)
}
public reachOrRefuse(identity: string) {
@@ -597,14 +681,14 @@ export default class ProgramManager extends TheLink {
throw new Error(`The host does not know the storage operation "${operation}"`)
}
- public streamArea(identity: string, area: Area, joins: string[]) {
+ public streamArea(subject: unknown, area: Area, joins: string[]) {
- return this.areaOf(this.reachOrRefuse(identity), area).stream(joins)
+ return this.areaOf(this.held(subject), area).stream(joins)
}
- public async writeArea(identity: string, area: Area, joins: string[], content: ReadableStream<Uint8Array> | null, signal?: AbortSignal) {
+ public async writeArea(subject: unknown, area: Area, joins: string[], content: ReadableStream<Uint8Array> | null, signal?: AbortSignal) {
- await this.areaOf(this.reachOrRefuse(identity), area).write(joins, content, signal)
+ await this.areaOf(this.held(subject), area).write(joins, content, signal)
}
// ── Installing and uninstalling ──────────────────────────────────
@@ -621,41 +705,88 @@ export default class ProgramManager extends TheLink {
// Installation changes every path a process may have remembered, so
// validation happens first and every process ends before the live
// Program is pointed at its canonical files.
- @Connect("/install-program")
- public async installNamed(identity: string, asker: string | null = null) {
+ @Connect("/forget-program")
+ public async forgetNamed(subject: unknown, asker: string | null = null) {
- const program = this.reach(identity)
+ return await this.forget(this.held(subject), asker)
+ }
- if (!program) throw new Error("The system does not know this program")
+ @Connect("/client-command")
+ protected async clientCommand(stream: string, operation: string, subject: unknown, value: unknown, asker: string) {
- return await this.install(program, asker)
- }
+ if (!stream || this.clientCommands.has(stream)) throw new Error("A Client Program command needs a unique stream")
- @Connect("/uninstall-program-stream")
- public async uninstallNamedStreaming(identity: string, everything = false, asker: string | null = null, stream: unknown) {
+ const program = this.held(subject)
+ let active = true
+ let running: Process | null = null
+ const cancel = () => {
- if (typeof stream !== "string" || !stream) throw new Error("Uninstalling needs a stream identity")
+ active = false
+ if (running) this.authManager.linkManager.application.system.exitProcess(running).catch(() => undefined)
+ }
- const program = this.reach(identity)
+ this.clientCommands.set(stream, cancel)
- if (!program) throw new Error("The system does not know this program")
+ try {
- for await (const chunk of this.uninstallStreaming(program, everything, asker)) {
+ if (operation === "run") {
- await this.$outbound.publish("/uninstall-program-output", stream, chunk)
- }
+ let finish!: () => void
+ const completion = new Promise<void>(resolve => { finish = resolve })
+ let sending = Promise.resolve()
+ const emit = (event: unknown) => {
- return program.identity
- }
+ if (!active) return
+ sending = sending.then(async () => { await this.$outbound.publish("/client-command-output", stream, event) })
+ }
- @Connect("/forget-program")
- public async forgetNamed(identity: string, asker: string | null = null) {
+ await this.runProcess(program, value as Launch ?? {}, {
+ started: process => {
+
+ running = process
+ emit({ event: "started", process })
+ },
+ output: (output, text) => emit({ event: "output", stream: output === "err" ? "stderr" : "stdout", text }),
+ exited: (code, signal) => {
+
+ emit({
+ event: "exited",
+ process: running,
+ exit: { status: signal ? "signaled" : "exited", code, signal }
+ })
+ finish()
+ }
+ }, this.authManager.processManager.processes.get(asker) ?? null)
+
+ await completion
+ await sending
+ return
+ }
- const program = this.reach(identity)
+ const command = operation === "install"
+ ? this.installStreaming(program, asker)
+ : operation === "uninstall"
+ ? this.uninstallStreaming(program, value === true, asker)
+ : null
- if (!program) throw new Error("The system does not know this program")
+ if (!command) throw new Error(`The Program command API does not know "${operation}"`)
- return await this.forget(program, asker)
+ for await (const chunk of command) {
+
+ if (!active) return
+ await this.$outbound.publish("/client-command-output", stream, chunk)
+ }
+ }
+ finally {
+
+ this.clientCommands.delete(stream)
+ }
+ }
+
+ @Subscribe("/client-command-cancel")
+ protected cancelClientCommand(stream: unknown) {
+
+ if (typeof stream === "string") this.clientCommands.get(stream)?.()
}
/** Install while exposing command output with consumer-driven backpressure. */
@@ -975,16 +1106,16 @@ export default class ProgramManager extends TheLink {
}
@Connect("/create-process")
- public async createProcess(identity: string, launch: Launch = {}, parent: Process | string | null = null) {
+ public async createProcess(subject: unknown, launch: Launch = {}, parent: Process | string | null = null) {
+
+ const program = this.held(subject)
- return await this.serializeCreation(identity, async () => {
+ return await this.serializeCreation(program.identity, async () => {
// Every runtime program, installed or not, is reached through the
// same registry. A created process therefore starts from the exact
// Program its caller addressed, never from an installed-only view.
- const program = this.reach(identity)
-
- if (!program) throw new Error("The system does not know this program")
+ if (this.reach(program.identity) !== program) throw new Error("The Program represented by this handle does not exist")
const creator = typeof parent === "string" ? this.authManager.processManager.processes.get(parent) : parent
@@ -1006,17 +1137,15 @@ export default class ProgramManager extends TheLink {
}
@Connect("/find-or-create-process")
- public async findOrCreateProcess(subject: string | Program, launch: Launch & { name: string }, parent: Process | string | null = null) {
-
- const identity = typeof subject === "string" ? subject : subject.identity
+ public async findOrCreateProcess(subject: unknown, launch: Launch & { name: string }, parent: Process | string | null = null) {
- return await this.serializeCreation(identity, async () => {
+ const held = this.held(subject)
- const program = this.reach(identity)
+ return await this.serializeCreation(held.identity, async () => {
- if (!program) throw new Error("The system does not know this program")
+ const program = this.reach(held.identity)
- if (typeof subject !== "string" && program !== subject) throw new Error("The Program represented by this handle does not exist")
+ if (program !== held) throw new Error("The Program represented by this handle does not exist")
const resolved = this.resolveLaunch(program, launch)
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.ts
index 892abf8..091d35c 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
@@ -3,8 +3,10 @@ import { existsSync, readFileSync, realpathSync, statSync } from "node:fs"
import { dirname, isAbsolute, normalize, relative, resolve, sep } from "node:path"
import { spawn } from "node:child_process"
import { randomUUID } from "node:crypto"
+import { isDeepStrictEqual } from "node:util"
import { validateIcon } from "./icon"
-import type { ProgramCommandChunk } from "@phreshos/core"
+import type { ClientPermissions, ProgramCommandChunk } from "@phreshos/core"
+import { permissionCatalog } from "@server/core/permissions"
/**
* A program: a description, and the things it names.
@@ -44,12 +46,16 @@ export default class Program {
public config: ProgramConfig
+ public readonly clientPermissions: ClientPermissions
+
public constructor(source: string | ProgramConfig, root?: string) {
const [config, where] = typeof source === "string" ? read(source) : [source, process.cwd()]
this.config = coherent(config)
+ this.clientPermissions = permissionCatalog.declarations(this.config.client?.permissions)
+
this.identity = this.config.identity
// Given only when a program is made from another: the same
@@ -73,6 +79,8 @@ export default class Program {
if (source.identity !== this.identity) throw new Error("A program cannot change its identity")
+ if (!isDeepStrictEqual(source.clientPermissions, this.clientPermissions)) throw new Error("A Program's Client permissions cannot change during its lifetime")
+
this.config = source.config
this.root = source.root
@@ -108,7 +116,8 @@ export default class Program {
return this.config.client ? {
...this.config.client,
start: this.config.client.start ?? true,
- service: this.config.client.service ?? false
+ service: this.config.client.service ?? false,
+ permissions: this.clientPermissions
} : null
}
@@ -241,7 +250,9 @@ export default class Program {
layer: client.layer ?? null,
- minimize: client.minimize ?? null
+ minimize: client.minimize ?? null,
+
+ permissions: client.permissions
}
}
}
diff --git a/source/server/core/permissions.ts b/source/server/core/permissions.ts
new file mode 100644
index 0000000..e8f656b
--- /dev/null
+++ b/source/server/core/permissions.ts
@@ -0,0 +1,148 @@
+import {
+ type ClientPermissions,
+ type Permission,
+ type PermissionDefinition,
+ type Permissions
+} from "@phreshos/core"
+import { isDeepStrictEqual } from "node:util"
+
+/** Validation and derivation over one exact permission definition set. */
+export class PermissionCatalog {
+
+ private readonly definitions: Readonly<Record<string, PermissionDefinition>>
+
+ public constructor(definitions: Readonly<Record<string, PermissionDefinition>>) {
+
+ const validated: Record<string, PermissionDefinition> = {}
+
+ for (const [name, definition] of Object.entries(definitions)) {
+
+ if (!name.length || !definition || typeof definition !== "object") throw new Error("A permission definition needs a name and definition")
+ if (definition.activation !== "live" && definition.activation !== "reload") throw new Error(`Permission "${name}" has an invalid activation`)
+ if (typeof definition.title !== "string" || !definition.title.trim()) throw new Error(`Permission "${name}" needs a title`)
+ if (typeof definition.description !== "string" || !definition.description.trim()) throw new Error(`Permission "${name}" needs a description`)
+
+ const values = strings(definition.values, `Permission "${name}" values`)
+ const defaults = strings(definition.default, `Permission "${name}" default`)
+
+ if (values.length !== new Set(values).size) throw new Error(`Permission "${name}" values must be unique`)
+ if (defaults.length !== new Set(defaults).size || defaults.some(value => !values.includes(value))) throw new Error(`Permission "${name}" has an invalid default`)
+
+ validated[name] = Object.freeze({
+ values: Object.freeze([...values]),
+ default: Object.freeze([...defaults]),
+ activation: definition.activation,
+ title: definition.title,
+ description: definition.description
+ })
+ }
+
+ this.definitions = Object.freeze(validated)
+ }
+
+ public definition(name: unknown) {
+
+ if (typeof name !== "string" || !Object.hasOwn(this.definitions, name)) throw new Error(`The System does not know the permission "${String(name)}"`)
+
+ return this.definitions[name]
+ }
+
+ public resolve(name: unknown, value: unknown): Permission {
+
+ const definition = this.definition(name)
+
+ if (value === true) return [...definition.default]
+ if (value === false || value === null) return value
+
+ const requested = strings(value, `Permission "${String(name)}"`)
+
+ if (requested.length !== new Set(requested).size || requested.some(entry => !definition.values.includes(entry))) {
+ throw new Error(`Permission "${String(name)}" contains an unknown value`)
+ }
+
+ return definition.values.filter(entry => requested.includes(entry))
+ }
+
+ public declarations(value: unknown): ClientPermissions {
+
+ if (value === undefined) return Object.freeze({})
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("A Client's permissions must be a record")
+
+ const resolved: Record<string, readonly string[]> = {}
+
+ for (const [name, assignment] of Object.entries(value)) {
+
+ const permission = this.resolve(name, assignment)
+
+ if (!Array.isArray(permission)) throw new Error(`A Client-declared permission must be true or a list of values`)
+
+ resolved[name] = Object.freeze(permission)
+ }
+
+ return Object.freeze(resolved)
+ }
+
+ public stored(value: unknown): Permissions {
+
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("The Program permissions file is invalid")
+
+ const permissions: Permissions = {}
+
+ for (const [name, assignment] of Object.entries(value)) {
+
+ if (assignment === true) throw new Error("The Program permissions file contains unresolved shorthand")
+
+ permissions[name] = this.resolve(name, assignment)
+ }
+
+ return permissions
+ }
+
+ public grants(grant: PermissionGrant, requested: readonly string[]) {
+
+ return Array.isArray(grant) && requested.every(value => grant.includes(value))
+ }
+
+ public combine(name: string, ...grants: PermissionGrant[]): Permission {
+
+ const present = grants.filter((grant): grant is readonly string[] => Array.isArray(grant))
+
+ return present.length
+ ? present.reduce<string[]>((combined, grant) => this.merge(name, combined, grant), [])
+ : null
+ }
+
+ public effective(name: string, ...grants: PermissionGrant[]): Permission {
+
+ return this.combine(name, ...grants) ?? (grants.includes(false) ? false : null)
+ }
+
+ public merge(name: string, grant: PermissionGrant, requested: readonly string[]) {
+
+ const current = Array.isArray(grant) ? grant : []
+
+ return this.resolve(name, [...current, ...requested]) as string[]
+ }
+
+ public changed(left: Permission, right: Permission) {
+
+ return !isDeepStrictEqual(left, right)
+ }
+
+ public needReload(name: string, changed: boolean) {
+
+ return changed && this.definition(name).activation === "reload"
+ }
+}
+
+type PermissionGrant = readonly string[] | false | null
+
+function strings(value: unknown, subject: string): string[] {
+
+ if (!Array.isArray(value) || value.some(entry => typeof entry !== "string")) throw new Error(`${subject} must be a list of strings`)
+
+ return value
+}
+
+/** The complete permission domain recognized by this System release. */
+export const permissionCatalog = new PermissionCatalog({})
diff --git a/source/server/core/protocol/storage.ts b/source/server/core/protocol/storage.ts
index 570f900..be23fe4 100644
--- a/source/server/core/protocol/storage.ts
+++ b/source/server/core/protocol/storage.ts
@@ -1,12 +1,16 @@
export const storageMediaType = "application/x-storage-stream"
-export interface StorageRequest {
-
- program: string
-
- area: "data" | "cache"
-
+type StorageOperation = Readonly<{
operation: "stream" | "write"
-
path: string[]
-}
+}>
+
+export type ProgramAddress = Readonly<{
+ identity: string
+ reference: string
+}>
+
+export type StorageRequest = StorageOperation & (
+ | Readonly<{ scope: "system" }>
+ | Readonly<{ scope: "program", program: ProgramAddress, area: "data" | "cache" }>
+)
diff --git a/source/server/core/system.ts b/source/server/core/system.ts
index 6127069..c94ddd3 100644
--- a/source/server/core/system.ts
+++ b/source/server/core/system.ts
@@ -2,7 +2,7 @@ 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, PermissionName, Position, ServerLaunch, Size, WindowGeometry } from "@phreshos/core"
+import type { ClientLaunch, Launch, PermissionInput, Position, ServerLaunch, 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"
@@ -79,19 +79,19 @@ export default class System {
return this.programManager.permissions(program)
}
- public programPermission(program: Program, permission: PermissionName) {
+ public programPermission(program: Program, name: string) {
- return this.programManager.permission(program, permission)
+ return this.programManager.permission(program, name)
}
- public setProgramPermission(program: Program, permission: PermissionName, value: boolean) {
+ public setProgramPermission(program: Program, name: string, permission: Exclude<PermissionInput, null>) {
- this.programManager.setPermission(program, permission, value)
+ return this.programManager.setPermission(program, name, permission)
}
- public deleteProgramPermission(program: Program, permission: PermissionName) {
+ public deleteProgramPermission(program: Program, name: string) {
- this.programManager.deletePermission(program, permission)
+ return this.programManager.deletePermission(program, name)
}
public listProcesses(program?: Program) {
@@ -151,12 +151,12 @@ export default class System {
public async createProcess(program: string | Program, launch: Launch = {}, parent: Process | string | null = null) {
- return this.programManager.createProcess(typeof program === "string" ? program : program.identity, launch, parent)
+ return this.programManager.createProcess(typeof program === "string" ? this.requireProgram(program) : program, launch, parent)
}
public async findOrCreateProcess(program: string | Program, launch: Launch & { name: string }, parent: Process | string | null = null) {
- return this.programManager.findOrCreateProcess(program, launch, parent)
+ return this.programManager.findOrCreateProcess(typeof program === "string" ? this.requireProgram(program) : program, launch, parent)
}
public runProcess(program: Program, launch: Launch = {}, watching?: Watching, parent: Process | null = null) {
@@ -280,7 +280,8 @@ export default class System {
size: program.client.size ?? null,
position: program.client.position ?? null,
layer: program.client.layer ?? null,
- minimize: program.client.minimize ?? null
+ minimize: program.client.minimize ?? null,
+ permissions: program.client.permissions
}) : null
})
}
@@ -339,12 +340,12 @@ export default class System {
public programIcon(program: Program, size: unknown) {
- return this.programManager.icon(program.identity, size)
+ return this.programManager.icon(program, size)
}
public programAgent(program: Program) {
- return this.programManager.agent(program.identity)
+ return this.programManager.agent(program)
}
public programStartup(program: Program, operation: string, value?: unknown) {
@@ -379,12 +380,12 @@ export default class System {
public programStoragePath(program: Program, area: Area) {
- return this.programManager.area(program.identity, area, "path", [])
+ return this.programManager.area(program, area, "path", [])
}
public programStore(program: Program, operation: string, key: string, value?: unknown, ttl?: number) {
- return this.programManager.store(program.identity, operation, key, value, ttl)
+ return this.programManager.store(program, operation, key, value, ttl)
}
public programQuery(program: Program, database: "logs" | "database", statement: string, values: unknown[]) {
diff --git a/source/server/view/gateway/api-request.ts b/source/server/view/gateway/api-request.ts
index 5da577c..86656c8 100644
--- a/source/server/view/gateway/api-request.ts
+++ b/source/server/view/gateway/api-request.ts
@@ -1,6 +1,5 @@
import type Application from "@server/core/application"
import { uploadLimit } from "@server/core/upload-manager"
-import { isPermissionName } from "@phreshos/core"
/** Execute one operation belonging to the shared System SDK contract. */
export default async function apiRequest(application: Application, value: unknown, signal: AbortSignal) {
@@ -45,6 +44,16 @@ export default async function apiRequest(application: Application, value: unknow
if (request.operation === "agent") return system.programAgent(program)
+ if (request.operation === "permissions") {
+
+ if (request.permissionOperation === "all") return system.programPermissions(program)
+ if (request.permissionOperation === "get") return system.programPermission(program, String(request.name))
+ if (request.permissionOperation === "set") return system.setProgramPermission(program, String(request.name), request.permission as never)
+ if (request.permissionOperation === "delete") return system.deleteProgramPermission(program, String(request.name))
+
+ throw new Error(`The Program permissions API does not know "${String(request.permissionOperation)}"`)
+ }
+
if (request.operation === "store") {
if (typeof request.storeOperation !== "string") throw new Error("A Program store operation is required")
@@ -58,33 +67,6 @@ export default async function apiRequest(application: Application, value: unknow
return system.programQuery(program, request.database, request.statement, request.values)
}
- if (request.operation === "permission") {
-
- const operation = request.permissionOperation
-
- if (operation === "getAll") return system.programPermissions(program)
- if (!isPermissionName(request.name)) throw new Error(`The system does not know the permission "${String(request.name)}"`)
- if (operation === "get") return system.programPermission(program, request.name)
-
- if (operation === "set") {
-
- if (typeof request.value !== "boolean") throw new Error("A permission decision must be boolean")
-
- system.setProgramPermission(program, request.name, request.value)
-
- return
- }
-
- if (operation === "delete") {
-
- system.deleteProgramPermission(program, request.name)
-
- return
- }
-
- throw new Error(`The Program permission API does not know "${String(operation)}"`)
- }
-
if (request.operation === "wait") {
if (request.event !== "forget" && request.event !== "uninstall") throw new Error("A Program event is forget or uninstall")
diff --git a/source/server/view/program.ts b/source/server/view/program.ts
index 2726393..8bda6c2 100644
--- a/source/server/view/program.ts
+++ b/source/server/view/program.ts
@@ -23,19 +23,6 @@ export default function (application: Application) {
const program = new Hono()
- // The desktop asks from a sandbox identical to a Program frame. Keeping
- // this beneath the same door and giving it the same public CORS response
- // makes it a real test of the asset boundary rather than a health check
- // performed from the desktop's own origin.
- program.get("/ping", context => {
-
- context.header("Access-Control-Allow-Origin", "*")
-
- context.header("Cache-Control", "no-store")
-
- return context.text("Program assets are available")
- })
-
// A client is entered at its directory: the trailing slash makes
// the page's relative assets resolve beneath it.
program.get("/:assetId{[0-9a-f-]{36}}/assets", context => context.redirect(`${new URL(context.req.url).pathname}/`))
@@ -53,8 +40,6 @@ export default function (application: Application) {
// A retained Program may outlive files removed by uninstall(false).
if (!root || !existsSync(root)) return context.text("The program has no assets", 404)
- context.header("Access-Control-Allow-Origin", "*")
-
return await serveStatic({
root,
@@ -76,13 +61,11 @@ export default function (application: Application) {
if (!isIconSize(size)) return context.text("Unknown icon size", 404)
- context.header("Access-Control-Allow-Origin", "*")
-
context.header("Cache-Control", "no-cache")
context.header("Content-Type", "image/png")
- return context.body(Uint8Array.from(await programManager.icon(found.identity, size)))
+ return context.body(Uint8Array.from(await programManager.icon(found, size)))
})
return program
diff --git a/source/server/view/storage.ts b/source/server/view/storage.ts
index 075b1b8..aa83b81 100644
--- a/source/server/view/storage.ts
+++ b/source/server/view/storage.ts
@@ -4,7 +4,7 @@ import { unframe } from "@libs/framing"
import Application from "@server/core/application"
import { Hono } from "hono"
-/** The desktop-authorized byte stream into or out of a Program area. */
+/** The authorized byte-stream door for System and Program storage. */
export default function (application: Application) {
const { authManager } = application.linkManager
@@ -41,13 +41,18 @@ export default function (application: Application) {
try {
- const { area, operation, path, program } = request.metadata
+ const metadata = request.metadata
+ const { operation, path } = metadata
if (operation === "stream") {
await request.body.cancel()
- return new Response(authManager.streamArea(authorization, program, area, path), {
+ const body = metadata.scope === "system"
+ ? application.home.stream(path)
+ : authManager.streamArea(authorization, metadata.program, metadata.area, path)
+
+ return new Response(body, {
headers: {
@@ -58,7 +63,8 @@ export default function (application: Application) {
})
}
- await authManager.writeArea(authorization, program, area, path, request.body, context.req.raw.signal)
+ if (metadata.scope === "system") await application.home.write(path, request.body, context.req.raw.signal)
+ else await authManager.writeArea(authorization, metadata.program, metadata.area, path, request.body, context.req.raw.signal)
return new Response(null, { status: 204 })
}
@@ -89,11 +95,18 @@ function validate(request: StorageRequest) {
if (!request || typeof request !== "object") throw new Error("A storage request is required")
- if (typeof request.program !== "string") throw new Error("A storage request needs a Program")
-
- if (request.area !== "data" && request.area !== "cache") throw new Error("A storage area is data or cache")
+ if (request.scope !== "system" && request.scope !== "program") throw new Error("A storage request scope is system or program")
+ if (request.scope === "program" && !isProgramAddress(request.program)) throw new Error("A Program storage request needs a Program handle")
+ if (request.scope === "program" && request.area !== "data" && request.area !== "cache") throw new Error("A storage area is data or cache")
if (request.operation !== "stream" && request.operation !== "write") throw new Error("A storage operation is stream or write")
if (!Array.isArray(request.path) || request.path.some(part => typeof part !== "string")) throw new Error("A storage path is a list of names")
}
+
+function isProgramAddress(value: unknown): value is { identity: string, reference: string } {
+
+ return typeof value === "object" && value !== null && !Array.isArray(value)
+ && "identity" in value && typeof value.identity === "string"
+ && "reference" in value && typeof value.reference === "string"
+}