Skip to content

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

Services by System-wide names, and messages carry who sent them as public values

zohayrslilehe373f20c7839
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 a724961..d3734ab 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,7 +5,7 @@ import { Publish, Subscribe } from "@the-link/core/decorators"
import { TheLink } from "@the-link/core"
import AuthManager from "../auth-manager"
import Process from "./process"
-import { type ClientLaunch, type IconSize, type ServerLaunch } from "@phreshos/core"
+import { type ClientLaunch, type ServerLaunch } from "@phreshos/core"
import { type TrafficKind } from "@server/core/link-manager/auth-manager/process-manager/process-traffic"
import { type ServiceAddress, type WindowLayer } from "@phreshos/core"
import { type ServiceScope } from "@server/core/link-manager/auth-manager/process-manager/endpoint-services"
@@ -90,35 +90,17 @@ export default class ProcessManager extends TheLink {
await this.$outbound.publish("/emit", source, event, payload)
}
- /** Reads current availability for one exact Service address. */
+ /** Whether an Endpoint of the addressed kind holds this Service name and is ready now. */
public async serviceAvailable(address: ServiceAddress) {
return await this.$outbound.publishFirst("/service/available", address) as boolean
}
- public async listServices(options: { name?: string } = {}) {
-
- return await this.$outbound.publishFirst("/service/list", options) as ServiceAddress[]
- }
-
public async waitServiceReady(address: ServiceAddress, timeout: number | undefined) {
await this.$outbound.publishFirst("/service/wait-ready", address, timeout)
}
- public async serviceProgramMetadata(address: ServiceAddress) {
-
- return await this.$outbound.publishFirst("/service/program-metadata", address) as {
- name: string
- version: string
- }
- }
-
- public async serviceProgramIcon(address: ServiceAddress, iconSize: IconSize = "medium") {
-
- return await this.$outbound.publishFirst("/service/program-icon", address, iconSize) as number[]
- }
-
/** Registers one exact service interest for this frame lease. */
public async followService(pane: string, owner: string, subscription: string, address: ServiceAddress, scope: ServiceScope, event: string | null) {
diff --git a/source/client/core/link-manager/auth-manager/process-manager/process.ts b/source/client/core/link-manager/auth-manager/process-manager/process.ts
index 28a9c91..6d6462d 100644
--- a/source/client/core/link-manager/auth-manager/process-manager/process.ts
+++ b/source/client/core/link-manager/auth-manager/process-manager/process.ts
@@ -27,7 +27,7 @@ export default class Process {
public readonly startedAt: Date
// Current live endpoint state mirrored from the authoritative host.
- public server: { ready: boolean, service: boolean } | null
+ public server: { ready: boolean, service: string | false } | null
public client: ClientState | null
@@ -139,7 +139,7 @@ export interface ProcessLineage {
readonly startedAt: Date
- readonly server: { service: boolean } | null
+ readonly server: { service: string | false } | null
- readonly client: { service: boolean } | null
+ readonly client: { service: string | false } | null
}
diff --git a/source/client/view/components/desktop-host/announcements.ts b/source/client/view/components/desktop-host/announcements.ts
index 8af7b6e..a66f61e 100644
--- a/source/client/view/components/desktop-host/announcements.ts
+++ b/source/client/view/components/desktop-host/announcements.ts
@@ -8,7 +8,6 @@ import ClientProcessBoundary from "./client-process-boundary"
import ClientTraffic from "./client-traffic"
import { sdkProcess, sdkProgram } from "./sdk-records"
import SystemAccess from "./system-access"
-import { isServiceAddress } from "@phreshos/core"
/** Projects authoritative System announcements into every Client frame. */
export default function useAnnouncements(authManager: AuthManager, panes: Map<string, ClientProcessBoundary>, traffic: ClientTraffic) {
@@ -151,16 +150,6 @@ export default function useAnnouncements(authManager: AuthManager, panes: Map<st
processes.useSubscribe("/client-start", useCallback((_identity: unknown, payload: HostedProcessRecord | null) => endpoint("endpointStart", "client", payload), [endpoint]))
processes.useSubscribe("/client-stop", useCallback((_identity: unknown, payload: HostedProcessRecord | null) => endpoint("endpointStop", "client", payload), [endpoint]))
- const serviceEvent = useCallback((event: "available" | "unavailable", value: unknown) => {
-
- if (!isServiceAddress(value)) return
-
- postVisible(access => access.canService(value), "host-service", event, value.process, value)
- }, [postVisible])
-
- processes.useSubscribe("/service-available", useCallback((value: unknown) => serviceEvent("available", value), [serviceEvent]))
- processes.useSubscribe("/service-unavailable", useCallback((value: unknown) => serviceEvent("unavailable", value), [serviceEvent]))
-
processes.useSubscribe("/said", useCallback((identity: string, event: string, value: unknown) => {
const target = authManager.processManager.processes.get(identity)
@@ -318,6 +307,6 @@ type HostedProcessRecord = {
name: string | null
options: Record<string, string>
opened: OpenTarget | null
- server: { ready: boolean, service: boolean } | null
- client: { service: boolean } | null
+ server: { ready: boolean, service: string | false } | null
+ client: { service: string | false } | null
}
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 8284e78..b976e74 100644
--- a/source/client/view/components/desktop-host/client-process-boundary.ts
+++ b/source/client/view/components/desktop-host/client-process-boundary.ts
@@ -345,8 +345,6 @@ export default class ClientProcessBoundary extends TheLink {
if (!await this.canDeliverSystemSubscription(route, values[0])) return
- values = await this.visibleReferences(values)
-
if (values[0] === "answer" && typeof values[1] === "string") {
if (!this.expected.has(values[1])) return
@@ -358,6 +356,17 @@ export default class ClientProcessBoundary extends TheLink {
return
}
+ // A stream's messages answer a question this Client asked, as an answer does: they go to it
+ // while it waits, never through the filter of events it subscribed to.
+ if (values[0] === "stream" && typeof values[1] === "string") {
+
+ if (!this.expected.has(values[1])) return
+
+ await this.$outbound.publish(route, ...values)
+
+ return
+ }
+
const question = values[0] === "wait" && typeof values[1] === "string" ? values[1] : null
const eventIndex = question && route === "end-end" ? 3 : 2
@@ -463,26 +472,6 @@ export default class ClientProcessBoundary extends TheLink {
: false
}
- private async visibleReferences(values: unknown[]) {
-
- const visible = async (reference: EndpointReference) => {
-
- return await this.systemAccess.canProgram(reference.process.program) ? reference : null
- }
-
- return await Promise.all(values.map(async value => {
-
- if (!value || typeof value !== "object" || Array.isArray(value)) return value
-
- const envelope = value as Record<string, unknown>
-
- if (isEndpointReference(envelope.from)) return { ...envelope, from: await visible(envelope.from) }
- if (isEndpointReference(envelope.to)) return { ...envelope, to: await visible(envelope.to) }
-
- return value
- }))
- }
-
private control(values: unknown[]) {
const [operation, ...args] = values
@@ -1360,24 +1349,6 @@ function isHandleAddress(value: unknown): value is { identity: string, reference
&& typeof value.identity === "string" && typeof value.reference === "string"
}
-type EndpointReference = Readonly<{
- kind: "server" | "client"
- process: Readonly<{ program: { identity: string } }>
-}>
-
-function isEndpointReference(value: unknown): value is EndpointReference {
-
- if (!value || typeof value !== "object" || Array.isArray(value)) return false
-
- const reference = value as { kind?: unknown, process?: unknown }
-
- if (reference.kind !== "server" && reference.kind !== "client") return false
- if (!reference.process || typeof reference.process !== "object" || Array.isArray(reference.process)) return false
-
- const program = (reference.process as { program?: unknown }).program
-
- return !!program && typeof program === "object" && !Array.isArray(program) && typeof (program as { identity?: unknown }).identity === "string"
-}
interface WaitingQuestion {
diff --git a/source/client/view/components/desktop-host/host.ts b/source/client/view/components/desktop-host/host.ts
index f9a5fb0..83343f8 100644
--- a/source/client/view/components/desktop-host/host.ts
+++ b/source/client/view/components/desktop-host/host.ts
@@ -21,7 +21,6 @@ import {
parsePermissions,
opensType,
parseSystemProgramListOptions,
- parseSystemServiceListOptions,
type PermissionRequestInput,
type IconSize
} from "@phreshos/core"
@@ -137,7 +136,7 @@ export default function host(authManager: AuthManager, pane: string, viewport: D
function permittedService(value: unknown) {
- if (!isServiceAddress(value)) throw new Error("A complete Service address is required")
+ if (!isServiceAddress(value)) throw new Error("A Service is reached by its name, such as file-picker-v1, and optionally the kind of Endpoint")
return access.service(value)
}
@@ -415,7 +414,7 @@ export default function host(authManager: AuthManager, pane: string, viewport: D
return []
}
- if (word === "is-service") {
+ if (word === "endpoint-service") {
const target = await permittedProcess(args[1])
const endpoint = args[0] ?? "client"
@@ -430,19 +429,7 @@ export default function host(authManager: AuthManager, pane: string, viewport: D
}
// The synchronized Process holds it, as it holds whether the Endpoint runs.
- return [endpoint === "server" ? target.server?.service === true : target.client?.service === true]
- }
-
- if (word === "host-service-list") {
-
- const options = parseSystemServiceListOptions(args[0])
-
- const services = await processManager.listServices(options)
- const visible = []
-
- for (const service of services) if (await access.canService(service)) visible.push(service)
-
- return [visible]
+ return [(endpoint === "server" ? target.server?.service : target.client?.service) ?? false]
}
if (word === "service-available") {
@@ -459,20 +446,6 @@ export default function host(authManager: AuthManager, pane: string, viewport: D
return [await processManager.waitServiceReady(service, args[1] as number | undefined)]
}
- if (word === "service-program-metadata") {
-
- const service = await permittedService(args[0])
-
- return [await processManager.serviceProgramMetadata(service)]
- }
-
- if (word === "service-program-icon") {
-
- const service = await permittedService(args[0])
-
- return [await processManager.serviceProgramIcon(service, args[1] as IconSize | undefined)]
- }
-
if (word === "service-follow") {
const [subscription, address, scope, event] = args
@@ -514,7 +487,7 @@ export default function host(authManager: AuthManager, pane: string, viewport: D
if (word === "service-ask") {
- if (!isServiceAddress(args[0]) || args[0].endpoint !== "server") throw new Error("Only a Server service can be asked")
+ if (!isServiceAddress(args[0]) || args[0].endpoint !== "server") throw new Error("Only a Server Service answers questions")
const service = await access.service(args[0])
diff --git a/source/client/view/components/desktop-host/system-access.ts b/source/client/view/components/desktop-host/system-access.ts
index 72777eb..66679e1 100644
--- a/source/client/view/components/desktop-host/system-access.ts
+++ b/source/client/view/components/desktop-host/system-access.ts
@@ -45,7 +45,7 @@ export default class SystemAccess {
public async canService(service: ServiceAddress) {
- return allowsSynchronizedPermission(this.permissions(), "services", [service.process])
+ return allowsSynchronizedPermission(this.permissions(), "consumeServices", [service.name])
}
/** Whether one Connection belongs to this Client's visible scope. */
diff --git a/source/client/view/structure/desktop/layers/shell/dialogs/permission-requests.tsx b/source/client/view/structure/desktop/layers/shell/dialogs/permission-requests.tsx
index 1f0e050..e4f16bb 100644
--- a/source/client/view/structure/desktop/layers/shell/dialogs/permission-requests.tsx
+++ b/source/client/view/structure/desktop/layers/shell/dialogs/permission-requests.tsx
@@ -56,7 +56,8 @@ function PermissionRequestView({ request }: Readonly<{ request: PermissionReques
const permissionPresentation = {
all: { title: "all permissions", description: "Grant every available Program permission." },
- services: { title: "Services", description: "Access Services by their Process and Service name." },
+ consumeServices: { title: "Using Services", description: "Reach Services by their names." },
+ provideServices: { title: "Providing Services", description: "Offer Services under their names, taking a name from whoever holds it." },
programs: { title: "Programs", description: "Access every Program or selected Programs." },
layers: { title: "Window layers", description: "Select raw Desktop layers in Client Endpoint launches." },
network: { title: "Network", description: "Use System networking with every request target or selected target scopes." },
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 07a8e59..9290ce7 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
@@ -35,9 +35,7 @@ export default class ClientProcessForwarder {
private readonly subscriptions = new Map<string, string | null>()
- private readonly shapeObservedValues: (values: unknown[]) => unknown[]
-
- public constructor(connection: string, pane: string, owner: string, authManager: AuthManager, traffic: ProcessTraffic, endpointEvents: EndpointEvents, shapeObservedValues: (values: unknown[]) => unknown[]) {
+ public constructor(connection: string, pane: string, owner: string, authManager: AuthManager, traffic: ProcessTraffic, endpointEvents: EndpointEvents) {
this.connection = connection
@@ -50,8 +48,6 @@ export default class ClientProcessForwarder {
this.traffic = traffic
this.endpointEvents = endpointEvents
-
- this.shapeObservedValues = shapeObservedValues
}
public observe(subscription: string, target: string, half: Half, kind: TrafficKind, event: string | null, reportImpossible: boolean) {
@@ -60,7 +56,7 @@ export default class ClientProcessForwarder {
const stop = this.traffic.observe(target, half, kind, event, (word, ...payload) => {
- const values = this.shapeObservedValues(event === null ? [word, ...payload] : payload)
+ const values = event === null ? [word, ...payload] : payload
this.authManager.publishToBoundary(this.connection, "/process/observed", this.pane, this.owner, subscription, values).catch(() => undefined)
}, reportImpossible ? reason => this.impossible(subscription, reason) : undefined)
diff --git a/source/server/core/link-manager/auth-manager/process-manager/client-state.ts b/source/server/core/link-manager/auth-manager/process-manager/client-state.ts
index 9e8adfc..4f0ae32 100644
--- a/source/server/core/link-manager/auth-manager/process-manager/client-state.ts
+++ b/source/server/core/link-manager/auth-manager/process-manager/client-state.ts
@@ -10,9 +10,10 @@ export default class ClientState {
public readonly memory = new ClientMemoryState()
- public readonly service: boolean
+ /** The Service name this Client run is reached by, or `false` for none. */
+ public readonly service: string | false
- public constructor(service: boolean) {
+ public constructor(service: string | false) {
this.service = service
}
diff --git a/source/server/core/link-manager/auth-manager/process-manager/endpoint-reference.ts b/source/server/core/link-manager/auth-manager/process-manager/endpoint-reference.ts
index 94cb196..5c4c336 100644
--- a/source/server/core/link-manager/auth-manager/process-manager/endpoint-reference.ts
+++ b/source/server/core/link-manager/auth-manager/process-manager/endpoint-reference.ts
@@ -1,4 +1,4 @@
-import type { EndpointReference as CoreEndpointReference, ProcessSnapshot } from "@phreshos/core"
+import type { EndpointMetadata, EndpointReference as CoreEndpointReference, ProcessSnapshot } from "@phreshos/core"
import { type Half } from "./process-traffic"
import Process from "./process"
@@ -22,3 +22,12 @@ export function endpointReference(process: Process, kind: Half): EndpointReferen
return { kind, process: processReference(process) } satisfies CoreEndpointReference
}
+
+/**
+ * Who an Endpoint is, as every message to or from it carries it: public values, the same for every
+ * receiver and observer. Reaching the Endpoint itself goes through its Process, under permissions.
+ */
+export function endpointMetadata(process: Process, kind: Half): EndpointMetadata {
+
+ return { program: { identity: process.program.identity, name: process.program.name }, process: process.identity, endpoint: kind }
+}
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 3bfda9b..84a0d23 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
@@ -3,46 +3,37 @@ import { TheLink } from "@the-link/core"
import type Process from "./process"
import type { Half } from "./process-traffic"
-/** Resolves and routes the Service view of named Endpoint execution contexts. */
+/**
+ * The Services of running Endpoints, by their names. A Service name is public across the System and
+ * held by one Endpoint at a time; a caller reaches it by the name, of a kind it names or of either.
+ * Who holds it stays out of sight.
+ */
export default class EndpointServices extends TheLink {
- private readonly active = new Set<string>()
+ /** The names whose holder is ready, and the kind of Endpoint holding each. */
+ private readonly active = new Map<string, Half>()
- public constructor(
- private readonly resolve: (address: ServiceAddress) => ServiceTarget | null,
- private readonly processes: () => Iterable<Process>,
- private readonly changed: (event: "available" | "unavailable", address: ServiceAddress) => Promise<unknown> | unknown
- ) {
+ public constructor(private readonly processes: () => Iterable<Process>) {
super()
}
- /** Returns the ready Service addresses currently represented by the model. */
- public list(name?: string) {
-
- const addresses: ServiceAddress[] = []
+ /** The Endpoint holding a Service name, of any kind, while it runs. */
+ public holder(name: string): ServiceTarget | null {
for (const process of this.processes()) {
- if (process.name === null || name !== undefined && process.name !== name) continue
-
- for (const endpoint of ["server", "client"] as const) {
+ if (process.server?.service === name) return { process, endpoint: "server" }
- const address = this.addressOf(process, endpoint)
-
- if (address && this.available(address)) addresses.push(address)
- }
+ if (process.client?.service === name) return { process, endpoint: "client" }
}
- return addresses
+ return null
}
public available(value: unknown) {
- const address = this.address(value)
- const target = this.resolve(address)
-
- return target !== null && this.readyState(target.process, target.endpoint)
+ return this.target(value) !== null
}
public async waitReady(value: unknown, timeout: unknown = 10_000, signal?: AbortSignal) {
@@ -79,43 +70,46 @@ export default class EndpointServices extends TheLink {
})
}
- public target(value: unknown, endpoint?: Half) {
+ /**
+ * The ready Endpoint holding an address's name, when it is of the kind the address names, and of the
+ * kind the caller needs, such as a Server for a question.
+ */
+ public target(value: unknown, needed?: Half) {
const address = this.address(value)
- const target = this.resolve(address)
+ const target = this.holder(address.name)
- if (!target || endpoint && target.endpoint !== endpoint || !this.readyState(target.process, target.endpoint)) return null
+ if (!target || address.endpoint && target.endpoint !== address.endpoint || needed && target.endpoint !== needed) return null
- return target
+ return this.readyState(target.process, target.endpoint) ? target : null
}
- /** Mirrors one application event through the Service's stable address. */
+ /** Mirrors one application event of a Service's holder to everyone following its name. */
public async emit(process: Process, endpoint: Half, event: string, payload: unknown) {
- const address = this.addressOf(process, endpoint)
- if (!address || !this.available(address)) return []
+ const name = this.nameOf(process, endpoint)
- return await this.$inbound.publish(this.event(address, "events", event), event, payload)
+ if (name === false || this.active.get(name) !== endpoint) return []
+
+ return await Promise.all(this.routes(name, endpoint, "events").map(route => this.$inbound.publish(route + encodeURIComponent(event), event, payload)))
}
- /** Re-evaluates Service availability after an Endpoint starts. */
+ /** Re-evaluates a name after its Endpoint starts. */
public started(process: Process, endpoint: Half) {
return this.refresh(process, endpoint)
}
- /** Re-evaluates Server Service availability after it signals readiness. */
+ /** Re-evaluates a name after its Server signals readiness. */
public ready(process: Process, endpoint: Half) {
return this.refresh(process, endpoint)
}
- /** Removes availability after a previously configured Service Endpoint stops. */
- public stopped(process: Process, endpoint: Half, service: boolean) {
-
- const address = service ? this.addressOf(process, endpoint, true) : null
+ /** Lets a name go after the Endpoint that held it stops. */
+ public stopped(endpoint: Half, service: string | false) {
- return address ? this.transition(address, false) : Promise.resolve([])
+ return service !== false && this.active.get(service) === endpoint ? this.transition(service, endpoint, false) : Promise.resolve([])
}
public follow(value: unknown, scope: Scope, event: string | null, subscriber: Subscriber, permitted: () => boolean = () => true) {
@@ -124,7 +118,7 @@ export default class EndpointServices extends TheLink {
if (scope !== "lifecycle" && scope !== "events") throw new Error("A Service subscription scope is invalid")
- const prefix = this.prefix(address, scope)
+ const prefix = this.prefix(address.name, address.endpoint ?? "any", 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.
@@ -141,69 +135,52 @@ export default class EndpointServices extends TheLink {
private refresh(process: Process, endpoint: Half) {
- const address = this.addressOf(process, endpoint)
+ const name = this.nameOf(process, endpoint)
- if (!address) return Promise.resolve([])
+ if (name === false) return Promise.resolve([])
- return this.transition(address, this.available(address))
+ return this.transition(name, endpoint, this.readyState(process, endpoint))
}
- private async transition(address: ServiceAddress, available: boolean) {
+ private async transition(name: string, endpoint: Half, available: boolean) {
- const identity = this.identity(address)
+ if ((this.active.get(name) === endpoint) === available) return []
- if (this.active.has(identity) === available) return []
-
- if (available) this.active.add(identity)
- else this.active.delete(identity)
+ if (available) this.active.set(name, endpoint)
+ else this.active.delete(name)
const event = available ? "available" : "unavailable"
- return await Promise.all([
- this.$inbound.publish(this.event(address, "lifecycle", event), event, undefined),
- this.changed(event, address)
- ])
- }
-
- private address(value: unknown) {
-
- if (!isServiceAddress(value)) throw new Error("A complete Service address is required")
-
- return Object.freeze({ program: value.program, process: value.process, endpoint: value.endpoint })
+ // Heard by whoever follows the name for this kind, and by whoever follows it for either.
+ return await Promise.all(this.routes(name, endpoint, "lifecycle").map(route => this.$inbound.publish(route + event, event, undefined)))
}
- private addressOf(process: Process, endpoint: Half, previouslyConfigured = false): ServiceAddress | null {
+ private address(value: unknown): ServiceAddress {
- if (process.name === null || !previouslyConfigured && !this.configured(process, endpoint)) return null
+ if (!isServiceAddress(value)) throw new Error("A Service is reached by its name, such as file-picker-v1, and optionally the kind of Endpoint")
- return Object.freeze({ program: process.program.identity, process: process.name, endpoint })
+ return Object.freeze({ name: value.name, ...(value.endpoint === undefined ? {} : { endpoint: value.endpoint }) })
}
- private configured(process: Process, endpoint: Half) {
+ private nameOf(process: Process, endpoint: Half): string | false {
- return endpoint === "server" ? process.server?.service === true : process.client?.service === true
+ return (endpoint === "server" ? process.server?.service : process.client?.service) ?? false
}
private readyState(process: Process, endpoint: Half) {
- return endpoint === "server"
- ? process.server?.service === true && process.server.ready
- : process.client?.service === true
- }
-
- private identity(address: ServiceAddress) {
-
- return JSON.stringify([address.program, address.process, address.endpoint])
+ return endpoint === "server" ? process.server?.service !== false && process.server?.ready === true : process.client?.service !== false && process.client !== null
}
- private prefix(address: ServiceAddress, scope: Scope) {
+ /** The routes an event of a name's holder travels: for its own kind, and for either kind. */
+ private routes(name: string, endpoint: Half, scope: Scope) {
- return `program/${encodeURIComponent(address.program)}/${encodeURIComponent(address.process)}/${address.endpoint}/${scope}/`
+ return [this.prefix(name, endpoint, scope), this.prefix(name, "any", scope)]
}
- private event(address: ServiceAddress, scope: Scope, event: string) {
+ private prefix(name: string, kind: Half | "any", scope: Scope) {
- return this.prefix(address, scope) + encodeURIComponent(event)
+ return `service/${encodeURIComponent(name)}/${kind}/${scope}/`
}
}
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 29fff50..7486110 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
@@ -11,7 +11,7 @@ import ProcessTraffic, { type Half, type TrafficKind } from "./process-traffic"
import ClientProcessForwarder from "./client-process-forwarder"
import HostTraffic, { type HostDomain, type HostOwner } from "./host-traffic"
import { failed, succeeded, type RequestOutcome } from "@libs/request-outcome"
-import { endpointReference, processReference } from "./endpoint-reference"
+import { endpointMetadata, processReference } from "./endpoint-reference"
import EndpointEvents from "./endpoint-events"
import EndpointServices, { serviceTimeout } from "./endpoint-services"
import OutsideQuestions from "./outside-questions"
@@ -22,16 +22,14 @@ import {
parseProgramInstallOptions,
parseProgramUninstallOptions,
parseSystemProgramListOptions,
- parseSystemServiceListOptions,
+ parseServiceValue,
type ClientLaunch,
type Launch,
type Permission,
type PermissionName,
type PermissionRequestInput,
type PermissionValue,
- type IconSize,
type ServerLaunch,
- type ServiceAddress,
type WindowGeometry,
type WindowLayer,
type WindowState,
@@ -39,7 +37,7 @@ import {
} from "@phreshos/core"
import { isDesktopReplacementLayer, type DesktopReplacementLayer } from "@shared/window-layers"
import type { ServerRuntime, ServerRuntimeFactory } from "@server/core/server-runtime"
-import SystemAccess from "./system-access"
+import SystemAccess, { type LaunchReach } from "./system-access"
import { WebSocket } from "ws"
import { permissionCatalog } from "@server/core/permissions"
import { defaultPermissionRequestTimeout } from "@server/core/permission-manager"
@@ -115,14 +113,7 @@ export default class ProcessManager extends TheLink {
this.authManager = authManager
- this.services = new EndpointServices(
- address => this.resolveService(address),
- () => this.processes.values(),
- (event, address) => Promise.all([
- this.hostTraffic.emitHost("service", null, event, address.process, address),
- this.$outbound.publish(`/service-${event}`, address)
- ])
- )
+ this.services = new EndpointServices(() => this.processes.values())
this.connectTo(this.authManager, "/process")
@@ -137,17 +128,6 @@ export default class ProcessManager extends TheLink {
return process
}
- private resolveService(address: ServiceAddress) {
-
- const program = this.authManager.programManager.reach(address.program)
- const process = program
- ? [...this.processes.values()].find(candidate => candidate.program === program && candidate.name === address.process)
- : null
- const service = address.endpoint === "server" ? process?.server?.service : process?.client?.service
-
- return process && service === true ? { process, endpoint: address.endpoint } : null
- }
-
private heldWindow(value: unknown, fallback: Process) {
const process = this.system.holdProcess(value, fallback)
@@ -290,13 +270,12 @@ export default class ProcessManager extends TheLink {
return this.services.available(address)
}
- public listServicesFromOutside(name?: string) { return this.services.list(name) }
-
- public endpointIsServiceFromOutside(identity: string, endpoint: Half) {
+ /** The Service name an Endpoint of a Process holds, or `false` for none. */
+ public endpointServiceFromOutside(identity: string, endpoint: Half) {
const process = this.find(identity)
- return endpoint === "server" ? process.server?.service === true : process.client?.service === true
+ return (endpoint === "server" ? process.server?.service : process.client?.service) ?? false
}
public waitServiceReadyFromOutside(address: unknown, timeout?: number) {
@@ -444,7 +423,7 @@ export default class ProcessManager extends TheLink {
current?.release()
- this.clientForwarders.set(key, new ClientProcessForwarder(connection, pane, owner, this.authManager, this.traffic, this.endpointEvents, values => this.clientVisibleTraffic(pane, values)))
+ this.clientForwarders.set(key, new ClientProcessForwarder(connection, pane, owner, this.authManager, this.traffic, this.endpointEvents))
}
private releaseClient(connection: string, pane: string, owner: string) {
@@ -492,11 +471,6 @@ export default class ProcessManager extends TheLink {
boundary.observe(subscription, observed.reference, observation.half, kind, event, reportImpossible)
}
- private clientVisibleTraffic(_pane: string, values: unknown[]) {
-
- return values
- }
-
private removeClientObservation(connection: string, pane: string, owner: string, subscription: string) {
const boundary = this.clientForwarders.get(this.clientOwnerKey(connection, pane))
@@ -741,14 +715,14 @@ export default class ProcessManager extends TheLink {
const received = {
- from: endpointReference(sourceProcess, sourceHalf),
+ from: endpointMetadata(sourceProcess, sourceHalf),
payload
}
const observed = this.traffic.emit(sourceProcess.reference, sourceHalf, "publish", event, {
- to: endpointReference(targetProcess, targetHalf),
+ to: endpointMetadata(targetProcess, targetHalf),
payload
})
@@ -767,22 +741,25 @@ export default class ProcessManager extends TheLink {
if (!back) return false
+ const outcome = values[4] as RequestOutcome
+
if (back.half === "outside") {
- this.outsideQuestions.answer(values[1], values[4] as RequestOutcome)
+ // Observed like any other answer: `null`, as the asker is no Program Endpoint.
+ if (answerer) this.traffic.emit(answerer.reference, "server", "answer", values[3], values[2], { to: null, outcome }).catch(() => undefined)
+
+ this.outsideQuestions.answer(values[1], outcome)
return true
}
const process = this.processes.get(back.identity)
- const outcome = values[4] as RequestOutcome
-
if (answerer && process) {
this.traffic.emit(answerer.reference, "server", "answer", values[3], values[2], {
- to: endpointReference(process, back.half),
+ to: endpointMetadata(process, back.half),
outcome
}).catch(() => undefined)
@@ -919,7 +896,7 @@ export default class ProcessManager extends TheLink {
() => { process.serverStopped(boundary, code, signal) },
- () => this.services.stopped(process, "server", boundary.service),
+ () => this.services.stopped("server", boundary.service),
() => { boundary.release() },
@@ -966,7 +943,20 @@ export default class ProcessManager extends TheLink {
else await this.transition(process, finish).catch(() => undefined)
}
- private activateServer(process: Process, runtime: ServerRuntime, service: boolean) {
+ /**
+ * Takes a Service name for an Endpoint about to start: whatever Process holds it now ends, whole, as
+ * an occupied layer's does. Whoever started it was let provide the name; that is all it takes.
+ */
+ private async claimService(process: Process, service: string | false) {
+
+ if (service === false) return
+
+ const holder = this.services.holder(service)
+
+ if (holder && holder.process !== process) await this.exitProcess(holder.process.identity, "complete")
+ }
+
+ private activateServer(process: Process, runtime: ServerRuntime, service: string | false) {
const server = process.startServer(runtime, service,
@@ -999,7 +989,7 @@ export default class ProcessManager extends TheLink {
if (domain === "log") return this.grants(process.identity, "logs", [])
- if (domain === "service") return subject !== null && this.grants(process.identity, "services", [subject])
+ if (domain === "service") return subject !== null && this.grants(process.identity, "consumeServices", [subject])
return owner !== null && access.canProgram({ identity: owner })
}
@@ -1051,7 +1041,7 @@ export default class ProcessManager extends TheLink {
}
/** Claims the role after serialized replacement has released its previous owner. */
- private activateClient(process: Process, service: boolean) {
+ private activateClient(process: Process, service: string | false) {
const window = process.clientEndpoint?.window
if (!window) throw new Error("This Program declared no Client Endpoint")
if (isDesktopReplacementLayer(window.layer) && [...this.processes.values()].some(
@@ -1140,11 +1130,15 @@ export default class ProcessManager extends TheLink {
await this.transition(process, async () => {
if (client && window && shape) {
+ await this.claimService(process, launch.client?.service ?? false)
this.startWindow(window, shape)
this.activateClient(process, launch.client?.service ?? false)
}
- if (runtime) this.activateServer(process, runtime, launch.server?.service ?? false)
+ if (runtime) {
+ await this.claimService(process, launch.server?.service ?? false)
+ this.activateServer(process, runtime, launch.server?.service ?? false)
+ }
// The subject first, which is what scopes a listener without
// anything being checked: a kit's `Events` refuses a value whose
@@ -1213,12 +1207,12 @@ export default class ProcessManager extends TheLink {
const serverWasLive = process.server !== null
const clientWasLive = process.client !== null
- const serverWasService = process.server?.service === true
- const clientWasService = process.client?.service === true
+ const serverWasService = process.server?.service ?? false
+ const clientWasService = process.client?.service ?? false
const failures = await settleEvery([
- ...serverWasLive ? [() => this.services.stopped(process, "server", serverWasService)] : [],
- ...clientWasLive ? [() => this.services.stopped(process, "client", clientWasService)] : []
+ ...serverWasLive ? [() => this.services.stopped("server", serverWasService)] : [],
+ ...clientWasLive ? [() => this.services.stopped("client", clientWasService)] : []
])
// Another converging teardown may have completed while services were
@@ -1293,7 +1287,9 @@ export default class ProcessManager extends TheLink {
if (!process.program.server) throw new Error("This program declared no server half")
- if (typeof launch !== "object" || launch === null || Array.isArray(launch) || launch.service !== undefined && typeof launch.service !== "boolean") throw new Error("A Server launch must contain an optional boolean service value")
+ if (typeof launch !== "object" || launch === null || Array.isArray(launch)) throw new Error("A Server launch is an object")
+
+ const service = launch.service === undefined ? process.program.server.service : parseServiceValue(launch.service, "A Server launch's service")
if (process.server) return
@@ -1303,7 +1299,9 @@ export default class ProcessManager extends TheLink {
try {
- this.activateServer(process, runtime, launch.service ?? process.program.server.service)
+ await this.claimService(process, service)
+
+ this.activateServer(process, runtime, service)
await this.serverStarted(process)
}
@@ -1394,6 +1392,8 @@ export default class ProcessManager extends TheLink {
await this.prepareClientLayer(window.layer, process.program)
+ await this.claimService(process, launch.service ?? declaration.service)
+
this.activateClient(process, launch.service ?? declaration.service)
try {
@@ -1441,7 +1441,7 @@ export default class ProcessManager extends TheLink {
const layer = process.client ? process.clientEndpoint?.window.layer ?? null : null
- const service = process.client?.service === true
+ const service = process.client?.service ?? false
const before = layer ? this.front(layer) : null
@@ -1449,7 +1449,7 @@ export default class ProcessManager extends TheLink {
() => { process.stopClient() },
- () => this.services.stopped(process, "client", service),
+ () => this.services.stopped("client", service),
() => { this.releaseClientForwarders(process.identity) },
@@ -1576,54 +1576,12 @@ export default class ProcessManager extends TheLink {
return this.services.available(address)
}
- @Subscribe("/service/list")
- protected async listServices(options: unknown = {}) {
-
- return this.services.list(parseSystemServiceListOptions(options).name)
- }
-
@Subscribe("/service/wait-ready")
protected async waitServiceReady(address: unknown, timeout: unknown) {
await this.services.waitReady(address, timeout, this.authManager.connectionSignal())
}
- @Subscribe("/service/program-metadata")
- protected async serviceProgramMetadata(address: unknown) {
-
- if (!isServiceAddress(address)) throw new Error("A complete Service address is required")
-
- const target = this.services.target(address)
-
- if (!target) throw new Error("The Service is unavailable")
-
- const program = target.process.program
-
- return Object.freeze({ name: program.name, version: program.version })
- }
-
- @Subscribe("/service/program-icon")
- protected async serviceProgramIcon(address: unknown, iconSize: unknown = "medium") {
-
- if (!isServiceAddress(address)) throw new Error("A complete Service address is required")
-
- const target = this.services.target(address)
-
- if (!target) throw new Error("The Service is unavailable")
-
- const icon = await this.authManager.programManager.icon(target.process.program, iconSize)
-
- // Rendering can outlive one provider incarnation; never return an icon
- // after the exact Service target that authorized the read has vanished.
- const current = this.services.target(address)
-
- if (!current || current.process !== target.process || current.endpoint !== target.endpoint) {
- throw new Error("The Service is unavailable")
- }
-
- return icon
- }
-
@Subscribe("/service/send")
protected async sendClientService(source: string, address: unknown, event: unknown, payload: unknown) {
@@ -1705,13 +1663,13 @@ export default class ProcessManager extends TheLink {
if (event !== null && typeof event !== "string") return
- if (!this.grants(pane, "services", [address.process])) return
+ if (!this.grants(pane, "consumeServices", [address.name])) 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])
+ return process !== undefined && this.authManager.programManager.grantsPermission(process.program, "consumeServices", [address.name])
})
}
@@ -1754,6 +1712,17 @@ export default class ProcessManager extends TheLink {
}
/** Tests one concrete permission for the Program executing this Process. */
+ /**
+ * Refuses a resolved Launch its executor may not run: an Endpoint asked for it; the owner, with
+ * no asker, runs any.
+ */
+ public requireLaunch(asker: string | null, launch: LaunchReach) {
+
+ const process = asker === null ? undefined : this.processes.get(asker)
+
+ if (process) new SystemAccess(this, process).requireLaunch(launch)
+ }
+
public grants<Name extends PermissionName>(identity: string, name: Name, requested: readonly PermissionValue<Name>[]) {
const process = this.find(identity)
@@ -1836,9 +1805,9 @@ export default class ProcessManager extends TheLink {
const heldService = (value: unknown) => {
- if (!isServiceAddress(value)) throw new Error("A complete Service address is required")
+ if (!isServiceAddress(value)) throw new Error("A Service is reached by its name, such as file-picker-v1, and optionally the kind of Endpoint")
- if (!this.grants(process.identity, "services", [value.process])) throw new Error("Execution is not permitted")
+ if (!this.grants(process.identity, "consumeServices", [value.name])) throw new Error("Execution is not permitted")
return value
}
@@ -2100,7 +2069,7 @@ export default class ProcessManager extends TheLink {
const program = heldProgram(rest[0])
- const value = rest[1] === "set" ? access.launch(rest[2]) : rest[2]
+ const value = rest[1] === "set" ? access.launch(program, rest[2]) : rest[2]
return [await this.system.programStartup(program, String(rest[1]), value)]
}
@@ -2189,14 +2158,14 @@ export default class ProcessManager extends TheLink {
// other end — identity and program, nothing else — was how every
// process held by its launcher had no startedAt while every
// other road's did.
- return [processReference(this.system.requireProcess(await this.system.createProcess(program, access.launch(rest[1]), process)))]
+ return [processReference(this.system.requireProcess(await this.system.createProcess(program, access.launch(program, rest[1]), process)))]
}
if (word === "program-find-or-create-process") {
const program = heldProgram(rest[0])
- return [processReference(this.system.requireProcess(await this.system.findOrCreateProcess(program, access.launch(rest[1]) as Launch & { name: string }, process)))]
+ return [processReference(this.system.requireProcess(await this.system.findOrCreateProcess(program, access.launch(program, rest[1]) as Launch & { name: string }, process)))]
}
// Named, only that program's instances; unnamed, every one.
@@ -2261,7 +2230,7 @@ export default class ProcessManager extends TheLink {
throw new Error("A Process endpoint is server or client")
}
- if (word === "is-service") {
+ if (word === "endpoint-service") {
const target = heldProcess(rest[1])
const endpoint = rest[0] ?? "server"
@@ -2270,16 +2239,16 @@ export default class ProcessManager extends TheLink {
if (!target.program[endpoint]) throw new Error(`This Program declared no ${endpoint === "server" ? "Server" : "Client"} Endpoint`)
- return [endpoint === "server" ? target.server?.service === true : target.client?.service === true]
+ return [(endpoint === "server" ? target.server?.service : target.client?.service) ?? false]
}
if (word === "start-endpoint") {
const target = heldProcess(rest[0])
- if (rest[1] === "server") return [await this.system.startEndpoint(target, "server", rest[2] as ServerLaunch | undefined)]
+ if (rest[1] === "server") return [await this.system.startEndpoint(target, "server", access.serverLaunch(target.program, rest[2]))]
- if (rest[1] === "client") return [await this.system.startEndpoint(target, "client", access.clientLaunch(rest[2]))]
+ if (rest[1] === "client") return [await this.system.startEndpoint(target, "client", access.clientLaunch(target.program, rest[2]))]
throw new Error("A Process endpoint is server or client")
}
@@ -2297,21 +2266,10 @@ export default class ProcessManager extends TheLink {
if (word === "stop-current") return [await this.system.stopEndpoint(process, "server")]
- if (word === "host-service-list") {
-
- const { name } = parseSystemServiceListOptions(rest[0])
-
- return [this.services.list(name).filter(address => this.grants(process.identity, "services", [address.process]))]
- }
-
if (word === "service-available") return [this.services.available(heldService(rest[0]))]
if (word === "service-wait-ready") return [await this.services.waitReady(heldService(rest[0]), rest[1])]
- if (word === "service-program-metadata") return [await this.serviceProgramMetadata(heldService(rest[0]))]
-
- if (word === "service-program-icon") return [await this.serviceProgramIcon(heldService(rest[0]), rest[1] as IconSize | undefined)]
-
if (word === "service-follow") {
const [subscription, address, scope, event] = rest
@@ -2322,11 +2280,11 @@ export default class ProcessManager extends TheLink {
if (event !== null && typeof event !== "string") return []
- if (!this.grants(process.identity, "services", [address.process])) return []
+ if (!this.grants(process.identity, "consumeServices", [address.name])) return []
server.followService(this.services, subscription, address, scope, event, () => (
this.processes.get(process.identity) === process
- && this.authManager.programManager.grantsPermission(process.program, "services", [address.process])
+ && this.authManager.programManager.grantsPermission(process.program, "consumeServices", [address.name])
))
return []
@@ -3092,7 +3050,7 @@ export default class ProcessManager extends TheLink {
if (running) this.system.exitProcess(running).catch(() => undefined)
}
- const identity = await this.system.runProcess(program, access.launch(args[2]), {
+ const identity = await this.system.runProcess(program, access.launch(program, args[2]), {
started: created => {
running = created
@@ -3217,11 +3175,11 @@ export default class ProcessManager extends TheLink {
const payload = values[3]
- const received = { from: endpointReference(sourceProcess, sourceHalf), payload }
+ const received = { from: endpointMetadata(sourceProcess, sourceHalf), payload }
this.traffic.emit(sourceProcess.reference, sourceHalf, "ask", values[2], values[1], {
- to: endpointReference(targetProcess, "server"),
+ to: endpointMetadata(targetProcess, "server"),
payload
}).catch(() => undefined)
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 4b7f9fa..1a61020 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
@@ -118,7 +118,7 @@ export default class Process {
this.clientEndpoint = window ? Object.freeze({ window }) : null
}
- public startServer(runtime: ServerRuntime, service: boolean, ended: (boundary: ServerProcessBoundary, code: number | null, signal: NodeJS.Signals | null) => Promise<void> | void, unanswered: (values: unknown[], reason: string) => void, appearance: Tunnel, hostVisible: HostVisibility) {
+ public startServer(runtime: ServerRuntime, service: string | false, ended: (boundary: ServerProcessBoundary, code: number | null, signal: NodeJS.Signals | null) => Promise<void> | void, unanswered: (values: unknown[], reason: string) => void, appearance: Tunnel, hostVisible: HostVisibility) {
if (this.server) return this.server
@@ -165,7 +165,7 @@ export default class Process {
return () => { this.readyWaiters[endpoint].delete(notify) }
}
- public startClient(service: boolean) {
+ public startClient(service: string | false) {
if (this.client) return false
@@ -377,7 +377,8 @@ export interface ProcessLaunch {
readonly server: Readonly<{
- service: boolean
+ /** The Service name it is reached by, or `false` for none. */
+ service: string | false
}> | null
readonly client: Readonly<{
@@ -395,7 +396,8 @@ export interface ProcessLaunch {
minimize: boolean
maximize: boolean
- service: boolean
+ /** The Service name it is reached by, or `false` for none. */
+ service: string | false
}> | null
readonly options: Readonly<Record<string, string>>
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 194e861..abb06e1 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
@@ -18,7 +18,8 @@ export default class ServerProcessBoundary extends TheLink {
public ready = false
- public readonly service: boolean
+ /** The Service name this Server run is reached by, or `false` for none. */
+ public readonly service: string | false
private readonly clientDeclared: boolean
@@ -62,7 +63,7 @@ export default class ServerProcessBoundary extends TheLink {
public readonly finished: Promise<{ code: number | null, signal: NodeJS.Signals | null }>
- public constructor(runtime: ServerRuntime, clientDeclared: boolean, service: boolean, ended: Ending, unanswered: (values: unknown[], reason: string) => void, hostTraffic: HostTraffic, appearance: Tunnel, private readonly hostVisible: HostVisibility) {
+ public constructor(runtime: ServerRuntime, clientDeclared: boolean, service: string | false, ended: Ending, unanswered: (values: unknown[], reason: string) => void, hostTraffic: HostTraffic, appearance: Tunnel, private readonly hostVisible: HostVisibility) {
super()
diff --git a/source/server/core/link-manager/auth-manager/process-manager/system-access.ts b/source/server/core/link-manager/auth-manager/process-manager/system-access.ts
index 5652ff6..35b6100 100644
--- a/source/server/core/link-manager/auth-manager/process-manager/system-access.ts
+++ b/source/server/core/link-manager/auth-manager/process-manager/system-access.ts
@@ -1,6 +1,12 @@
-import { parseLaunch, type ClientLaunch, type PermissionName, type PermissionValue } from "@phreshos/core"
+import { parseLaunch, type PermissionName, type PermissionValue } from "@phreshos/core"
import type Program from "../program-manager/program"
import type Process from "./process"
+
+/** What of a resolved Launch needs a permission: where its Client opens, and the Service names its Endpoints take. */
+export type LaunchReach = Readonly<{
+ server?: Readonly<{ service: string | false }> | null
+ client: Readonly<{ layer?: string, service?: string | false }> | null
+}>
import type ProcessManager from "./process-manager"
const denied = "Execution is not permitted"
@@ -53,28 +59,56 @@ export default class SystemAccess {
if (!this.manager.grantsStorage(this.owner.identity, path, operation)) throw new Error(denied)
}
- public launch(value: unknown = {}) {
+ /**
+ * A Launch as it will run for a Program: what it passes, and what the Program declares where it
+ * passes nothing. Whoever executes it must be able to do all of it, whatever the Program declares.
+ */
+ public launch(program: Program, value: unknown = {}) {
const launch = parseLaunch(value)
- if (typeof launch.client === "object") this.clientLayer(launch.client)
+ this.requireLaunch(this.manager.authManager.programManager.resolveLaunch(program, launch).intent)
return launch
}
- public clientLaunch(value: unknown = {}) {
+ /** A Server started for a running Process of this Program, as it will run. */
+ public serverLaunch(program: Program, value: unknown = {}) {
+
+ const launch = parseLaunch({ server: value }).server
+
+ if (!launch || typeof launch !== "object") throw new Error("A Server launch must be an object")
+
+ this.requireLaunch(this.manager.authManager.programManager.resolveLaunch(program, { server: launch, client: false }).intent)
+
+ return launch
+ }
+
+ /** A Client started for a running Process of this Program, as it will run. */
+ public clientLaunch(program: Program, value: unknown = {}) {
const launch = parseLaunch({ client: value }).client
if (!launch || typeof launch !== "object") throw new Error("A Client launch must be an object")
- this.clientLayer(launch)
+ this.requireLaunch(this.manager.authManager.programManager.resolveLaunch(program, { server: false, client: launch }).intent)
return launch
}
- private clientLayer(launch: ClientLaunch) {
+ /**
+ * What a resolved Launch does that needs a permission: a Client in a layer other than `window`, and
+ * each Service name its Endpoints take, taking it from whoever holds it.
+ */
+ public requireLaunch(launch: LaunchReach) {
+
+ const layer = launch.client?.layer
+
+ if (layer !== undefined && layer !== "window") this.require("layers", [layer as PermissionValue<"layers">])
+
+ for (const service of [launch.server?.service, launch.client?.service]) {
- if (launch.layer !== undefined && launch.layer !== "window") this.require("layers", [launch.layer])
+ if (typeof service === "string") this.require("provideServices", [service])
+ }
}
}
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 a4173ed..38baad3 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
@@ -10,7 +10,7 @@ import { dirname, isAbsolute, join } from "node:path"
import { isDeepStrictEqual } from "node:util"
import Logs, { type LogSource } from "./logs"
import { isValue, layers } from "./config"
-import { parseLaunch, withProcessDefaults, parseProgramDefinition, parseProgramInstallOptions, parseProgramUninstallOptions, parseRelativeValue, type ProgramInstallOptions, type ProgramUninstallOptions, type ClientLaunch, type Launch, type Position, type ProgramCommandChunk, type ProgramDefinition, type Size, type Value } from "@phreshos/core"
+import { parseLaunch, parseServiceValue, withProcessDefaults, parseProgramDefinition, parseProgramInstallOptions, parseProgramUninstallOptions, parseRelativeValue, type ProgramInstallOptions, type ProgramUninstallOptions, type ClientLaunch, type Launch, type Position, type ProgramCommandChunk, type ProgramDefinition, type Size, type Value } from "@phreshos/core"
import type { OpenTarget } from "@phreshos/core"
import { type default as Process, type ProcessLaunch, type Stream } from "../process-manager/process"
import { type StandardShape } from "../process-manager/process-manager"
@@ -717,6 +717,11 @@ export default class ProgramManager extends TheLink {
if (operation === "set") {
+ // Starting with the System is what an attached Program cannot have: when the System starts,
+ // its project is not there to start. Its state is its identity's, shared with an installed
+ // copy, so setting it here would change that copy's start instead.
+ if (!this.programs.get(program.identity)?.installed) throw new Error("A Program starts with the System only once it is installed")
+
await program.validate()
const launch = parseLaunch(value === undefined ? {} : value)
@@ -1161,7 +1166,8 @@ export default class ProgramManager extends TheLink {
const requestedLaunch = selectedLaunch === false || selectedLaunch === undefined
? undefined
: selectedLaunch === true ? {} : selectedLaunch
- if (requestedLaunch !== undefined) this.resolveLaunch(stagedProgram, requestedLaunch)
+ // Whoever asked for the install answers for the launch it will run, declared defaults included.
+ if (requestedLaunch !== undefined) this.authManager.processManager.requireLaunch(asker, this.resolveLaunch(stagedProgram, requestedLaunch).intent)
swapping = true
@@ -1238,8 +1244,13 @@ export default class ProgramManager extends TheLink {
catch (exception) { console.log(`programs: ${entry.identity} did not start — ${exception instanceof Error ? exception.message : "invalid startup settings"}`) }
}
+ // The install launch makes sure its Process runs: one the startup has just started
+ // under the same name is that Process already, unless the launch asks to replace it.
if (requestedLaunch !== undefined) {
- await this.start(entry.program, requestedLaunch, undefined, null, true)
+ const program = entry.program
+ const running = requestedLaunch.name !== undefined && [...this.authManager.processManager.processes.values()]
+ .some(process => process.program === program && process.name === requestedLaunch.name)
+ if (!running || requestedLaunch.replace) await this.start(program, requestedLaunch, undefined, null, true)
}
return entry
@@ -1321,6 +1332,8 @@ export default class ProgramManager extends TheLink {
rmSync(this.fileManager.join(entry.identity), { recursive: true, force: true })
+ await this.authManager.openingManager.forgetProgram(entry.identity)
+
return await this.forgetEntry(entry)
}
@@ -1338,7 +1351,13 @@ export default class ProgramManager extends TheLink {
const home = this.fileManager.join(entry.identity)
- if (purge) rmSync(home, { recursive: true, force: true })
+ // Purged, nothing in the System says it was here: its own files, and what the System kept naming it.
+ if (purge) {
+
+ rmSync(home, { recursive: true, force: true })
+
+ await this.authManager.openingManager.forgetProgram(entry.identity)
+ }
else {
@@ -1489,7 +1508,8 @@ export default class ProgramManager extends TheLink {
// One interpretation of a Process launch, used both when it is created now
// and when a future startup launch is persisted. Runtime-only facts such as
// name occupancy and capacity remain in `start`.
- private resolveLaunch(program: Program, value: unknown, fallbackPosition: Position | null = null) {
+ /** A Launch as it will run for a Program: what it passes, and what the Program declares where it passes nothing. */
+ public resolveLaunch(program: Program, value: unknown, fallbackPosition: Position | null = null) {
const launch = this.launchOf(program, value)
@@ -1647,7 +1667,7 @@ export default class ProgramManager extends TheLink {
if (typeof asked !== "object" || asked === null || Array.isArray(asked)) throw new Error("A client launch must be a named shape")
- if (asked.service !== undefined && typeof asked.service !== "boolean") throw new Error("A launch client's service role must be true or false")
+ if (asked.service !== undefined) parseServiceValue(asked.service, "A launch client's service")
if (asked.title !== undefined && typeof asked.title !== "string") throw new Error("A launch client's title must be text")
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 1f44404..74bd09a 100644
--- a/source/server/core/link-manager/auth-manager/program-manager/program.ts
+++ b/source/server/core/link-manager/auth-manager/program-manager/program.ts
@@ -4,7 +4,7 @@ import { dirname, isAbsolute, normalize, relative, resolve, sep } from "node:pat
import { spawn } from "node:child_process"
import { randomUUID } from "node:crypto"
import { validateIcon } from "./icon"
-import { defaultProgramVersion, parseLaunch, parseOpens, parseProgramDefinition, type ProgramCommandChunk, type ProgramDefinition, type ProgramSnapshot } from "@phreshos/core"
+import { defaultProgramVersion, parseLaunch, parseOpens, parseProgramDefinition, parseServiceValue, type ProgramCommandChunk, type ProgramDefinition, type ProgramSnapshot } from "@phreshos/core"
import { permissionCatalog, type DeclaredPermissions } from "@server/core/permissions"
/**
@@ -399,7 +399,7 @@ function coherent(config: ProgramConfig) {
if (declared.start !== undefined && typeof declared.start !== "boolean") throw new Error(`A declared ${half} endpoint's start default must be true or false`)
- if (declared.service !== undefined && typeof declared.service !== "boolean") throw new Error(`A declared ${half} endpoint's service default must be true or false`)
+ if (declared.service !== undefined) parseServiceValue(declared.service, `A declared ${half} endpoint's service`)
}
@@ -444,8 +444,8 @@ function coherent(config: ProgramConfig) {
return { ...config, version: config.version ?? defaultProgramVersion }
}
-type Resolved<Half extends { start?: boolean, service?: boolean }> = Half extends unknown
- ? Omit<Half, "start" | "service"> & { start: boolean, service: boolean }
+type Resolved<Half extends { start?: boolean, service?: string | false }> = Half extends unknown
+ ? Omit<Half, "start" | "service"> & { start: boolean, service: string | false }
: never
type ResolvedClient = Omit<Resolved<ClientConfig>, "sandbox"> & { sandbox: boolean }
diff --git a/source/server/core/permissions.ts b/source/server/core/permissions.ts
index 0f52e52..2f3af78 100644
--- a/source/server/core/permissions.ts
+++ b/source/server/core/permissions.ts
@@ -272,7 +272,10 @@ export const permissionCatalog = new PermissionCatalog({
all: {
default: []
},
- services: {
+ consumeServices: {
+ default: []
+ },
+ provideServices: {
default: []
},
programs: {
diff --git a/source/server/core/system.ts b/source/server/core/system.ts
index c327bee..50a6427 100644
--- a/source/server/core/system.ts
+++ b/source/server/core/system.ts
@@ -587,9 +587,10 @@ export default class System {
return (database === "logs" ? this.programManager.logsOf(program) : this.programManager.databaseOf(program)).query(statement, values)
}
- public endpointIsService(process: Process, endpoint: Half) {
+ /** The Service name an Endpoint holds, or `false` for none. */
+ public endpointService(process: Process, endpoint: Half) {
- return this.processManager.endpointIsServiceFromOutside(process.identity, endpoint)
+ return this.processManager.endpointServiceFromOutside(process.identity, endpoint)
}
public serviceAvailable(address: unknown) {
@@ -597,8 +598,6 @@ export default class System {
return this.processManager.serviceAvailableFromOutside(address)
}
- public listServices(name?: string) { return this.processManager.listServicesFromOutside(name) }
-
public waitServiceReady(address: unknown, timeout?: number) {
return this.processManager.waitServiceReadyFromOutside(address, timeout)
diff --git a/tests/client-permission-boundary.test.ts b/tests/client-permission-boundary.test.ts
index c0dfbe1..9ec6dfc 100644
--- a/tests/client-permission-boundary.test.ts
+++ b/tests/client-permission-boundary.test.ts
@@ -182,60 +182,28 @@ test("the system-wide permission registry requires all", async () => {
await expect(answer("host-permission-requests")).resolves.toEqual([[{ identity: "request" }]])
})
-test.each([
- {
- owningProgram: "owner",
- denied: [{}, { services: ["unrelated"] }, { programs: [] }],
- granted: [{ services: ["main"] }, { services: [] }, { all: [] }]
- },
- {
- owningProgram: "outside",
- denied: [
- {},
- { all: [], services: false },
- { services: ["unrelated"] },
- { programs: ["unrelated"] },
- { programs: ["outside"] },
- { programs: [] }
- ],
- granted: [
- { services: ["main"] },
- { services: [] },
- { all: [] }
- ]
- }
-] satisfies ReadonlyArray<{
- owningProgram: string
- denied: Permissions[]
- granted: Permissions[]
-}>)("Service operations expose only Services in the accessible scope for $owningProgram", async ({ owningProgram, denied, granted }) => {
- const destination = "6d138083-7a51-44ec-9abe-ff0194ad1e5b"
+test("Service operations reach a Service only by a name the caller may consume, whoever provides it", async () => {
+ const denied: Permissions[] = [{}, { all: [], consumeServices: false }, { consumeServices: ["unrelated"] }, { programs: [] }, { provideServices: ["main"] }]
+ const granted: Permissions[] = [{ consumeServices: ["main"] }, { consumeServices: [] }, { all: [] }]
let permissions: Permissions = {}
const serviceAvailable = vi.fn(async () => true)
const waitServiceReady = vi.fn()
- const serviceProgramMetadata = vi.fn(async () => ({ name: "Provider", version: "0.0.0" }))
- const serviceProgramIcon = vi.fn(async () => [])
const followService = vi.fn()
const sendService = vi.fn()
const askService = vi.fn()
const auth = {
programManager: { programs: new Map([["owner", { identity: "owner", get permissions() { return permissions } }]]) },
processManager: {
- processes: new Map([
- ["caller", { program: "owner" }],
- [destination, { program: owningProgram }]
- ]),
- serviceAvailable, waitServiceReady, serviceProgramMetadata, serviceProgramIcon, followService, sendService, askService
+ processes: new Map([["caller", { program: "owner" }]]),
+ serviceAvailable, waitServiceReady, followService, sendService, askService
},
grantsPermission: async (_pane: string, name: PermissionName, values: never[]) => permissionCatalog.allows(name, values, permissions)
} as unknown as AuthManager
const answer = host(auth, "caller", { state: () => { throw new Error("unused viewport") }, move: () => { throw new Error("unused viewport") } }, {} as never, () => "frame", clientFrame(), {} as never)
- const key = { program: owningProgram, process: "main", endpoint: "server" } as const
+ const key = { name: "main", endpoint: "server" } as const
const operations = [
["service-available", key],
["service-wait-ready", key],
- ["service-program-metadata", key],
- ["service-program-icon", key, "small"],
["service-send", key, "change", {}],
["service-ask", key, "read", {}]
] as const
@@ -251,40 +219,23 @@ test.each([
for (const [operation, ...args] of operations) await answer(operation, ...args)
await answer("service-follow", "subscription", key, "events", "change")
}
- for (const call of [serviceAvailable, waitServiceReady, serviceProgramMetadata, serviceProgramIcon, followService, sendService, askService]) {
+ for (const call of [serviceAvailable, waitServiceReady, followService, sendService, askService]) {
expect(call).toHaveBeenCalledTimes(granted.length)
}
+ // A Service is reached by name, never by its provider's Program and Process.
+ permissions = { all: [] }
+ await expect(answer("service-available", { program: "notes", process: "main", endpoint: "server" })).rejects.toThrow(/reached by its name/)
})
-test("Service discovery filters ready addresses only by Service-name authority", async () => {
- let permissions: Permissions = { programs: [] }
- const mainServer = { program: "notes", process: "main", endpoint: "server" } as const
- const mainClient = { program: "editor", process: "main", endpoint: "client" } as const
- const background = { program: "notes", process: "background", endpoint: "server" } as const
- const listServices = vi.fn(async (options: { name?: string } = {}) => [mainServer, mainClient, background].filter(service => options.name === undefined || service.process === options.name))
+test("Services are reached by name, never listed", async () => {
const auth = {
- programManager: { programs: new Map([["owner", { identity: "owner", get permissions() { return permissions } }]]) },
- processManager: {
- processes: new Map([["caller", { program: "owner" }]]),
- listServices
- },
- grantsPermission: async (_pane: string, name: PermissionName, values: never[]) => permissionCatalog.allows(name, values, permissions)
+ programManager: { programs: new Map([["owner", { identity: "owner", permissions: { all: [] } }]]) },
+ processManager: { processes: new Map([["caller", { program: "owner" }]]) },
+ grantsPermission: async () => true
} as unknown as AuthManager
const answer = host(auth, "caller", { state: () => { throw new Error("unused viewport") }, move: () => { throw new Error("unused viewport") } }, {} as never, () => "frame", clientFrame(), {} as never)
- await expect(answer("host-service-list")).resolves.toEqual([[]])
- await expect(answer("host-service-list", { name: "main" })).resolves.toEqual([[]])
-
- permissions = { services: ["main"] }
-
- await expect(answer("host-service-list")).resolves.toEqual([[mainServer, mainClient]])
- await expect(answer("host-service-list", { name: "main" })).resolves.toEqual([[mainServer, mainClient]])
- await expect(answer("host-service-list", { name: "background" })).resolves.toEqual([[]])
- await expect(answer("host-service-list", "main")).rejects.toThrow(/object/)
-
- permissions = { services: [] }
-
- await expect(answer("host-service-list")).resolves.toEqual([[mainServer, mainClient, background]])
+ await expect(answer("host-service-list")).rejects.toThrow(/does not know the word/)
})
function program(identity: string): ProgramSnapshot & { permissions: Permissions } {
diff --git a/tests/client-process-boundary-lifecycle.test.ts b/tests/client-process-boundary-lifecycle.test.ts
index 10f6631..e95a739 100644
--- a/tests/client-process-boundary-lifecycle.test.ts
+++ b/tests/client-process-boundary-lifecycle.test.ts
@@ -75,7 +75,7 @@ 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: [] } }]]) },
+ programManager: { programs: new Map([["flambo", { identity: "flambo", permissions: { consumeServices: [] } }]]) },
processManager,
} as unknown as AuthManager
const boundary = new ClientProcessBoundary(
@@ -87,7 +87,7 @@ test("a later Client request cannot overtake its Service subscription registrati
{} as ClientTraffic,
{ begin() {} } as unknown as PresentationHost
)
- const address = { program: "flambo", process: "browser-server", endpoint: "server" } as const
+ const address = { name: "browser-server", endpoint: "server" } as const
await boundary.own("document")
boundary.receive(["end-host", "service-follow", "subscription", address, "events", "workspace.change", false])
@@ -102,7 +102,7 @@ test("a registered Service event is delivered without a second permission round-
const sent: unknown[][] = []
let followed = false
- const address = { program: "browser", process: "browser", endpoint: "server" } as const
+ const address = { name: "browser", endpoint: "server" } as const
const processManager = {
processes: new Map([["process", { program: "browser" }]]),
async ownFrame() {},
@@ -110,7 +110,7 @@ test("a registered Service event is delivered without a second permission round-
async followService() { followed = true }
}
const authManager = {
- programManager: { programs: new Map([["browser", { identity: "browser", permissions: { services: [] } }]]) },
+ programManager: { programs: new Map([["browser", { identity: "browser", permissions: { consumeServices: [] } }]]) },
processManager,
} as unknown as AuthManager
const traffic = {
diff --git a/tests/client-system-access.test.ts b/tests/client-system-access.test.ts
index e3dcca7..d861f50 100644
--- a/tests/client-system-access.test.ts
+++ b/tests/client-system-access.test.ts
@@ -47,9 +47,10 @@ test("client system access contract", async () => {
const access = new SystemAccess(authManager, owner.identity)
const ownProgram = { identity: "owner" }
const outsideProgram = { identity: "outside" }
- const ownService = { program: "owner", process: "owner-service", endpoint: "server" } as const
- const siblingService = { program: "owner", process: "sibling-service", endpoint: "client" } as const
- const outsideService = { program: "outside", process: "outside-service", endpoint: "server" } as const
+ // Reached by their names alone, whichever Program provides them.
+ const ownService = { name: "owner-service", endpoint: "server" } as const
+ const siblingService = { name: "sibling-service", endpoint: "client" } as const
+ const outsideService = { name: "outside-service", endpoint: "server" } as const
assert(access.ownsProgram(ownProgram))
assert(!access.ownsProgram(outsideProgram))
@@ -76,14 +77,14 @@ test("client system access contract", async () => {
assert.equal(await access.canConnection("desktop-connection"), false)
assert.equal(await access.canSession("desktop-session"), false)
- permissions = { services: ["outside-service"] }
+ permissions = { consumeServices: ["outside-service"] }
assert.equal(await access.service(outsideService), outsideService)
await assert.rejects(access.program(outsideProgram as never), /Program represented by this handle does not exist/)
await assert.rejects(access.process(outside), /Process represented by this handle does not exist/)
await assert.rejects(access.requireAll(), /Execution is not permitted/)
- permissions = { services: [] }
+ permissions = { consumeServices: [] }
assert.equal(await access.service(outsideService), outsideService)
assert.equal(await access.service(ownService), ownService)
@@ -170,12 +171,12 @@ test("client system access contract", async () => {
await access.requireAll()
assert.equal(permissionChecks, 0)
- permissions = { all: [], services: false }
+ permissions = { all: [], consumeServices: false }
await assert.rejects(access.service(ownService), /Execution is not permitted/)
await assert.rejects(access.service(siblingService), /Execution is not permitted/)
- permissions = { services: [] }
+ permissions = { consumeServices: [] }
assert.equal(await access.service(outsideService), outsideService)
- permissions = { services: ["owner-service"] }
+ permissions = { consumeServices: ["owner-service"] }
assert.equal(await access.service(ownService), ownService)
await assert.rejects(access.service(siblingService), /Execution is not permitted/)
await assert.rejects(access.service(outsideService), /Execution is not permitted/)
diff --git a/tests/endpoint-services.test.ts b/tests/endpoint-services.test.ts
index 425fd4c..35d5132 100644
--- a/tests/endpoint-services.test.ts
+++ b/tests/endpoint-services.test.ts
@@ -2,100 +2,93 @@ import assert from "node:assert/strict"
import EndpointServices from "@server/core/link-manager/auth-manager/process-manager/endpoint-services"
import Program from "@server/core/link-manager/auth-manager/program-manager/program"
import type Process from "@server/core/link-manager/auth-manager/process-manager/process"
-import type { ServiceAddress } from "@phreshos/core"
import { test } from "vitest"
-test("endpoint services use stable name addresses and ready availability", async () => {
- const program = new Program({
- identity: "program",
- server: { location: ".", command: "true" },
- client: { location: "." }
- })
- assert.equal(program.version, "0.0.0")
+const program = new Program({
+ identity: "program",
+ server: { location: ".", command: "true" },
+ client: { location: "." }
+})
- function process(identity: string, name: string | null, ready = true, service = true) {
- const server = { ready, service }
- return {
- identity,
- name,
- reference: `${identity}-reference`,
- program,
- launch: { server: { service }, client: { service } },
- server,
- client: { service },
- becomeReady() { server.ready = true }
- } as unknown as Process & { becomeReady(): void }
- }
+/** A Process whose Endpoints hold the Service names given, a Process name of its own beside them. */
+function process(identity: string, server: string | false, client: string | false = false, ready = true) {
+ const serverState = { ready, service: server }
+ return {
+ identity,
+ name: "local",
+ reference: `${identity}-reference`,
+ program,
+ server: serverState,
+ client: { service: client },
+ becomeReady() { serverState.ready = true }
+ } as unknown as Process & { becomeReady(): void }
+}
- let provider = process("first", "main")
- const transitions: Array<[string, ServiceAddress]> = []
- const services = new EndpointServices(
- address => address.program === program.identity
- && address.process === provider.name
- && (address.endpoint === "server" ? provider.server?.service : provider.client?.service) === true
- ? { process: provider, endpoint: address.endpoint }
- : null,
- () => [provider],
- (event, address) => { transitions.push([event, address]) }
- )
- const address = { program: "program", process: "main", endpoint: "server" } satisfies ServiceAddress
- const clientAddress = { ...address, endpoint: "client" } satisfies ServiceAddress
- const lifecycle: string[] = []
- const publications: unknown[] = []
- const authorizedPublications: unknown[] = []
- let permitted = true
+test("a Service is reached by its name, of the kind asked for or either, whatever its Process is named", async () => {
+ let running = [process("first", "file-picker-v1")]
+ const services = new EndpointServices(() => running)
+ const lifecycle: string[] = []
+ const anyLifecycle: string[] = []
+ const publications: unknown[] = []
+ const anyPublications: 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/)
+ assert.throws(() => services.available({ program: "program", process: "local", endpoint: "server" }), /reached by its name/)
+ await assert.rejects(() => services.waitReady({ name: "file-picker-v1" }, -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)
+ services.follow({ name: "file-picker-v1", endpoint: "server" }, "lifecycle", null, event => lifecycle.push(event))
+ services.follow({ name: "file-picker-v1" }, "lifecycle", null, event => anyLifecycle.push(event))
+ services.follow({ name: "file-picker-v1", endpoint: "server" }, "events", "change", (_event, payload) => publications.push(payload))
+ services.follow({ name: "file-picker-v1" }, "events", "change", (_event, payload) => anyPublications.push(payload))
+ services.follow({ name: "file-picker-v1" }, "events", "authorized", (_event, payload) => authorizedPublications.push(payload), () => permitted)
- await services.started(provider, "server")
- await services.started(provider, "client")
- assert.equal(services.available(address), true)
- assert.deepEqual(services.list("main"), [address, clientAddress])
- assert.deepEqual(lifecycle, ["available"])
- await services.waitReady(address, 0)
+ await services.started(running[0]!, "server")
+ assert.equal(services.available({ name: "file-picker-v1" }), true)
+ assert.equal(services.available({ name: "file-picker-v1", endpoint: "server" }), true)
+ // Held by a Server, it is no Client's.
+ assert.equal(services.available({ name: "file-picker-v1", endpoint: "client" }), false)
+ assert.equal(services.target({ name: "file-picker-v1" }, "server")?.process, running[0])
+ assert.deepEqual(lifecycle, ["available"])
+ assert.deepEqual(anyLifecycle, ["available"])
+ await services.waitReady({ name: "file-picker-v1", endpoint: "server" }, 0)
- await services.emit(provider, "server", "ignored", 1)
- await services.emit(provider, "server", "change", 2)
- assert.deepEqual(publications, [2])
+ await services.emit(running[0]!, "server", "change", 2)
+ assert.deepEqual(publications, [2])
+ assert.deepEqual(anyPublications, [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])
+ await services.emit(running[0]!, "server", "authorized", 3)
+ permitted = false
+ await services.emit(running[0]!, "server", "authorized", 4)
+ permitted = true
+ assert.deepEqual(authorizedPublications, [3])
- provider.server = null
- await services.stopped(provider, "server", true)
- assert.equal(services.available(address), false)
- assert.deepEqual(lifecycle, ["available", "unavailable"])
- await assert.rejects(() => services.waitReady(address, 0), /timeout|available/)
+ const ended = running[0]!
+ running = []
+ await services.stopped("server", ended.server!.service)
+ assert.equal(services.available({ name: "file-picker-v1" }), false)
+ assert.deepEqual(lifecycle, ["available", "unavailable"])
+ await assert.rejects(() => services.waitReady({ name: "file-picker-v1" }, 0), /timeout|available/)
- // A stable address follows a replacement with the same Program and Process name.
- provider = process("replacement", "main", false)
- await services.started(provider, "server")
- assert.equal(services.available(address), false)
+ // The same name reaches its next holder, another Process altogether, once it is ready.
+ running = [process("next", "file-picker-v1", false, false)]
+ await services.started(running[0]!, "server")
+ assert.equal(services.available({ name: "file-picker-v1" }), false)
+ const ready = services.waitReady({ name: "file-picker-v1" }, 100)
+ running[0]!.becomeReady()
+ await services.ready(running[0]!, "server")
+ await ready
+ assert.equal(services.holder("file-picker-v1")?.process, running[0])
+})
- const ready = services.waitReady(address, 100)
- provider.becomeReady()
- await services.ready(provider, "server")
- await ready
- assert.equal(services.available(address), true)
+test("a Client holds a name as a Server does, and an Endpoint with none is reached by no name", async () => {
+ const running = [process("canvas", false, "board-canvas-v1")]
+ const services = new EndpointServices(() => running)
- // An unnamed Process is never discoverable, even when its Endpoint is configured.
- provider = process("unnamed", null)
- await services.started(provider, "server")
- assert.deepEqual(services.list(), [])
-
- // A running Endpoint that did not opt into Service mode remains unavailable.
- provider = process("unconfigured", "main", true, false)
- await services.started(provider, "server")
- assert.equal(services.available(address), false)
-
- assert.deepEqual(transitions.map(([event]) => event), ["available", "available", "unavailable", "available"])
-}, 120_000)
+ await services.started(running[0]!, "client")
+ assert.equal(services.available({ name: "board-canvas-v1", endpoint: "client" }), true)
+ assert.equal(services.available({ name: "board-canvas-v1", endpoint: "server" }), false)
+ // A question needs a Server.
+ assert.equal(services.target({ name: "board-canvas-v1" }, "server"), null)
+ assert.equal(services.holder("local"), null)
+})
diff --git a/tests/launch-permission.test.ts b/tests/launch-permission.test.ts
new file mode 100644
index 0000000..5b60104
--- /dev/null
+++ b/tests/launch-permission.test.ts
@@ -0,0 +1,73 @@
+import { mkdtempSync, rmSync } from "node:fs"
+import { tmpdir } from "node:os"
+import { join } from "node:path"
+import { TheLink } from "@the-link/core"
+import { expect, test, type TestContext } from "vitest"
+import type { PermissionName } from "@phreshos/core"
+import FileManager from "@libs/file-manager"
+import type AuthManager from "@server/core/link-manager/auth-manager/auth-manager"
+import Program from "@server/core/link-manager/auth-manager/program-manager/program"
+import ProgramManager from "@server/core/link-manager/auth-manager/program-manager/program-manager"
+import type Process from "@server/core/link-manager/auth-manager/process-manager/process"
+import SystemAccess from "@server/core/link-manager/auth-manager/process-manager/system-access"
+import type ProcessManager from "@server/core/link-manager/auth-manager/process-manager/process-manager"
+
+/** The System's own launch resolution, and an executor holding only the layers given. */
+function fixture(context: TestContext, layers: readonly string[], provides: readonly string[] = []) {
+ const directory = mkdtempSync(join(tmpdir(), "phresh-launch-permission-"))
+ context.onTestFinished(() => rmSync(directory, { recursive: true, force: true }))
+ const auth = Object.assign(new TheLink(), {
+ linkManager: { application: { storage: new FileManager(directory, "system"), icons: { system: "", defaultProgram: "" } } }
+ }) as unknown as AuthManager
+ const programManager = new ProgramManager(auth)
+ const manager = {
+ authManager: { programManager },
+ grants: (_identity: string, name: PermissionName, requested: readonly string[]) =>
+ name === "layers" ? requested.every(layer => layers.includes(layer))
+ : name === "provideServices" ? requested.every(service => provides.includes(service))
+ : false
+ } as unknown as ProcessManager
+ const program = (identity: string, layer?: string) => new Program({ identity, client: { location: "https://example.test/", ...(layer ? { layer } : {}) } } as never)
+ const provider = (identity: string, service: string) => new Program({ identity, server: { location: ".", command: "true", service } } as never)
+ const executor = (owner: Program) => new SystemAccess(manager, { identity: `${owner.identity}-process`, program: owner } as unknown as Process)
+ return { program, provider, executor }
+}
+
+test("whoever starts a Program answers for the layer it declares, as for one it passes", context => {
+ const { program, executor } = fixture(context, [])
+ const overlay = program("overlay", "over"), other = program("other")
+
+ // Started with nothing passed, it would open where it declares: in `over`.
+ expect(() => executor(other).launch(overlay, {})).toThrow(/not permitted/)
+ // Even by itself: declaring is not holding.
+ expect(() => executor(overlay).launch(overlay, {})).toThrow(/not permitted/)
+ // Passed explicitly, the same.
+ expect(() => executor(other).launch(other, { client: { layer: "over" } })).toThrow(/not permitted/)
+ // What the launch passes decides over what is declared.
+ expect(() => executor(other).launch(overlay, { client: { layer: "window" } })).not.toThrow()
+ expect(() => executor(other).launch(other, {})).not.toThrow()
+ // A launch that opens no Client opens it nowhere.
+ expect(() => executor(other).clientLaunch(overlay, {})).toThrow(/not permitted/)
+})
+
+test("an executor holding the layer starts a Program declared in it", context => {
+ const { program, executor } = fixture(context, ["over"])
+ const overlay = program("overlay", "over"), other = program("other")
+
+ expect(() => executor(other).launch(overlay, {})).not.toThrow()
+ expect(() => executor(other).launch(other, { client: { layer: "under" } })).toThrow(/not permitted/)
+})
+
+test("whoever starts a Program answers for the Service name it declares, as for one it passes", context => {
+ const { provider, executor } = fixture(context, [], ["file-picker-v1"])
+ const files = provider("files", "file-picker-v1"), other = provider("other", "other-picker-v1")
+
+ // It may provide file-picker-v1, declared or passed, and take it from whoever holds it.
+ expect(() => executor(files).launch(files, {})).not.toThrow()
+ expect(() => executor(other).launch(other, { server: { service: "file-picker-v1" } })).not.toThrow()
+ // Not another name, even one its own Program declares.
+ expect(() => executor(other).launch(other, {})).toThrow(/not permitted/)
+ expect(() => executor(files).serverLaunch(other, {})).toThrow(/not permitted/)
+ // `false` provides nothing, whatever is declared.
+ expect(() => executor(other).launch(other, { server: { service: false } })).not.toThrow()
+})
diff --git a/tests/message-parties.test.ts b/tests/message-parties.test.ts
new file mode 100644
index 0000000..6adabb6
--- /dev/null
+++ b/tests/message-parties.test.ts
@@ -0,0 +1,67 @@
+import { TheLink } from "@the-link/core"
+import { expect, test, vi } from "vitest"
+import type AuthManager from "@server/core/link-manager/auth-manager/auth-manager"
+import Program from "@server/core/link-manager/auth-manager/program-manager/program"
+import ProcessManager from "@server/core/link-manager/auth-manager/process-manager/process-manager"
+import type ProcessTraffic from "@server/core/link-manager/auth-manager/process-manager/process-traffic"
+
+type Internals = {
+ traffic: ProcessTraffic
+ deliver(identity: string, half: "server" | "client", values: unknown[]): Promise<void>
+ publish(source: string, sourceHalf: "server" | "client", target: string, targetHalf: "server" | "client", values: unknown[]): Promise<void>
+ returnAnswer(answerer: unknown, values: unknown[]): boolean
+ outsideQuestions: { answer(question: string, outcome: unknown): void }
+}
+
+test("a message carries who sent it and where it went as public values, the same for every receiver and observer", async () => {
+ // No Program may see another: the values arrive all the same, and never as handles.
+ const authManager = new TheLink() as unknown as AuthManager
+ Object.assign(authManager, { programManager: { grantsPermission: () => false } })
+ const manager = new ProcessManager(authManager)
+ const internals = manager as unknown as Internals
+ const launch = { server: null, client: null, options: {} } as const
+ const board = new Program({ identity: "board", name: "Board", server: { location: ".", command: "true" } })
+ const files = new Program({ identity: "files", server: { location: ".", command: "true" } })
+ const window = await manager.register("board-window", null, board, {}, launch, null, false, null, null)
+ const picker = await manager.register("picker", null, files, {}, launch, null, false, null, null)
+
+ const delivered = vi.spyOn(internals, "deliver").mockResolvedValue(undefined)
+ const observed: unknown[] = []
+ internals.traffic.observe(window.reference, "client", "publish", null, (_event, ...values) => observed.push(...values))
+
+ await internals.publish(window.identity, "client", picker.identity, "server", ["changed", 1])
+
+ expect(delivered).toHaveBeenCalledWith(picker.identity, "server", ["changed", {
+ from: { program: { identity: "board", name: "Board" }, process: "board-window", endpoint: "client" },
+ payload: 1
+ }])
+ // A Program that names nothing is read by its identity.
+ expect(observed).toEqual([{ to: { program: { identity: "files", name: "files" }, process: "picker", endpoint: "server" }, payload: 1 }])
+})
+
+test("an answer is observed whoever asked: where it went, or null when a script outside every Program asked", async () => {
+ const authManager = new TheLink() as unknown as AuthManager
+ Object.assign(authManager, { programManager: { grantsPermission: () => false } })
+ const manager = new ProcessManager(authManager)
+ const internals = manager as unknown as Internals
+ const launch = { server: null, client: null, options: {} } as const
+ const board = new Program({ identity: "board", name: "Board", server: { location: ".", command: "true" } })
+ const files = new Program({ identity: "files", name: "Files", server: { location: ".", command: "true" } })
+ const window = await manager.register("board-window", null, board, {}, launch, null, false, null, null)
+ const picker = await manager.register("picker", null, files, {}, launch, null, false, null, null)
+ vi.spyOn(internals, "deliver").mockResolvedValue(undefined)
+ const answered = vi.spyOn(internals.outsideQuestions, "answer").mockImplementation(() => undefined)
+ const observed: unknown[] = []
+ internals.traffic.observe(picker.reference, "server", "answer", null, (event, ...values) => observed.push([event, ...values]))
+ const outcome = { success: true, result: null }
+
+ internals.returnAnswer(picker, ["answer", `client:${window.identity}`, "question-1", "open", outcome])
+ internals.returnAnswer(picker, ["answer", "outside:script-question", "question-2", "access", outcome])
+
+ expect(observed).toEqual([
+ ["open", "question-1", { to: { program: { identity: "board", name: "Board" }, process: "board-window", endpoint: "client" }, outcome }],
+ ["access", "question-2", { to: null, outcome }]
+ ])
+ // The script still receives its answer.
+ expect(answered).toHaveBeenCalledWith("outside:script-question", outcome)
+})
diff --git a/tests/permission-requests.test.ts b/tests/permission-requests.test.ts
index 490f8c3..bbefe38 100644
--- a/tests/permission-requests.test.ts
+++ b/tests/permission-requests.test.ts
@@ -39,7 +39,7 @@ test("permission request lifecycle belongs to one live Endpoint", async () => {
process,
"client",
identity,
- "services",
+ "consumeServices",
["browser"],
timeout
)
@@ -55,19 +55,19 @@ test("permission request lifecycle belongs to one live Endpoint", async () => {
assert(manager.pending("allow"))
await manager.allow("allow")
assert.deepEqual(await allowed, ["browser"])
- assert.deepEqual(new ProgramStateStorage(program).permissions(), { services: ["browser"] })
+ assert.deepEqual(new ProgramStateStorage(program).permissions(), { consumeServices: ["browser"] })
assert(!manager.pending("allow"))
await assert.rejects(manager.allow("allow"), /does not exist/)
const denied = request("deny")
await manager.deny("deny")
assert.equal(await denied, false)
- assert.deepEqual(new ProgramStateStorage(program).permissions(), { services: false })
+ assert.deepEqual(new ProgramStateStorage(program).permissions(), { consumeServices: false })
const cancelled = request("cancel")
await manager.cancel("cancel")
assert.equal(await cancelled, null)
- assert.deepEqual(new ProgramStateStorage(program).permissions(), { services: false })
+ assert.deepEqual(new ProgramStateStorage(program).permissions(), { consumeServices: false })
const expired = request("timeout", 5)
assert.equal(await expired, null)
@@ -78,7 +78,7 @@ test("permission request lifecycle belongs to one live Endpoint", async () => {
assert.equal(decisions.filter(result => result.status === "fulfilled").length, 1)
assert.equal(decisions.filter(result => result.status === "rejected").length, 1)
assert.deepEqual(await raced, ["browser"])
- assert.deepEqual(new ProgramStateStorage(program).permissions(), { services: ["browser"] })
+ assert.deepEqual(new ProgramStateStorage(program).permissions(), { consumeServices: ["browser"] })
const stopped = request("endpoint-stop")
process.stopClient()
@@ -122,7 +122,7 @@ test("an exact effective assignment creates no pending request", async () => {
process.identity,
"client",
"invalid-timeout",
- "services",
+ "consumeServices",
["browser"],
Number.MAX_VALUE
), /expiration is invalid/)
@@ -131,7 +131,7 @@ test("an exact effective assignment creates no pending request", async () => {
process.identity,
"client",
"exact",
- "services",
+ "consumeServices",
["browser"],
undefined
))
@@ -141,7 +141,7 @@ test("an exact effective assignment creates no pending request", async () => {
process.identity,
"client",
"different",
- "services",
+ "consumeServices",
["editor"],
1_000
)
@@ -152,7 +152,7 @@ test("an exact effective assignment creates no pending request", async () => {
process.identity,
"client",
"default",
- "services",
+ "consumeServices",
["editor"],
undefined
)
diff --git a/tests/permissions.test.ts b/tests/permissions.test.ts
index c4b4837..10992e5 100644
--- a/tests/permissions.test.ts
+++ b/tests/permissions.test.ts
@@ -8,7 +8,10 @@ test("permissions contract", async () => {
all: {
default: []
},
- services: {
+ consumeServices: {
+ default: []
+ },
+ provideServices: {
default: []
},
programs: {
@@ -68,26 +71,26 @@ test("permissions contract", async () => {
})
assert.deepEqual(catalog.resolve("all", true), [])
assert.deepEqual(catalog.resolve("all", []), [])
- assert.deepEqual(catalog.resolve("services", true), [])
- assert.deepEqual(catalog.resolve("services", ["flambo", "terminal", "flambo"]), ["flambo", "terminal"])
+ assert.deepEqual(catalog.resolve("consumeServices", true), [])
+ assert.deepEqual(catalog.resolve("consumeServices", ["flambo", "terminal", "flambo"]), ["flambo", "terminal"])
assert.deepEqual(catalog.resolve("network", ["HTTPS://API.Example.com:443/v1/**"]), ["https://api.example.com/v1/**"])
assert.deepEqual(catalog.resolve("storage", ["delete,read:Documents/**"]), ["read,delete:Documents/**"])
assert.deepEqual(catalog.resolve("uploads", true), [])
assert.equal(catalog.resolve("all", false), false)
assert.equal(catalog.resolve("all", null), null)
- assert.deepEqual(catalog.declarations({ all: true, services: ["flambo"] }), { all: [], services: ["flambo"] })
+ assert.deepEqual(catalog.declarations({ all: true, consumeServices: ["flambo"] }), { all: [], consumeServices: ["flambo"] })
assert(Object.isFrozen(catalog.declarations({})))
assert(Object.isFrozen(catalog.declarations({ all: true }).all))
assert(catalog.grants("all", [], []))
assert(!catalog.grants("all", false, []))
assert(!catalog.grants("all", null, []))
- assert(catalog.grants("services", [], []))
- assert(catalog.grants("services", [], ["flambo"]))
- assert(catalog.grants("services", ["flambo"], ["flambo"]))
- assert(!catalog.grants("services", ["flambo"], ["terminal"]))
- assert(!catalog.grants("services", ["flambo"], []))
+ assert(catalog.grants("consumeServices", [], []))
+ assert(catalog.grants("consumeServices", [], ["flambo"]))
+ assert(catalog.grants("consumeServices", ["flambo"], ["flambo"]))
+ assert(!catalog.grants("consumeServices", ["flambo"], ["terminal"]))
+ assert(!catalog.grants("consumeServices", ["flambo"], []))
assert(catalog.grants("network", ["https://api.example.com"], ["https://api.example.com/v1/users"]))
assert(catalog.grants("network", ["https://*.example.com/v1/**"], ["https://eu.example.com/v1/users"]))
assert(!catalog.grants("network", ["https://*.example.com/v1/**"], ["https://example.com/v1/users"]))
@@ -98,17 +101,17 @@ test("permissions contract", async () => {
assert(!catalog.grants("storage", ["Documents/report.txt"], ["read:Documents/**"]))
assert(catalog.allows("all", [], { all: [] }))
assert(!catalog.allows("all", [], {}))
- assert(catalog.allows("services", ["browser"], { all: [] }))
- assert(catalog.allows("services", ["browser"], { services: ["browser"] }))
- assert(!catalog.allows("services", ["browser"], { programs: [] }))
- assert(!catalog.allows("services", [], { programs: [] }))
- assert(!catalog.allows("services", ["browser"], { programs: ["browser"] }))
- assert(!catalog.allows("services", ["browser", "editor"], { programs: ["browser"], services: ["editor"] }))
- assert(catalog.allows("services", ["editor"], { programs: ["browser"], services: ["editor"] }))
- assert(!catalog.allows("services", ["editor"], { programs: ["browser"] }))
- assert(!catalog.allows("services", [], { programs: ["browser"] }))
- assert(!catalog.allows("programs", ["browser"], { services: [] }))
- assert(!catalog.allows("services", ["browser"], { programs: [], services: false }))
+ assert(catalog.allows("consumeServices", ["browser"], { all: [] }))
+ assert(catalog.allows("consumeServices", ["browser"], { consumeServices: ["browser"] }))
+ assert(!catalog.allows("consumeServices", ["browser"], { programs: [] }))
+ assert(!catalog.allows("consumeServices", [], { programs: [] }))
+ assert(!catalog.allows("consumeServices", ["browser"], { programs: ["browser"] }))
+ assert(!catalog.allows("consumeServices", ["browser", "editor"], { programs: ["browser"], consumeServices: ["editor"] }))
+ assert(catalog.allows("consumeServices", ["editor"], { programs: ["browser"], consumeServices: ["editor"] }))
+ assert(!catalog.allows("consumeServices", ["editor"], { programs: ["browser"] }))
+ assert(!catalog.allows("consumeServices", [], { programs: ["browser"] }))
+ assert(!catalog.allows("programs", ["browser"], { consumeServices: [] }))
+ assert(!catalog.allows("consumeServices", ["browser"], { programs: [], consumeServices: false }))
assert(catalog.allows("desktopConnection", [], { desktopConnection: [] }))
assert(catalog.allows("desktopConnection", [], { authentication: [] }))
assert(catalog.allows("desktopConnection", [], { authentication: [], desktopConnection: false }))
@@ -128,7 +131,7 @@ test("permissions contract", async () => {
assert.throws(() => parsePermissionName("files"), /does not know/)
assert.throws(() => catalog.resolve("all", ["unknown"]), /unknown value/)
assert.throws(() => catalog.resolve("appearance", ["flambo"]), /unknown value/)
- assert.throws(() => catalog.resolve("services", [" "]), /unknown value/)
+ assert.throws(() => catalog.resolve("consumeServices", [" "]), /unknown value/)
assert.throws(() => catalog.resolve("network", ["api.example.com"]), /unknown value/)
assert.throws(() => catalog.resolve("storage", ["all:Documents"]), /unknown value/)
assert.throws(() => catalog.resolve("storage", ["all,read:Documents"]), /unknown value/)
@@ -139,7 +142,7 @@ test("permissions contract", async () => {
all: {
default: ["unknown"]
},
- services: catalog.definition("services"),
+ consumeServices: catalog.definition("consumeServices"),
programs: catalog.definition("programs"),
network: catalog.definition("network"),
storage: catalog.definition("storage"),
diff --git a/tests/process-find-or-create.test.ts b/tests/process-find-or-create.test.ts
index 2357a91..e56aa71 100644
--- a/tests/process-find-or-create.test.ts
+++ b/tests/process-find-or-create.test.ts
@@ -107,12 +107,12 @@ test("process find or create contract", async () => {
assert.equal(omitted.client.size, null)
const activated = fixture.resolveLaunch(program, {
- server: { service: true },
- client: { service: true }
+ server: { service: "editor-v1" },
+ client: { service: "canvas-v1" }
}).intent
- assert.equal(activated.server?.service, true)
- assert.equal(activated.client?.service, true)
+ assert.equal(activated.server?.service, "editor-v1")
+ assert.equal(activated.client?.service, "canvas-v1")
const stale = { identity: program.identity, reference: "replaced-program-reference" } as unknown as Program
diff --git a/tests/process-lifecycle.test.ts b/tests/process-lifecycle.test.ts
index 4fbd71d..6c253ff 100644
--- a/tests/process-lifecycle.test.ts
+++ b/tests/process-lifecycle.test.ts
@@ -24,7 +24,7 @@ test("process lifecycle contract", async () => {
grantsStorage() { return true },
clientShape(_program: Program, launch: ClientLaunch = {}) {
- if (launch.service !== undefined && typeof launch.service !== "boolean") throw new Error("A launch client's service role must be true or false")
+ if (launch.service !== undefined && launch.service !== false && typeof launch.service !== "string") throw new Error("A launch client's service is a Service name, such as \"file-picker-v1\", or false")
return {
title: launch.title ?? "Client",
@@ -188,7 +188,7 @@ test("process lifecycle contract", async () => {
await manager.stopClient(process.identity)
await manager.startServer(process.identity)
- await assert.rejects(manager.startServer(process.identity, { service: "invalid" } as never), /service value/)
+ await assert.rejects(manager.startServer(process.identity, { service: true } as never), /Service name/)
manager.processes.delete(process.identity)
diff --git a/tests/program-creation.test.ts b/tests/program-creation.test.ts
index afd0176..8728ecf 100644
--- a/tests/program-creation.test.ts
+++ b/tests/program-creation.test.ts
@@ -1,4 +1,4 @@
-import { existsSync, mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"
+import { existsSync, mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs"
import { tmpdir } from "node:os"
import { join } from "node:path"
import { TheLink } from "@the-link/core"
@@ -45,8 +45,8 @@ test("stored permission assignments override definition fallbacks by name", asyn
expect(manager.permissions(program)).toEqual({ network: false, uploads: [], appearance: [] })
- program = await manager.forceCreate(definition({ network: true, services: ["editor"] }))
- expect(manager.permissions(program)).toEqual({ network: false, services: ["editor"], appearance: [] })
+ program = await manager.forceCreate(definition({ network: true, consumeServices: ["editor"] }))
+ expect(manager.permissions(program)).toEqual({ network: false, consumeServices: ["editor"], appearance: [] })
})
test("a Program definition resolves System-owned paths into reusable creation input", context => {
@@ -61,48 +61,13 @@ test("a Program definition resolves System-owned paths into reusable creation in
})
})
-test("startup and pinned state share one file without overwriting each other", async context => {
+test("an attached Program does not start with the System, yet its startup can be read and removed", async context => {
const { manager, definition } = fixture(context)
const program = await manager.create(definition())
- const startup = { name: "background", options: { mode: "quiet" } }
- await manager.startup(program, "set", startup)
- const pinnedAt = await manager.pinned(program, "pin")
- await manager.setPermission(program, "network", false)
-
- expect(await manager.startup(program, "get")).toEqual(startup)
- expect(pinnedAt).toMatch(/^\d{4}-\d{2}-\d{2}T/)
- expect(await manager.pinned(program, "get")).toBe(pinnedAt)
- expect(new ProgramStateStorage(program).permissions()).toEqual({ network: false })
- expect(JSON.parse(readFileSync(join(program.storagePath, "state.json"), "utf8"))).toEqual({
- startup,
- pinnedAt,
- permissions: { network: false }
- })
-
- await manager.startup(program, "remove")
- await manager.pinned(program, "unpin")
+ await expect(manager.startup(program, "set", { name: "background" })).rejects.toThrow(/only once it is installed/)
expect(await manager.startup(program, "get")).toBeNull()
- expect(await manager.pinned(program, "get")).toBeNull()
- expect(new ProgramStateStorage(program).permissions()).toEqual({ network: false })
-})
-
-test("Program state mutations do not rewrite an already-satisfied value", async context => {
- const { manager, definition } = fixture(context)
- const program = await manager.create(definition())
- const startupWrite = vi.spyOn(ProgramStateStorage.prototype, "setStartup")
- const permissionWrite = vi.spyOn(ProgramStateStorage.prototype, "setPermission")
- context.onTestFinished(() => { startupWrite.mockRestore(); permissionWrite.mockRestore() })
-
- await manager.startup(program, "set", { name: "background" })
- await manager.startup(program, "set", { name: "background" })
- await manager.setPermission(program, "network", false)
- await manager.setPermission(program, "network", false)
- await manager.startup(program, "remove")
await manager.startup(program, "remove")
-
- expect(startupWrite).toHaveBeenCalledTimes(2)
- expect(permissionWrite).toHaveBeenCalledTimes(1)
})
test("permission changes publish one complete effective snapshot through both Program event scopes", async context => {
@@ -167,36 +132,6 @@ test("pinning keeps its first time, and emits Program and global events only whe
])
})
-test("startup changes emit Program and global events, and filter the Program list", async context => {
- const { manager, definition, announceHost, announceSubject } = fixture(context)
- const program = await manager.create(definition())
- const records: unknown[][] = []
- const stop = manager.$outbound.subscribe("/startup-change", (record, launch) => { records.push([record, launch]) })
- context.onTestFinished(stop)
- announceHost.mockClear()
- announceSubject.mockClear()
-
- await manager.startup(program, "set", { name: "background" })
- await manager.startup(program, "set", { name: "background" })
- expect(manager.find(program.identity).record().startup).toBe(true)
- await manager.startup(program, "remove")
- await manager.startup(program, "remove")
- expect(manager.find(program.identity).record().startup).toBe(false)
-
- expect(announceHost.mock.calls.map(([, owner, event, , , launch]) => [owner, event, launch])).toEqual([
- [program.identity, "changeStartup", { name: "background" }],
- [program.identity, "changeStartup", null]
- ])
- expect(announceSubject.mock.calls.map(([, , event, subject, launch]) => [event, subject, launch])).toEqual([
- ["changeStartup", program.reference, { name: "background" }],
- ["changeStartup", program.reference, null]
- ])
- expect(records.map(([record, launch]) => [(record as { startup: boolean }).startup, launch])).toEqual([
- [true, { name: "background" }],
- [false, null]
- ])
-})
-
test("Program store changes originate once at System and retain their key revisions", async context => {
const { manager, definition, announceSubject } = fixture(context)
announceSubject.mockResolvedValue(undefined)
diff --git a/tests/program-installation-lifecycle.test.ts b/tests/program-installation-lifecycle.test.ts
index 0fa28d9..24ee38c 100644
--- a/tests/program-installation-lifecycle.test.ts
+++ b/tests/program-installation-lifecycle.test.ts
@@ -8,6 +8,7 @@ import FileManager from "@libs/file-manager"
import type AuthManager from "@server/core/link-manager/auth-manager/auth-manager"
import Program from "@server/core/link-manager/auth-manager/program-manager/program"
import ProgramManager from "@server/core/link-manager/auth-manager/program-manager/program-manager"
+import ProgramStateStorage from "@server/core/link-manager/auth-manager/program-manager/state"
function fixture(context: TestContext) {
const directory = mkdtempSync(join(tmpdir(), "phresh-install-lifecycle-"))
@@ -16,9 +17,12 @@ function fixture(context: TestContext) {
mkdirSync(server, { recursive: true })
const exitAll = vi.fn()
const announceHost = vi.fn()
+ const announceSubject = vi.fn(async (..._values: unknown[]) => undefined)
+ const forgetProgram = vi.fn(async (_program: string) => undefined)
const auth = Object.assign(new TheLink(), {
linkManager: { application: { storage: new FileManager(directory, "system"), icons: { system: "", defaultProgram: "" } } },
- processManager: { processes: new Map(), exitAll, announceHost, announceSubject: vi.fn(async () => undefined) }
+ processManager: { processes: new Map(), exitAll, announceHost, announceSubject, requireLaunch: vi.fn() },
+ openingManager: { forgetProgram }
}) as unknown as AuthManager
const manager = new ProgramManager(auth)
const definition = (installCommand = `node -e "process.stdout.write('preparing')"`, installLaunch?: true | Launch) => new Program({
@@ -26,7 +30,7 @@ function fixture(context: TestContext) {
installLaunch,
server: { location: server, installCommand, command: "node main.js" }
})
- return { directory, manager, exitAll, announceHost, definition }
+ return { directory, manager, exitAll, announceHost, announceSubject, forgetProgram, definition }
}
test("installation output precedes Process exit and handle switch; an explicit launch overrides the definition", async context => {
@@ -133,6 +137,26 @@ test("a reinstall starts the Program's startup launch again, as the System does
expect(start.mock.calls[0]?.[4]).toBe(true)
})
+test("a reinstall whose startup already started the install launch's named Process keeps that one", async context => {
+ const { manager, definition, exitAll } = fixture(context)
+ const processes = manager.authManager.processManager.processes as unknown as Map<string, { program: Program, name: string | null }>
+ // Starting adds the Process; ending every Process of the Program, as a reinstall does, removes them.
+ const start = vi.spyOn(manager as unknown as { start(program: Program, launch: Launch): Promise<string> }, "start")
+ .mockImplementation(async (program, launch) => { processes.set(String(launch.name), { program, name: launch.name ?? null }); return String(launch.name) })
+ exitAll.mockImplementation(async () => processes.clear())
+ const server = { name: "files", server: true, client: false } as const
+
+ const first = await manager.install(definition(undefined, server))
+ await manager.startup(first.program, "set", server)
+ // The startup starts "files" again; the install launch finds it running and is done.
+ await expect(manager.install(definition(undefined, server))).resolves.toBeDefined()
+ expect(start.mock.calls.map(([, launch]) => launch.name)).toEqual(["files", "files"])
+
+ // An install launch that asks to replace it still starts its own.
+ await manager.install(definition(undefined, { ...server, replace: true }))
+ expect(start.mock.calls.map(([, launch]) => launch.name)).toEqual(["files", "files", "files", "files"])
+})
+
test("explicit launch errors propagate without rolling back the installed Program", async context => {
const { manager, definition } = fixture(context)
const start = vi.spyOn(manager as unknown as { start(program: Program, launch: Launch): Promise<string> }, "start")
@@ -143,7 +167,7 @@ test("explicit launch errors propagate without rolling back the installed Progra
})
test("uninstalling ends the Program's Processes and forgets its handle; its data stays for the next install", async context => {
- const { manager, exitAll, announceHost, definition } = fixture(context)
+ const { manager, forgetProgram, exitAll, announceHost, definition } = fixture(context)
const entry = await manager.install(definition())
const program = entry.program
const home = manager.fileManager.join(program.identity)
@@ -159,8 +183,9 @@ test("uninstalling ends the Program's Processes and forgets its handle; its data
expect(announceHost.mock.calls.filter(([, , event]) => event === "uninstall")).toHaveLength(1)
expect(announceHost.mock.calls.filter(([, , event]) => event === "forget")).toHaveLength(1)
await expect(manager.uninstall(program)).rejects.toThrow("does not know this program")
- // Its data stayed.
+ // Its data stayed, and what the System keeps naming it.
expect(existsSync(join(program.storagePath, "state.json"))).toBe(true)
+ expect(forgetProgram).not.toHaveBeenCalled()
// Installed again: a new handle, which finds the time it was first installed and its pin.
const again = await manager.install(definition())
@@ -170,8 +195,10 @@ test("uninstalling ends the Program's Processes and forgets its handle; its data
await manager.uninstall(again.program, { purge: true })
+ // Purged, nothing in the System says it was here.
expect(manager.programs.has(program.identity)).toBe(false)
expect(existsSync(home)).toBe(false)
+ expect(forgetProgram).toHaveBeenCalledExactlyOnceWith(program.identity)
})
test("clearing storage ends the Program's Processes and empties what it keeps, keeping the owner's decisions and its logs", async context => {
@@ -209,3 +236,81 @@ test("clearing storage ends the Program's Processes and empties what it keeps, k
// Forgetting it closes what it holds open, which Windows needs before the folder can go.
await manager.forget(program)
})
+
+test("startup and pinned state share one file without overwriting each other", async context => {
+ const { manager, definition } = fixture(context)
+ vi.spyOn(manager as unknown as { start(): Promise<string> }, "start").mockResolvedValue("process")
+ const { program } = await manager.install(definition())
+ const startup = { name: "background", options: { mode: "quiet" } }
+
+ await manager.startup(program, "set", startup)
+ const pinnedAt = await manager.pinned(program, "pin")
+ await manager.setPermission(program, "network", false)
+
+ expect(await manager.startup(program, "get")).toEqual(startup)
+ expect(pinnedAt).toMatch(/^\d{4}-\d{2}-\d{2}T/)
+ expect(await manager.pinned(program, "get")).toBe(pinnedAt)
+ expect(new ProgramStateStorage(program).permissions()).toEqual({ network: false })
+ expect(JSON.parse(readFileSync(join(program.storagePath, "state.json"), "utf8"))).toEqual({
+ installedAt: expect.any(String),
+ startup,
+ pinnedAt,
+ permissions: { network: false }
+ })
+
+ await manager.startup(program, "remove")
+ await manager.pinned(program, "unpin")
+ expect(await manager.startup(program, "get")).toBeNull()
+ expect(await manager.pinned(program, "get")).toBeNull()
+ expect(new ProgramStateStorage(program).permissions()).toEqual({ network: false })
+})
+
+test("Program state mutations do not rewrite an already-satisfied value", async context => {
+ const { manager, definition } = fixture(context)
+ vi.spyOn(manager as unknown as { start(): Promise<string> }, "start").mockResolvedValue("process")
+ const { program } = await manager.install(definition())
+ const startupWrite = vi.spyOn(ProgramStateStorage.prototype, "setStartup")
+ const permissionWrite = vi.spyOn(ProgramStateStorage.prototype, "setPermission")
+ context.onTestFinished(() => { startupWrite.mockRestore(); permissionWrite.mockRestore() })
+
+ await manager.startup(program, "set", { name: "background" })
+ await manager.startup(program, "set", { name: "background" })
+ await manager.setPermission(program, "network", false)
+ await manager.setPermission(program, "network", false)
+ await manager.startup(program, "remove")
+ await manager.startup(program, "remove")
+
+ expect(startupWrite).toHaveBeenCalledTimes(2)
+ expect(permissionWrite).toHaveBeenCalledTimes(1)
+})
+
+test("startup changes emit Program and global events, and filter the Program list", async context => {
+ const { manager, definition, announceHost, announceSubject } = fixture(context)
+ vi.spyOn(manager as unknown as { start(): Promise<string> }, "start").mockResolvedValue("process")
+ const { program } = await manager.install(definition())
+ const records: unknown[][] = []
+ const stop = manager.$outbound.subscribe("/startup-change", (record, launch) => { records.push([record, launch]) })
+ context.onTestFinished(stop)
+ announceHost.mockClear()
+ announceSubject.mockClear()
+
+ await manager.startup(program, "set", { name: "background" })
+ await manager.startup(program, "set", { name: "background" })
+ expect(manager.find(program.identity).record().startup).toBe(true)
+ await manager.startup(program, "remove")
+ await manager.startup(program, "remove")
+ expect(manager.find(program.identity).record().startup).toBe(false)
+
+ expect(announceHost.mock.calls.map(([, owner, event, , , launch]) => [owner, event, launch])).toEqual([
+ [program.identity, "changeStartup", { name: "background" }],
+ [program.identity, "changeStartup", null]
+ ])
+ expect(announceSubject.mock.calls.map(([, , event, subject, launch]) => [event, subject, launch])).toEqual([
+ ["changeStartup", program.reference, { name: "background" }],
+ ["changeStartup", program.reference, null]
+ ])
+ expect(records.map(([record, launch]) => [(record as { startup: boolean }).startup, launch])).toEqual([
+ [true, { name: "background" }],
+ [false, null]
+ ])
+})
diff --git a/tests/sdk-records.test.ts b/tests/sdk-records.test.ts
index adc3e6b..74f18db 100644
--- a/tests/sdk-records.test.ts
+++ b/tests/sdk-records.test.ts
@@ -8,8 +8,8 @@ test("Desktop preserves Endpoint service roles in SDK snapshots", () => {
name: "Example", version: "0.0.0", description: null, website: null, categories: [], keywords: [], opens: [], declaredPermissions: {}, hasAgent: false,
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 }]) {
+ for (const server of [null, { service: false as const }, { service: "editor-v1" }]) {
+ for (const client of [null, { service: false as const }, { service: "canvas-v1" }]) {
const source: SdkProcessSource = {
identity: "process-identity", reference: "process-reference", program: program.identity,
name: null, options: { language: "en" }, opened: { type: "text/markdown", uri: "file:///notes.md" }, startedAt: new Date(0), server, client
diff --git a/tests/server-permission-boundary.test.ts b/tests/server-permission-boundary.test.ts
index f076f93..b7bb86d 100644
--- a/tests/server-permission-boundary.test.ts
+++ b/tests/server-permission-boundary.test.ts
@@ -53,7 +53,12 @@ test("Server Endpoints use their Program's permission scope", async () => {
return permissionCatalog.allows(name, requested, permissions)
},
- grantsStorage() { return false }
+ grantsStorage() { return false },
+ // As the System resolves it: the layer the launch passes, else the one the Program declares.
+ resolveLaunch(program: Program, value: { client?: unknown }) {
+ const asked = typeof value?.client === "object" && value.client !== null ? value.client as { layer?: string } : {}
+ return { intent: { client: value?.client === false ? null : { layer: asked.layer ?? program.config.client?.layer ?? "window" } } }
+ }
},
linkManager: { application: { system } }
})
diff --git a/tests/service-claim.test.ts b/tests/service-claim.test.ts
new file mode 100644
index 0000000..ef02116
--- /dev/null
+++ b/tests/service-claim.test.ts
@@ -0,0 +1,29 @@
+import { TheLink } from "@the-link/core"
+import { expect, test, vi } from "vitest"
+import type AuthManager from "@server/core/link-manager/auth-manager/auth-manager"
+import Program from "@server/core/link-manager/auth-manager/program-manager/program"
+import ProcessManager from "@server/core/link-manager/auth-manager/process-manager/process-manager"
+import type Process from "@server/core/link-manager/auth-manager/process-manager/process"
+import type ServerProcessBoundary from "@server/core/link-manager/auth-manager/process-manager/server-process-boundary"
+
+test("a Service name is taken from whoever holds it: its whole Process ends", async () => {
+ const manager = new ProcessManager(new TheLink() as unknown as AuthManager)
+ const launch = { server: null, client: null, options: {} } as const
+ const start = (identity: string, owner: Program) => manager.register(identity, null, owner, {}, launch, null, false, null, null)
+ const holding = (process: Process, service: string | false) => { process.server = { service, ready: true } as unknown as ServerProcessBoundary }
+ const files = await start("files-picker", new Program({ identity: "files", server: { location: ".", command: "true" } }))
+ const other = await start("other-picker", new Program({ identity: "other", server: { location: ".", command: "true" } }))
+ holding(files, "file-picker-v1")
+ const ended = vi.spyOn(manager as unknown as { exitProcess(identity: string, whenGone: string): Promise<string> }, "exitProcess").mockResolvedValue("")
+ const claim = (process: Process, service: string | false) => (manager as unknown as { claimService(process: Process, service: string | false): Promise<void> }).claimService(process, service)
+
+ await claim(other, "file-picker-v1")
+ expect(ended).toHaveBeenCalledExactlyOnceWith("files-picker", "complete")
+
+ // Its own name, a free name, or no name: nothing ends.
+ ended.mockClear()
+ await claim(files, "file-picker-v1")
+ await claim(other, "board-canvas-v1")
+ await claim(other, false)
+ expect(ended).not.toHaveBeenCalled()
+})