Skip to content

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

Push

zohayrslilehdad3e1981323
diff --git a/source/client/core/link-manager/auth-manager/auth-manager.ts b/source/client/core/link-manager/auth-manager/auth-manager.ts
index cf01f74..c312e4a 100644
--- a/source/client/core/link-manager/auth-manager/auth-manager.ts
+++ b/source/client/core/link-manager/auth-manager/auth-manager.ts
@@ -2,15 +2,10 @@ import { AuthManagerSnapshot } from "@server/core/link-manager/auth-manager/auth
import { Intercept, Subscribe } from "@the-link/core/decorators"
import ProcessManager from "./process-manager/process-manager"
import ProgramManager from "./program-manager/program-manager"
-import DialogManager from "./dialog-manager"
import { TheLink } from "@the-link/core"
import LinkManager from "../link-manager"
-import {
- type Permission,
- type PermissionName,
- type PermissionRequest
-} from "@phreshos/core"
import ShellManager from "./shell-manager"
+import PermissionManager from "./permission-manager"
import StreamRelay from "@client/core/link-manager/stream-relay"
import { type StorageChange } from "@phreshos/core"
@@ -26,7 +21,7 @@ export default class AuthManager extends TheLink {
public readonly processManager: ProcessManager
- public readonly dialogManager: DialogManager
+ public readonly permissionManager: PermissionManager
public readonly shellManager: ShellManager
@@ -48,7 +43,7 @@ export default class AuthManager extends TheLink {
this.processManager = new ProcessManager(this, payload.processManager)
- this.dialogManager = new DialogManager(this, payload.dialogManager)
+ this.permissionManager = new PermissionManager(this, payload.permissionManager)
this.shellManager = new ShellManager(this)
}
@@ -80,6 +75,11 @@ export default class AuthManager extends TheLink {
return this.$outbound.publishFirst(`/session/${operation}`, ...(identity === undefined ? [] : [identity]))
}
+ public logs(statement: string, values: unknown[] = []) {
+
+ return this.$outbound.publishFirst("/logs/query", statement, values)
+ }
+
/** Emit one authorized private fact without creating a response path. */
public emit(event: string, ...values: unknown[]) {
@@ -122,20 +122,13 @@ export default class AuthManager extends TheLink {
return await this.$outbound.publishFirst("/permission/storage", process, path, operation) as boolean
}
- public async requestPermission<Name extends PermissionName>(
- process: string,
- program: unknown,
- request: string,
- name: Name,
- permission: PermissionRequest<Name>
- ): Promise<Permission<Name>> {
+ public async requestPermission(process: string, request: string, name: unknown, input: unknown, timeout: unknown) {
- return await this.$outbound.publishFirst("/permission/request", request, process, program, name, permission) as Permission<Name>
- }
+ const values = [request, process, name, input]
- public async cancelPermission(process: string, request: string) {
+ if (timeout !== undefined) values.push(timeout)
- await this.$outbound.publish("/permission/cancel", request, process)
+ return await this.$outbound.publishFirst("/permission/request", ...values)
}
public disconnect() {
diff --git a/source/client/core/link-manager/auth-manager/dialog-manager.ts b/source/client/core/link-manager/auth-manager/dialog-manager.ts
deleted file mode 100644
index b496ae9..0000000
--- a/source/client/core/link-manager/auth-manager/dialog-manager.ts
+++ /dev/null
@@ -1,60 +0,0 @@
-import { type DialogManagerSnapshot, type PermissionChoice, type SystemDialog } from "@server/core/dialog-manager"
-import { Publish, Subscribe } from "@the-link/core/decorators"
-import { TheLink } from "@the-link/core"
-import AuthManager from "./auth-manager"
-
-/** Synchronized desktop counterpart of the authoritative system-dialog queue. */
-export default class DialogManager extends TheLink {
-
- public readonly authManager: AuthManager
-
- public readonly dialogs: Map<string, SystemDialog>
-
- public constructor(authManager: AuthManager, payload: DialogManagerSnapshot) {
-
- super()
-
- this.authManager = authManager
-
- this.dialogs = new Map(payload.dialogs)
-
- this.connectTo(this.authManager, "/dialog")
- }
-
- public list() {
-
- return [...this.dialogs.values()]
- }
-
- public async acknowledge(identity: string) {
-
- await this.$outbound.publish("/acknowledge", identity)
- }
-
- public async resolvePermission(identity: string, choice: PermissionChoice) {
-
- await this.$outbound.publish("/resolve-permission", identity, choice)
- }
-
- @Subscribe("/created")
- @Publish("/dialogs", "inbound")
- protected async created(dialog: SystemDialog | null) {
-
- if (!dialog) return
-
- this.dialogs.set(dialog.identity, dialog)
-
- return this.list()
- }
-
- @Subscribe("/removed")
- @Publish("/dialogs", "inbound")
- protected async removed(identity: string | null) {
-
- if (!identity) return
-
- this.dialogs.delete(identity)
-
- return this.list()
- }
-}
diff --git a/source/client/core/link-manager/auth-manager/permission-manager.ts b/source/client/core/link-manager/auth-manager/permission-manager.ts
new file mode 100644
index 0000000..0193f9f
--- /dev/null
+++ b/source/client/core/link-manager/auth-manager/permission-manager.ts
@@ -0,0 +1,63 @@
+import type { Permission, PermissionRequestSnapshot } from "@phreshos/core"
+import { Publish, Subscribe } from "@the-link/core/decorators"
+import { TheLink } from "@the-link/core"
+import type { PermissionManagerSnapshot } from "@server/core/permission-manager"
+import type AuthManager from "./auth-manager"
+
+/** Synchronized Desktop view of authoritative pending permission requests. */
+export default class PermissionManager extends TheLink {
+
+ public readonly requests: Map<string, PermissionRequestSnapshot>
+
+ public constructor(authManager: AuthManager, payload: PermissionManagerSnapshot) {
+
+ super()
+
+ this.requests = new Map(payload.requests)
+
+ this.connectTo(authManager, "/permission")
+ }
+
+ public list() {
+
+ return [...this.requests.values()]
+ }
+
+ public pending(identity: string) {
+
+ return this.requests.has(identity)
+ }
+
+ public async allow(identity: string) {
+
+ await this.$outbound.publishFirst("/allow", identity)
+ }
+
+ public async deny(identity: string) {
+
+ await this.$outbound.publishFirst("/deny", identity)
+ }
+
+ public async cancel(identity: string) {
+
+ await this.$outbound.publishFirst("/cancel", identity)
+ }
+
+ @Subscribe("/request")
+ @Publish("/requests", "inbound")
+ protected async requested(request: PermissionRequestSnapshot) {
+
+ this.requests.set(request.identity, request)
+
+ return this.list()
+ }
+
+ @Subscribe("/resolve")
+ @Publish("/requests", "inbound")
+ protected async resolved(request: PermissionRequestSnapshot, _permission: Permission) {
+
+ this.requests.delete(request.identity)
+
+ return this.list()
+ }
+}
diff --git a/source/client/core/link-manager/auth-manager/program-manager/program-manager.ts b/source/client/core/link-manager/auth-manager/program-manager/program-manager.ts
index decffd3..e2aaa4d 100644
--- a/source/client/core/link-manager/auth-manager/program-manager/program-manager.ts
+++ b/source/client/core/link-manager/auth-manager/program-manager/program-manager.ts
@@ -7,7 +7,7 @@ import Program from "./program"
import {
type Launch,
type PermissionName,
- type PermissionRequest,
+ type PermissionRequestInput,
type ProgramCommandChunk,
type ProgramIconSize
} from "@phreshos/core"
@@ -94,7 +94,7 @@ export default class ProgramManager extends TheLink {
subject: unknown,
operation: "all" | "get" | "allows" | "allow" | "deny",
name?: Name,
- value?: PermissionRequest<Name>
+ value?: PermissionRequestInput<Name>
) {
return await this.$outbound.publishFirst("/permissions", subject, operation, name, value)
diff --git a/source/client/view/components/desktop-host/announcements.ts b/source/client/view/components/desktop-host/announcements.ts
index 8aa251d..7581520 100644
--- a/source/client/view/components/desktop-host/announcements.ts
+++ b/source/client/view/components/desktop-host/announcements.ts
@@ -15,6 +15,9 @@ export default function useAnnouncements(authManager: AuthManager, panes: Map<st
const processes = ReactTunnel.useFactory(authManager.processManager.$inbound)
const programs = ReactTunnel.useFactory(authManager.programManager.$inbound)
const authentication = ReactTunnel.useFactory(authManager.$inbound)
+ const permissions = ReactTunnel.useFactory(authManager.permissionManager.$inbound)
+
+ const logs = ReactTunnel.useFactory(authManager.$inbound)
const post = useCallback(function (program: string, route: string, ...message: unknown[]) {
@@ -193,6 +196,59 @@ export default function useAnnouncements(authManager: AuthManager, panes: Map<st
post(entry.identity, "host-program", "permissions", entry.identity, record)
post(entry.identity, "program-host", "permissions", entry.reference, record)
}, [post]))
+
+ programs.useSubscribe("/log", useCallback((reference: unknown, record: unknown) => {
+
+ if (typeof reference !== "string") return
+
+ const entry = [...authManager.programManager.programs.values()].find(program => program.reference === reference)
+
+ if (!entry) return
+
+ postVisible(access => access.canProgram(entry), "program-log", "log", reference, record)
+ }, [authManager, postVisible]))
+
+ logs.useSubscribe("/logs/log", useCallback((record: unknown) => {
+
+ postVisible(access => access.systemLogs(), "host-log", "log", "system", record)
+ }, [postVisible]))
+
+ permissions.useSubscribe("/request", useCallback((request: unknown) => {
+
+ const program = permissionProgram(request)
+
+ if (program) postVisible(access => access.all(), "host-permission", "request", program, request)
+ }, [postVisible]))
+
+ permissions.useSubscribe("/resolve", useCallback((request: unknown, permission: unknown) => {
+
+ const program = permissionProgram(request)
+ const identity = domainIdentity(request)
+
+ if (!program || !identity) return
+
+ postVisible(access => access.all(), "host-permission", "resolve", program, request, permission)
+ postVisible(access => access.all(), "permission-host", "resolve", identity, request, permission)
+ }, [postVisible]))
+}
+
+function permissionProgram(value: unknown) {
+
+ if (!value || typeof value !== "object") return null
+
+ const from = (value as { from?: unknown }).from
+
+ if (!from || typeof from !== "object") return null
+
+ const process = (from as { process?: unknown }).process
+
+ if (!process || typeof process !== "object") return null
+
+ const program = (process as { program?: unknown }).program
+
+ if (!program || typeof program !== "object") return null
+
+ return domainIdentity(program)
}
function domainIdentity(value: unknown) {
diff --git a/source/client/view/components/desktop-host/client-process-boundary.ts b/source/client/view/components/desktop-host/client-process-boundary.ts
index 15561ae..6200f2b 100644
--- a/source/client/view/components/desktop-host/client-process-boundary.ts
+++ b/source/client/view/components/desktop-host/client-process-boundary.ts
@@ -582,12 +582,12 @@ export default class ClientProcessBoundary extends TheLink {
return
}
- if (args[0] === "program-permissions" && args[2] === "request" && typeof args[3] === "string") {
+ if (args[0] === "context-permission-request" && typeof args[1] === "string") {
this.answerRequest(
question,
this.runHost(args[0], args.slice(1)),
- () => { this.authManager.cancelPermission(this.pane, args[3] as string).catch(() => undefined) }
+ () => { this.authManager.permissionManager.cancel(args[1] as string).catch(() => undefined) }
)
return
diff --git a/source/client/view/components/desktop-host/host.ts b/source/client/view/components/desktop-host/host.ts
index cc9b89d..59c1a7a 100644
--- a/source/client/view/components/desktop-host/host.ts
+++ b/source/client/view/components/desktop-host/host.ts
@@ -17,7 +17,7 @@ import {
parsePermission,
parsePermissionName,
parsePermissions,
- type PermissionRequest,
+ type PermissionRequestInput,
type ProgramIconSize
} from "@phreshos/core"
import {
@@ -704,30 +704,53 @@ export default function host(authManager: AuthManager, pane: string, viewport: (
return [sdkProgram(program)]
}
- if (word === "program-permissions") {
+ if (word === "context-permission-request") {
- const program = await permittedProgram(args[0])
+ if (typeof args[0] !== "string") throw new Error("A permission request needs a unique identity")
- const operation = args[1]
+ const permission = parsePermissionName(args[1])
- if (operation !== "all" && operation !== "get" && operation !== "allows" && operation !== "allow" && operation !== "deny" && operation !== "request") throw new Error(`The System does not know the Program permission operation "${String(operation)}"`)
+ return [await authManager.requestPermission(
+ pane,
+ args[0],
+ permission,
+ args[2] as PermissionRequestInput<typeof permission>,
+ args[3]
+ )]
+ }
- if (operation === "all") return [parsePermissions(program.permissions)]
+ if (word === "host-permission-requests") {
- if (operation === "request") {
+ await access.requireAll()
- if (typeof args[2] !== "string") throw new Error("A permission request needs an identity")
+ return [authManager.permissionManager.list()]
+ }
- const permission = parsePermissionName(args[3])
+ if (typeof word === "string" && word.startsWith("permission-request-")) {
- return [await authManager.requestPermission(
- pane,
- address(program),
- args[2],
- permission,
- args[4] as PermissionRequest<typeof permission>
- )]
- }
+ await access.requireAll()
+
+ const operation = word.slice("permission-request-".length)
+ const identity = String(args[0])
+
+ if (operation === "pending") return [authManager.permissionManager.pending(identity)]
+ if (operation === "allow") await authManager.permissionManager.allow(identity)
+ else if (operation === "deny") await authManager.permissionManager.deny(identity)
+ else if (operation === "cancel") await authManager.permissionManager.cancel(identity)
+ else throw new Error(`The System does not know the PermissionRequest operation "${operation}"`)
+
+ return []
+ }
+
+ if (word === "program-permissions") {
+
+ const program = await permittedProgram(args[0])
+
+ const operation = args[1]
+
+ if (operation !== "all" && operation !== "get" && operation !== "allows" && operation !== "allow" && operation !== "deny") throw new Error(`The System does not know the Program permission operation "${String(operation)}"`)
+
+ if (operation === "all") return [parsePermissions(program.permissions)]
const permission = parsePermissionName(args[2])
@@ -740,7 +763,7 @@ export default function host(authManager: AuthManager, pane: string, viewport: (
address(program),
operation,
permission,
- args[3] as PermissionRequest<typeof permission>
+ args[3] as PermissionRequestInput<typeof permission>
)]
const requested = args[3] === undefined || args[3] === true
@@ -759,7 +782,7 @@ export default function host(authManager: AuthManager, pane: string, viewport: (
address(program),
operation,
permission,
- args[3] as PermissionRequest<typeof permission>
+ args[3] as PermissionRequestInput<typeof permission>
)
return []
@@ -1089,6 +1112,13 @@ export default function host(authManager: AuthManager, pane: string, viewport: (
return [await programManager.logs(address(await permittedProgram(args[0])), String(args[1]), Array.isArray(args[2]) ? args[2] : [])]
}
+ if (word === "system-logs") {
+
+ await access.require("logs", [])
+
+ return [await authManager.logs(String(args[0]), Array.isArray(args[1]) ? args[1] : [])]
+ }
+
// Read and write one exact Program database.
if (word === "database") {
diff --git a/source/client/view/components/desktop-host/system-access.ts b/source/client/view/components/desktop-host/system-access.ts
index 619c6a6..72777eb 100644
--- a/source/client/view/components/desktop-host/system-access.ts
+++ b/source/client/view/components/desktop-host/system-access.ts
@@ -26,6 +26,11 @@ export default class SystemAccess {
return allowsSynchronizedPermission(this.permissions(), "all", [])
}
+ public async systemLogs() {
+
+ return allowsSynchronizedPermission(this.permissions(), "logs", [])
+ }
+
public async canProgram(program: Pick<Program, "identity">) {
return this.ownsProgram(program)
diff --git a/source/client/view/structure/desktop/layers/shell/default-shell.tsx b/source/client/view/structure/desktop/layers/shell/default-shell.tsx
index 4cbd18a..3dab300 100644
--- a/source/client/view/structure/desktop/layers/shell/default-shell.tsx
+++ b/source/client/view/structure/desktop/layers/shell/default-shell.tsx
@@ -1,6 +1,7 @@
import { type AppearanceTaskbar } from "@phreshos/core"
import { type ReactNode } from "react"
-import SystemDialogs from "./dialogs/system-dialogs"
+import SystemErrors from "./dialogs/system-errors"
+import PermissionRequests from "./dialogs/permission-requests"
import StartMenu, { StartMenuButton, StartMenuProvider, useStartMenuOpen } from "./start-menu/start-menu"
import SignOut from "./taskbar/sign-out"
import Taskbar from "./taskbar/taskbar"
@@ -26,7 +27,9 @@ export default function DefaultShell({ spacing, taskbar, children }: Readonly<{
</StartMenuProvider>
- <SystemDialogs />
+ <SystemErrors />
+
+ <PermissionRequests />
</>
}
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
new file mode 100644
index 0000000..29b7bf0
--- /dev/null
+++ b/source/client/view/structure/desktop/layers/shell/dialogs/permission-requests.tsx
@@ -0,0 +1,93 @@
+import type { PermissionName, PermissionRequestSnapshot } from "@phreshos/core"
+import { ReactTunnel } from "@the-link/react"
+import { surfaceLifecyclePose, surfacePresenceTransition } from "@client/view/appearance/surface-presence"
+import { useReducedMotion } from "@libs/react-motion"
+import { motion } from "motion/react"
+import { useEffect, useId, useRef } from "react"
+import { AuthManagerContext } from "@client/view/contexts"
+import ShellSurface, { shellSurfaceClassName } from "../shell-surface"
+import usePromise from "@libs/react-promise"
+import Alert from "@client/view/components/alert"
+import { Button, useAppearance } from "@phreshos/react-ui"
+
+/** Default Shell representation of raw pending permission requests. */
+export default function PermissionRequests() {
+
+ const manager = AuthManagerContext.useValue().permissionManager
+ const inbound = ReactTunnel.useFactory(manager.$inbound)
+ const requests = inbound.useFirstState("/requests", manager.list())
+ const request = requests[0]
+ const surface = useRef<HTMLDialogElement>(null)
+ const title = useId()
+ const description = useId()
+ const reducedMotion = useReducedMotion()
+ const transaction = useAppearance().transaction
+
+ useEffect(() => {
+
+ const element = surface.current
+
+ if (!request || !element || element.open) return
+
+ element.showModal()
+
+ return () => { if (element.open) element.close() }
+ }, [request?.identity])
+
+ if (!request) return null
+
+ return <motion.dialog
+ ref={surface}
+ role="alertdialog"
+ aria-modal="true"
+ aria-labelledby={title}
+ aria-describedby={description}
+ initial={reducedMotion ? surfaceLifecyclePose.visible : surfaceLifecyclePose.hidden}
+ animate={surfaceLifecyclePose.visible}
+ transition={surfacePresenceTransition(reducedMotion, transaction)}
+ onCancel={event => event.preventDefault()}
+ className={`${shellSurfaceClassName} pointer-events-auto fixed inset-0 m-auto h-fit w-[min(28rem,calc(100vw-var(--desktop-gutter)*2))] backdrop:bg-transparent`}
+ >
+ <ShellSurface material="full" label="Permission request" labelId={title}>
+ <PermissionRequestView request={request} description={description} />
+ </ShellSurface>
+ </motion.dialog>
+}
+
+function PermissionRequestView({ request, description }: Readonly<{ request: PermissionRequestSnapshot, description: string }>) {
+
+ const manager = AuthManagerContext.useValue().permissionManager
+ const decision = usePromise((choice: "allow" | "deny" | "cancel") => manager[choice](request.identity))
+ const presentation = permissionPresentation[request.name]
+ const program = request.from.process.program
+
+ return <div className="grid grid-cols-[auto_minmax(0,1fr)] items-start gap-x-3 gap-y-5 p-4">
+ <span aria-hidden="true" className="grid size-8 place-items-center rounded-full border border-sky-600/25 bg-sky-500/15 text-sm font-medium">?</span>
+ <div className="grid gap-1">
+ <h3 className="text-base font-medium">{program.name} needs {presentation.title}</h3>
+ <p id={description} className="text-sm leading-6 opacity-60">{presentation.description}</p>
+ {request.scope.length > 0 && <p className="text-xs leading-5 opacity-50">{request.scope.join(", ")}</p>}
+ </div>
+ <div className="col-span-full flex flex-wrap justify-end gap-2">
+ <Button size="xsmall" disabled={decision.isPending} onPress={() => decision.safeExecute("deny")}>Deny</Button>
+ <Button size="xsmall" autoFocus disabled={decision.isPending} onPress={() => decision.safeExecute("cancel")}>Cancel</Button>
+ <Button size="xsmall" disabled={decision.isPending} onPress={() => decision.safeExecute("allow")}>Allow for this Program</Button>
+ </div>
+ {decision.exception && <Alert className="col-span-full text-sm">{String(decision.exception.current)}</Alert>}
+ </div>
+}
+
+const permissionPresentation = {
+ all: { title: "all permissions", description: "Grant every available Program permission." },
+ services: { title: "Services", description: "Access Services by their Process and Service name." },
+ 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." },
+ storage: { title: "Storage", description: "Use every native filesystem path or selected operation-and-path scopes." },
+ uploads: { title: "Uploads", description: "Create values in the System uploads collection." },
+ logs: { title: "System logs", description: "Read and follow records produced by the System." },
+ appearance: { title: "Appearance", description: "Change the System Appearance." },
+ desktopPreferences: { title: "Desktop preferences", description: "Change this Desktop's preferences." },
+ desktopConnection: { title: "Desktop connection", description: "Access the browser Connection carrying this Desktop and its Session." },
+ authentication: { title: "Authentication", description: "Access and manage owner authentication, browser Connections, and Sessions." }
+} satisfies Record<PermissionName, Readonly<{ title: string, description: string }>>
diff --git a/source/client/view/structure/desktop/layers/shell/dialogs/system-dialogs.tsx b/source/client/view/structure/desktop/layers/shell/dialogs/system-dialogs.tsx
deleted file mode 100644
index 220dfe9..0000000
--- a/source/client/view/structure/desktop/layers/shell/dialogs/system-dialogs.tsx
+++ /dev/null
@@ -1,188 +0,0 @@
-import { type PermissionChoice, type PermissionDialog, type ServerCrashDialog } from "@server/core/dialog-manager"
-import { ReactTunnel } from "@the-link/react"
-import { surfaceLifecyclePose, surfacePresenceTransition } from "@client/view/appearance/surface-presence"
-import { useReducedMotion } from "@libs/react-motion"
-import { motion } from "motion/react"
-import { useEffect, useId, useRef } from "react"
-import { AuthManagerContext } from "@client/view/contexts"
-import ShellSurface, { shellSurfaceClassName } from "../shell-surface"
-import usePromise from "@libs/react-promise"
-import Alert from "@client/view/components/alert"
-import { Button, useAppearance } from "@phreshos/react-ui"
-
-/** Centered Shell presentation of the system's authoritative dialog queue. */
-export default function SystemDialogs() {
-
- const authManager = AuthManagerContext.useValue()
-
- const dialogManager = authManager.dialogManager
-
- const inbound = ReactTunnel.useFactory(dialogManager.$inbound)
-
- const dialogs = inbound.useFirstState("/dialogs", dialogManager.list())
-
- const dialog = dialogs[0]
-
- const dialogIdentity = dialog?.identity
-
- const surface = useRef<HTMLDialogElement>(null)
-
- const title = useId()
-
- const description = useId()
-
- const reducedMotion = useReducedMotion()
- const transaction = useAppearance().transaction
-
- useEffect(function () {
-
- const element = surface.current
-
- if (!dialog || !element || element.open) return
-
- element.showModal()
-
- return function () {
-
- if (element.open) element.close()
- }
-
- }, [dialogIdentity, reducedMotion])
-
- if (!dialog) return null
-
- return <motion.dialog
-
- ref={surface}
-
- role="alertdialog"
-
- aria-modal="true"
-
- aria-labelledby={title}
-
- aria-describedby={description}
-
- initial={reducedMotion ? surfaceLifecyclePose.visible : surfaceLifecyclePose.hidden}
-
- animate={surfaceLifecyclePose.visible}
-
- transition={surfacePresenceTransition(reducedMotion, transaction)}
-
- onCancel={event => event.preventDefault()}
-
- className={`${shellSurfaceClassName} pointer-events-auto fixed inset-0 m-auto h-fit w-[min(28rem,calc(100vw-var(--desktop-gutter)*2))] backdrop:bg-transparent`}
-
- >
-
- <ShellSurface material="full" label={dialog.kind === "permission" ? "Permission request" : "System error"} labelId={title}>
-
- {dialog.kind === "permission"
-
- ? <PermissionRequest key={dialog.identity} dialog={dialog} description={description} decide={choice => dialogManager.resolvePermission(dialog.identity, choice)} />
-
- : <CrashReport key={dialog.identity} dialog={dialog} description={description} acknowledge={() => dialogManager.acknowledge(dialog.identity)} />}
-
- </ShellSurface>
-
- </motion.dialog>
-}
-
-function PermissionRequest({ dialog, description, decide }: PermissionRequestProps) {
-
- const decision = usePromise(decide)
-
- return <div className="grid grid-cols-[auto_minmax(0,1fr)] items-start gap-x-3 gap-y-5 p-4">
-
- <span aria-hidden="true" className="grid size-8 place-items-center rounded-full border border-sky-600/25 bg-sky-500/15 text-sm font-medium">?</span>
-
- <div className="grid gap-1">
-
- <h3 className="text-base font-medium">{dialog.program.name} needs {dialog.title}</h3>
-
- <p id={description} className="text-sm leading-6 opacity-60">{dialog.description}</p>
-
- {dialog.values.length > 0 && <p className="text-xs leading-5 opacity-50">{dialog.values.join(", ")}</p>}
-
- </div>
-
- <div className="col-span-full flex flex-wrap justify-end gap-2">
-
- <Button size="xsmall" disabled={decision.isPending} onPress={() => decision.safeExecute(false)}>Deny</Button>
-
- <Button size="xsmall" autoFocus disabled={decision.isPending} onPress={() => decision.safeExecute(null)}>Later</Button>
-
- <Button size="xsmall" disabled={decision.isPending} onPress={() => decision.safeExecute(true)}>Allow for this Program</Button>
-
- </div>
-
- {decision.exception && <Alert className="col-span-full text-sm">{String(decision.exception.current)}</Alert>}
-
- </div>
-}
-
-function CrashReport({ dialog, description, acknowledge }: CrashReportProps) {
-
- const acknowledgment = usePromise(acknowledge)
-
- return <div className="grid grid-cols-[auto_minmax(0,1fr)] items-start gap-x-3 gap-y-5 p-4">
-
- <span aria-hidden="true" className="grid size-8 place-items-center rounded-full border border-rose-600/25 bg-rose-500/15 text-lg font-medium">!</span>
-
- <div className="grid gap-1">
-
- <h3 className="text-base font-medium">Server endpoint crashed</h3>
-
- <p id={description} className="text-sm leading-6 opacity-60">{crashDescription(dialog)}</p>
-
- </div>
-
- <Button
-
- size="xsmall"
-
- autoFocus
-
- disabled={acknowledgment.isPending}
-
- onPress={() => acknowledgment.safeExecute()}
-
- className="col-span-full justify-self-end font-medium"
-
- >
-
- I understand
-
- </Button>
-
- {acknowledgment.exception && <Alert className="col-span-full text-sm">{String(acknowledgment.exception.current)}</Alert>}
-
- </div>
-}
-
-function crashDescription(dialog: ServerCrashDialog) {
-
- const endpoint = dialog.process.name ? `the “${dialog.process.name}” Process’s server endpoint` : "its server endpoint"
-
- if (dialog.signal) return `${dialog.program.name} stopped unexpectedly because ${endpoint} was terminated by ${dialog.signal}.`
-
- if (dialog.code !== null) return `${dialog.program.name} stopped unexpectedly because ${endpoint} exited with code ${dialog.code}.`
-
- return `${dialog.program.name} stopped because ${endpoint} ended unexpectedly.`
-}
-
-interface CrashReportProps {
-
- dialog: ServerCrashDialog
-
- description: string
-
- acknowledge(): Promise<void>
-}
-
-interface PermissionRequestProps {
-
- dialog: PermissionDialog
- description: string
- decide(choice: PermissionChoice): Promise<void>
-}
diff --git a/source/client/view/structure/desktop/layers/shell/dialogs/system-errors.tsx b/source/client/view/structure/desktop/layers/shell/dialogs/system-errors.tsx
new file mode 100644
index 0000000..f500184
--- /dev/null
+++ b/source/client/view/structure/desktop/layers/shell/dialogs/system-errors.tsx
@@ -0,0 +1,112 @@
+import { parseSystemLogRecord, type SystemLogRecord } from "@phreshos/core"
+import { ReactTunnel } from "@the-link/react"
+import { surfaceLifecyclePose, surfacePresenceTransition } from "@client/view/appearance/surface-presence"
+import { useReducedMotion } from "@libs/react-motion"
+import { motion } from "motion/react"
+import { useCallback, useEffect, useId, useRef, useState } from "react"
+import { AuthManagerContext } from "@client/view/contexts"
+import ShellSurface, { shellSurfaceClassName } from "../shell-surface"
+import { Button, useAppearance } from "@phreshos/react-ui"
+
+/** Shell-owned real-time presentation of new System errors. */
+export default function SystemErrors() {
+
+ const authManager = AuthManagerContext.useValue()
+
+ const inbound = ReactTunnel.useFactory(authManager.$inbound)
+
+ const [record, setRecord] = useState<SystemLogRecord | null>(null)
+
+ inbound.useSubscribe("/logs/log", useCallback((value: unknown) => {
+
+ const received = parseSystemLogRecord(value)
+
+ if (received.level === "error") setRecord(received)
+ }, []))
+
+ const surface = useRef<HTMLDialogElement>(null)
+
+ const title = useId()
+
+ const description = useId()
+
+ const reducedMotion = useReducedMotion()
+
+ const transaction = useAppearance().transaction
+
+ const visible = record !== null
+
+ useEffect(function () {
+
+ const element = surface.current
+
+ if (!visible || !element || element.open) return
+
+ element.showModal()
+
+ return function () {
+
+ if (element.open) element.close()
+ }
+
+ // The latest error may replace the visible content, but it must not close
+ // and reopen the same Shell-owned dialog merely because its record changed.
+ }, [visible])
+
+ if (!record) return null
+
+ return <motion.dialog
+
+ ref={surface}
+
+ role="alertdialog"
+
+ aria-modal="true"
+
+ aria-labelledby={title}
+
+ aria-describedby={description}
+
+ initial={reducedMotion ? surfaceLifecyclePose.visible : surfaceLifecyclePose.hidden}
+
+ animate={surfaceLifecyclePose.visible}
+
+ transition={surfacePresenceTransition(reducedMotion, transaction)}
+
+ onCancel={event => event.preventDefault()}
+
+ className={`${shellSurfaceClassName} pointer-events-auto fixed inset-0 m-auto h-fit w-[min(28rem,calc(100vw-var(--desktop-gutter)*2))] backdrop:bg-transparent`}
+
+ >
+
+ <ShellSurface material="full" label="System error" labelId={title}>
+
+ <div className="grid grid-cols-[auto_minmax(0,1fr)] items-start gap-x-3 gap-y-5 p-4">
+
+ <span aria-hidden="true" className="grid size-8 place-items-center rounded-full border border-rose-600/25 bg-rose-500/15 text-lg font-medium">!</span>
+
+ <div className="grid gap-1">
+
+ <h3 className="text-base font-medium">{errorTitle(record)}</h3>
+
+ <p id={description} className="text-sm leading-6 opacity-60">{record.content}</p>
+
+ </div>
+
+ <Button size="xsmall" autoFocus onPress={() => setRecord(null)} className="col-span-full justify-self-end font-medium">
+
+ I understand
+
+ </Button>
+
+ </div>
+
+ </ShellSurface>
+
+ </motion.dialog>
+}
+
+function errorTitle(record: SystemLogRecord) {
+
+ return record.kind === "unexpectedServerEndpointExit" ? "Server endpoint stopped unexpectedly" : "System error"
+}
diff --git a/source/server/core/application.ts b/source/server/core/application.ts
index 8570cb1..206fde7 100644
--- a/source/server/core/application.ts
+++ b/source/server/core/application.ts
@@ -2,7 +2,6 @@ import LinkManager from "./link-manager/link-manager"
import Authentication from "./authentication/authentication"
import FileManager from "@libs/file-manager"
import UploadManager from "./upload-manager"
-import DialogManager from "./dialog-manager"
import AppearanceManager from "./appearance-manager"
import openStore from "./open-store"
import Keyv from "keyv"
@@ -10,6 +9,7 @@ import FileArea, { FileSystem } from "@libs/file-area"
import { homedir } from "node:os"
import System from "./system"
import createServerRuntime from "./server-runtime/factory"
+import SystemLogs from "./logs"
export default class Application {
@@ -34,7 +34,8 @@ export default class Application {
public readonly uploads: UploadManager
- public readonly dialogManager: DialogManager
+ /** System-owned persistent records and their internal write capability. */
+ public readonly logs: SystemLogs
public readonly appearanceManager: AppearanceManager
@@ -70,7 +71,7 @@ export default class Application {
this.createServerRuntime = createServerRuntime
- this.dialogManager = new DialogManager()
+ this.logs = new SystemLogs(this.storage.join("logs.sqlite"))
this.linkManager = new LinkManager(this)
diff --git a/source/server/core/dialog-manager.ts b/source/server/core/dialog-manager.ts
deleted file mode 100644
index 29b6f48..0000000
--- a/source/server/core/dialog-manager.ts
+++ /dev/null
@@ -1,208 +0,0 @@
-import { Subscribe } from "@the-link/core/decorators"
-import { TheLink } from "@the-link/core"
-import { randomUUID } from "node:crypto"
-import { type default as Process } from "./link-manager/auth-manager/process-manager/process"
-import { type default as Program } from "./link-manager/auth-manager/program-manager/program"
-import { permissionCatalog } from "./permissions"
-import type { PermissionName, PermissionValue } from "@phreshos/core"
-
-/** Authoritative runtime queue of system messages awaiting acknowledgment. */
-export default class DialogManager extends TheLink {
-
- public readonly dialogs = new Map<string, SystemDialog>()
-
- private readonly permissionRequests = new Map<string, PendingPermission>()
-
- private readonly permissionProcesses = new Map<string, string>()
-
- public list() {
-
- return [...this.dialogs.values()]
- }
-
- /** Records one unexpected Server ending independently of its dead handle. */
- public async serverCrashed(process: Process, code: number | null, signal: NodeJS.Signals | null) {
-
- const dialog: ServerCrashDialog = {
-
- identity: randomUUID(),
-
- kind: "serverCrash",
-
- createdAt: new Date(),
-
- program: {
-
- identity: process.program.identity,
-
- name: process.program.name
- },
-
- process: {
-
- identity: process.identity,
-
- name: process.name
- },
-
- code,
-
- signal
- }
-
- this.dialogs.set(dialog.identity, dialog)
-
- // Authority already retains the record. A lost desktop is born with
- // the queue when it returns; notification failure must not interrupt
- // the Process teardown that produced this dialog.
- await this.$outbound.publish("/created", dialog).catch(() => undefined)
- }
-
- /** Waits for one authoritative owner decision about a target Program. */
- public async requestPermission<Name extends PermissionName>(
- program: Program,
- request: string,
- permission: Name,
- values: readonly PermissionValue<Name>[],
- process: Process | null = null
- ): Promise<PermissionChoice> {
-
- if (!request || this.permissionRequests.has(request)) throw new Error("A permission request needs a unique identity")
- if (process && this.permissionProcesses.has(process.reference)) throw new Error("This Process already has a pending permission request")
-
- const definition = permissionCatalog.definition(permission)
- const dialog: PermissionDialog = {
-
- identity: randomUUID(),
- kind: "permission",
- createdAt: new Date(),
- permission,
- values: [...values],
- title: definition.title,
- description: definition.description,
- program: { identity: program.identity, name: program.name },
- process: process ? { identity: process.identity, name: process.name } : null
- }
-
- let settle: (choice: PermissionChoice) => void = () => undefined
- const answer = new Promise<PermissionChoice>(resolve => { settle = resolve })
- // Endpoint requests belong to that Process lifetime; owner-local
- // requests have no invented Process and are cancelled by their caller.
- const stopExit = process
- ? process.onExit(() => { this.cancelPermission(request, process.reference).catch(() => undefined) })
- : () => undefined
-
- this.permissionRequests.set(request, { request, dialog, process: process?.reference ?? null, settle, stopExit })
- if (process) this.permissionProcesses.set(process.reference, request)
- this.dialogs.set(dialog.identity, dialog)
-
- await this.$outbound.publish("/created", dialog).catch(() => undefined)
-
- return await answer
- }
-
- /** Resolves one permission prompt from any synchronized Desktop. */
- @Subscribe("/resolve-permission")
- protected async resolvePermission(identity: unknown, choice: unknown) {
-
- if (!isPermissionChoice(choice)) return
-
- const pending = [...this.permissionRequests.values()].find(entry => entry.dialog.identity === identity)
-
- if (pending) await this.finishPermission(pending, choice)
- }
-
- /** Cancels one boundary-owned prompt without creating a decision. */
- public async cancelPermission(request: string, process: string | null = null) {
-
- const pending = this.permissionRequests.get(request)
-
- if (pending && (process === null || pending.process === process)) await this.finishPermission(pending, null)
- }
-
- private async finishPermission(pending: PendingPermission, choice: PermissionChoice) {
-
- if (!this.permissionRequests.delete(pending.request)) return
-
- if (pending.process) this.permissionProcesses.delete(pending.process)
- this.dialogs.delete(pending.dialog.identity)
- pending.stopExit()
- pending.settle(choice)
-
- await this.$outbound.publish("/removed", pending.dialog.identity).catch(() => undefined)
- }
-
- /** Removes an acknowledged dialog once, including simultaneous acknowledgments. */
- @Subscribe("/acknowledge")
- protected async acknowledge(identity: unknown) {
-
- if (typeof identity !== "string" || this.dialogs.get(identity)?.kind !== "serverCrash" || !this.dialogs.delete(identity)) return
-
- await this.$outbound.publish("/removed", identity)
- }
-
- public toJSON() {
-
- return { dialogs: this.dialogs }
- }
-}
-
-export interface ServerCrashDialog {
-
- readonly identity: string
-
- readonly kind: "serverCrash"
-
- readonly createdAt: Date
-
- readonly program: Readonly<{
-
- identity: string
-
- name: string
- }>
-
- readonly process: Readonly<{
-
- identity: string
-
- name: string | null
- }>
-
- readonly code: number | null
-
- readonly signal: string | null
-}
-
-export interface PermissionDialog {
-
- readonly identity: string
- readonly kind: "permission"
- readonly createdAt: Date
- readonly permission: PermissionName
- readonly values: PermissionValue<PermissionName>[]
- readonly title: string
- readonly description: string
- readonly program: Readonly<{ identity: string, name: string }>
- readonly process: Readonly<{ identity: string, name: string | null }> | null
-}
-
-export type PermissionChoice = true | false | null
-
-export type SystemDialog = ServerCrashDialog | PermissionDialog
-
-interface PendingPermission {
-
- readonly request: string
- readonly dialog: PermissionDialog
- readonly process: string | null
- readonly settle: (choice: PermissionChoice) => void
- readonly stopExit: () => void
-}
-
-function isPermissionChoice(value: unknown): value is PermissionChoice {
-
- return value === true || value === false || value === null
-}
-
-export type DialogManagerSnapshot = ReturnType<DialogManager["toJSON"]>
diff --git a/source/server/core/link-manager/auth-manager/auth-manager.ts b/source/server/core/link-manager/auth-manager/auth-manager.ts
index 4e92767..196004a 100644
--- a/source/server/core/link-manager/auth-manager/auth-manager.ts
+++ b/source/server/core/link-manager/auth-manager/auth-manager.ts
@@ -1,12 +1,12 @@
import { Forward, Intercept, Subscribe } from "@the-link/core/decorators"
import UploadManager, { uploadLimit } from "@server/core/upload-manager"
-import DialogManager from "@server/core/dialog-manager"
import ProcessManager from "./process-manager/process-manager"
import ProgramManager from "./program-manager/program-manager"
import { TheLink } from "@the-link/core"
import LinkManager from "../link-manager"
-import { parsePermissionName, type PermissionRequest } from "@phreshos/core"
+import { parsePermissionName, type PermissionRequestInput } from "@phreshos/core"
import ShellManager from "./shell-manager"
+import PermissionManager from "../../permission-manager"
export default class AuthManager extends TheLink {
@@ -18,7 +18,7 @@ export default class AuthManager extends TheLink {
public readonly processManager: ProcessManager
- public readonly dialogManager: DialogManager
+ public readonly permissionManager: PermissionManager
public readonly shellManager: ShellManager
@@ -28,15 +28,20 @@ export default class AuthManager extends TheLink {
this.linkManager = linkManager
+ this.permissionManager = new PermissionManager(this)
+
this.programManager = new ProgramManager(this)
this.processManager = new ProcessManager(this)
- this.dialogManager = this.linkManager.application.dialogManager
-
this.shellManager = new ShellManager(this)
- this.dialogManager.connectTo(this, "/dialog")
+ this.linkManager.application.logs.subscribe(record => {
+
+ this.$outbound.publish("/logs/log", record).catch(() => undefined)
+
+ this.processManager.announceHost("log", "log", "system", record).catch(() => undefined)
+ })
this.subscribeTo(this.linkManager, "/auth")
}
@@ -354,19 +359,56 @@ export default class AuthManager extends TheLink {
}
@Subscribe("/permission/request")
- protected async requestPermission(request: unknown, process: unknown, program: unknown, name: unknown, permission: unknown) {
+ protected async requestPermission(request: unknown, process: unknown, name: unknown, permission: unknown, timeout: unknown) {
if (typeof request !== "string" || typeof process !== "string") throw new Error("A permission request is invalid")
const permissionName = parsePermissionName(name)
- return this.processManager.requestPermission(process, program, request, permissionName, permission as PermissionRequest<typeof permissionName>)
+ return this.processManager.requestPermission(
+ process,
+ "client",
+ request,
+ permissionName,
+ permission as PermissionRequestInput<typeof permissionName>,
+ timeout
+ )
+ }
+
+ @Subscribe("/permissions/requests")
+ protected permissionRequests() {
+
+ return this.permissionManager.requests()
+ }
+
+ @Subscribe("/permissions/pending")
+ protected permissionPending(identity: unknown) {
+
+ return typeof identity === "string" && this.permissionManager.pending(identity)
+ }
+
+ @Subscribe("/permissions/allow")
+ protected async allowPermissionRequest(identity: unknown) {
+
+ await this.permissionManager.allow(identity)
+ }
+
+ @Subscribe("/permissions/deny")
+ protected async denyPermissionRequest(identity: unknown) {
+
+ await this.permissionManager.deny(identity)
+ }
+
+ @Subscribe("/permissions/cancel")
+ protected async cancelPermissionRequest(identity: unknown) {
+
+ await this.permissionManager.cancel(identity)
}
- @Subscribe("/permission/cancel")
- protected async cancelPermission(request: unknown, process: unknown) {
+ @Subscribe("/logs/query")
+ protected systemLogs(statement: unknown, values: unknown) {
- if (typeof request === "string" && typeof process === "string") await this.processManager.cancelPermission(process, request)
+ return this.linkManager.application.logs.query(String(statement), Array.isArray(values) ? values : [])
}
public async writeArea(sessionToken: unknown, program: unknown, area: "data" | "cache", path: string[], content: ReadableStream<Uint8Array> | null, signal?: AbortSignal, overwrite = true) {
@@ -414,7 +456,7 @@ export default class AuthManager extends TheLink {
processManager: this.processManager,
- dialogManager: this.dialogManager
+ permissionManager: this.permissionManager
}
}
}
@@ -469,5 +511,5 @@ export interface AuthManagerSnapshot {
processManager: import("./process-manager/process-manager").ProcessManagerSnapshot
- dialogManager: ReturnType<DialogManager["toJSON"]>
+ permissionManager: import("../../permission-manager").PermissionManagerSnapshot
}
diff --git a/source/server/core/link-manager/auth-manager/process-manager/host-traffic.ts b/source/server/core/link-manager/auth-manager/process-manager/host-traffic.ts
index 372edcb..3780a0e 100644
--- a/source/server/core/link-manager/auth-manager/process-manager/host-traffic.ts
+++ b/source/server/core/link-manager/auth-manager/process-manager/host-traffic.ts
@@ -50,4 +50,4 @@ type Subscriber = (delivery: object, event: string, ...values: unknown[]) => unk
export type HostDomain = Domain
-type Domain = "program" | "process" | "window" | "connection" | "session" | "service"
+type Domain = "program" | "process" | "window" | "connection" | "session" | "service" | "permission" | "log" | "programLog"
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 4cf4967..4961418 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
@@ -25,7 +25,7 @@ import {
type Launch,
type Permission,
type PermissionName,
- type PermissionRequest,
+ type PermissionRequestInput,
type PermissionValue,
type ProgramIconSize,
type ServerLaunch,
@@ -38,6 +38,8 @@ import { isDesktopReplacementLayer, type DesktopReplacementLayer } from "@shared
import type { ServerRuntime, ServerRuntimeFactory } from "@server/core/server-runtime"
import SystemAccess from "./system-access"
import { WebSocket } from "ws"
+import { permissionCatalog } from "@server/core/permissions"
+import { defaultPermissionRequestTimeout } from "@server/core/permission-manager"
type SerializedClientLayer = DesktopReplacementLayer | "shell"
@@ -197,7 +199,7 @@ export default class ProcessManager extends TheLink {
}
/** Observe one authoritative host fact without creating a Program boundary. */
- public observeHost(domain: "program" | "process" | "window" | "connection" | "session" | "service", event: string, subject: string | null, subscriber: (event: string, ...values: unknown[]) => void) {
+ public observeHost(domain: "program" | "process" | "window" | "connection" | "session" | "service" | "permission", event: string, subject: string | null, subscriber: (event: string, ...values: unknown[]) => void) {
return this.hostTraffic.observe(domain, event, subject, (_delivery, word, ...values) => subscriber(word, ...values))
}
@@ -883,14 +885,26 @@ export default class ProcessManager extends TheLink {
() => this.endpointEvent("endpointStop", process, "server"),
- // A server crash invalidates the complete execution. Only the
+ // An unexpected server end invalidates the complete execution. Only the
// explicit server.stop() road may intentionally leave the client
// state alive without its server counterpart.
async () => {
if (explicitlyStopped) return
- await this.authManager.linkManager.application.dialogManager.serverCrashed(process, code, signal)
+ this.authManager.linkManager.application.logs.record(
+ "error",
+ "process",
+ "unexpectedServerEndpointExit",
+ unexpectedServerEndpointExitContent(process, code, signal),
+ {
+ program: { identity: process.program.identity, name: process.program.name },
+ process: { identity: process.identity, name: process.name },
+ endpoint: "server",
+ code,
+ signal
+ }
+ )
},
async () => {
@@ -928,12 +942,25 @@ export default class ProcessManager extends TheLink {
return server
}
- private serverHostVisible(process: Process, domain: "program" | "process" | "connection" | "session" | "service" | "window", subject: string | null) {
+ private serverHostVisible(process: Process, domain: "program" | "process" | "connection" | "session" | "service" | "window" | "permission" | "log" | "programLog", subject: string | null) {
const access = new SystemAccess(this, process)
if (domain === "connection" || domain === "session") return access.canAuthentication()
+ if (domain === "permission") return access.all()
+
+ if (domain === "log") return this.grants(process.identity, "logs", [])
+
+ if (domain === "programLog") {
+
+ if (!subject) return false
+
+ const program = [...this.authManager.programManager.programs.values()].find(entry => entry.program.reference === subject)?.program
+
+ return program ? access.canProgram(program) : false
+ }
+
if (!subject) return false
if (domain === "service") return this.grants(process.identity, "services", [subject])
@@ -1694,13 +1721,13 @@ export default class ProcessManager extends TheLink {
}
/** Announces one fact only through an authoritative Host registry. */
- public async announceHost(domain: "program" | "process" | "connection" | "session" | "service", event: string, subject: string, ...values: unknown[]) {
+ public async announceHost(domain: "program" | "process" | "connection" | "session" | "service" | "permission" | "log" | "programLog", event: string, subject: string, ...values: unknown[]) {
await this.hostTraffic.emitHost(domain, event, subject, ...values)
}
/** Announces one fact only to observers of an exact Program or Process subject. */
- public async announceSubject(domain: "program" | "process" | "connection" | "session" | "service", event: string, subject: string, ...values: unknown[]) {
+ public async announceSubject(domain: "program" | "process" | "connection" | "session" | "service" | "permission" | "log" | "programLog", event: string, subject: string, ...values: unknown[]) {
await this.hostTraffic.emitSubject(domain, event, subject, ...values)
}
@@ -1727,27 +1754,29 @@ export default class ProcessManager extends TheLink {
return this.authManager.programManager.grantsStorage(process.program, path, operation)
}
- /** Requests owner approval and replaces the authoritative stored permission. */
+ /** Requests one owner decision for the Program of an exact live Endpoint. */
public async requestPermission<Name extends PermissionName>(
identity: string,
- subject: unknown,
+ endpoint: "server" | "client",
request: string,
name: Name,
- input: PermissionRequest<Name>
+ input: PermissionRequestInput<Name>,
+ timeout: unknown
): Promise<Permission<Name>> {
const process = this.find(identity)
- const access = new SystemAccess(this, process)
- const program = access.program(this.system.holdProgram(subject, process.program))
+ const requested = permissionCatalog.resolve(name, input)
+ const duration = timeout === undefined ? defaultPermissionRequestTimeout : timeout
- return this.authManager.programManager.requestPermission(program, request, name, input, process)
- }
-
- public cancelPermission(identity: string, request: string) {
+ if (!Array.isArray(requested)) throw new Error("A permission request must be true or a list of values")
+ if (!request) throw new Error("A permission request needs a unique identity")
+ if (typeof duration !== "number" || !Number.isFinite(duration) || duration < 0) throw new Error("A permission timeout must be a non-negative finite number")
+ if (Number.isNaN(new Date(Date.now() + duration).getTime())) throw new Error("A permission request expiration is invalid")
- const process = this.processes.get(identity)
+ // An already-satisfied request has no pending lifecycle occurrence.
+ if (!permissionCatalog.changed(this.authManager.programManager.permission(process.program, name), requested)) return requested
- return process ? this.authManager.dialogManager.cancelPermission(request, process.reference) : Promise.resolve()
+ return this.authManager.permissionManager.request(process, endpoint, request, name, requested, duration)
}
// A window's news, said once and heard by both kinds of half.
@@ -1906,6 +1935,44 @@ export default class ProcessManager extends TheLink {
if (word === "current-program") return [this.system.requireProgram(process.program.identity)]
+ if (word === "context-permission-request") {
+
+ if (typeof rest[0] !== "string") throw new Error("A permission request needs a unique identity")
+
+ const permission = parsePermissionName(rest[1])
+
+ return [await this.requestPermission(
+ process.identity,
+ "server",
+ rest[0],
+ permission,
+ rest[2] as PermissionRequestInput<typeof permission>,
+ rest[3]
+ )]
+ }
+
+ if (word === "host-permission-requests") {
+
+ access.requireAll()
+
+ return [this.authManager.permissionManager.requests()]
+ }
+
+ if (typeof word === "string" && word.startsWith("permission-request-")) {
+
+ access.requireAll()
+
+ const operation = word.slice("permission-request-".length)
+
+ if (operation === "pending") return [this.authManager.permissionManager.pending(String(rest[0]))]
+ if (operation === "allow") await this.authManager.permissionManager.allow(rest[0])
+ else if (operation === "deny") await this.authManager.permissionManager.deny(rest[0])
+ else if (operation === "cancel") await this.authManager.permissionManager.cancel(rest[0])
+ else throw new Error(`The System does not know the PermissionRequest operation "${operation}"`)
+
+ return []
+ }
+
if (word === "program-permissions") {
const program = heldProgram(rest[0])
@@ -1918,7 +1985,7 @@ export default class ProcessManager extends TheLink {
const permission = parsePermissionName(rest[2])
- return [this.authManager.programManager.allowsPermission(program, permission, rest[3] as PermissionRequest<typeof permission>)]
+ return [this.authManager.programManager.allowsPermission(program, permission, rest[3] as PermissionRequestInput<typeof permission>)]
}
if (operation === "allow") {
@@ -1928,7 +1995,7 @@ export default class ProcessManager extends TheLink {
await this.authManager.programManager.setPermission(
program,
permission,
- rest[3] as PermissionRequest<typeof permission>
+ rest[3] as PermissionRequestInput<typeof permission>
)
return []
@@ -1940,20 +2007,6 @@ export default class ProcessManager extends TheLink {
return []
}
- if (operation === "request") {
-
- if (typeof rest[2] !== "string") throw new Error("A permission request needs a unique identity")
-
- const permission = parsePermissionName(rest[3])
-
- return [await this.authManager.programManager.requestPermission(
- program,
- rest[2],
- permission,
- rest[4] as PermissionRequest<typeof permission>,
- process
- )]
- }
throw new Error(`The System does not know the Program permission operation "${String(operation)}"`)
}
@@ -2605,6 +2658,13 @@ export default class ProcessManager extends TheLink {
return [this.system.programQuery(program, "logs", String(rest[1]), Array.isArray(rest[2]) ? rest[2] : [])]
}
+ if (word === "system-logs") {
+
+ access.require("logs", [])
+
+ return [this.authManager.linkManager.application.logs.query(String(rest[0]), Array.isArray(rest[1]) ? rest[1] : [])]
+ }
+
// A program's own database. Written as well as read, unlike the
// log above: that is the system's account of a program and this
// is the program's own, which is why they are two files.
@@ -2755,13 +2815,6 @@ export default class ProcessManager extends TheLink {
// wire carries one value, so the list is that value. A
// program's own endpoint answers a value directly; these are
// the two shapes and they meet here.
- if (args[0] === "program-permissions" && args[2] === "request" && typeof args[3] === "string") {
-
- // A timed SDK request forgets its transport question. Retain
- // the matching dialog cancellation at that same boundary.
- server.retain(question, () => { this.cancelPermission(process.identity, args[3] as string).catch(() => undefined) })
- }
-
const result = await this.endHost(process, server, args)
this.say(server, "host-end", "answer", question, succeeded(result))
@@ -3444,6 +3497,17 @@ function isHandleAddress(value: unknown): value is HandleAddress {
&& typeof value.identity === "string" && typeof value.reference === "string"
}
+function unexpectedServerEndpointExitContent(process: Process, code: number | null, signal: NodeJS.Signals | null) {
+
+ const endpoint = process.name ? `the “${process.name}” Process's server Endpoint` : "its server Endpoint"
+
+ if (signal) return `${process.program.name} stopped unexpectedly because ${endpoint} was terminated by ${signal}.`
+
+ if (code !== null) return `${process.program.name} stopped unexpectedly because ${endpoint} exited with code ${code}.`
+
+ return `${process.program.name} stopped because ${endpoint} ended unexpectedly.`
+}
+
function stringPath(value: unknown) {
if (!Array.isArray(value) || value.some(part => typeof part !== "string")) throw new Error("A Storage path is a list of names")
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 c0cfb7c..afbdee1 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
@@ -372,6 +372,9 @@ export default class ServerProcessBoundary extends TheLink {
: route === "host-connection" || route === "connection-host" ? "connection"
: route === "host-session" || route === "session-host" ? "session"
: route === "host-service" || route === "service-host" ? "service"
+ : route === "host-permission" || route === "permission-host" ? "permission"
+ : route === "host-log" ? "log"
+ : route === "program-log" ? "programLog"
: route === "host-end" ? "window"
: null
@@ -535,4 +538,4 @@ export type { Stream } from "@server/core/server-runtime"
export type Ending = (code: number | null, signal: NodeJS.Signals | null) => void
-export type HostVisibility = (domain: "program" | "process" | "connection" | "session" | "service" | "window", subject: string | null) => boolean
+export type HostVisibility = (domain: "program" | "process" | "connection" | "session" | "service" | "window" | "permission" | "log" | "programLog", subject: string | null) => boolean
diff --git a/source/server/core/link-manager/auth-manager/program-manager/logs.ts b/source/server/core/link-manager/auth-manager/program-manager/logs.ts
index 1a1871d..e6a76ed 100644
--- a/source/server/core/link-manager/auth-manager/program-manager/logs.ts
+++ b/source/server/core/link-manager/auth-manager/program-manager/logs.ts
@@ -1,6 +1,9 @@
import { DatabaseSync } from "node:sqlite"
import { existsSync, mkdirSync } from "node:fs"
import { dirname } from "node:path"
+import type { ProgramLogRecord } from "@phreshos/core"
+
+type Listener = (record: ProgramLogRecord) => unknown
/**
* What a program's halves have said, kept.
@@ -57,7 +60,7 @@ export default class Logs {
private since = 0
- public constructor(path: string) {
+ public constructor(path: string, private readonly listener?: Listener) {
this.path = path
}
@@ -189,7 +192,16 @@ export default class Logs {
const insert = database.prepare("insert into logs (createdAt, process, source, kind, content) values (?, ?, ?, ?, ?)")
- for (const [process, source, kind, content] of rows) insert.run(at, process, source, kind, content)
+ for (const [process, source, kind, content] of rows) {
+
+ const record = Object.freeze({ createdAt: at, process, source, kind, content }) satisfies ProgramLogRecord
+
+ insert.run(record.createdAt, record.process, record.source, record.kind, record.content)
+
+ try { this.listener?.(record) }
+
+ catch { /* One live listener cannot obstruct the durable log. */ }
+ }
this.since += rows.length
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 3a52f38..4445e18 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
@@ -25,7 +25,7 @@ import {
type Permission,
type PermissionInput,
type PermissionName,
- type PermissionRequest,
+ type PermissionRequestInput,
type PermissionValue,
type Permissions
} from "@phreshos/core"
@@ -189,7 +189,7 @@ export default class ProgramManager extends TheLink {
public allowsPermission<Name extends PermissionName>(
program: Program,
name: Name,
- input: PermissionRequest<Name> = true
+ input: PermissionRequestInput<Name> = true
) {
const requested = permissionCatalog.resolve(name, input)
@@ -273,39 +273,8 @@ export default class ProgramManager extends TheLink {
])
}
- /** Requests one owner decision for this target Program, independently of its initiator. */
- public async requestPermission<Name extends PermissionName>(
- program: Program,
- request: string,
- name: Name,
- input: PermissionRequest<Name>,
- process: Process | null = null
- ): Promise<Permission<Name>> {
-
- const requested = permissionCatalog.resolve(name, input)
-
- if (!Array.isArray(requested)) throw new Error("A permission request must be true or a list of values")
- if (!request) throw new Error("A permission request needs a unique identity")
-
- // A request asks for one exact canonical assignment. When effective
- // authority already equals it, no owner decision or state write exists
- // to perform; broader and narrower assignments remain distinct.
- if (!permissionCatalog.changed(this.permission(program, name), requested)) return requested
-
- const choice = await this.authManager.dialogManager.requestPermission(program, request, name, requested, process)
-
- if (choice === true) {
-
- await this.setPermission(program, name, requested)
-
- return requested
- }
-
- return choice
- }
-
@Subscribe("/permissions")
- protected async programPermissions(subject: unknown, operation: unknown, first?: unknown, second?: unknown, third?: unknown) {
+ protected async programPermissions(subject: unknown, operation: unknown, first?: unknown, second?: unknown) {
const program = this.held(subject)
@@ -315,13 +284,13 @@ export default class ProgramManager extends TheLink {
const permission = parsePermissionName(first)
- return this.allowsPermission(program, permission, second as PermissionRequest<typeof permission>)
+ return this.allowsPermission(program, permission, second as PermissionRequestInput<typeof permission>)
}
if (operation === "allow") {
const permission = parsePermissionName(first)
- await this.setPermission(program, permission, second as PermissionRequest<typeof permission>)
+ await this.setPermission(program, permission, second as PermissionRequestInput<typeof permission>)
return
}
@@ -331,29 +300,6 @@ export default class ProgramManager extends TheLink {
return
}
- if (operation === "request") {
-
- if (typeof first !== "string") throw new Error("A permission request needs a unique identity")
-
- const permission = parsePermissionName(second)
- const signal = this.authManager.connectionSignal()
- const cancel = () => { this.authManager.dialogManager.cancelPermission(first).catch(() => undefined) }
-
- signal.addEventListener("abort", cancel, { once: true })
-
- try {
- return await this.requestPermission(program, first, permission, third as PermissionRequest<typeof permission>)
- }
- finally {
- signal.removeEventListener("abort", cancel)
- }
- }
- if (operation === "cancel-request") {
-
- if (typeof first === "string") await this.authManager.dialogManager.cancelPermission(first)
-
- return
- }
throw new Error(`The System does not know the Program permission operation "${String(operation)}"`)
}
@@ -616,7 +562,14 @@ export default class ProgramManager extends TheLink {
if (already) return already
- const logs = new Logs(join(program.storagePath, "logs.sqlite"))
+ const logs = new Logs(join(program.storagePath, "logs.sqlite"), record => {
+
+ // Persistence owns the fact; the boundaries only forward the
+ // post-commit record to observers that are authorized to see it.
+ this.$outbound.publish("/log", program.reference, record).catch(() => undefined)
+
+ this.authManager.processManager.announceSubject("programLog", "log", program.reference, record).catch(() => undefined)
+ })
this.said.set(program.identity, logs)
diff --git a/source/server/core/logs.ts b/source/server/core/logs.ts
new file mode 100644
index 0000000..24c6888
--- /dev/null
+++ b/source/server/core/logs.ts
@@ -0,0 +1,209 @@
+import { DatabaseSync } from "node:sqlite"
+import { existsSync, mkdirSync } from "node:fs"
+import { dirname } from "node:path"
+import type { JsonValue, SystemLogLevel, SystemLogRecord } from "@phreshos/core"
+
+type Listener = (record: SystemLogRecord) => unknown
+
+/** Persistent System records and their live, post-commit event source. */
+export default class SystemLogs {
+
+ private writer: DatabaseSync | null = null
+
+ private ready = false
+
+ private readonly queued: PendingRecord[] = []
+
+ private scheduled = false
+
+ private since = 0
+
+ private readonly listeners = new Set<Listener>()
+
+ private static readonly keeps = 20_000
+
+ private static readonly sweepEvery = 500
+
+ public constructor(private readonly path: string) {}
+
+ /** Record one intentional System fact without making its producer wait. */
+ public record(level: SystemLogLevel, source: string, kind: string, content: string, data: JsonValue = null) {
+
+ this.queued.push({ level, source, kind, content, data })
+
+ if (this.scheduled) return
+
+ this.scheduled = true
+
+ queueMicrotask(() => {
+
+ this.scheduled = false
+
+ this.write(this.queued.splice(0))
+ })
+ }
+
+ /** Observe records only after they have become queryable. */
+ public subscribe(listener: Listener) {
+
+ this.listeners.add(listener)
+
+ return () => { this.listeners.delete(listener) }
+ }
+
+ public query(sql: string, values: unknown[] = []) {
+
+ if (!existsSync(this.path)) return []
+
+ if (!this.ready) {
+
+ const writable = new DatabaseSync(this.path)
+
+ try {
+
+ this.prepare(writable)
+
+ this.ready = true
+ }
+
+ finally { writable.close() }
+ }
+
+ const database = new DatabaseSync(this.path, { readOnly: true })
+
+ try { return database.prepare(sql).all(...values as never[]).map(row => ({ ...row })) }
+
+ finally { database.close() }
+ }
+
+ public close() {
+
+ const writer = this.writer
+
+ this.writer = null
+
+ this.ready = false
+
+ try { writer?.close() }
+
+ catch { /* Closing logs cannot obstruct System shutdown. */ }
+
+ this.queued.length = 0
+
+ this.scheduled = false
+
+ this.listeners.clear()
+ }
+
+ private open() {
+
+ if (this.writer) return this.writer
+
+ mkdirSync(dirname(this.path), { recursive: true })
+
+ const database = new DatabaseSync(this.path)
+
+ try {
+
+ database.exec("pragma journal_mode = wal")
+
+ this.prepare(database)
+ }
+
+ catch (exception) {
+
+ database.close()
+
+ throw exception
+ }
+
+ this.writer = database
+
+ this.ready = true
+
+ return database
+ }
+
+ private prepare(database: DatabaseSync) {
+
+ const columns = database.prepare("pragma table_info(logs)").all() as { name: string }[]
+
+ if (!columns.length) {
+
+ database.exec("create table logs (createdAt integer not null, level text not null, source text not null, kind text not null, content text not null, data text not null)")
+
+ database.exec("create index logs_level on logs (level)")
+
+ database.exec("create index logs_source on logs (source)")
+
+ return
+ }
+
+ const expected = ["createdAt", "level", "source", "kind", "content", "data"]
+
+ if (columns.map(column => column.name).join("\0") !== expected.join("\0")) throw new Error("The System logs database has an unsupported schema")
+
+ database.exec("create index if not exists logs_level on logs (level)")
+
+ database.exec("create index if not exists logs_source on logs (source)")
+ }
+
+ private write(rows: PendingRecord[]) {
+
+ if (!rows.length) return
+
+ try {
+
+ const database = this.open()
+
+ const insert = database.prepare("insert into logs (createdAt, level, source, kind, content, data) values (?, ?, ?, ?, ?, ?)")
+
+ for (const row of rows) {
+
+ const record = Object.freeze({ createdAt: Date.now(), ...row }) satisfies SystemLogRecord
+
+ insert.run(record.createdAt, record.level, record.source, record.kind, record.content, JSON.stringify(record.data))
+
+ for (const listener of this.listeners) {
+
+ try { listener(record) }
+
+ catch { /* One listener cannot obstruct persistence or another listener. */ }
+ }
+ }
+
+ this.since += rows.length
+
+ if (this.since >= SystemLogs.sweepEvery) this.sweep(database)
+ }
+
+ // System logs are best-effort. If their own storage fails, preserve the
+ // intended records on stderr without turning logging into System work.
+ catch (exception) {
+
+ for (const row of rows) {
+
+ try { process.stderr.write(`${JSON.stringify({ createdAt: Date.now(), ...row })}\n`) }
+
+ catch { /* No further logging path exists. */ }
+ }
+
+ void exception
+ }
+ }
+
+ private sweep(database: DatabaseSync) {
+
+ this.since = 0
+
+ database.prepare("delete from logs where rowid <= (select rowid from logs order by rowid desc limit 1 offset ?)").run(SystemLogs.keeps)
+ }
+}
+
+type PendingRecord = Readonly<{
+ level: SystemLogLevel
+ source: string
+ kind: string
+ content: string
+ data: JsonValue
+}>
diff --git a/source/server/core/permission-manager.ts b/source/server/core/permission-manager.ts
new file mode 100644
index 0000000..db431ad
--- /dev/null
+++ b/source/server/core/permission-manager.ts
@@ -0,0 +1,221 @@
+import { TheLink } from "@the-link/core"
+import { Subscribe } from "@the-link/core/decorators"
+import type {
+ Permission,
+ PermissionName,
+ PermissionRequestSnapshot,
+ PermissionScope
+} from "@phreshos/core"
+import type AuthManager from "./link-manager/auth-manager/auth-manager"
+import type Process from "./link-manager/auth-manager/process-manager/process"
+import { endpointReference } from "./link-manager/auth-manager/process-manager/endpoint-reference"
+
+export const defaultPermissionRequestTimeout = 120_000
+
+/** Authoritative lifecycle of pending permission decisions. */
+export default class PermissionManager extends TheLink {
+
+ private readonly pendingRequests = new Map<string, PendingPermissionRequest>()
+
+ public constructor(private readonly authManager: AuthManager) {
+
+ super()
+
+ this.connectTo(authManager, "/permission")
+ }
+
+ public requests() {
+
+ return [...this.pendingRequests.values()].map(request => request.snapshot)
+ }
+
+ public pending(identity: string) {
+
+ return this.pendingRequests.has(identity)
+ }
+
+ /** Creates one request whose lifetime belongs to its exact Endpoint incarnation. */
+ public async request<Name extends PermissionName>(
+ process: Process,
+ endpoint: "server" | "client",
+ identity: string,
+ name: Name,
+ scope: PermissionScope<Name>,
+ timeout: number
+ ): Promise<Permission<Name>> {
+
+ if (!identity || this.pendingRequests.has(identity)) throw new Error("A permission request needs a unique identity")
+ if (endpoint === "server" ? !process.server : !process.client) throw new Error("The requesting Endpoint is not running")
+ if (!Number.isFinite(timeout) || timeout < 0) throw new Error("A permission timeout must be a non-negative finite number")
+
+ const createdAt = new Date()
+ const expiresAt = new Date(createdAt.getTime() + timeout)
+
+ if (Number.isNaN(expiresAt.getTime())) throw new Error("A permission request expiration is invalid")
+
+ const snapshot = Object.freeze({
+ identity,
+ from: endpointReference(process, endpoint),
+ createdAt,
+ expiresAt: new Date(expiresAt),
+ name,
+ scope: Object.freeze([...scope])
+ }) satisfies PermissionRequestSnapshot<Name>
+
+ let settle: (permission: Permission<Name>) => void = () => undefined
+ const result = new Promise<Permission<Name>>(resolve => { settle = resolve })
+ const cancelEndpoint = endpoint === "server"
+ ? process.onServerStop(() => { this.cancel(identity).catch(() => undefined) })
+ : process.onClientStop(() => { this.cancel(identity).catch(() => undefined) })
+ this.pendingRequests.set(identity, {
+ process,
+ snapshot: snapshot as PermissionRequestSnapshot,
+ settle: settle as (permission: Permission) => void,
+ timer: null,
+ cancelEndpoint,
+ resolving: false
+ })
+
+ await Promise.all([
+ this.authManager.processManager.announceHost("permission", "request", process.program.identity, snapshot).catch(() => undefined),
+ this.$outbound.publish("/request", snapshot).catch(() => undefined)
+ ])
+
+ const pending = this.pendingRequests.get(identity)
+
+ // A request must become observable before its expiry can resolve it.
+ // Otherwise a zero-duration request can publish resolve before request.
+ if (pending) pending.timer = this.expire(identity, expiresAt)
+
+ return await result
+ }
+
+ @Subscribe("/pending")
+ protected requestPending(identity: unknown) {
+
+ return typeof identity === "string" && this.pending(identity)
+ }
+
+ @Subscribe("/allow")
+ public async allow(identity: unknown) {
+
+ const request = this.claim(identity)
+
+ try {
+ await this.authManager.programManager.setPermission(request.process.program, request.snapshot.name, request.snapshot.scope)
+ await this.finish(request, request.snapshot.scope)
+ }
+ catch (error) {
+ if (this.pendingRequests.get(request.snapshot.identity) === request) request.resolving = false
+ throw error
+ }
+ }
+
+ @Subscribe("/deny")
+ public async deny(identity: unknown) {
+
+ const request = this.claim(identity)
+
+ try {
+ await this.authManager.programManager.setPermission(request.process.program, request.snapshot.name, false)
+ await this.finish(request, false)
+ }
+ catch (error) {
+ if (this.pendingRequests.get(request.snapshot.identity) === request) request.resolving = false
+ throw error
+ }
+ }
+
+ @Subscribe("/cancel")
+ public async cancel(identity: unknown) {
+
+ const request = this.claim(identity)
+
+ try { await this.finish(request, null) }
+ catch (error) {
+ if (this.pendingRequests.get(request.snapshot.identity) === request) request.resolving = false
+ throw error
+ }
+ }
+
+ private claim(identity: unknown) {
+
+ const request = typeof identity === "string" ? this.pendingRequests.get(identity) : undefined
+
+ if (!request || request.resolving) throw new Error("The permission request does not exist")
+
+ if (request.snapshot.expiresAt.getTime() <= Date.now()) {
+ request.resolving = true
+ void this.finish(request, null)
+ throw new Error("The permission request does not exist")
+ }
+
+ // Claim synchronously before persistence or announcements so two
+ // terminal operations can never both mutate the same request.
+ request.resolving = true
+
+ return request
+ }
+
+ private async finish(request: PendingPermissionRequest, permission: Permission) {
+
+ if (!this.pendingRequests.delete(request.snapshot.identity)) throw new Error("The permission request does not exist")
+
+ if (request.timer) clearTimeout(request.timer)
+ request.cancelEndpoint()
+
+ await Promise.all([
+ this.authManager.processManager.announceHost(
+ "permission",
+ "resolve",
+ request.process.program.identity,
+ request.snapshot,
+ permission
+ ).catch(() => undefined),
+ this.authManager.processManager.announceSubject(
+ "permission",
+ "resolve",
+ request.snapshot.identity,
+ request.snapshot,
+ permission
+ ).catch(() => undefined),
+ this.$outbound.publish("/resolve", request.snapshot, permission).catch(() => undefined)
+ ])
+
+ request.settle(permission)
+ }
+
+ private expire(identity: string, expiresAt: Date): ReturnType<typeof setTimeout> {
+
+ const maximumDelay = 2_147_483_647
+ const remaining = expiresAt.getTime() - Date.now()
+
+ return setTimeout(() => {
+
+ if (remaining > maximumDelay) {
+
+ const request = this.pendingRequests.get(identity)
+
+ if (request) request.timer = this.expire(identity, expiresAt)
+ }
+
+ else this.cancel(identity).catch(() => undefined)
+ }, Math.max(0, Math.min(maximumDelay, remaining)))
+ }
+
+ public toJSON() {
+
+ return { requests: new Map(this.requests().map(request => [request.identity, request])) }
+ }
+}
+
+interface PendingPermissionRequest {
+ readonly process: Process
+ readonly snapshot: PermissionRequestSnapshot
+ readonly settle: (permission: Permission) => void
+ timer: ReturnType<typeof setTimeout> | null
+ readonly cancelEndpoint: () => void
+ resolving: boolean
+}
+
+export type PermissionManagerSnapshot = ReturnType<PermissionManager["toJSON"]>
diff --git a/source/server/core/permissions.ts b/source/server/core/permissions.ts
index 85dcc06..7525319 100644
--- a/source/server/core/permissions.ts
+++ b/source/server/core/permissions.ts
@@ -25,9 +25,6 @@ export class PermissionCatalog {
const rule = rules[name]
if (!rule || typeof rule !== "object") throw new Error(`Permission "${name}" needs a definition`)
- if (typeof rule.title !== "string" || !rule.title.trim()) throw new Error(`Permission "${name}" needs a title`)
- if (typeof rule.description !== "string" || !rule.description.trim()) throw new Error(`Permission "${name}" needs a description`)
-
let defaults: PermissionValue<typeof name>[]
try {
@@ -46,9 +43,7 @@ export class PermissionCatalog {
validated[name] = Object.freeze({
valueDomain: programPermissionCatalog[name],
- default: Object.freeze(defaults),
- title: rule.title,
- description: rule.description
+ default: Object.freeze(defaults)
})
}
@@ -217,8 +212,6 @@ type PermissionGrant = readonly string[] | false | null
type PermissionDefinition<Name extends PermissionName = PermissionName> = Readonly<{
valueDomain: PermissionValueDomain<Name>
default: readonly PermissionValue<Name>[]
- title: string
- description: string
}>
type PermissionDefinitions = Readonly<{
@@ -238,8 +231,6 @@ type PermissionRules = Readonly<{
type StoredDefinition = Readonly<{
valueDomain: PermissionValueDomain
default: readonly string[]
- title: string
- description: string
}>
function strings(value: unknown, subject: string): string[] {
@@ -276,61 +267,42 @@ function valueCovers(domain: PermissionValueDomain, grant: string, requested: st
return false
}
-/** The presentation and defaults for every Core-defined permission. */
+/** Authoritative defaults for every Core-defined permission. */
export const permissionCatalog = new PermissionCatalog({
all: {
- default: [],
- title: "All permissions",
- description: "Grant every available Program permission."
+ default: []
},
services: {
- default: [],
- title: "Services",
- description: "Access Services by their Process and Service name."
+ default: []
},
programs: {
- default: [],
- title: "Programs",
- description: "Access every Program or selected Programs."
+ default: []
},
layers: {
- default: [],
- title: "Window layers",
- description: "Select the under, over, wallpaper, and shell layers in Client Endpoint launches."
+ default: []
},
network: {
- default: [],
- title: "Network",
- description: "Use System networking with every request target or selected target scopes."
+ default: []
},
storage: {
- default: [],
- title: "Storage",
- description: "Use every native filesystem path or selected operation-and-path scopes."
+ default: []
},
uploads: {
- default: [],
- title: "Uploads",
- description: "Create values in the System uploads collection."
+ default: []
+ },
+ logs: {
+ default: []
},
appearance: {
- default: [],
- title: "Appearance",
- description: "Change the System Appearance."
+ default: []
},
desktopPreferences: {
- default: [],
- title: "Desktop preferences",
- description: "Change this Desktop's preferences."
+ default: []
},
desktopConnection: {
- default: [],
- title: "Desktop connection",
- description: "Access the browser Connection carrying this Desktop and its Session."
+ default: []
},
authentication: {
- default: [],
- title: "Authentication",
- description: "Access and manage owner authentication, browser Connections, and Sessions."
+ default: []
}
})
diff --git a/tests/client-permission-boundary.test.ts b/tests/client-permission-boundary.test.ts
index c001691..0ea1697 100644
--- a/tests/client-permission-boundary.test.ts
+++ b/tests/client-permission-boundary.test.ts
@@ -76,7 +76,7 @@ test("Program and Process discovery exposes only the accessible scope", async ()
await expect(answer("host-process-find", hidden.identity)).resolves.toEqual([expect.objectContaining({ identity: hidden.identity })])
})
-test("Program permission reads and requests require Program access while direct mutation alone requires all", async () => {
+test("Program permission reads require Program access while owner decisions require all", async () => {
let permissions: Permissions = { programs: ["outside"] }
const owner = program("owner")
Object.defineProperty(owner, "permissions", { get: () => permissions })
@@ -86,20 +86,17 @@ test("Program permission reads and requests require Program access while direct
const read = vi.fn(async (_address, operation: string) => operation === "all"
? { network: ["https://example.com"] }
: ["https://example.com"])
- const requestPermission = vi.fn(async () => ["https://example.com"])
const auth = {
programManager: { programs: new Map([[owner.identity, owner], [outside.identity, outside]]), permissions: read },
processManager: { processes: new Map([[current.identity, current]]) },
- grantsPermission: async (_pane: string, name: PermissionName, values: never[]) => permissionCatalog.allows(name, values, permissions),
- requestPermission
+ grantsPermission: async (_pane: string, name: PermissionName, values: never[]) => permissionCatalog.allows(name, values, permissions)
} as unknown as AuthManager
const answer = host(auth, current.identity, () => { throw new Error("unused viewport") }, () => null, moveCoordinates(), {} as never)
const target = { identity: outside.identity, reference: outside.reference }
await expect(answer("program-permissions", target, "get", "network")).resolves.toEqual([["https://example.com"]])
await expect(answer("program-permissions", target, "all")).resolves.toEqual([{ network: ["https://example.com"] }])
- await expect(answer("program-permissions", target, "request", "request", "network", ["https://example.com"])).resolves.toEqual([["https://example.com"]])
- expect(requestPermission).toHaveBeenCalledWith("current", target, "request", "network", ["https://example.com"])
+ await expect(answer("program-permissions", target, "request", "request", "network", ["https://example.com"])).rejects.toThrow("does not know")
await expect(answer("program-permissions", target, "allow", "network", ["https://example.com"])).rejects.toThrow("Execution is not permitted")
await expect(answer("program-permissions", target, "deny", "network")).rejects.toThrow("Execution is not permitted")
@@ -108,6 +105,74 @@ test("Program permission reads and requests require Program access while direct
await expect(answer("program-permissions", target, "deny", "network")).resolves.toEqual([])
})
+test("Program log access follows the Program handle while System logs require logs", async () => {
+ let permissions: Permissions = {}
+ const owner = program("owner")
+ Object.defineProperty(owner, "permissions", { get: () => permissions })
+ const outside = program("outside")
+ const current = process("current", owner)
+ const programLogs = vi.fn(async () => [{ kind: "stdout" }])
+ const systemLogs = vi.fn(async () => [{ kind: "system" }])
+ const auth = {
+ programManager: { programs: new Map([[owner.identity, owner], [outside.identity, outside]]), logs: programLogs },
+ processManager: { processes: new Map([[current.identity, current]]) },
+ logs: systemLogs,
+ grantsPermission: async (_pane: string, name: PermissionName, values: never[]) => permissionCatalog.allows(name, values, permissions)
+ } as unknown as AuthManager
+ const answer = host(auth, current.identity, () => { throw new Error("unused viewport") }, () => null, moveCoordinates(), {} as never)
+ const own = { identity: owner.identity, reference: owner.reference }
+ const other = { identity: outside.identity, reference: outside.reference }
+
+ await expect(answer("logs", own, "select * from logs", [])).resolves.toEqual([[{ kind: "stdout" }]])
+ await expect(answer("logs", other, "select * from logs", [])).rejects.toThrow("Program represented by this handle does not exist")
+ await expect(answer("system-logs", "select * from logs", [])).rejects.toThrow("Execution is not permitted")
+
+ permissions = { programs: [outside.identity] }
+ await expect(answer("logs", other, "select * from logs", [])).resolves.toEqual([[{ kind: "stdout" }]])
+ await expect(answer("system-logs", "select * from logs", [])).rejects.toThrow("Execution is not permitted")
+
+ permissions = { logs: [] }
+ await expect(answer("system-logs", "select * from logs", [])).resolves.toEqual([[{ kind: "system" }]])
+})
+
+test("a Client Context requests only for its own Endpoint Program", async () => {
+ const owner = program("owner")
+ const current = process("current", owner)
+ const requestPermission = vi.fn(async () => ["https://example.com"])
+ const auth = {
+ programManager: { programs: new Map([[owner.identity, owner]]) },
+ processManager: { processes: new Map([[current.identity, current]]) },
+ requestPermission
+ } as unknown as AuthManager
+ const answer = host(auth, current.identity, () => { throw new Error("unused viewport") }, () => null, moveCoordinates(), {} as never)
+ const timeout = 1_000
+
+ await expect(answer("context-permission-request", "request", "network", ["https://example.com"], timeout))
+ .resolves.toEqual([["https://example.com"]])
+ expect(requestPermission).toHaveBeenCalledWith("current", "request", "network", ["https://example.com"], timeout)
+})
+
+test("the system-wide permission registry requires all", async () => {
+ let permissions: Permissions = {}
+ const owner = program("owner")
+ Object.defineProperty(owner, "permissions", { get: () => permissions })
+ const current = process("current", owner)
+ const list = vi.fn(() => [{ identity: "request" }])
+ const auth = {
+ programManager: { programs: new Map([[owner.identity, owner]]) },
+ processManager: { processes: new Map([[current.identity, current]]) },
+ permissionManager: { list },
+ grantsPermission: async (_pane: string, name: PermissionName, values: never[]) => permissionCatalog.allows(name, values, permissions)
+ } as unknown as AuthManager
+ const answer = host(auth, current.identity, () => { throw new Error("unused viewport") }, () => null, moveCoordinates(), {} as never)
+
+ await expect(answer("host-permission-requests")).rejects.toThrow("Execution is not permitted")
+ expect(list).not.toHaveBeenCalled()
+
+ permissions = { all: [] }
+ await expect(answer("host-permission-requests")).resolves.toEqual([[{ identity: "request" }]])
+})
+
test.each([
{
owningProgram: "owner",
diff --git a/tests/client-system-access.test.ts b/tests/client-system-access.test.ts
index e772753..57c350a 100644
--- a/tests/client-system-access.test.ts
+++ b/tests/client-system-access.test.ts
@@ -65,6 +65,7 @@ test("client system access contract", async () => {
await assert.rejects(access.requireNetwork("https://api.example.com/v1/users"), /Execution is not permitted/)
await assert.rejects(access.requireStorage("/Users/person/Documents/report.txt", "read"), /Execution is not permitted/)
await assert.rejects(access.require("uploads", []), /Execution is not permitted/)
+ await assert.rejects(access.require("logs", []), /Execution is not permitted/)
await assert.rejects(access.require("appearance", []), /Execution is not permitted/)
await assert.rejects(access.require("desktopPreferences", []), /Execution is not permitted/)
await assert.rejects(access.require("desktopConnection", []), /Execution is not permitted/)
@@ -127,6 +128,11 @@ test("client system access contract", async () => {
await access.require("uploads", [])
await assert.rejects(access.requireAll(), /Execution is not permitted/)
+ permissions = { logs: [] }
+
+ await access.require("logs", [])
+ await assert.rejects(access.require("uploads", []), /Execution is not permitted/)
+
permissions = { network: ["https://*.example.com/v1/**"] }
await access.requireNetwork("https://api.example.com/v1/users")
@@ -157,6 +163,7 @@ test("client system access contract", async () => {
await access.requireNetwork("wss://events.example.com/socket")
await access.requireStorage("/any/native/path", "delete")
await access.require("uploads", [])
+ await access.require("logs", [])
await access.requireAll()
assert.equal(permissionChecks, 0)
diff --git a/tests/host-traffic.test.ts b/tests/host-traffic.test.ts
index 1420859..d4a72f6 100644
--- a/tests/host-traffic.test.ts
+++ b/tests/host-traffic.test.ts
@@ -10,6 +10,8 @@ test("host traffic contract", async () => {
const programProcess: unknown[][] = []
const hostConnection: unknown[][] = []
const ownSession: unknown[][] = []
+ const systemLogs: unknown[][] = []
+ const programLogs: unknown[][] = []
traffic.observe("program", "uninstall", null, (_delivery, event, ...values) => hostProgram.push([event, ...values]))
traffic.observe("program", "uninstall", "program-reference", (_delivery, event, ...values) => ownProgram.push([event, ...values]))
@@ -17,6 +19,8 @@ test("host traffic contract", async () => {
traffic.observe("process", "create", "program-reference", (_delivery, event, ...values) => programProcess.push([event, ...values]))
traffic.observe("connection", "create", null, (_delivery, event, ...values) => hostConnection.push([event, ...values]))
traffic.observe("session", "connectionAttach", "session-identity", (_delivery, event, ...values) => ownSession.push([event, ...values]))
+ traffic.observe("log", "log", null, (_delivery, event, ...values) => systemLogs.push([event, ...values]))
+ traffic.observe("programLog", "log", "program-reference", (_delivery, event, ...values) => programLogs.push([event, ...values]))
const program = { identity: "counter", reference: "program-reference" }
const process = { identity: "worker", reference: "process-reference" }
@@ -37,7 +41,11 @@ test("host traffic contract", async () => {
await traffic.emitHost("connection", "create", "connection-identity", { identity: "connection-identity" })
await traffic.emitSubject("session", "connectionAttach", "session-identity", { identity: "connection-identity" })
+ await traffic.emitHost("log", "log", "system", { kind: "started" })
+ await traffic.emitSubject("programLog", "log", "program-reference", { kind: "stdout" })
assert.deepEqual(hostConnection, [["create", "connection-identity", { identity: "connection-identity" }]])
assert.deepEqual(ownSession, [["connectionAttach", "session-identity", { identity: "connection-identity" }]])
+ assert.deepEqual(systemLogs, [["log", "system", { kind: "started" }]])
+ assert.deepEqual(programLogs, [["log", "program-reference", { kind: "stdout" }]])
}, 120_000)
diff --git a/tests/permission-requests.test.ts b/tests/permission-requests.test.ts
index 11b121f..c976229 100644
--- a/tests/permission-requests.test.ts
+++ b/tests/permission-requests.test.ts
@@ -2,119 +2,163 @@ import assert from "node:assert/strict"
import { mkdtempSync, rmSync } from "node:fs"
import { tmpdir } from "node:os"
import { join } from "node:path"
-import type { Permission, PermissionName, PermissionRequest } from "@phreshos/core"
+import { TheLink } from "@the-link/core"
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 ProcessManager from "@server/core/link-manager/auth-manager/process-manager/process-manager"
import Process from "@server/core/link-manager/auth-manager/process-manager/process"
+import ProcessManager from "@server/core/link-manager/auth-manager/process-manager/process-manager"
import Window from "@server/core/link-manager/auth-manager/process-manager/window"
import type HostTraffic from "@server/core/link-manager/auth-manager/process-manager/host-traffic"
import ProgramStateStorage from "@server/core/link-manager/auth-manager/program-manager/state"
+import PermissionManager from "@server/core/permission-manager"
import { test } from "vitest"
-test("permission requests contract", async () => {
- const temporary = mkdtempSync(join(tmpdir(), "phresh-permission-requests-"))
-
- try {
- const program = new Program({ identity: "example", storage: temporary, client: { location: "." } })
- let dialogs = 0
- let choice: boolean | null = null
- let whilePending: (() => void) | undefined
- let dialogProgram: Program | null = null
-
- const window = new Window()
- window.start({ title: "Client", header: true, layer: "window" }, { x: 0, y: 0 }, { width: 640, height: 480 }, 1, false)
- const process = new Process("process", null, program, {}, { server: null, client: null, options: {} }, null, {} as HostTraffic, window)
- process.startClient(false)
-
- const authManager = {
- dialogManager: {
- async requestPermission(target: Program) {
- dialogProgram = target
- dialogs++
- whilePending?.()
- return choice
- }
- }
- }
- const programManager = Object.assign(Object.create(ProgramManager.prototype), { authManager }) as ProgramManager
- const processManager = Object.assign(Object.create(ProcessManager.prototype), {
- authManager,
- processes: new Map([["process", process]])
- }) as ProcessManager
- Object.assign(authManager, { programManager, processManager })
-
- const request = <Name extends PermissionName>(name: Name, value: PermissionRequest<Name> = true) => (
- programManager.requestPermission(program, "request", name, value, process)
- )
- const stored = () => new ProgramStateStorage(program).permissions()
- const assign = <Name extends PermissionName>(name: Name, value: Exclude<Permission<Name>, null>) => (
- new ProgramStateStorage(program).setPermission(name, value)
- )
- // Stored authority never bypasses approval, even for a narrower request.
- assign("services", ["browser", "editor"])
- assert.equal(await request("services", ["browser"]), null)
- assert.equal(dialogs, 1)
- assert.deepEqual(stored(), { services: ["browser", "editor"] })
-
- choice = false
- assert.equal(await request("services", ["browser"]), false)
- assert.equal(dialogs, 2)
- assert.deepEqual(stored(), { services: ["browser", "editor"] })
-
- // Approval replaces the exact permission instead of widening or merging it.
- choice = true
- assert.deepEqual(await request("services", ["browser"]), ["browser"])
- assert.equal(dialogs, 3)
- assert.deepEqual(stored(), { services: ["browser"] })
-
- // Canonically equal authority already satisfies the request without an
- // owner decision, while array order has no permission meaning.
- choice = null
- assert.deepEqual(await request("services", ["browser"]), ["browser"])
- assert.equal(dialogs, 3)
- assign("services", ["editor", "browser"])
- assert.deepEqual(await request("services", ["browser", "editor"]), ["browser", "editor"])
- assert.equal(dialogs, 3)
-
- // A Program handle requests for its target; the initiating Process is
- // only the request lifetime owner and never retargets the assignment.
- choice = true
- const target = new Program({ identity: "target", storage: join(temporary, "target"), permissions: {}, server: { location: ".", command: "node server.js" } })
- assert.deepEqual(await programManager.requestPermission(target, "owner-request", "uploads", true), [])
- assert.equal(dialogProgram, target)
- assert.deepEqual(new ProgramStateStorage(target).permissions(), { uploads: [] })
- assert.equal(stored().uploads, undefined)
-
- // A concurrent edit cannot turn one approved request into a broader grant.
- whilePending = () => assign("services", ["editor"])
- assert.deepEqual(await request("services", ["browser"]), ["browser"])
- assert.deepEqual(stored(), { services: ["browser"] })
- whilePending = undefined
-
- // An exact assignment restricts a broader fallback grant. Otherwise an
- // approved narrowing request would change the file without changing authority.
- assign("all", [])
- assert.deepEqual(await request("network", ["https://api.example.com"]), ["https://api.example.com"])
- assert(programManager.grantsPermission(program, "network", ["https://api.example.com/v1"]))
- assert(!programManager.grantsPermission(program, "network", ["https://other.example.com"]))
-
- // Permission decisions read the authoritative stored state.
- const declared = new Program({ identity: "declared", storage: temporary, permissions: { programs: ["browser"] }, client: { location: "." } })
- new ProgramStateStorage(declared).setPermission("services", ["editor"])
- assert(!programManager.grantsPermission(declared, "services", ["browser"]))
- assert(programManager.grantsPermission(declared, "services", ["editor"]))
- const dialogsBeforeDeclaredMatch = dialogs
- assert.deepEqual(await programManager.requestPermission(declared, "declared-match", "programs", ["browser"]), ["browser"])
- assert.equal(dialogs, dialogsBeforeDeclaredMatch)
-
- assign("all", false)
- assert.deepEqual(await request("all"), [])
- await programManager.setPermission(program, "all", [])
- await programManager.setPermission(program, "all", false)
- assert.equal(programManager.permission(program, "all"), false)
- }
- finally {
- rmSync(temporary, { recursive: true, force: true })
- }
+test("permission request lifecycle belongs to one live Endpoint", async () => {
+ const temporary = mkdtempSync(join(tmpdir(), "phresh-permission-requests-"))
+
+ try {
+ const program = new Program({ identity: "example", storage: temporary, client: { location: "." } })
+ const window = new Window()
+ window.start({ title: "Client", header: true, layer: "window" }, { x: 0, y: 0 }, { width: 640, height: 480 }, 1, false)
+ const process = new Process("process", "main", program, {}, { server: null, client: null, options: {} }, null, {} as HostTraffic, window)
+ process.startClient(false)
+
+ const hostEvents: unknown[][] = []
+ const programManager = {
+ async setPermission(target: Program, name: string, permission: unknown) {
+ new ProgramStateStorage(target).setPermission(name as never, permission as never)
+ }
+ }
+ const processManager = {
+ async announceHost(...values: unknown[]) { hostEvents.push(values) },
+ async announceSubject(...values: unknown[]) { hostEvents.push(values) }
+ }
+ const authManager = Object.assign(new TheLink(), { programManager, processManager })
+ const manager = new PermissionManager(authManager as never)
+
+ const request = (identity: string, timeout = 10_000) => manager.request(
+ process,
+ "client",
+ identity,
+ "services",
+ ["browser"],
+ timeout
+ )
+
+ const allowed = request("allow")
+ const snapshot = manager.requests()[0]
+ assert.equal(snapshot.identity, "allow")
+ assert.equal(snapshot.from.kind, "client")
+ assert.equal(snapshot.from.process.identity, process.identity)
+ assert.equal(snapshot.from.process.program.identity, program.identity)
+ assert.deepEqual(snapshot.scope, ["browser"])
+ assert.equal(snapshot.expiresAt.getTime() - snapshot.createdAt.getTime(), 10_000)
+ assert(manager.pending("allow"))
+ await manager.allow("allow")
+ assert.deepEqual(await allowed, ["browser"])
+ assert.deepEqual(new ProgramStateStorage(program).permissions(), { services: ["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 })
+
+ const cancelled = request("cancel")
+ await manager.cancel("cancel")
+ assert.equal(await cancelled, null)
+ assert.deepEqual(new ProgramStateStorage(program).permissions(), { services: false })
+
+ const expired = request("timeout", 5)
+ assert.equal(await expired, null)
+ assert(!manager.pending("timeout"))
+
+ const raced = request("race")
+ const decisions = await Promise.allSettled([manager.allow("race"), manager.deny("race")])
+ 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"] })
+
+ const stopped = request("endpoint-stop")
+ process.stopClient()
+ assert.equal(await stopped, null)
+ assert(!manager.pending("endpoint-stop"))
+
+ assert(hostEvents.some(values => values[0] === "permission" && values[1] === "request"))
+ assert(hostEvents.some(values => values[0] === "permission" && values[1] === "resolve"))
+ }
+ finally {
+ rmSync(temporary, { recursive: true, force: true })
+ }
}, 120_000)
+
+test("an exact effective assignment creates no pending request", async () => {
+ const temporary = mkdtempSync(join(tmpdir(), "phresh-permission-exact-"))
+
+ try {
+ const program = new Program({ identity: "example", storage: temporary, client: { location: "." } })
+ const window = new Window()
+ window.start({ title: "Client", header: true, layer: "window" }, { x: 0, y: 0 }, { width: 640, height: 480 }, 1, false)
+ const process = new Process("process", null, program, {}, { server: null, client: null, options: {} }, null, {} as HostTraffic, window)
+ process.startClient(false)
+
+ const pending: unknown[][] = []
+ const authManager = {
+ programManager: { permission: () => ["browser"] },
+ permissionManager: {
+ request(...values: unknown[]) {
+ pending.push(values)
+ return Promise.resolve(["browser"])
+ }
+ }
+ }
+ const manager = Object.assign(Object.create(ProcessManager.prototype), {
+ authManager,
+ processes: new Map([[process.identity, process]])
+ }) as ProcessManager
+
+ await assert.rejects(manager.requestPermission(
+ process.identity,
+ "client",
+ "invalid-timeout",
+ "services",
+ ["browser"],
+ Number.MAX_VALUE
+ ), /expiration is invalid/)
+
+ await assert.doesNotReject(manager.requestPermission(
+ process.identity,
+ "client",
+ "exact",
+ "services",
+ ["browser"],
+ undefined
+ ))
+ assert.equal(pending.length, 0)
+
+ await manager.requestPermission(
+ process.identity,
+ "client",
+ "different",
+ "services",
+ ["editor"],
+ 1_000
+ )
+ assert.equal(pending.length, 1)
+ assert.equal(pending[0]?.at(-1), 1_000)
+
+ await manager.requestPermission(
+ process.identity,
+ "client",
+ "default",
+ "services",
+ ["editor"],
+ undefined
+ )
+ assert.equal(pending.at(-1)?.at(-1), 120_000)
+ }
+ finally {
+ rmSync(temporary, { recursive: true, force: true })
+ }
+})
diff --git a/tests/permissions.test.ts b/tests/permissions.test.ts
index e8cf8f2..33f6644 100644
--- a/tests/permissions.test.ts
+++ b/tests/permissions.test.ts
@@ -6,91 +6,62 @@ import { test } from "vitest"
test("permissions contract", async () => {
const catalog = new PermissionCatalog({
all: {
- default: [],
- title: "All permissions",
- description: "Grant every available Program permission."
+ default: []
},
services: {
- default: [],
- title: "Services",
- description: "Access Services without broader authority over their Programs."
+ default: []
},
programs: {
- default: [],
- title: "Programs",
- description: "Access every Program or selected Programs, including their Services."
+ default: []
},
layers: {
- default: [],
- title: "Window layers",
- description: "Select the under, over, wallpaper, and shell layers in Client Endpoint launches."
+ default: []
},
network: {
- default: [],
- title: "Network",
- description: "Use System networking with every request target or selected target scopes."
+ default: []
},
storage: {
- default: [],
- title: "Storage",
- description: "Use every native filesystem path or selected operation-and-path scopes."
+ default: []
},
uploads: {
- default: [],
- title: "Uploads",
- description: "Create values in the System uploads collection."
+ default: []
+ },
+ logs: {
+ default: []
},
appearance: {
- default: [],
- title: "Appearance",
- description: "Change the System Appearance."
+ default: []
},
desktopPreferences: {
- default: [],
- title: "Desktop preferences",
- description: "Change this Desktop's preferences."
+ default: []
},
desktopConnection: {
- default: [],
- title: "Desktop connection",
- description: "Access the browser Connection carrying this Desktop and its Session."
+ default: []
},
authentication: {
- default: [],
- title: "Authentication",
- description: "Access and manage owner authentication, browser Connections, and Sessions."
+ default: []
}
})
assert.deepEqual(catalog.definition("all"), {
valueDomain: "none",
- default: [],
- title: "All permissions",
- description: "Grant every available Program permission."
+ default: []
})
assert.deepEqual(catalog.definition("programs"), {
valueDomain: "program",
- default: [],
- title: "Programs",
- description: "Access every Program or selected Programs, including their Services."
+ default: []
})
assert.deepEqual(catalog.definition("network"), {
valueDomain: "network",
- default: [],
- title: "Network",
- description: "Use System networking with every request target or selected target scopes."
+ default: []
})
assert.deepEqual(catalog.definition("storage"), {
valueDomain: "storage",
- default: [],
- title: "Storage",
- description: "Use every native filesystem path or selected operation-and-path scopes."
+ default: []
})
assert.deepEqual(catalog.definition("uploads"), {
valueDomain: "none",
- default: [],
- title: "Uploads",
- description: "Create values in the System uploads collection."
+ default: []
})
assert.deepEqual(catalog.resolve("all", true), [])
assert.deepEqual(catalog.resolve("all", []), [])
@@ -163,9 +134,7 @@ test("permissions contract", async () => {
assert.throws(() => new PermissionCatalog({} as never), /needs a definition/)
assert.throws(() => new PermissionCatalog({
all: {
- default: ["unknown"],
- title: "All permissions",
- description: "Invalid default."
+ default: ["unknown"]
},
services: catalog.definition("services"),
programs: catalog.definition("programs"),
diff --git a/tests/system-logs.test.ts b/tests/system-logs.test.ts
new file mode 100644
index 0000000..2476410
--- /dev/null
+++ b/tests/system-logs.test.ts
@@ -0,0 +1,112 @@
+import assert from "node:assert/strict"
+import { mkdtempSync, rmSync } from "node:fs"
+import { tmpdir } from "node:os"
+import { join } from "node:path"
+import type { SystemLogRecord } from "@phreshos/core"
+import SystemLogs from "@server/core/logs"
+import ProgramLogs from "@server/core/link-manager/auth-manager/program-manager/logs"
+import { test } from "vitest"
+
+test("System logs become observable only after they are durable", async () => {
+ const directory = mkdtempSync(join(tmpdir(), "phresh-system-logs-"))
+ const logs = new SystemLogs(join(directory, "logs.sqlite"))
+ const received: SystemLogRecord[] = []
+
+ try {
+ logs.subscribe(record => received.push(record))
+
+ logs.record("error", "process", "unexpectedServerEndpointExit", "Counter stopped unexpectedly.", {
+ program: "counter",
+ process: "main"
+ })
+
+ assert.equal(received.length, 0)
+
+ await Promise.resolve()
+
+ assert.equal(received.length, 1)
+ assert.deepEqual(received[0], {
+ createdAt: received[0]?.createdAt,
+ level: "error",
+ source: "process",
+ kind: "unexpectedServerEndpointExit",
+ content: "Counter stopped unexpectedly.",
+ data: { program: "counter", process: "main" }
+ })
+
+ const rows = logs.query("select createdAt, level, source, kind, content, data from logs") as Record<string, unknown>[]
+
+ assert.deepEqual(rows, [{
+ createdAt: received[0]?.createdAt,
+ level: "error",
+ source: "process",
+ kind: "unexpectedServerEndpointExit",
+ content: "Counter stopped unexpectedly.",
+ data: JSON.stringify({ program: "counter", process: "main" })
+ }])
+
+ assert.throws(() => logs.query("delete from logs"))
+ } finally {
+ logs.close()
+ rmSync(directory, { recursive: true, force: true })
+ }
+})
+
+test("subscribing does not replay stored System logs", async () => {
+ const directory = mkdtempSync(join(tmpdir(), "phresh-system-logs-future-"))
+ const logs = new SystemLogs(join(directory, "logs.sqlite"))
+
+ try {
+ logs.record("info", "system", "started", "The System started.")
+ await Promise.resolve()
+
+ const received: SystemLogRecord[] = []
+ logs.subscribe(record => received.push(record))
+
+ assert.equal(received.length, 0)
+
+ logs.record("warning", "storage", "capacity", "Storage is nearing capacity.")
+ await Promise.resolve()
+
+ assert.equal(received.length, 1)
+ assert.equal(received[0]?.kind, "capacity")
+ } finally {
+ logs.close()
+ rmSync(directory, { recursive: true, force: true })
+ }
+})
+
+test("Program log listeners receive the record after its row is stored", async () => {
+ const directory = mkdtempSync(join(tmpdir(), "phresh-program-logs-live-"))
+ const received: { record: unknown, rows: unknown[] }[] = []
+ let logs!: ProgramLogs
+
+ logs = new ProgramLogs(join(directory, "logs.sqlite"), record => {
+ received.push({
+ record,
+ rows: logs.query("select process, source, kind, content from logs")
+ })
+ })
+
+ try {
+ logs.record("main", "client", "info", "ready")
+
+ assert.equal(received.length, 0)
+
+ await Promise.resolve()
+
+ assert.deepEqual(received, [{
+ record: {
+ createdAt: (received[0]?.record as { createdAt?: unknown }).createdAt,
+ process: "main",
+ source: "client",
+ kind: "info",
+ content: "ready"
+ },
+ rows: [{ process: "main", source: "client", kind: "info", content: "ready" }]
+ }])
+ } finally {
+ logs.close()
+ rmSync(directory, { recursive: true, force: true })
+ }
+})