Skip to content

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

Unify permission state synchronization

zohayrslilehbfae940ee579
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 e4cfcba..8ee3ac1 100644
--- a/source/client/core/link-manager/auth-manager/auth-manager.ts
+++ b/source/client/core/link-manager/auth-manager/auth-manager.ts
@@ -112,16 +112,6 @@ export default class AuthManager extends TheLink {
return await this.$outbound.publishFirst("/appearance/update", value)
}
- public async permission<Name extends PermissionName>(process: string, name: Name) {
-
- return await this.$outbound.publishFirst("/permission/get", process, name)
- }
-
- public async grantsPermission<Name extends PermissionName>(process: string, name: Name, requested: PermissionRequest<Name>) {
-
- return await this.$outbound.publishFirst("/permission/grants", process, name, requested) as boolean
- }
-
public async grantsStorage(process: string, path: string, operation?: "read" | "write" | "delete") {
return await this.$outbound.publishFirst("/permission/storage", process, path, operation) as boolean
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 f16d746..b98fba8 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
@@ -90,6 +90,20 @@ export default class ProgramManager extends TheLink {
return await this.$outbound.publishFirst("/pinned", subject, operation) as boolean
}
+ @Subscribe("/permissions-change")
+ protected async permissionsChanged(payload: ProgramRecord | null) {
+
+ if (!payload) return
+
+ const program = this.programs.get(payload.identity)
+
+ if (!program || program.reference !== payload.reference) return
+
+ program.updatePermissions(payload.permissions)
+
+ await this.$inbound.publish("/permissions", program, program.permissions)
+ }
+
/** Atomically resolves one named Process at the authoritative host. */
public async findOrCreateProcess(subject: unknown, launch: Launch & { name: string }, parent?: string) {
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 7d9854b..26cbec3 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,5 +1,5 @@
import { ProgramRecord } from "@server/core/link-manager/auth-manager/program-manager/entry"
-import { type Launch, type ProgramInstallOptions, type ProgramUninstallOptions } from "@phreshos/core"
+import { parsePermissions, type Launch, type Permissions, type ProgramInstallOptions, type ProgramUninstallOptions } from "@phreshos/core"
import ProgramManager from "./program-manager"
/**
@@ -39,6 +39,9 @@ export default class Program {
public readonly client: ProgramRecord["client"]
+ /** Effective authority synchronized with the authoritative Program state. */
+ public permissions: Permissions
+
public constructor(programManager: ProgramManager, payload: ProgramRecord) {
this.programManager = programManager
@@ -66,6 +69,13 @@ export default class Program {
this.server = payload.server
this.client = payload.client
+
+ this.permissions = parsePermissions(payload.permissions)
+ }
+
+ public updatePermissions(permissions: unknown) {
+
+ this.permissions = parsePermissions(permissions)
}
public async createProcess(launch: Launch = {}) {
diff --git a/source/client/core/link-manager/desktop-preferences-state.ts b/source/client/core/link-manager/desktop-preferences-state.ts
new file mode 100644
index 0000000..54fa8db
--- /dev/null
+++ b/source/client/core/link-manager/desktop-preferences-state.ts
@@ -0,0 +1,33 @@
+import { type DesktopPreferences } from "@phreshos/core"
+import { Tunnel } from "@the-link/core"
+
+/** Complete effective preferences owned by one browser Desktop. */
+export default class DesktopPreferencesState {
+
+ public readonly tunnel = new Tunnel()
+
+ public constructor(private current: DesktopPreferences) {}
+
+ public get value() {
+
+ return this.current
+ }
+
+ public async update(preferences: DesktopPreferences) {
+
+ if (samePreferences(this.current, preferences)) return
+
+ this.current = preferences
+
+ // This event is intentionally local: Desktop preferences do not belong
+ // to the System transport or to any other Desktop representation.
+ await this.tunnel.publish("change", preferences)
+ }
+}
+
+function samePreferences(first: DesktopPreferences, second: DesktopPreferences) {
+
+ return first.theme === second.theme
+ && first.animations === second.animations
+ && first.scale === second.scale
+}
diff --git a/source/client/core/link-manager/link-manager.ts b/source/client/core/link-manager/link-manager.ts
index c50967d..7b2135d 100644
--- a/source/client/core/link-manager/link-manager.ts
+++ b/source/client/core/link-manager/link-manager.ts
@@ -9,6 +9,7 @@ import { Property } from "@the-link/core"
import Application from "../application"
import { v4 as uuidv4 } from "uuid"
import { type RequestOutcome, unwrap } from "@libs/request-outcome"
+import DesktopPreferencesState from "./desktop-preferences-state"
export default class LinkManager extends TheLink {
@@ -20,7 +21,7 @@ export default class LinkManager extends TheLink {
public readonly appearance: Property<Appearance>
/** Complete effective local Desktop preferences and future updates. */
- public readonly desktopPreferences: Property<DesktopPreferences>
+ public readonly desktopPreferences: DesktopPreferencesState
public constructor(application: Application, sourceLink: TheLink, payload: LinkManagerSnapshot, desktopPreferences: DesktopPreferences) {
@@ -34,7 +35,7 @@ export default class LinkManager extends TheLink {
this.appearance = Property.consumer(this, payload.appearance.key, payload.appearance.value)
- this.desktopPreferences = Property.private(this, desktopPreferences)
+ this.desktopPreferences = new DesktopPreferencesState(desktopPreferences)
}
public requestDesktopPreferences(preferences: DesktopPreferencesUpdate) {
diff --git a/source/client/view/components/desktop-host/announcements.ts b/source/client/view/components/desktop-host/announcements.ts
index 17e800e..8aa251d 100644
--- a/source/client/view/components/desktop-host/announcements.ts
+++ b/source/client/view/components/desktop-host/announcements.ts
@@ -187,6 +187,12 @@ export default function useAnnouncements(authManager: AuthManager, panes: Map<st
post(entry.identity, "host-program", "pinned", entry.identity, record, pinned)
post(entry.identity, "program-host", "pinned", entry.reference, pinned)
}, [post]))
+ programs.useSubscribe("/permissions", useCallback((entry: Program | null) => {
+ if (!entry) return
+ const record = sdkProgram(entry)
+ post(entry.identity, "host-program", "permissions", entry.identity, record)
+ post(entry.identity, "program-host", "permissions", entry.reference, record)
+ }, [post]))
}
function domainIdentity(value: unknown) {
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 0e479ce..50a2b07 100644
--- a/source/client/view/components/desktop-host/client-process-boundary.ts
+++ b/source/client/view/components/desktop-host/client-process-boundary.ts
@@ -417,8 +417,11 @@ export default class ClientProcessBoundary extends TheLink {
const target = this.systemSubscriptions.get(subscription)
+ // The System checks Service authority both when registering and when
+ // emitting. Repeating that round-trip here would put delivery behind
+ // the traffic it is supposed to authorize.
return target?.domain === "service"
- ? await this.systemAccess.canService(target.service)
+ ? true
: target?.domain === "program"
? await this.systemAccess.canProgram({ identity: target.program })
: false
diff --git a/source/client/view/components/desktop-host/host.ts b/source/client/view/components/desktop-host/host.ts
index a4c6b6f..69a7cfc 100644
--- a/source/client/view/components/desktop-host/host.ts
+++ b/source/client/view/components/desktop-host/host.ts
@@ -14,7 +14,9 @@ import {
isServiceAddress,
isUploadFile,
parseDesktopPreferencesUpdate,
+ parsePermission,
parsePermissionName,
+ parsePermissions,
type PermissionRequest,
type ProgramIconSize
} from "@phreshos/core"
@@ -28,6 +30,7 @@ import {
} from "./window-presentation"
import { isWindowPresentationProperty, requireWindowPresentationTransactions } from "@shared/window-layers"
import SystemAccess from "./system-access"
+import { allowsSynchronizedPermission } from "@shared/permission-state"
/** A host answer whose stream must be transferred rather than cloned. */
export class TransferredAnswer {
@@ -695,7 +698,7 @@ export default function host(authManager: AuthManager, pane: string, viewport: (
if (operation !== "all" && operation !== "get" && operation !== "allows" && operation !== "allow" && operation !== "deny" && operation !== "request") throw new Error(`The System does not know the Program permission operation "${String(operation)}"`)
- if (operation === "all") return [await programManager.permissions(address(program), operation)]
+ if (operation === "all") return [parsePermissions(program.permissions)]
if (operation === "request") {
@@ -714,12 +717,26 @@ export default function host(authManager: AuthManager, pane: string, viewport: (
const permission = parsePermissionName(args[2])
- if (operation === "allows") return [await programManager.permissions(
- address(program),
- operation,
- permission,
- args[3] as PermissionRequest<typeof permission>
- )]
+ if (operation === "allows") {
+
+ // Native Storage scopes require host path canonicalization;
+ // every other permission is fully represented by the synced
+ // Program snapshot already held by this trusted Desktop.
+ if (permission === "storage") return [await programManager.permissions(
+ address(program),
+ operation,
+ permission,
+ args[3] as PermissionRequest<typeof permission>
+ )]
+
+ const requested = args[3] === undefined || args[3] === true
+ ? []
+ : parsePermission(permission, args[3])
+
+ if (!Array.isArray(requested)) throw new Error("A permission check must be true or a list of values")
+
+ return [allowsSynchronizedPermission(program.permissions, permission, requested)]
+ }
if (operation === "allow") {
@@ -742,7 +759,7 @@ export default function host(authManager: AuthManager, pane: string, viewport: (
return []
}
- return [await programManager.permissions(address(program), operation, permission)]
+ return [program.permissions[permission] ?? null]
}
if (word === "startup") {
diff --git a/source/client/view/components/desktop-host/sdk-records.ts b/source/client/view/components/desktop-host/sdk-records.ts
index 35fe699..6ea3191 100644
--- a/source/client/view/components/desktop-host/sdk-records.ts
+++ b/source/client/view/components/desktop-host/sdk-records.ts
@@ -1,11 +1,13 @@
-import type { ProcessSnapshot, ProgramSnapshot } from "@phreshos/core"
+import type { Permissions, ProcessSnapshot, ProgramSnapshot } from "@phreshos/core"
export type SdkProgramSource = ProgramSnapshot
+export type SdkProgramRecord = ProgramSnapshot & Readonly<{ permissions: Permissions }>
+
export type SdkProcessSource = Omit<ProcessSnapshot, "program"> & { program: string }
/** Plain SDK Program state carried across the iframe boundary. */
-export function sdkProgram(program: SdkProgramSource): ProgramSnapshot {
+export function sdkProgram(program: SdkProgramSource & { permissions: Permissions }): SdkProgramRecord {
return {
@@ -27,12 +29,14 @@ export function sdkProgram(program: SdkProgramSource): ProgramSnapshot {
server: program.server,
- client: program.client
+ client: program.client,
+
+ permissions: program.permissions
}
}
/** Plain Process state with its ownership chain embedded for synchronous navigation. */
-export function sdkProcess(process: SdkProcessSource, program: SdkProgramSource): ProcessSnapshot {
+export function sdkProcess(process: SdkProcessSource, program: SdkProgramSource & { permissions: Permissions }): ProcessSnapshot {
return {
diff --git a/source/client/view/components/desktop-host/system-access.ts b/source/client/view/components/desktop-host/system-access.ts
index 93d938c..abd52e3 100644
--- a/source/client/view/components/desktop-host/system-access.ts
+++ b/source/client/view/components/desktop-host/system-access.ts
@@ -2,6 +2,7 @@ import type AuthManager from "@client/core/link-manager/auth-manager/auth-manage
import type Program from "@client/core/link-manager/auth-manager/program-manager/program"
import type Process from "@client/core/link-manager/auth-manager/process-manager/process"
import { parseLaunch, type ClientLaunch, type ConnectionSnapshot, type PermissionName, type PermissionValue, type ServiceAddress } from "@phreshos/core"
+import { allowsSynchronizedPermission } from "@shared/permission-state"
const denied = "Execution is not permitted"
@@ -22,24 +23,24 @@ export default class SystemAccess {
public async all() {
- return await this.authManager.grantsPermission(this.pane, "all", [])
+ return allowsSynchronizedPermission(this.permissions(), "all", [])
}
public async canProgram(program: Pick<Program, "identity">) {
return this.ownsProgram(program)
- || await this.authManager.grantsPermission(this.pane, "programs", [program.identity])
+ || allowsSynchronizedPermission(this.permissions(), "programs", [program.identity])
}
public async canProcess(process: Pick<Process, "program">) {
return this.ownsProcess(process)
- || await this.authManager.grantsPermission(this.pane, "programs", [process.program])
+ || allowsSynchronizedPermission(this.permissions(), "programs", [process.program])
}
public async canService(service: ServiceAddress) {
- return await this.authManager.grantsPermission(this.pane, "services", [service.process])
+ return allowsSynchronizedPermission(this.permissions(), "services", [service.process])
}
/** Whether one Connection belongs to this Client's visible scope. */
@@ -145,7 +146,7 @@ export default class SystemAccess {
public async require<Name extends PermissionName>(name: Name, values: readonly PermissionValue<Name>[]) {
- if (!await this.authManager.grantsPermission(this.pane, name, values)) throw new Error(denied)
+ if (!allowsSynchronizedPermission(this.permissions(), name, values)) throw new Error(denied)
}
private async currentConnection(): Promise<ConnectionSnapshot> {
@@ -155,8 +156,8 @@ export default class SystemAccess {
private async connectionScope(): Promise<"all" | ConnectionSnapshot | null> {
- if (await this.authManager.grantsPermission(this.pane, "connections", [])) return "all"
- if (!await this.authManager.grantsPermission(this.pane, "desktopConnection", [])) return null
+ if (allowsSynchronizedPermission(this.permissions(), "connections", [])) return "all"
+ if (!allowsSynchronizedPermission(this.permissions(), "desktopConnection", [])) return null
return await this.currentConnection()
}
@@ -169,4 +170,13 @@ export default class SystemAccess {
return process
}
+
+ private permissions() {
+
+ const program = this.authManager.programManager.programs.get(this.owner().program)
+
+ if (!program) throw new Error("The desktop does not know this program")
+
+ return program.permissions
+ }
}
diff --git a/source/client/view/structure/desktop/windows/window-header.tsx b/source/client/view/structure/desktop/windows/window-header.tsx
index 27d4b19..3991436 100644
--- a/source/client/view/structure/desktop/windows/window-header.tsx
+++ b/source/client/view/structure/desktop/windows/window-header.tsx
@@ -6,9 +6,12 @@ export default function WindowHeader({ title, icon, active, whole, stopping, onG
return <Window.Header active={active} onPointerDown={onGrab} onDoubleClick={onMaximize}>
<Window.Header.Identity icon={icon} title={title} />
<Window.Header.Actions>
- {onMinimize && <Window.Header.Minimize onPress={onMinimize} />}
+ {/* The Desktop transfers focus before either operation makes the
+ iframe unavailable. React Aria must not preserve focus in that
+ disappearing cross-document target. */}
+ {onMinimize && <Window.Header.Minimize preventFocusOnPress={false} onPress={onMinimize} />}
{onMaximize && <Window.Header.Maximize maximized={whole} onPress={onMaximize} />}
- {onClose && <Window.Header.Close onPress={onClose} disabled={stopping} />}
+ {onClose && <Window.Header.Close preventFocusOnPress={false} onPress={onClose} disabled={stopping} />}
</Window.Header.Actions>
</Window.Header>
}
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 72d0286..798a480 100644
--- a/source/server/core/link-manager/auth-manager/auth-manager.ts
+++ b/source/server/core/link-manager/auth-manager/auth-manager.ts
@@ -1,4 +1,4 @@
-import { Connect, Forward, Intercept, Subscribe } from "@the-link/core/decorators"
+import { Forward, Intercept, Subscribe } from "@the-link/core/decorators"
import UploadManager, { uploadLimit } from "@server/core/upload-manager"
import DialogManager from "@server/core/dialog-manager"
import ProcessManager from "./process-manager/process-manager"
@@ -6,7 +6,6 @@ import ProgramManager from "./program-manager/program-manager"
import { TheLink } from "@the-link/core"
import LinkManager from "../link-manager"
import { parsePermissionName, type PermissionRequest } from "@phreshos/core"
-import { permissionCatalog } from "@server/core/permissions"
import ShellManager from "./shell-manager"
export default class AuthManager extends TheLink {
@@ -107,7 +106,7 @@ export default class AuthManager extends TheLink {
return this.programManager.streamArea(program, area, path, options)
}
- @Connect("/storage")
+ @Subscribe("/storage")
protected async storage(operation: unknown, values: unknown, input?: unknown) {
if (typeof operation !== "string" || !Array.isArray(values) || values.some(value => typeof value !== "string")) throw new Error("A System storage operation is invalid")
@@ -160,7 +159,7 @@ export default class AuthManager extends TheLink {
throw new Error(`System storage does not know "${operation}"`)
}
- @Connect("/storage-watch")
+ @Subscribe("/storage-watch")
protected async watchStorage(stream: unknown, target: unknown) {
if (typeof stream !== "string" || !stream) throw new Error("A Storage watch needs an identity")
@@ -185,7 +184,7 @@ export default class AuthManager extends TheLink {
? this.linkManager.application.home.watch(request.path, request.recursive, signal)
: this.programManager.watchArea(request.program, request.area, request.path, request.recursive, signal)
- for await (const change of operation) await this.publishToConnection(connection, "/storage-change", stream, change)
+ for await (const change of operation) await this.publishToBoundary(connection, "/storage-change", stream, change)
}
finally {
@@ -202,31 +201,31 @@ export default class AuthManager extends TheLink {
this.storageWatches.get(`${this.connection()}:${stream}`)?.abort()
}
- @Connect("/uploads/path")
+ @Subscribe("/uploads/path")
protected async uploadsPath() {
return this.uploads.fileManager.path
}
- @Connect("/uploads/access")
+ @Subscribe("/uploads/access")
protected async uploadsAccess() {
return { path: this.uploads.fileManager.path, limit: uploadLimit }
}
- @Connect("/uploads/stat")
+ @Subscribe("/uploads/stat")
protected async uploadStat(file: unknown) {
return this.uploads.stat(String(file))
}
- @Connect("/appearance/update")
+ @Subscribe("/appearance/update")
protected async changeAppearance(value: unknown) {
return await this.updateAppearance(value)
}
- @Connect("/session/sign-out-current")
+ @Subscribe("/session/sign-out-current")
protected async signOutCurrentSession() {
const session = this.linkManager.connection().session
@@ -236,7 +235,7 @@ export default class AuthManager extends TheLink {
await this.linkManager.signOutSession(session)
}
- @Connect("/connection/list")
+ @Subscribe("/connection/list")
protected async connections() {
return this.linkManager.application.system.listConnections()
@@ -244,13 +243,13 @@ export default class AuthManager extends TheLink {
.map(connection => this.linkManager.connectionSnapshot(connection))
}
- @Connect("/connection/current")
+ @Subscribe("/connection/current")
protected async currentConnection() {
return this.linkManager.connectionSnapshot(this.linkManager.connection())
}
- @Connect("/connection/find")
+ @Subscribe("/connection/find")
protected async connectionFind(identity: unknown) {
const connection = this.linkManager.application.system.findConnection(domainIdentity(identity, "Connection"))
@@ -258,25 +257,25 @@ export default class AuthManager extends TheLink {
return connection ? this.linkManager.connectionSnapshot(connection) : null
}
- @Connect("/connection/state")
+ @Subscribe("/connection/state")
protected async connectionState(identity: unknown) {
return this.linkManager.application.system.connectionSnapshot(domainIdentity(identity, "Connection"))
}
- @Connect("/connection/session")
+ @Subscribe("/connection/session")
protected async connectionSession(identity: unknown) {
return this.linkManager.application.system.connectionSession(domainIdentity(identity, "Connection"))
}
- @Connect("/connection/sign-in")
+ @Subscribe("/connection/sign-in")
protected async connectionSignIn(identity: unknown) {
return this.linkManager.application.system.signInConnection(domainIdentity(identity, "Connection"))
}
- @Connect("/session/list")
+ @Subscribe("/session/list")
protected async sessions() {
return this.linkManager.application.system.listSessions()
@@ -284,7 +283,7 @@ export default class AuthManager extends TheLink {
.map(identity => this.linkManager.sessionSnapshot(identity))
}
- @Connect("/session/find")
+ @Subscribe("/session/find")
protected async sessionFind(identity: unknown) {
const session = this.linkManager.application.system.findSession(domainIdentity(identity, "Session"))
@@ -292,13 +291,13 @@ export default class AuthManager extends TheLink {
return session ? this.linkManager.sessionSnapshot(session) : null
}
- @Connect("/session/state")
+ @Subscribe("/session/state")
protected async sessionState(identity: unknown) {
return this.linkManager.application.system.sessionSnapshot(domainIdentity(identity, "Session"))
}
- @Connect("/session/connections")
+ @Subscribe("/session/connections")
protected async sessionConnections(identity: unknown) {
return this.linkManager.application.system.sessionConnections(domainIdentity(identity, "Session"))
@@ -306,7 +305,7 @@ export default class AuthManager extends TheLink {
.map(connection => this.linkManager.connectionSnapshot(connection))
}
- @Connect("/session/sign-out")
+ @Subscribe("/session/sign-out")
protected async sessionSignOut(identity: unknown) {
return this.linkManager.application.system.signOutSession(domainIdentity(identity, "Session"))
@@ -318,30 +317,7 @@ export default class AuthManager extends TheLink {
return await this.linkManager.updateAppearance(value)
}
- @Connect("/permission/get")
- protected async permission(process: unknown, name: unknown) {
-
- if (typeof process !== "string") throw new Error("A permission read is invalid")
-
- return this.processManager.permission(process, parsePermissionName(name))
- }
-
- @Connect("/permission/grants")
- protected async grantsPermission(process: unknown, name: unknown, requested: unknown) {
-
- if (typeof process !== "string") {
- throw new Error("A permission check is invalid")
- }
-
- const permission = parsePermissionName(name)
- const values = permissionCatalog.resolve(permission, requested)
-
- if (!Array.isArray(values)) throw new Error("A permission check is invalid")
-
- return this.processManager.grants(process, permission, values)
- }
-
- @Connect("/permission/storage")
+ @Subscribe("/permission/storage")
protected async grantsStorage(process: unknown, path: unknown, operation: unknown) {
if (typeof process !== "string"
@@ -353,7 +329,7 @@ export default class AuthManager extends TheLink {
return this.processManager.grantsStorage(process, path, operation)
}
- @Connect("/permission/request")
+ @Subscribe("/permission/request")
protected async requestPermission(request: unknown, process: unknown, program: unknown, name: unknown, permission: unknown) {
if (typeof request !== "string" || typeof process !== "string") throw new Error("A permission request is invalid")
@@ -383,14 +359,12 @@ export default class AuthManager extends TheLink {
await this.programManager.appendArea(program, area, path, content, signal)
}
- // A targeted client observation belongs to one authorized desktop
- // connection. Send its copy only there; the ordinary outbound road is a
- // broadcast and would widen one frame's interest to every session.
- public async publishToConnection(connectionIdentity: string, event: string, ...values: unknown[]) {
-
- const connection = this.linkManager.findConnection(connectionIdentity)
+ // Targeted observations also belong to trusted external boundaries, which
+ // are intentionally absent from the public Desktop Connection registry.
+ public async publishToBoundary(connectionIdentity: string, event: string, ...values: unknown[]) {
- if (!connection?.session) return
+ const connection = this.linkManager.boundaries.get(connectionIdentity)
+ if (!connection || !connection.external && !connection.session) return
await connection.link.$outbound.publish(`/auth${event}`, ...values)
}
diff --git a/source/server/core/link-manager/auth-manager/process-manager/client-process-forwarder.ts b/source/server/core/link-manager/auth-manager/process-manager/client-process-forwarder.ts
index 256cdb3..07a8e59 100644
--- a/source/server/core/link-manager/auth-manager/process-manager/client-process-forwarder.ts
+++ b/source/server/core/link-manager/auth-manager/process-manager/client-process-forwarder.ts
@@ -62,7 +62,7 @@ export default class ClientProcessForwarder {
const values = this.shapeObservedValues(event === null ? [word, ...payload] : payload)
- this.authManager.publishToConnection(this.connection, "/process/observed", this.pane, this.owner, subscription, values).catch(() => undefined)
+ this.authManager.publishToBoundary(this.connection, "/process/observed", this.pane, this.owner, subscription, values).catch(() => undefined)
}, reportImpossible ? reason => this.impossible(subscription, reason) : undefined)
this.observations.set(subscription, stop)
@@ -72,7 +72,7 @@ export default class ClientProcessForwarder {
this.unobserve(subscription)
- this.authManager.publishToConnection(this.connection, "/process/impossible", this.pane, this.owner, subscription, reason).catch(() => undefined)
+ this.authManager.publishToBoundary(this.connection, "/process/impossible", this.pane, this.owner, subscription, reason).catch(() => undefined)
}
public unobserve(subscription: string) {
@@ -123,7 +123,7 @@ export default class ClientProcessForwarder {
const values = event === null ? [word, payload] : [payload]
- this.authManager.publishToConnection(this.connection, "/process/emitted", this.pane, this.owner, subscription, values).catch(() => undefined)
+ this.authManager.publishToBoundary(this.connection, "/process/emitted", this.pane, this.owner, subscription, values).catch(() => undefined)
}, reportImpossible ? reason => this.impossibleFollow(subscription, reason) : undefined)
this.endpointSubscriptions.set(subscription, stop)
@@ -131,7 +131,7 @@ export default class ClientProcessForwarder {
private impossibleFollow(subscription: string, reason: string) {
- this.authManager.publishToConnection(this.connection, "/process/impossible", this.pane, this.owner, subscription, reason).catch(() => undefined)
+ this.authManager.publishToBoundary(this.connection, "/process/impossible", this.pane, this.owner, subscription, reason).catch(() => undefined)
}
public unfollow(subscription: string) {
@@ -141,7 +141,7 @@ export default class ClientProcessForwarder {
this.endpointSubscriptions.delete(subscription)
}
- public followService(services: EndpointServices, subscription: string, address: ServiceAddress, scope: ServiceScope, event: string | null) {
+ public followService(services: EndpointServices, subscription: string, address: ServiceAddress, scope: ServiceScope, event: string | null, permitted: () => boolean) {
this.unfollowService(subscription)
@@ -149,8 +149,8 @@ export default class ClientProcessForwarder {
const values = event === null ? [word, payload] : [payload]
- return this.authManager.publishToConnection(this.connection, "/process/service-event", this.pane, this.owner, subscription, values).catch(() => undefined)
- })
+ return this.authManager.publishToBoundary(this.connection, "/process/service-event", this.pane, this.owner, subscription, values).catch(() => undefined)
+ }, permitted)
this.serviceSubscriptions.set(subscription, stop)
}
@@ -204,6 +204,6 @@ export default class ClientProcessForwarder {
private async send(values: unknown[]) {
- await this.authManager.publishToConnection(this.connection, "/process/end-end", this.pane, values)
+ await this.authManager.publishToBoundary(this.connection, "/process/end-end", this.pane, values)
}
}
diff --git a/source/server/core/link-manager/auth-manager/process-manager/endpoint-services.ts b/source/server/core/link-manager/auth-manager/process-manager/endpoint-services.ts
index a90fc9a..3bfda9b 100644
--- a/source/server/core/link-manager/auth-manager/process-manager/endpoint-services.ts
+++ b/source/server/core/link-manager/auth-manager/process-manager/endpoint-services.ts
@@ -93,7 +93,6 @@ export default class EndpointServices extends TheLink {
public async emit(process: Process, endpoint: Half, event: string, payload: unknown) {
const address = this.addressOf(process, endpoint)
-
if (!address || !this.available(address)) return []
return await this.$inbound.publish(this.event(address, "events", event), event, payload)
@@ -119,19 +118,24 @@ export default class EndpointServices extends TheLink {
return address ? this.transition(address, false) : Promise.resolve([])
}
- public follow(value: unknown, scope: Scope, event: string | null, subscriber: Subscriber) {
+ public follow(value: unknown, scope: Scope, event: string | null, subscriber: Subscriber, permitted: () => boolean = () => true) {
const address = this.address(value)
if (scope !== "lifecycle" && scope !== "events") throw new Error("A Service subscription scope is invalid")
const prefix = this.prefix(address, scope)
+ // The subscribing boundary supplies current authority; checking it at
+ // this local fan-out point keeps revocation live without a transport
+ // round-trip for every event.
+ if (event !== null) return this.$inbound.subscribe(prefix + encodeURIComponent(event), (_word, payload) => {
- if (event !== null) return this.$inbound.subscribe(prefix + encodeURIComponent(event), (_word, payload) => subscriber(event, payload))
+ if (permitted()) return subscriber(event, payload)
+ })
return this.$inbound.forwardTo((_route, word, payload) => {
- if (typeof word === "string") return subscriber(word, payload)
+ if (typeof word === "string" && permitted()) return subscriber(word, payload)
}, prefix)
}
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 9647dc7..6bebbb3 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
@@ -1,4 +1,4 @@
-import { Connect, Subscribe } from "@the-link/core/decorators"
+import { Subscribe } from "@the-link/core/decorators"
import { type Options } from "../program-manager/program-manager"
import Program from "../program-manager/program"
import { Layer } from "../program-manager/config"
@@ -545,7 +545,7 @@ export default class ProcessManager extends TheLink {
const answer = ["answer", values[1], values[2], values[3], failed(new Error(reason))]
- this.authManager.publishToConnection(connection, "/process/end-end", pane, answer).catch(() => undefined)
+ this.authManager.publishToBoundary(connection, "/process/end-end", pane, answer).catch(() => undefined)
}
public releaseConnection(connection: string) {
@@ -581,11 +581,11 @@ export default class ProcessManager extends TheLink {
const observation = value as Record<string, unknown>
const event = observation.event === null || typeof observation.event === "string" ? observation.event : invalid("A System observation event must be text or null")
- const followed = (received: string, payload: unknown) => this.authManager.publishToConnection(connection, "/process/followed", subscription, received, payload).catch(() => undefined)
+ const followed = (received: string, payload: unknown) => this.authManager.publishToBoundary(connection, "/process/followed", subscription, received, payload).catch(() => undefined)
const impossible = (reason: string) => {
this.removeConnectionObservation(connection, subscription)
- this.authManager.publishToConnection(connection, "/process/impossible", subscription, reason).catch(() => undefined)
+ this.authManager.publishToBoundary(connection, "/process/impossible", subscription, reason).catch(() => undefined)
}
let stop: () => void
@@ -1459,7 +1459,7 @@ export default class ProcessManager extends TheLink {
// One implementation for both roads — a process asks over its
// channel, a pane over the link — because two that agreed today
// would be two that could stop agreeing.
- @Connect("/exit-all")
+ @Subscribe("/exit-all")
public async exitAll(program: string, asker: string | null = null) {
const owner = this.authManager.programManager.reachOrRefuse(program)
@@ -1476,7 +1476,7 @@ export default class ProcessManager extends TheLink {
// A desktop supplies the publishing pane separately from the destination.
// The pane comes from its structural frame gate rather than application
// data, so a client cannot attribute its publication to another Process.
- @Connect("/send")
+ @Subscribe("/send")
public async publishClient(source: string, identity: string, which: string, values: unknown[]) {
if (which !== "server" && which !== "client") throw new Error(`A process has no "${which}" end`)
@@ -1487,7 +1487,7 @@ export default class ProcessManager extends TheLink {
}
/** A Client emits from the structurally identified pane, never a claimed source. */
- @Connect("/emit")
+ @Subscribe("/emit")
public async emitClient(source: string, event: string, payload: unknown) {
const process = this.find(source)
@@ -1502,7 +1502,7 @@ export default class ProcessManager extends TheLink {
])
}
- @Connect("/endpoint/is-service")
+ @Subscribe("/endpoint/is-service")
protected async clientEndpointIsService(source: string, target: unknown, endpoint: unknown) {
const process = this.find(source)
@@ -1518,16 +1518,16 @@ export default class ProcessManager extends TheLink {
return endpoint === "server" ? held.server?.service === true : held.client?.service === true
}
- @Connect("/service/available")
+ @Subscribe("/service/available")
protected async serviceAvailable(address: unknown) {
return this.services.available(address)
}
- @Connect("/service/list")
+ @Subscribe("/service/list")
protected async listServices() { return this.services.list() }
- @Connect("/service/search")
+ @Subscribe("/service/search")
protected async searchServices(name: unknown) {
if (typeof name !== "string" || !name.trim()) throw new Error("A Service name is required")
@@ -1535,13 +1535,13 @@ export default class ProcessManager extends TheLink {
return this.services.list(name)
}
- @Connect("/service/wait-ready")
+ @Subscribe("/service/wait-ready")
protected async waitServiceReady(address: unknown, timeout: unknown) {
await this.services.waitReady(address, timeout, this.authManager.connectionSignal())
}
- @Connect("/service/program-metadata")
+ @Subscribe("/service/program-metadata")
protected async serviceProgramMetadata(address: unknown) {
if (!isServiceAddress(address)) throw new Error("A complete Service address is required")
@@ -1555,7 +1555,7 @@ export default class ProcessManager extends TheLink {
return Object.freeze({ name: program.name, version: program.version })
}
- @Connect("/service/program-icon")
+ @Subscribe("/service/program-icon")
protected async serviceProgramIcon(address: unknown, iconSize: unknown = "medium") {
if (!isServiceAddress(address)) throw new Error("A complete Service address is required")
@@ -1658,7 +1658,14 @@ export default class ProcessManager extends TheLink {
if (event !== null && typeof event !== "string") return
- boundary.followService(this.services, subscription, address, scope, event)
+ if (!this.grants(pane, "services", [address.process])) return
+
+ boundary.followService(this.services, subscription, address, scope, event, () => {
+
+ const process = this.processes.get(pane)
+
+ return process !== undefined && this.authManager.programManager.grantsPermission(process.program, "services", [address.process])
+ })
}
@Subscribe("/frame/service/unfollow")
@@ -2157,7 +2164,10 @@ export default class ProcessManager extends TheLink {
if (!this.grants(process.identity, "services", [address.process])) return []
- server.followService(this.services, subscription, address, scope, event)
+ server.followService(this.services, subscription, address, scope, event, () => (
+ this.processes.get(process.identity) === process
+ && this.authManager.programManager.grantsPermission(process.program, "services", [address.process])
+ ))
return []
}
@@ -3094,13 +3104,13 @@ export default class ProcessManager extends TheLink {
await this.publish(identity, "client", identity, "server", values)
}
- @Connect("/exit")
+ @Subscribe("/exit")
public async exit(identity: string) {
return await this.exitProcess(identity)
}
- @Connect("/parent")
+ @Subscribe("/parent")
protected async parent(value: unknown) {
const process = this.system.holdProcess(value)
@@ -3108,7 +3118,7 @@ export default class ProcessManager extends TheLink {
return process.parent ? processReference(process.parent) : null
}
- @Connect("/endpoint/start")
+ @Subscribe("/endpoint/start")
protected async startEndpoint(identity: string, which: string, launch?: ServerLaunch | ClientLaunch) {
if (which === "server") return await this.startServer(identity, launch as ServerLaunch | undefined)
@@ -3118,7 +3128,7 @@ export default class ProcessManager extends TheLink {
throw new Error("A Process endpoint is server or client")
}
- @Connect("/endpoint/stop")
+ @Subscribe("/endpoint/stop")
protected async stopEndpoint(identity: string, which: string) {
if (which === "server") return await this.stopServer(identity)
@@ -3138,7 +3148,7 @@ export default class ProcessManager extends TheLink {
// Minimized is untouched by both. Where a window is and whether it
// is shown are two questions, so a hidden window can be moved and
// resized and will appear where it now is.
- @Connect("/move")
+ @Subscribe("/move")
public async move(identity: string, position: Position) {
const window = this.mutableWindowOf(identity)
@@ -3147,10 +3157,10 @@ export default class ProcessManager extends TheLink {
this.said(identity, "move", window.position)
- return { identity, window }
+ return await this.publishWindowChange("/move", identity, window)
}
- @Connect("/resize")
+ @Subscribe("/resize")
public async resize(identity: string, size: Size) {
const window = this.mutableWindowOf(identity)
@@ -3159,10 +3169,10 @@ export default class ProcessManager extends TheLink {
this.said(identity, "resize", window.size)
- return { identity, window }
+ return await this.publishWindowChange("/resize", identity, window)
}
- @Connect("/set-geometry")
+ @Subscribe("/set-geometry")
public async setGeometry(identity: string, geometry: WindowGeometry) {
const window = this.mutableWindowOf(identity)
@@ -3175,10 +3185,10 @@ export default class ProcessManager extends TheLink {
if (changed.resized) this.said(identity, "resize", window.size)
- return { identity, window }
+ return await this.publishWindowChange("/set-geometry", identity, window)
}
- @Connect("/set-title", "/change-title")
+ @Subscribe("/set-title")
public async setTitle(identity: string, title: string) {
const window = this.mutableWindowOf(identity)
@@ -3187,10 +3197,10 @@ export default class ProcessManager extends TheLink {
this.said(identity, "changeTitle", window.title)
- return { identity, window }
+ return await this.publishWindowChange("/change-title", identity, window)
}
- @Connect("/set-header", "/change-header")
+ @Subscribe("/set-header")
public async setHeader(identity: string, header: boolean) {
const window = this.mutableWindowOf(identity)
@@ -3199,10 +3209,10 @@ export default class ProcessManager extends TheLink {
this.said(identity, "changeHeader", window.header)
- return { identity, window }
+ return await this.publishWindowChange("/change-header", identity, window)
}
- @Connect("/set-frame", "/change-frame")
+ @Subscribe("/set-frame")
public async setFrame(identity: string, frame: import("@phreshos/core").WindowFrame) {
const window = this.mutableWindowOf(identity)
@@ -3211,10 +3221,10 @@ export default class ProcessManager extends TheLink {
this.said(identity, "changeFrame", window.frame)
- return { identity, window }
+ return await this.publishWindowChange("/change-frame", identity, window)
}
- @Connect("/set-transaction", "/change-transaction")
+ @Subscribe("/set-transaction")
public async setTransaction(identity: string, transaction: import("@phreshos/core").WindowTransaction) {
const window = this.mutableWindowOf(identity)
@@ -3223,7 +3233,7 @@ export default class ProcessManager extends TheLink {
this.said(identity, "changeTransaction", window.transaction)
- return { identity, window }
+ return await this.publishWindowChange("/change-transaction", identity, window)
}
// To the front of its own layer, and that is the whole of it.
@@ -3240,7 +3250,7 @@ export default class ProcessManager extends TheLink {
// program a person believes they are typing into. Keyboard focus is
// the browser's, reached by a person clicking and no other way, so
// the system's word for ordering must not be called focus.
- @Connect("/raise")
+ @Subscribe("/raise")
public async raise(identity: string) {
const window = this.mutableWindowOf(identity)
@@ -3253,13 +3263,13 @@ export default class ProcessManager extends TheLink {
this.settleFront(window.layer, front)
- return { identity, window }
+ return await this.publishWindowChange("/raise", identity, window)
}
// Shown, or not shown. Nothing else: the order is untouched, so a
// window hidden and shown again comes back exactly where it was in
// its layer rather than on top of it.
- @Connect("/maximize")
+ @Subscribe("/maximize")
public async maximize(identity: string, maximized: boolean) {
if (typeof maximized !== "boolean") throw new Error("Window maximize takes a boolean state")
@@ -3267,10 +3277,10 @@ export default class ProcessManager extends TheLink {
if (window.maximized === maximized) return { identity, window }
window.maximized = maximized
this.said(identity, "maximize", maximized)
- return { identity, window }
+ return await this.publishWindowChange("/maximize", identity, window)
}
- @Connect("/minimize")
+ @Subscribe("/minimize")
public async minimize(identity: string, minimized: boolean) {
if (typeof minimized !== "boolean") throw new Error("Window minimize takes a boolean state")
@@ -3286,7 +3296,18 @@ export default class ProcessManager extends TheLink {
this.settleFront(window.layer, front)
- return { identity, window }
+ return await this.publishWindowChange("/minimize", identity, window)
+ }
+
+ // RPC results answer only their caller. A Window transition is separate
+ // shared state and is published explicitly, once, only after it changed.
+ private async publishWindowChange(event: string, identity: string, window: Window) {
+
+ const payload = { identity, window }
+
+ await this.$outbound.publish(event, payload)
+
+ return payload
}
// ── The front window of a layer ──────────────────────────────────
diff --git a/source/server/core/link-manager/auth-manager/process-manager/server-process-boundary.ts b/source/server/core/link-manager/auth-manager/process-manager/server-process-boundary.ts
index 55b2267..c0cfb7c 100644
--- a/source/server/core/link-manager/auth-manager/process-manager/server-process-boundary.ts
+++ b/source/server/core/link-manager/auth-manager/process-manager/server-process-boundary.ts
@@ -214,7 +214,7 @@ export default class ServerProcessBoundary extends TheLink {
}
/** Follow one exact service route for this boundary's lifetime. */
- public followService(services: EndpointServices, subscription: string, address: ServiceAddress, scope: ServiceScope, event: string | null) {
+ public followService(services: EndpointServices, subscription: string, address: ServiceAddress, scope: ServiceScope, event: string | null, permitted: () => boolean) {
this.unfollowService(subscription)
@@ -223,7 +223,7 @@ export default class ServerProcessBoundary extends TheLink {
const values = event === null ? [word, payload] : [payload]
return this.deliver("service-event", subscription, ...values).catch(() => undefined)
- })
+ }, permitted)
this.serviceSubscriptions.set(subscription, stop)
}
diff --git a/source/server/core/link-manager/auth-manager/program-manager/entry.ts b/source/server/core/link-manager/auth-manager/program-manager/entry.ts
index d531a7a..4826ba1 100644
--- a/source/server/core/link-manager/auth-manager/program-manager/entry.ts
+++ b/source/server/core/link-manager/auth-manager/program-manager/entry.ts
@@ -1,5 +1,5 @@
import Program from "./program"
-import type { ProgramSnapshot } from "@phreshos/core"
+import type { Permissions, ProgramSnapshot } from "@phreshos/core"
/**
* One program in the runtime registry. Installation is a state of this
@@ -14,15 +14,29 @@ export default class Entry {
/** Restore the durable installed Program when this runtime overlay ends. */
public restoreInstalled: boolean
- public constructor(program: Program, installed = true, restoreInstalled = false) {
+ private permissionState: Permissions
+
+ public constructor(program: Program, permissions: Permissions, installed = true, restoreInstalled = false) {
this.program = program
+ this.permissionState = clonePermissions(permissions)
+
this.installed = installed
this.restoreInstalled = restoreInstalled
}
+ public permissions() {
+
+ return clonePermissions(this.permissionState)
+ }
+
+ public updatePermissions(permissions: Permissions) {
+
+ this.permissionState = clonePermissions(permissions)
+ }
+
public get identity() {
return this.program.identity
@@ -37,8 +51,10 @@ export default class Entry {
...this.program.record(),
+ permissions: this.permissions(),
+
installed: this.installed
- } satisfies ProgramSnapshot
+ } satisfies ProgramSnapshot & { permissions: Permissions }
}
public toJSON() {
@@ -48,3 +64,11 @@ export default class Entry {
}
export type ProgramRecord = ReturnType<Entry["record"]>
+
+function clonePermissions(permissions: Permissions): Permissions {
+
+ return Object.fromEntries(Object.entries(permissions).map(([name, permission]) => [
+ name,
+ Array.isArray(permission) ? [...permission] : permission
+ ]))
+}
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 7d5b1fa..750b68b 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, Subscribe } from "@the-link/core/decorators"
+import { Subscribe } from "@the-link/core/decorators"
import { randomUUID } from "node:crypto"
import { TheLink } from "@the-link/core"
import SqliteDatabase from "@libs/sqlite-database"
@@ -173,6 +173,15 @@ export default class ProgramManager extends TheLink {
/** Returns an independent effective snapshot without writing definition fallbacks to state. */
public permissions(program: Program): Permissions {
+ const entry = this.programs?.get(program.identity)
+
+ if (entry?.program === program) return entry.permissions()
+
+ return this.resolvePermissions(program)
+ }
+
+ private resolvePermissions(program: Program): Permissions {
+
return clonePermissions({ ...program.declaredPermissions, ...new ProgramStateStorage(program).permissions() })
}
@@ -230,14 +239,38 @@ export default class ProgramManager extends TheLink {
if (value === null) throw new Error("A stored Program permission cannot be null")
+ const entry = this.programs?.get(program.identity)
+ if (entry && entry.program !== program) throw new Error("The Program represented by this handle does not exist")
+
+ const before = entry?.permissions() ?? this.resolvePermissions(program)
const state = new ProgramStateStorage(program)
const stored = state.permissions()
- const before = stored[name]
const permission = permissionCatalog.resolve(name, value)
if (permission === null) throw new Error("A stored Program permission cannot be null")
- if (before === undefined || permissionCatalog.changed(before, permission)) {
- state.setPermission(name, permission)
- }
+ const previousStored = stored[name]
+
+ if (previousStored !== undefined && !permissionCatalog.changed(previousStored, permission)) return
+
+ state.setPermission(name, permission)
+
+ const after = this.resolvePermissions(program)
+ entry?.updatePermissions(after)
+
+ // Permission events carry one complete effective snapshot. Consumers
+ // can replace local authority atomically instead of reconstructing it
+ // from mutation history or issuing a follow-up read.
+ if (entry && !isDeepStrictEqual(before, after)) await this.announcePermissions(entry)
+ }
+
+ private async announcePermissions(entry: Entry) {
+
+ const permissions = entry.permissions()
+
+ await Promise.all([
+ this.authManager.processManager.announceHost("program", "permissions", entry.identity, entry),
+ this.authManager.processManager.announceSubject("program", "permissions", entry.program.reference, permissions),
+ this.$outbound.publish("/permissions-change", entry.record())
+ ])
}
/** Requests one owner decision for this target Program, independently of its initiator. */
@@ -252,6 +285,12 @@ export default class ProgramManager extends TheLink {
const requested = permissionCatalog.resolve(name, input)
if (!Array.isArray(requested)) throw new Error("A permission request must be true or a list of values")
+ if (!request) throw new Error("A permission request needs a unique identity")
+
+ // A request asks for one exact canonical assignment. When effective
+ // authority already equals it, no owner decision or state write exists
+ // to perform; broader and narrower assignments remain distinct.
+ if (!permissionCatalog.changed(this.permission(program, name), requested)) return requested
const choice = await this.authManager.dialogManager.requestPermission(program, request, name, requested, process)
@@ -265,7 +304,7 @@ export default class ProgramManager extends TheLink {
return choice
}
- @Connect("/permissions")
+ @Subscribe("/permissions")
protected async programPermissions(subject: unknown, operation: unknown, first?: unknown, second?: unknown, third?: unknown) {
const program = this.held(subject)
@@ -318,25 +357,25 @@ export default class ProgramManager extends TheLink {
throw new Error(`The System does not know the Program permission operation "${String(operation)}"`)
}
- @Connect("/create-program")
+ @Subscribe("/create-program")
protected async createProgram(source: ProgramDefinition | string) {
return (await this.create(source)).identity
}
- @Connect("/force-create-program")
+ @Subscribe("/force-create-program")
protected async forceCreateProgram(source: ProgramDefinition | string, asker: string) {
return (await this.forceCreate(source, asker)).identity
}
- @Connect("/startup")
+ @Subscribe("/startup")
protected async startupProgram(subject: unknown, operation: string, value?: unknown) {
return await this.startup(this.held(subject), operation, value)
}
- @Connect("/pinned")
+ @Subscribe("/pinned")
protected async pinnedProgram(subject: unknown, operation: "get" | "pin" | "unpin") {
return await this.pinned(this.held(subject), operation)
@@ -482,7 +521,7 @@ export default class ProgramManager extends TheLink {
// that deliberately owns this identity across both representations.
if (this.programs.has(program.identity) || (!transitionOwnsIdentity && (this.changing.has(program.identity) || existsSync(this.fileManager.join(program.identity, "program.json"))))) throw new Error("The system already knows this program identity")
- const entry = new Entry(program, installed, restoreInstalled)
+ const entry = new Entry(program, this.resolvePermissions(program), installed, restoreInstalled)
this.programs.set(entry.identity, entry)
@@ -595,7 +634,7 @@ export default class ProgramManager extends TheLink {
// Read, and only ever read. The same word a process says over its
// channel and a pane says over the link, because the two roads must
// mean the same thing.
- @Connect("/logs")
+ @Subscribe("/logs")
public async logs(subject: unknown, sql: string, values: unknown[]) {
return this.logsOf(this.held(subject)).query(sql, values)
@@ -621,14 +660,14 @@ 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")
+ @Subscribe("/database")
public async database(subject: unknown, sql: string, values: unknown[]) {
return this.databaseOf(this.held(subject)).query(sql, values)
}
/** One authoritative icon operation shared by SDKs and HTTP hosting. */
- @Connect("/icon")
+ @Subscribe("/icon")
public async icon(subject: unknown, size: unknown) {
if (!isIconSize(size)) throw new Error("A Program icon size is small, medium, or large")
@@ -637,14 +676,14 @@ export default class ProgramManager extends TheLink {
}
/** Reads Program-specific operating knowledge for agents. */
- @Connect("/agent")
+ @Subscribe("/agent")
public async agent(subject: unknown) {
return this.held(subject).agent()
}
/** Reads the canonical definition owned by one exact Program handle. */
- @Connect("/definition")
+ @Subscribe("/definition")
public async definition(subject: unknown) {
return this.held(subject).definition()
@@ -721,7 +760,7 @@ export default class ProgramManager extends TheLink {
// over its own channel and from a session over the link, and both
// must mean the same thing. The exact handle always names a Program;
// application persistence has no generic route through this manager.
- @Connect("/store")
+ @Subscribe("/store")
public async store(subject: unknown, operation: string, key: string, value?: unknown, ttl?: number) {
const store = this.storeOf(this.held(subject))
@@ -741,7 +780,7 @@ 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")
+ @Subscribe("/area")
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)}"`)
@@ -868,13 +907,13 @@ 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("/forget-program")
+ @Subscribe("/forget-program")
public async forgetNamed(subject: unknown, asker: string | null = null) {
return await this.forget(this.held(subject), asker)
}
- @Connect("/command")
+ @Subscribe("/command")
protected async command(stream: string, operation: string, subject: unknown, value: unknown, asker: string) {
if (!stream || this.commands.has(stream)) throw new Error("A Program command needs a unique stream")
@@ -1107,6 +1146,7 @@ export default class ProgramManager extends TheLink {
await installed.installServer(output)
let entry = this.programs.get(source.identity)
+ const previousPermissions = entry?.permissions() ?? null
// Active callers can consume installation output until activation.
if (entry) await this.authManager.processManager.exitAll(source.identity, asker)
@@ -1124,6 +1164,8 @@ export default class ProgramManager extends TheLink {
entry.installed = true
entry.restoreInstalled = false
+
+ entry.updatePermissions(this.resolvePermissions(entry.program))
}
else {
@@ -1139,13 +1181,14 @@ export default class ProgramManager extends TheLink {
await this.authManager.processManager.announceHost("program", "install", entry.identity, entry)
- // Said to the sessions, though none of them may ask for it.
- // `@Connect` used to be both the road in and the echo out,
- // and removing the road took the echo with it — a desktop
- // that never learns a program arrived is a desktop showing
- // yesterday's list.
+ // Installation is shared registry state, so it is announced
+ // independently of the response returned to its caller.
await this.$outbound.publish("/install", entry.record())
+ if (previousPermissions && !isDeepStrictEqual(previousPermissions, entry.permissions())) {
+ await this.announcePermissions(entry)
+ }
+
if (requestedLaunch !== undefined) {
await this.start(entry.program, requestedLaunch, undefined, null, true)
}
@@ -1299,7 +1342,7 @@ export default class ProgramManager extends TheLink {
this.kept.delete(identity)
}
- @Connect("/create-process")
+ @Subscribe("/create-process")
public async createProcess(subject: unknown, launch: Launch = {}, parent: Process | string | null = null) {
const program = this.held(subject)
@@ -1330,7 +1373,7 @@ export default class ProgramManager extends TheLink {
})
}
- @Connect("/find-or-create-process")
+ @Subscribe("/find-or-create-process")
public async findOrCreateProcess(subject: unknown, launch: Launch & { name: string }, parent: Process | string | null = null) {
const held = this.held(subject)
diff --git a/source/server/core/link-manager/auth-manager/shell-manager.ts b/source/server/core/link-manager/auth-manager/shell-manager.ts
index 768e935..1c37ae4 100644
--- a/source/server/core/link-manager/auth-manager/shell-manager.ts
+++ b/source/server/core/link-manager/auth-manager/shell-manager.ts
@@ -1,5 +1,5 @@
import { TheLink } from "@the-link/core"
-import { Connect, Subscribe } from "@the-link/core/decorators"
+import { Subscribe } from "@the-link/core/decorators"
import type { ShellOptions } from "@phreshos/core"
import type AuthManager from "./auth-manager"
@@ -15,7 +15,7 @@ export default class ShellManager extends TheLink {
this.connectTo(authManager, "/frame/shell")
}
- @Connect("/run")
+ @Subscribe("/run")
protected async run(connection: string, stream: string, command: string, options: Omit<ShellOptions, "signal">, asker: string) {
if (typeof connection !== "string" || typeof asker !== "string" || !asker) throw new Error("A Client shell command needs a requesting Process")
@@ -38,7 +38,7 @@ export default class ShellManager extends TheLink {
for await (const event of this.authManager.linkManager.application.system.shell(command, { ...options, signal: controller.signal })) {
- await this.authManager.publishToConnection(connection, "/frame/shell/event", stream, event)
+ await this.authManager.publishToBoundary(connection, "/frame/shell/event", stream, event)
}
}
finally {
diff --git a/source/server/view/http/link.ts b/source/server/view/http/link.ts
index a4db9bf..770e206 100644
--- a/source/server/view/http/link.ts
+++ b/source/server/view/http/link.ts
@@ -31,6 +31,9 @@ export default function (application: Application, debugging: boolean) {
try {
+ // The correlation address exclusively owns an RPC result.
+ // Shared state changes use their own explicit publications;
+ // request handlers must not also broadcast their return value.
const results = await connection.publish(event, ...values)
await socketLink.$outbound.publish(responseUuid, succeeded(results))
diff --git a/source/shared/permission-state.ts b/source/shared/permission-state.ts
new file mode 100644
index 0000000..47b9e05
--- /dev/null
+++ b/source/shared/permission-state.ts
@@ -0,0 +1,59 @@
+import {
+ networkScopeCovers,
+ programPermissionCatalog,
+ type PermissionName,
+ type PermissionValue,
+ type Permissions
+} from "@phreshos/core"
+
+/** Evaluates permissions whose complete meaning is available in the browser. */
+export function allowsSynchronizedPermission<Name extends PermissionName>(
+ permissions: Permissions,
+ name: Name,
+ requested: readonly PermissionValue<Name>[]
+) {
+
+ if (name === "desktopConnection" && allowsSynchronizedPermission(permissions, "connections", [])) return true
+
+ const assigned = permissions[name]
+
+ // An exact assignment is final. `all` is only a fallback for permissions
+ // with no stored or declared assignment of their own.
+ if (assigned !== undefined && assigned !== null) return grants(name, assigned, requested)
+
+ return name !== "all" && Array.isArray(permissions.all)
+}
+
+function grants<Name extends PermissionName>(
+ name: Name,
+ assigned: Permissions[Name],
+ requested: readonly PermissionValue<Name>[]
+) {
+
+ if (!Array.isArray(assigned)) return false
+
+ const domain = programPermissionCatalog[name]
+
+ if (domain === "none") return requested.length === 0
+
+ if (assigned.length === 0) return true
+ if (requested.length === 0) return false
+
+ return requested.every(value => assigned.some(granted => covers(domain, granted, value)))
+}
+
+function covers(domain: (typeof programPermissionCatalog)[PermissionName], granted: string, requested: string) {
+
+ if (domain === "network") return networkScopeCovers(granted, requested)
+
+ // Native Storage authority is deliberately evaluated at the host because
+ // canonical paths and symlink resolution do not exist in the browser.
+ if (domain === "storage") throw new Error("Storage permission requires host path resolution")
+
+ if (domain === "program" || domain === "service" || domain === "layer") return granted === requested
+ if (domain === "none") return false
+
+ domain satisfies never
+
+ return false
+}
diff --git a/tests/client-layer-permissions.test.ts b/tests/client-layer-permissions.test.ts
index 1394a93..430bb8a 100644
--- a/tests/client-layer-permissions.test.ts
+++ b/tests/client-layer-permissions.test.ts
@@ -8,10 +8,11 @@ import { permissionCatalog } from "@server/core/permissions"
function fixture() {
let permissions: Permissions = {}
- const program: ProgramSnapshot = {
+ const program: ProgramSnapshot & { readonly permissions: Permissions } = {
identity: "owner", reference: "program-reference", assetId: "assets", name: "Owner",
version: "0.0.0", description: null, hasAgent: false, server: null,
- client: { sandbox: true, start: true, service: false, title: null, header: null, frame: null, transaction: null, size: null, position: null, layer: "over", minimize: null, maximize: null }
+ client: { sandbox: true, start: true, service: false, title: null, header: null, frame: null, transaction: null, size: null, position: null, layer: "over", minimize: null, maximize: null },
+ get permissions() { return permissions }
}
const process = { identity: "caller", reference: "process-reference", program: program.identity, name: null, startedAt: 0, options: {}, server: null, client: null }
const createProcess = vi.fn(async () => process.identity)
diff --git a/tests/client-permission-boundary.test.ts b/tests/client-permission-boundary.test.ts
index 880fca5..c2d27c9 100644
--- a/tests/client-permission-boundary.test.ts
+++ b/tests/client-permission-boundary.test.ts
@@ -6,16 +6,17 @@ import { permissionCatalog } from "@server/core/permissions"
test("Client Program creation requires all before reaching the creation boundary", async () => {
let permissions: Permissions = { programs: [] }
- const program: ProgramSnapshot = {
+ const program: ProgramSnapshot & { readonly permissions: Permissions } = {
identity: "created", reference: "created-reference", assetId: "created-assets",
name: "Created", version: "0.0.0", description: null, hasAgent: false,
- server: null, client: null
+ server: null, client: null,
+ get permissions() { return permissions }
}
const create = vi.fn(async () => program.identity)
const forceCreate = vi.fn(async () => program.identity)
const auth = {
programManager: { programs: new Map([[program.identity, program]]), create, forceCreate },
- processManager: { processes: new Map() },
+ processManager: { processes: new Map([["caller", { identity: "caller", program: program.identity }]]) },
grantsPermission: async (_pane: string, name: PermissionName, values: never[]) => permissionCatalog.allows(name, values, permissions)
} as unknown as AuthManager
const answer = host(auth, "caller", () => { throw new Error("unused viewport") }, () => null, {} as never)
@@ -36,7 +37,9 @@ test("Program and Process discovery exposes only the accessible scope", async ()
let permissions: Permissions = {}
const owner = program("owner")
+ Object.defineProperty(owner, "permissions", { get: () => permissions })
const outside = program("outside")
+ outside.permissions = { network: ["https://example.com"] }
const current = process("current", owner)
const hidden = process("hidden", outside)
const auth = {
@@ -70,7 +73,9 @@ test("Program and Process discovery exposes only the accessible scope", async ()
test("Program permission reads and requests require Program access while direct mutation alone requires all", async () => {
let permissions: Permissions = { programs: ["outside"] }
const owner = program("owner")
+ Object.defineProperty(owner, "permissions", { get: () => permissions })
const outside = program("outside")
+ outside.permissions = { network: ["https://example.com"] }
const current = process("current", owner)
const read = vi.fn(async (_address, operation: string) => operation === "all"
? { network: ["https://example.com"] }
@@ -134,7 +139,7 @@ test.each([
const sendService = vi.fn()
const askService = vi.fn()
const auth = {
- programManager: { programs: new Map() },
+ programManager: { programs: new Map([["owner", { identity: "owner", get permissions() { return permissions } }]]) },
processManager: {
processes: new Map([
["caller", { program: "owner" }],
@@ -178,7 +183,7 @@ test("Service discovery filters ready addresses only by Service-name authority",
const background = { program: "notes", process: "background", endpoint: "server" } as const
const listServices = vi.fn(async (name?: string) => [mainServer, mainClient, background].filter(service => name === undefined || service.process === name))
const auth = {
- programManager: { programs: new Map() },
+ programManager: { programs: new Map([["owner", { identity: "owner", get permissions() { return permissions } }]]) },
processManager: {
processes: new Map([["caller", { program: "owner" }]]),
listServices
@@ -201,7 +206,7 @@ test("Service discovery filters ready addresses only by Service-name authority",
await expect(answer("host-service-list")).resolves.toEqual([[mainServer, mainClient, background]])
})
-function program(identity: string): ProgramSnapshot {
+function program(identity: string): ProgramSnapshot & { permissions: Permissions } {
return {
identity,
@@ -212,7 +217,8 @@ function program(identity: string): ProgramSnapshot {
description: null,
hasAgent: false,
server: null,
- client: null
+ client: null,
+ permissions: {}
}
}
diff --git a/tests/client-process-boundary-lifecycle.test.ts b/tests/client-process-boundary-lifecycle.test.ts
index b95286e..5404143 100644
--- a/tests/client-process-boundary-lifecycle.test.ts
+++ b/tests/client-process-boundary-lifecycle.test.ts
@@ -58,8 +58,8 @@ test("a later Client request cannot overtake its Service subscription registrati
async askService() { order.push("ask") }
}
const authManager = {
+ programManager: { programs: new Map([["flambo", { identity: "flambo", permissions: { services: [] } }]]) },
processManager,
- async grantsPermission() { return true }
} as unknown as AuthManager
const boundary = new ClientProcessBoundary(
"process",
@@ -79,3 +79,47 @@ test("a later Client request cannot overtake its Service subscription registrati
completeFollow()
await vi.waitFor(() => assert.deepEqual(order, ["follow:start", "follow:end", "ask"]))
})
+
+test("a registered Service event is delivered without a second permission round-trip", async () => {
+
+ const sent: unknown[][] = []
+ let followed = false
+ const address = { program: "browser", process: "browser", endpoint: "server" } as const
+ const processManager = {
+ processes: new Map([["process", { program: "browser" }]]),
+ async ownFrame() {},
+ async releaseFrame() {},
+ async followService() { followed = true }
+ }
+ const authManager = {
+ programManager: { programs: new Map([["browser", { identity: "browser", permissions: { services: [] } }]]) },
+ processManager,
+ } as unknown as AuthManager
+ const traffic = {
+ observe() { return () => undefined }
+ } as unknown as ClientTraffic
+ const element = {
+ contentWindow: {
+ postMessage(message: unknown[]) {
+ sent.push(messagepack.deserialize(message[0] as Uint8Array) as unknown[])
+ }
+ }
+ } as unknown as HTMLIFrameElement
+ const boundary = new ClientProcessBoundary(
+ "process",
+ element,
+ authManager,
+ () => ({ size: { width: 800, height: 600 } }),
+ traffic,
+ { begin() {} } as unknown as WindowPresentationHost
+ )
+
+ await boundary.own("document")
+ boundary.receive(["boundary", "subscribe", "wire-subscription", "publish", "service-event", "service-subscription", null, false])
+ boundary.receive(["end-host", "service-follow", "service-subscription", address, "events", "workspace.changed", false])
+ await vi.waitFor(() => assert.equal(followed, true))
+
+ await boundary.deliver("service-event", "service-subscription", { revision: 1 })
+
+ assert.deepEqual(sent, [["service-event", "service-subscription", { revision: 1 }]])
+})
diff --git a/tests/client-system-access.test.ts b/tests/client-system-access.test.ts
index de99192..eb2fadc 100644
--- a/tests/client-system-access.test.ts
+++ b/tests/client-system-access.test.ts
@@ -12,8 +12,11 @@ test("client system access contract", async () => {
const sibling = { identity: "process:sibling", program: "owner" }
const outside = { identity: "process:outside", program: "outside" }
let permissions: Permissions = {}
+ let permissionChecks = 0
+ const ownerProgramState = { identity: "owner", get permissions() { return permissions } }
const authManager = {
+ programManager: { programs: new Map([[ownerProgramState.identity, ownerProgramState]]) },
processManager: { processes: new Map([
[owner.identity, owner],
[sibling.identity, sibling],
@@ -21,6 +24,8 @@ test("client system access contract", async () => {
]) },
async grantsPermission(process: string, name: PermissionName, values: readonly string[]) {
+ permissionChecks++
+
assert.equal(process, owner.identity)
return permissionCatalog.allows(name, values as never, permissions)
@@ -64,6 +69,7 @@ test("client system access contract", async () => {
await assert.rejects(access.require("desktopPreferences", []), /Execution is not permitted/)
await assert.rejects(access.require("desktopConnection", []), /Execution is not permitted/)
await assert.rejects(access.require("connections", []), /Execution is not permitted/)
+ assert.equal(permissionChecks, 0)
assert.equal(await access.canConnection("desktop-connection"), false)
assert.equal(await access.canSession("desktop-session"), false)
@@ -152,6 +158,7 @@ test("client system access contract", async () => {
await access.requireStorage("/any/native/path", "delete")
await access.require("uploads", [])
await access.requireAll()
+ assert.equal(permissionChecks, 0)
permissions = { all: [], services: false }
await assert.rejects(access.service(ownService), /Execution is not permitted/)
diff --git a/tests/endpoint-services.test.ts b/tests/endpoint-services.test.ts
index 73fa70c..425fd4c 100644
--- a/tests/endpoint-services.test.ts
+++ b/tests/endpoint-services.test.ts
@@ -42,12 +42,15 @@ test("endpoint services use stable name addresses and ready availability", async
const clientAddress = { ...address, endpoint: "client" } satisfies ServiceAddress
const lifecycle: string[] = []
const publications: unknown[] = []
+ const authorizedPublications: unknown[] = []
+ let permitted = true
assert.throws(() => services.available({ process: "main", endpoint: "server" }), /complete Service address/)
await assert.rejects(() => services.waitReady(address, -1), /non-negative finite number/)
services.follow(address, "lifecycle", null, event => lifecycle.push(event))
services.follow(address, "events", "change", (_event, payload) => publications.push(payload))
+ services.follow(address, "events", "authorized", (_event, payload) => authorizedPublications.push(payload), () => permitted)
await services.started(provider, "server")
await services.started(provider, "client")
@@ -60,6 +63,13 @@ test("endpoint services use stable name addresses and ready availability", async
await services.emit(provider, "server", "change", 2)
assert.deepEqual(publications, [2])
+ await services.emit(provider, "server", "authorized", 3)
+ permitted = false
+ await services.emit(provider, "server", "authorized", 4)
+ permitted = true
+ await services.emit(provider, "server", "authorized", 5)
+ assert.deepEqual(authorizedPublications, [3, 5])
+
provider.server = null
await services.stopped(provider, "server", true)
assert.equal(services.available(address), false)
diff --git a/tests/external-boundary-delivery.test.ts b/tests/external-boundary-delivery.test.ts
new file mode 100644
index 0000000..ba88ab9
--- /dev/null
+++ b/tests/external-boundary-delivery.test.ts
@@ -0,0 +1,25 @@
+import assert from "node:assert/strict"
+import { TheLink } from "@the-link/core"
+import AuthManager from "@server/core/link-manager/auth-manager/auth-manager"
+import type LinkManager from "@server/core/link-manager/link-manager"
+import { test } from "vitest"
+
+test("targeted publications reach trusted external boundaries", async () => {
+
+ const sent: unknown[][] = []
+ const link = new TheLink()
+
+ link.$outbound.forwardTo((event, ...values) => { sent.push([event, ...values]) })
+
+ const manager = Object.create(AuthManager.prototype) as AuthManager
+
+ Object.defineProperty(manager, "linkManager", {
+ value: {
+ boundaries: new Map([["external", { external: true, session: null, link }]])
+ } as unknown as LinkManager
+ })
+
+ await manager.publishToBoundary("external", "/process/followed", "subscription", "changed", { revision: 1 })
+
+ assert.deepEqual(sent, [["/auth/process/followed", "subscription", "changed", { revision: 1 }]])
+})
diff --git a/tests/link-request-routing.test.ts b/tests/link-request-routing.test.ts
new file mode 100644
index 0000000..1aaf9a0
--- /dev/null
+++ b/tests/link-request-routing.test.ts
@@ -0,0 +1,83 @@
+import assert from "node:assert/strict"
+import { mkdtemp, rm } from "node:fs/promises"
+import { tmpdir } from "node:os"
+import { join } from "node:path"
+import { defaultAppearance, type DesktopPreferences } from "@phreshos/core"
+import { TheLink } from "@the-link/core"
+import ClientLinkManager from "@client/core/link-manager/link-manager"
+import Application from "@server/core/application"
+import { test } from "vitest"
+
+test("an RPC result returns only to its requesting boundary", async () => {
+
+ const home = await mkdtemp(join(tmpdir(), "phreshos-request-routing-"))
+ const application = await Application.initialize("phreshos", "PhreshOS", "test", home, join(home, "icon.png"))
+ const link = new TheLink()
+ const boundary = application.linkManager.addExternalConnection(link)
+ const broadcasts: unknown[][] = []
+ const stop = link.$outbound.forwardTo((event, ...values) => { broadcasts.push([event, ...values]) })
+
+ try {
+ assert.deepEqual(await boundary.publish("/auth/connection/list"), [[]])
+ assert.equal(broadcasts.length, 0)
+
+ const identity = "request-routing"
+ const storage = join(home, "request-routing-storage")
+ assert.deepEqual(await boundary.publish("/auth/program/create-program", {
+ identity,
+ storage,
+ client: { location: "https://example.test" }
+ }), [identity])
+ assert(broadcasts.some(([event]) => event === "/auth/program/create"))
+ assert(!broadcasts.some(([event]) => event === "/auth/program/create-program"))
+
+ const program = application.linkManager.authManager.programManager.reach(identity)
+ assert(program)
+ broadcasts.length = 0
+
+ const [process] = await boundary.publish("/auth/program/create-process", {
+ identity: program.identity,
+ reference: program.reference
+ }, {})
+
+ assert.equal(typeof process, "string")
+ assert(broadcasts.some(([event]) => event === "/auth/process/created"))
+ assert(!broadcasts.some(([event]) => event === "/auth/program/create-process"))
+ }
+ finally {
+ stop()
+ await application.linkManager.removeConnection(boundary)
+ await application.store.disconnect()
+ await rm(home, { recursive: true, force: true })
+ }
+})
+
+test("Desktop preferences remain inside their owning browser Desktop", async () => {
+
+ const source = new TheLink()
+ const outbound: unknown[][] = []
+ const preferences: DesktopPreferences = { theme: "light", animations: true, scale: 1 }
+ const changed: DesktopPreferences[] = []
+ const stopOutbound = source.$outbound.forwardTo((event, ...values) => { outbound.push([event, ...values]) })
+ const manager = new ClientLinkManager(
+ {} as never,
+ source,
+ { appearance: { key: "appearance", value: defaultAppearance } },
+ preferences
+ )
+ const stopChanged = manager.desktopPreferences.tunnel.subscribe("change", value => { changed.push(value as DesktopPreferences) })
+ const next: DesktopPreferences = { ...preferences, theme: "dark" }
+
+ try {
+ await manager.updateDesktopPreferences(next)
+ await manager.updateDesktopPreferences(next)
+
+ assert.deepEqual(manager.desktopPreferences.value, next)
+ assert.deepEqual(changed, [next])
+ assert.deepEqual(outbound, [])
+ }
+ finally {
+ stopChanged()
+ stopOutbound()
+ }
+})
diff --git a/tests/permission-requests.test.ts b/tests/permission-requests.test.ts
index e353857..06a3cb1 100644
--- a/tests/permission-requests.test.ts
+++ b/tests/permission-requests.test.ts
@@ -67,8 +67,18 @@ test("permission requests contract", async () => {
assert.equal(dialogs, 3)
assert.deepEqual(stored(), { services: ["browser"] })
+ // Canonically equal authority already satisfies the request without an
+ // owner decision, while array order has no permission meaning.
+ choice = null
+ assert.deepEqual(await request("services", ["browser"]), ["browser"])
+ assert.equal(dialogs, 3)
+ assign("services", ["editor", "browser"])
+ assert.deepEqual(await request("services", ["browser", "editor"]), ["browser", "editor"])
+ assert.equal(dialogs, 3)
+
// A Program handle requests for its target; the initiating Process is
// only the request lifetime owner and never retargets the assignment.
+ choice = true
const target = new Program({ identity: "target", storage: join(temporary, "target"), permissions: {}, server: { location: ".", command: "node server.js" } })
assert.deepEqual(await programManager.requestPermission(target, "owner-request", "uploads", true), [])
assert.equal(dialogProgram, target)
@@ -93,6 +103,9 @@ test("permission requests contract", async () => {
new ProgramStateStorage(declared).setPermission("services", ["editor"])
assert(!programManager.grantsPermission(declared, "services", ["browser"]))
assert(programManager.grantsPermission(declared, "services", ["editor"]))
+ const dialogsBeforeDeclaredMatch = dialogs
+ assert.deepEqual(await programManager.requestPermission(declared, "declared-match", "programs", ["browser"]), ["browser"])
+ assert.equal(dialogs, dialogsBeforeDeclaredMatch)
assign("all", false)
assert.deepEqual(await request("all"), [])
diff --git a/tests/permission-synchronization.test.ts b/tests/permission-synchronization.test.ts
new file mode 100644
index 0000000..a68a3db
--- /dev/null
+++ b/tests/permission-synchronization.test.ts
@@ -0,0 +1,52 @@
+import { expect, test, vi } from "vitest"
+import { TheLink } from "@the-link/core"
+import type AuthManager from "@client/core/link-manager/auth-manager/auth-manager"
+import ClientProgramManager from "@client/core/link-manager/auth-manager/program-manager/program-manager"
+import SystemAccess from "@client/view/components/desktop-host/system-access"
+import type { ProgramRecord } from "@server/core/link-manager/auth-manager/program-manager/entry"
+
+function record(permissions: ProgramRecord["permissions"]): ProgramRecord {
+ return {
+ identity: "owner",
+ reference: "00000000-0000-4000-8000-000000000001",
+ assetId: "00000000-0000-4000-8000-000000000002",
+ installed: true,
+ name: "Owner",
+ version: "0.0.0",
+ description: null,
+ categories: [],
+ keywords: [],
+ hasAgent: false,
+ server: null,
+ client: null,
+ permissions
+ }
+}
+
+test("the Desktop replaces synchronized permission state before publishing its change", async () => {
+ const auth = new TheLink() as AuthManager
+ const programs = new ClientProgramManager(auth, { programs: [["owner", record({})]] })
+ Object.assign(auth, {
+ programManager: programs,
+ processManager: { processes: new Map([["process", { identity: "process", program: "owner" }]]) },
+ grantsPermission: vi.fn(() => { throw new Error("permission checks must stay local") })
+ })
+ const access = new SystemAccess(auth, "process")
+ const changes: unknown[] = []
+ const stop = programs.$inbound.subscribe("/permissions", (program, permissions) => {
+ changes.push([program, permissions])
+ })
+
+ try {
+ await expect(access.require("appearance", [])).rejects.toThrow("Execution is not permitted")
+
+ await programs.$inbound.publish("/permissions-change", record({ appearance: [] }))
+
+ await expect(access.require("appearance", [])).resolves.toBeUndefined()
+ expect(changes).toHaveLength(1)
+ expect(changes[0]).toEqual([programs.programs.get("owner"), { appearance: [] }])
+ }
+ finally {
+ stop()
+ }
+})
diff --git a/tests/program-creation.test.ts b/tests/program-creation.test.ts
index 28c69bb..987cf85 100644
--- a/tests/program-creation.test.ts
+++ b/tests/program-creation.test.ts
@@ -17,15 +17,16 @@ function fixture(context: TestContext) {
mkdirSync(client)
writeFileSync(join(client, "index.html"), "<!doctype html>")
const announceHost = vi.fn()
+ const announceSubject = vi.fn()
const auth = Object.assign(new TheLink(), {
linkManager: { application: { storage: new FileManager(directory, "system"), defaultProgramIcon: "" } },
- processManager: { processes: new Map(), exitAll: vi.fn(), announceHost, announceSubject: vi.fn() }
+ processManager: { processes: new Map(), exitAll: vi.fn(), announceHost, announceSubject }
}) as unknown as AuthManager
const manager = new ProgramManager(auth)
function definition(permissions?: ProgramPermissionDeclarations) {
return { identity: "example", storage: join(directory, "data"), permissions, client: { location: client } }
}
- return { directory, client, manager, announceHost, definition }
+ return { directory, client, manager, announceHost, announceSubject, definition }
}
test("a Program definition supplies permission fallback without initializing state", async context => {
@@ -103,6 +104,30 @@ test("Program state mutations do not rewrite an already-satisfied value", async
expect(permissionWrite).toHaveBeenCalledTimes(1)
})
+test("permission changes publish one complete effective snapshot through both Program event scopes", async context => {
+ const { manager, definition, announceHost, announceSubject } = fixture(context)
+ const program = await manager.create(definition({ uploads: true }))
+ const records: unknown[] = []
+ const stop = manager.$outbound.subscribe("/permissions-change", value => { records.push(value) })
+ context.onTestFinished(stop)
+ announceHost.mockClear()
+ announceSubject.mockClear()
+
+ await manager.setPermission(program, "network", ["https://api.example.test/**"])
+ await manager.setPermission(program, "network", ["https://api.example.test/**"])
+
+ const permissions = { uploads: [], network: ["https://api.example.test"] }
+ expect(manager.find(program.identity).record()).toMatchObject({ permissions })
+ expect(records).toHaveLength(1)
+ expect(records[0]).toMatchObject({ permissions })
+ expect(announceHost).toHaveBeenCalledExactlyOnceWith(
+ "program", "permissions", program.identity, manager.find(program.identity)
+ )
+ expect(announceSubject).toHaveBeenCalledExactlyOnceWith(
+ "program", "permissions", program.reference, permissions
+ )
+})
+
test("pinning emits Program and global events only when the boolean changes", async context => {
const { manager, definition, announceHost } = fixture(context)
const program = await manager.create(definition())
diff --git a/tests/program-icon-launch.test.ts b/tests/program-icon-launch.test.ts
index 84b14e7..1ce1b21 100644
--- a/tests/program-icon-launch.test.ts
+++ b/tests/program-icon-launch.test.ts
@@ -7,7 +7,7 @@ import Entry from "@server/core/link-manager/auth-manager/program-manager/entry"
test("opening a Program uses Endpoint defaults while direct creation keeps its explicit request", async () => {
const publish = vi.fn()
const manager = { $outbound: { publish } } as unknown as ProgramManager
- const record = new Entry(new RuntimeProgram({ identity: "example", client: { location: "." } })).record()
+ const record = new Entry(new RuntimeProgram({ identity: "example", client: { location: "." } }), {}).record()
const program = new Program(manager, record)
const address = { identity: record.identity, reference: record.reference }
diff --git a/tests/sdk-records.test.ts b/tests/sdk-records.test.ts
index 9edb465..af35b89 100644
--- a/tests/sdk-records.test.ts
+++ b/tests/sdk-records.test.ts
@@ -3,10 +3,10 @@ import { parseProcessSnapshot, type ProgramSnapshot } from "@phreshos/core"
import { sdkProcess, type SdkProcessSource } from "@client/view/components/desktop-host/sdk-records"
test("Desktop preserves Endpoint service roles in SDK snapshots", () => {
- const program: ProgramSnapshot = {
+ const program: ProgramSnapshot & { permissions: {} } = {
identity: "example", reference: "program-reference", assetId: "program-assets",
name: "Example", version: "0.0.0", description: null, hasAgent: false,
- server: { start: true, service: false }, client: null
+ server: { start: true, service: false }, client: null, permissions: {}
}
for (const server of [null, { service: false }, { service: true }]) {
for (const client of [null, { service: false }, { service: true }]) {
diff --git a/tests/window-geometry.test.ts b/tests/window-geometry.test.ts
index 6de20a6..75adc3d 100644
--- a/tests/window-geometry.test.ts
+++ b/tests/window-geometry.test.ts
@@ -64,6 +64,11 @@ test("window geometry contract", async () => {
},
said(...event: unknown[]) {
events.push(event)
+ },
+ async publishWindowChange(event: string, identity: string, window: ServerWindow) {
+ const payload = { identity, window }
+ await this.$outbound.publish(event, payload)
+ return payload
}
}
@@ -82,12 +87,14 @@ test("window geometry contract", async () => {
assert.equal(echo.window, authority)
const unchangedEvents = events.length
+ const unchangedEchoes = echoes.length
await ProcessManager.prototype.setGeometry.call(manager as unknown as ProcessManager, "process", next)
await ProcessManager.prototype.move.call(manager as unknown as ProcessManager, "process", nextPosition)
await ProcessManager.prototype.resize.call(manager as unknown as ProcessManager, "process", nextSize)
await ProcessManager.prototype.setTitle.call(manager as unknown as ProcessManager, "process", "Geometry")
await ProcessManager.prototype.setHeader.call(manager as unknown as ProcessManager, "process", true)
assert.equal(events.length, unchangedEvents)
+ assert.equal(echoes.length, unchangedEchoes)
await ProcessManager.prototype.setHeader.call(manager as unknown as ProcessManager, "process", false)
assert.equal(authority.header, false)