Skip to content

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

Unify authentication domains and permission scope

zohayrslileh29f126b7b616
diff --git a/bun.lock b/bun.lock
index e5d0004..9a41567 100644
--- a/bun.lock
+++ b/bun.lock
@@ -18,7 +18,6 @@
"hono": "^4.13.2",
"keyv": "^5.6.0",
"motion": "^13.2.0",
- "node-rsa": "^2.0.0",
"react": "^19.2.8",
"react-dom": "^19.2.8",
"sharp": "^0.35.3",
@@ -243,8 +242,6 @@
"@msgpack/msgpack": ["@msgpack/[email protected]", "", {}, "sha512-47XIizs9XZXvuJgoaJUIE2lFoID8ugvc0jzSHP+Ptfk8nTbnR8g788wv48N03Kx0UkAv559HWRQ3yzOgzlRNUA=="],
- "@noble/hashes": ["@noble/[email protected]", "", {}, "sha512-oN+QwyX7VSHotibwubG3kpzbwKrfnyR6OOO+3Nk/53ADL7FmgHHz4TgrbaYKvvOw09u6QTx0oiH1cNCIOuN0CQ=="],
-
"@oxc-project/types": ["@oxc-project/[email protected]", "", {}, "sha512-nuhZIOLuI6TFQ32I/WnUx+SCPY7SdSKwgnFHydAuoS1+Z4BRcaP+RRJmGzl9lw+0OFF7UmaESf7KQRXaNLHypg=="],
"@phreshos/core": ["@phreshos/[email protected]", "", {}, "sha512-WRVvFag4L2c/ooflnbyrB3WmFROMF6yF6Cz3ABt0UeyEZ2UIccQHJR125OvM5imVJNv+buTZIryXA5yooMn21Q=="],
@@ -491,8 +488,6 @@
"node-releases": ["[email protected]", "", {}, "sha512-D9UOmYG3UH1V+ENW56t5QXBwJw1YEY18ruVeus89Rw+SyIgjPkCO84bRzO3uNIYosJbNwiabWVn48o3uJLjxFQ=="],
- "node-rsa": ["[email protected]", "", { "dependencies": { "@noble/hashes": "^2.2.0" } }, "sha512-7yfzccmBd5rm7pALJf709tPwLL987WvdT7LC/QK5Oxa5S2aabdBPjxRDxhWKkbfCc9/FiC82lwSc+ulGZHH44g=="],
-
"obug": ["[email protected]", "", {}, "sha512-4a+OsYv9UktOJKE+l1A4OufDgdRF9PifWj+tJnHURo/P+WOxpG4GzUFL9qCalmWauao6ogiG+QvnCovwPoyAWA=="],
"pathe": ["[email protected]", "", {}, "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w=="],
diff --git a/package.json b/package.json
index 85413d8..d265c6a 100644
--- a/package.json
+++ b/package.json
@@ -47,7 +47,6 @@
"hono": "^4.13.2",
"keyv": "^5.6.0",
"motion": "^13.2.0",
- "node-rsa": "^2.0.0",
"react": "^19.2.8",
"react-dom": "^19.2.8",
"sharp": "^0.35.3",
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 ad14217..29343c6 100644
--- a/source/client/core/link-manager/auth-manager/auth-manager.ts
+++ b/source/client/core/link-manager/auth-manager/auth-manager.ts
@@ -18,7 +18,7 @@ export default class AuthManager extends TheLink {
public readonly linkManager: LinkManager
- public readonly authorization: string
+ public readonly sessionToken: string
public readonly username: string | null
@@ -32,13 +32,13 @@ export default class AuthManager extends TheLink {
private readonly storageChanges = new StreamRelay("Storage changes", storageChange)
- public constructor(linkManager: LinkManager, authorization: string, payload: AuthManagerSnapshot) {
+ public constructor(linkManager: LinkManager, sessionToken: string, payload: AuthManagerSnapshot) {
super()
this.linkManager = linkManager
- this.authorization = authorization
+ this.sessionToken = sessionToken
this.username = payload.username
@@ -56,13 +56,29 @@ export default class AuthManager extends TheLink {
@Intercept("outbound")
protected authenticate(...values: unknown[]) {
- return [this.authorization, ...values]
+ return [this.sessionToken, ...values]
+ }
+
+ /** Explicitly ends the Session authorizing this Desktop connection. */
+ public async signOut() {
+
+ await this.$outbound.publishFirst("/session/sign-out-current")
+ }
+
+ public connection(operation: "current" | "list" | "find" | "state" | "session" | "sign-in", identity?: string) {
+
+ return this.$outbound.publishFirst(`/connection/${operation}`, ...(identity === undefined ? [] : [identity]))
+ }
+
+ public session(operation: "list" | "find" | "state" | "connections" | "sign-out", identity?: string) {
+
+ return this.$outbound.publishFirst(`/session/${operation}`, ...(identity === undefined ? [] : [identity]))
}
/** Emit one authorized private fact without creating a response path. */
public emit(event: string, ...values: unknown[]) {
- this.linkManager.emitToSession(`/auth${event}`, this.authorization, ...values)
+ this.linkManager.emitToSession(`/auth${event}`, this.sessionToken, ...values)
}
public async storage(operation: string, path: string[], input?: unknown) {
diff --git a/source/client/core/link-manager/link-manager.ts b/source/client/core/link-manager/link-manager.ts
index 1a84c95..c50967d 100644
--- a/source/client/core/link-manager/link-manager.ts
+++ b/source/client/core/link-manager/link-manager.ts
@@ -1,7 +1,7 @@
import { AuthManagerSnapshot } from "@server/core/link-manager/auth-manager/auth-manager"
import { LinkManagerSnapshot } from "@server/core/link-manager/link-manager"
import { type AuthenticationState } from "@server/core/authentication/authentication"
-import { type RegistrationResponse } from "@server/core/link-manager/link-manager"
+import { type SignUpResponse } from "@server/core/link-manager/link-manager"
import { type Appearance, type DesktopPreferences, type DesktopPreferencesUpdate } from "@phreshos/core"
import { Forward } from "@the-link/core/decorators"
import { TheLink } from "@the-link/core"
@@ -69,18 +69,18 @@ export default class LinkManager extends TheLink {
return await this.$outbound.publishFirst<AuthenticationState>("/owner/state")
}
- public async register(username: string, password: string) {
+ public async signUp(username: string, password: string) {
- return await this.$outbound.publishFirst<RegistrationResponse>("/owner/register", username, password)
+ return await this.$outbound.publishFirst<SignUpResponse>("/owner/sign-up", username, password)
}
public async signIn(username: string, password: string) {
- return await this.$outbound.publishFirst<string | false>("/owner/sign-in", username, password)
+ return await this.$outbound.publishFirst<boolean>("/owner/sign-in", username, password)
}
- public async sessionAuthenticate(authorization: string | null) {
+ public async sessionAuthenticate(token: string | null) {
- return await this.$outbound.publishFirst<[string, AuthManagerSnapshot] | false>("/session-authenticate", authorization)
+ return await this.$outbound.publishFirst<[string, AuthManagerSnapshot] | false>("/session-authenticate", token)
}
}
diff --git a/source/client/view/components/desktop-host/announcements.ts b/source/client/view/components/desktop-host/announcements.ts
index e7eee0d..2ac8eb7 100644
--- a/source/client/view/components/desktop-host/announcements.ts
+++ b/source/client/view/components/desktop-host/announcements.ts
@@ -12,6 +12,7 @@ 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 post = useCallback(function (program: string, route: string, ...message: unknown[]) {
@@ -27,6 +28,86 @@ export default function useAnnouncements(authManager: AuthManager, panes: Map<st
}, [authManager, panes, traffic])
+ const postVisible = useCallback(function (visible: (access: SystemAccess) => Promise<boolean>, route: string, ...message: unknown[]) {
+
+ for (const pane of panes.keys()) {
+
+ const access = new SystemAccess(authManager, pane)
+
+ visible(access).then(granted => {
+
+ if (granted) return traffic.emit(pane, route, ...message)
+ }).catch(() => undefined)
+ }
+
+ }, [authManager, panes, traffic])
+
+ const postConnection = useCallback(function (identity: string, route: string, ...message: unknown[]) {
+
+ postVisible(access => access.canConnection(identity), route, ...message)
+
+ }, [postVisible])
+
+ const postSession = useCallback(function (identity: string, route: string, ...message: unknown[]) {
+
+ postVisible(access => access.canSession(identity), route, ...message)
+
+ }, [postVisible])
+
+ authentication.useSubscribe("/connection/create", useCallback((value: unknown) => {
+
+ const identity = domainIdentity(value)
+ if (identity) postConnection(identity, "host-connection", "create", identity, value)
+ }, [postConnection]))
+ authentication.useSubscribe("/connection/disconnect", useCallback((value: unknown) => {
+
+ const identity = domainIdentity(value)
+ if (identity) postConnection(identity, "host-connection", "disconnect", identity, value)
+ }, [postConnection]))
+ authentication.useSubscribe("/connection/session-change", useCallback((value: unknown, session: unknown) => {
+
+ const identity = domainIdentity(value)
+ if (identity) postConnection(identity, "connection-host", "sessionChange", identity, session)
+ }, [postConnection]))
+ authentication.useSubscribe("/session/create", useCallback((value: unknown) => {
+
+ const identity = domainIdentity(value)
+ if (identity) postSession(identity, "host-session", "create", identity, value)
+ }, [postSession]))
+ authentication.useSubscribe("/session/connection-attach", useCallback((value: unknown, connection: unknown) => {
+
+ const session = domainIdentity(value)
+ const attached = domainIdentity(connection)
+ if (session && attached) postVisible(
+ async access => await access.canSession(session) && await access.canConnection(attached),
+ "session-host",
+ "connectionAttach",
+ session,
+ connection
+ )
+ }, [postVisible]))
+ authentication.useSubscribe("/session/connection-detach", useCallback((value: unknown, connection: unknown) => {
+
+ const session = domainIdentity(value)
+ const detached = domainIdentity(connection)
+ if (session && detached) postConnection(detached, "session-host", "connectionDetach", session, connection)
+ }, [postConnection]))
+ authentication.useSubscribe("/session/end", useCallback((value: unknown, reason: unknown, previousConnections: unknown) => {
+
+ const identity = domainIdentity(value)
+ if (!identity) return
+
+ const connections = Array.isArray(previousConnections)
+ ? previousConnections.map(domainIdentity).filter((entry): entry is string => entry !== null)
+ : []
+
+ const visible = async (access: SystemAccess) => await access.canSession(identity)
+ || await any(connections, connection => access.canConnection(connection))
+
+ postVisible(visible, "session-host", "end", identity, reason)
+ postVisible(visible, "host-session", "end", identity, value, reason)
+ }, [postVisible]))
+
processes.useSubscribe("/created", useCallback((payload: HostedProcessRecord | null) => {
if (!payload) return
@@ -34,7 +115,7 @@ export default function useAnnouncements(authManager: AuthManager, panes: Map<st
const record = processRecord(authManager, payload)
post(payload.program, "host-process", "create", payload.program, record)
- post(payload.program, "program-process", "create", program(authManager, payload.program).reference, record)
+ post(payload.program, "program-host", "processCreate", program(authManager, payload.program).reference, record)
}, [authManager, post]))
@@ -45,7 +126,7 @@ export default function useAnnouncements(authManager: AuthManager, panes: Map<st
const record = processRecord(authManager, payload)
post(payload.program, "host-process", "exit", payload.program, record, code, signal)
- post(payload.program, "program-process", "exit", program(authManager, payload.program).reference, record, code, signal)
+ post(payload.program, "program-host", "processExit", program(authManager, payload.program).reference, record, code, signal)
post(payload.program, "process-host", "exit", payload.reference, code, signal)
}, [authManager, post]))
@@ -90,6 +171,22 @@ export default function useAnnouncements(authManager: AuthManager, panes: Map<st
programs.useSubscribe("/forgotten", useCallback((entry: ProgramRecord | null) => programEvent("forget", entry), [programEvent]))
}
+function domainIdentity(value: unknown) {
+
+ if (!value || typeof value !== "object") return null
+
+ const identity = (value as { identity?: unknown }).identity
+
+ return typeof identity === "string" ? identity : null
+}
+
+async function any<Value>(values: readonly Value[], predicate: (value: Value) => Promise<boolean>) {
+
+ for (const value of values) if (await predicate(value)) return true
+
+ return false
+}
+
function processRecord(authManager: AuthManager, process: HostedProcessRecord) {
return sdkProcess(process, program(authManager, process.program))
diff --git a/source/client/view/components/desktop-host/host.ts b/source/client/view/components/desktop-host/host.ts
index 2fa9724..d28bb3f 100644
--- a/source/client/view/components/desktop-host/host.ts
+++ b/source/client/view/components/desktop-host/host.ts
@@ -162,6 +162,13 @@ export default function host(authManager: AuthManager, pane: string, viewport: (
// only because it was added on the other.
if (word === "current-process") return [record(process())]
+ if (word === "desktop-connection") {
+
+ await access.require("desktopConnection", [])
+
+ return [await authManager.connection("current")]
+ }
+
if (word === "host-program-list") {
const programs = [...programManager.programs.values()].filter(program => args[0] !== true || program.installed)
@@ -172,13 +179,68 @@ export default function host(authManager: AuthManager, pane: string, viewport: (
return [visible.map(sdkProgram)]
}
+ if (typeof word === "string" && word.startsWith("host-connection-")) {
+
+ const operation = word.slice("host-connection-".length) as "list" | "find" | "state" | "session" | "sign-in"
+
+ if (operation === "list") {
+
+ const connections = await authManager.connection("list") as { identity: string }[]
+
+ return [await access.connections(connections)]
+ }
+
+ const identity = String(args[0])
+
+ if (operation === "find") {
+
+ const connection = await authManager.connection("find", identity) as { identity: string } | null
+
+ return [connection && await access.canConnection(connection.identity) ? connection : null]
+ }
+
+ if (!await access.canConnection(identity)) throw new Error("Connection not found")
+
+ return [await authManager.connection(operation, identity)]
+ }
+
+ if (typeof word === "string" && word.startsWith("host-session-")) {
+
+ const operation = word.slice("host-session-".length) as "list" | "find" | "state" | "connections" | "sign-out"
+
+ if (operation === "list") {
+
+ const sessions = await authManager.session("list") as { identity: string }[]
+
+ return [await access.sessions(sessions)]
+ }
+
+ const identity = String(args[0])
+
+ if (operation === "find") {
+
+ const session = await authManager.session("find", identity) as { identity: string } | null
+
+ return [session && await access.canSession(session.identity) ? session : null]
+ }
+
+ if (!await access.canSession(identity)) throw new Error("Session not found")
+
+ if (operation === "connections") {
+
+ const connections = await authManager.session(operation, identity) as { identity: string }[]
+
+ return [await access.connections(connections)]
+ }
+
+ return [await authManager.session(operation, identity)]
+ }
+
if (word === "host-program-find") {
const program = programManager.programs.get(String(args[0]))
- if (program) await access.program(program)
-
- return [program ? sdkProgram(program) : null]
+ return [program && await access.canProgram(program) ? sdkProgram(program) : null]
}
if (word === "host-program-create" || word === "host-program-force-create") {
@@ -206,9 +268,7 @@ export default function host(authManager: AuthManager, pane: string, viewport: (
const found = processManager.processes.get(String(args[0]))
- if (found) await access.process(found)
-
- return [found ? record(found) : null]
+ return [found && await access.canProcess(found) ? record(found) : null]
}
if (word === "appearance") return [authManager.linkManager.appearance.value]
@@ -359,9 +419,7 @@ export default function host(authManager: AuthManager, pane: string, viewport: (
if (!target.parent) return [null]
- await access.process(target.parent)
-
- return [sdkProcess(target.parent, programOf(target.parent))]
+ return [await access.canProcess(target.parent) ? sdkProcess(target.parent, programOf(target.parent)) : null]
}
// A retained Process handle remains able to report its own ending.
@@ -377,7 +435,7 @@ export default function host(authManager: AuthManager, pane: string, viewport: (
}
// Every live Process belonging to one exact Program handle.
- if (word === "program-process-list") {
+ if (word === "program-processes") {
const program = await permittedProgram(args[0])
@@ -386,7 +444,7 @@ export default function host(authManager: AuthManager, pane: string, viewport: (
// One process of this program by immutable identity or by its
// living program-local name. An exact identity always wins.
- if (word === "program-process-find") {
+ if (word === "program-find-process") {
const program = await permittedProgram(args[0])
const wanted = String(args[1])
@@ -399,7 +457,7 @@ export default function host(authManager: AuthManager, pane: string, viewport: (
}
// Create another Process from one exact Program handle.
- if (word === "program-process-create") {
+ if (word === "program-create-process") {
const program = await permittedProgram(args[0])
const launch = await access.launch(args[1])
@@ -408,7 +466,7 @@ export default function host(authManager: AuthManager, pane: string, viewport: (
return [record(requireProcess(started))]
}
- if (word === "program-process-find-or-create") {
+ if (word === "program-find-or-create-process") {
const program = await permittedProgram(args[0])
const launch = await access.launch(args[1]) as Launch & { name: string }
@@ -420,7 +478,7 @@ export default function host(authManager: AuthManager, pane: string, viewport: (
// Every instance ended, the asker last. One implementation on the
// core serves this and a server half both.
- if (word === "program-process-exit-all") return [await processManager.exitAll((await permittedProgram(args[0])).identity, pane)]
+ if (word === "program-exit-processes") return [await processManager.exitAll((await permittedProgram(args[0])).identity, pane)]
if (word === "observe") {
@@ -451,7 +509,7 @@ export default function host(authManager: AuthManager, pane: string, viewport: (
if (!await access.canProcess(target)) {
- if (reportImpossible) throw new Error("Execution is not permitted")
+ if (reportImpossible) throw new Error("The desktop does not know this process")
return []
}
@@ -502,7 +560,7 @@ export default function host(authManager: AuthManager, pane: string, viewport: (
if (!await access.canProcess(target)) {
- if (reportImpossible) throw new Error("Execution is not permitted")
+ if (reportImpossible) throw new Error("The desktop does not know this process")
return []
}
@@ -595,18 +653,20 @@ export default function host(authManager: AuthManager, pane: string, viewport: (
if (word === "program-permissions") {
+ const program = await permittedProgram(args[0])
+
await access.requireAll()
const operation = args[1]
if (operation !== "all" && operation !== "get" && operation !== "allows" && operation !== "set" && operation !== "delete") throw new Error(`The System does not know the Program permission operation "${String(operation)}"`)
- if (operation === "all") return [await programManager.permissions(address(holdProgram(args[0])), operation)]
+ if (operation === "all") return [await programManager.permissions(address(program), operation)]
const permission = parsePermissionName(args[2])
if (operation === "allows") return [await programManager.permissions(
- address(holdProgram(args[0])),
+ address(program),
operation,
permission,
args[3] as PermissionRequest<typeof permission>
@@ -615,7 +675,7 @@ export default function host(authManager: AuthManager, pane: string, viewport: (
if (operation === "set") {
await programManager.permissions(
- address(holdProgram(args[0])),
+ address(program),
operation,
permission,
args[3] as Exclude<PermissionInput<typeof permission>, null>
@@ -624,7 +684,7 @@ export default function host(authManager: AuthManager, pane: string, viewport: (
return []
}
- await programManager.permissions(address(holdProgram(args[0])), operation, permission)
+ await programManager.permissions(address(program), operation, permission)
return []
}
@@ -891,7 +951,7 @@ export default function host(authManager: AuthManager, pane: string, viewport: (
if (!clientBody(args[3])) throw new Error("Writing takes bytes")
- if (operation === "append") await authManager.linkManager.application.storageAppend(request, args[3], authManager.authorization, controller.signal)
+ if (operation === "append") await authManager.linkManager.application.storageAppend(request, args[3], authManager.sessionToken, controller.signal)
else await authManager.linkManager.application.storageWrite(
@@ -899,7 +959,7 @@ export default function host(authManager: AuthManager, pane: string, viewport: (
args[3],
- authManager.authorization,
+ authManager.sessionToken,
controller.signal,
@@ -917,7 +977,7 @@ export default function host(authManager: AuthManager, pane: string, viewport: (
request,
- authManager.authorization,
+ authManager.sessionToken,
controller.signal,
@@ -1004,7 +1064,7 @@ export default function host(authManager: AuthManager, pane: string, viewport: (
if (writing) {
if (!clientBody(args[1])) throw new Error("Writing takes bytes")
- if (word === "host-storage-append") await authManager.linkManager.application.storageAppend(request, args[1], authManager.authorization, controller.signal)
+ if (word === "host-storage-append") await authManager.linkManager.application.storageAppend(request, args[1], authManager.sessionToken, controller.signal)
else await authManager.linkManager.application.storageWrite(
@@ -1012,7 +1072,7 @@ export default function host(authManager: AuthManager, pane: string, viewport: (
args[1],
- authManager.authorization,
+ authManager.sessionToken,
controller.signal,
@@ -1027,7 +1087,7 @@ export default function host(authManager: AuthManager, pane: string, viewport: (
request,
- authManager.authorization,
+ authManager.sessionToken,
controller.signal,
@@ -1124,7 +1184,7 @@ export default function host(authManager: AuthManager, pane: string, viewport: (
{ extension: description.extension, type: description.type },
- authManager.authorization,
+ authManager.sessionToken,
controller.signal
)
@@ -1163,7 +1223,7 @@ export default function host(authManager: AuthManager, pane: string, viewport: (
args[1] as ClientBody | null,
- authManager.authorization,
+ authManager.sessionToken,
controller.signal
)
diff --git a/source/client/view/components/desktop-host/system-access.ts b/source/client/view/components/desktop-host/system-access.ts
index 64d5c85..204c09a 100644
--- a/source/client/view/components/desktop-host/system-access.ts
+++ b/source/client/view/components/desktop-host/system-access.ts
@@ -1,7 +1,7 @@
import type AuthManager from "@client/core/link-manager/auth-manager/auth-manager"
import type Program from "@client/core/link-manager/auth-manager/program-manager/program"
import type Process from "@client/core/link-manager/auth-manager/process-manager/process"
-import { parseLaunch, type ClientLaunch, type PermissionName, type PermissionValue, type ServiceKey } from "@phreshos/core"
+import { parseLaunch, type ClientLaunch, type ConnectionSnapshot, type PermissionName, type PermissionValue, type ServiceKey } from "@phreshos/core"
const denied = "Execution is not permitted"
@@ -51,23 +51,61 @@ export default class SystemAccess {
return await this.authManager.grantsPermission(this.pane, "services", program === null ? [] : [program])
}
+ /** Whether one Connection belongs to this Client's visible scope. */
+ public async canConnection(identity: string) {
+
+ const scope = await this.connectionScope()
+
+ return scope === "all" || scope?.identity === identity
+ }
+
+ /** Whether one Session belongs to this Client's visible scope. */
+ public async canSession(identity: string) {
+
+ const scope = await this.connectionScope()
+
+ return scope === "all" || scope?.session === identity
+ }
+
+ /** Filters one Connection collection through a single authority snapshot. */
+ public async connections<Connection extends { identity: string }>(connections: readonly Connection[]) {
+
+ const scope = await this.connectionScope()
+
+ if (scope === "all") return [...connections]
+ if (scope === null) return []
+
+ return connections.filter(connection => connection.identity === scope.identity)
+ }
+
+ /** Filters one Session collection through a single authority snapshot. */
+ public async sessions<Session extends { identity: string }>(sessions: readonly Session[]) {
+
+ const scope = await this.connectionScope()
+
+ if (scope === "all") return [...sessions]
+ if (scope === null || scope.session === null) return []
+
+ return sessions.filter(session => session.identity === scope.session)
+ }
+
public async program(program: Program) {
- if (!await this.canProgram(program)) throw new Error(denied)
+ if (!await this.canProgram(program)) throw new Error("The Program represented by this handle does not exist")
return program
}
public async process<Subject extends Pick<Process, "program">>(process: Subject) {
- if (!await this.canProcess(process)) throw new Error(denied)
+ if (!await this.canProcess(process)) throw new Error("The Process represented by this handle does not exist")
return process
}
public async service(service: ServiceKey) {
- if (!await this.canService(service)) throw new Error(denied)
+ if (!await this.canService(service)) throw new Error("The Service represented by this key does not exist")
return service
}
@@ -119,6 +157,19 @@ export default class SystemAccess {
if (!await this.authManager.grantsPermission(this.pane, name, values)) throw new Error(denied)
}
+ private async currentConnection(): Promise<ConnectionSnapshot> {
+
+ return await this.authManager.connection("current") as ConnectionSnapshot
+ }
+
+ private async connectionScope(): Promise<"all" | ConnectionSnapshot | null> {
+
+ if (await this.authManager.grantsPermission(this.pane, "connections", [])) return "all"
+ if (!await this.authManager.grantsPermission(this.pane, "desktopConnection", [])) return null
+
+ return await this.currentConnection()
+ }
+
private owner() {
const process = this.authManager.processManager.processes.get(this.pane)
diff --git a/source/client/view/structure/authentication/authentication.tsx b/source/client/view/structure/authentication/authentication.tsx
index ca6559c..fdc4d8d 100644
--- a/source/client/view/structure/authentication/authentication.tsx
+++ b/source/client/view/structure/authentication/authentication.tsx
@@ -6,8 +6,8 @@ import useStorage from "@libs/storage-hook"
import useCleanup from "@libs/cleanup-hook"
import Desktop from "../desktop/desktop"
import SignIn from "./sign-in"
-import Register from "./register"
-import { useState, type ReactNode } from "react"
+import SignUp from "./sign-up"
+import { useEffect, useState, type ReactNode } from "react"
import { type AuthenticationState } from "@server/core/authentication/authentication"
import { WallpaperStage } from "../desktop/wallpaper/wallpaper"
import { useReady } from "@libs/readiness"
@@ -15,7 +15,7 @@ import { useAppearance, useThemedValue } from "@phreshos/react-ui"
export default function () {
- const authorization = useStorage("authorization")
+ const session = useStorage("session")
const linkManager = LinkManagerContext.useValue()
@@ -23,19 +23,41 @@ export default function () {
const [revision, setRevision] = useState(0)
+ useEffect(() => {
+
+ const signedIn = linkManager.$inbound.subscribe("/session/signed-in", token => {
+
+ if (typeof token === "string") session.update(token)
+ })
+
+ const signedOut = linkManager.$inbound.subscribe("/session/signed-out", () => session.remove())
+
+ return () => {
+
+ signedIn()
+ signedOut()
+ }
+
+ }, [linkManager, session])
+
const sessionAuthenticate = usePromise<SessionResolution>(async function () {
- const response = await linkManager.sessionAuthenticate(authorization.value)
+ const response = await linkManager.sessionAuthenticate(session.value)
+
+ if (!response) {
+
+ if (session.value !== null) session.remove()
- if (!response) return { kind: "anonymous", authentication: await linkManager.authenticationState() }
+ return { kind: "anonymous", authentication: await linkManager.authenticationState() }
+ }
- const [authorizationToken, payload] = response
+ const [sessionToken, payload] = response
- const authManager = new AuthManager(linkManager, authorizationToken, payload)
+ const authManager = new AuthManager(linkManager, sessionToken, payload)
return { kind: "authenticated", authManager }
- }, [authorization.value, revision])
+ }, [session.value, revision])
useCleanup(() => {
@@ -59,13 +81,13 @@ export default function () {
if (sessionAuthenticate.solve.kind === "anonymous") return <ReadySession>
- {sessionAuthenticate.solve.authentication.registered
+ {sessionAuthenticate.solve.authentication.signedUp
? <WallpaperStage file={signInWallpaper}><SignIn /></WallpaperStage>
: <WallpaperStage file={signInWallpaper}>
- <Register state={sessionAuthenticate.solve.authentication} onClosed={() => setRevision(value => value + 1)} />
+ <SignUp state={sessionAuthenticate.solve.authentication} onClosed={() => setRevision(value => value + 1)} />
</WallpaperStage>}
diff --git a/source/client/view/structure/authentication/credentials-form.tsx b/source/client/view/structure/authentication/credentials-form.tsx
index a3427b1..2cd1326 100644
--- a/source/client/view/structure/authentication/credentials-form.tsx
+++ b/source/client/view/structure/authentication/credentials-form.tsx
@@ -8,7 +8,7 @@ import { type SyntheticEvent } from "react"
import { ApplicationContext } from "../../contexts"
import SystemHeader from "../../components/system-header"
-/** The common username-and-password surface for registration and sign-in. */
+/** The common username-and-password surface for sign-up and sign-in. */
export default function CredentialsForm({ title, description, submitLabel, passwordAutocomplete, requirements, error, pending, onSubmit }: CredentialsFormProps) {
const reducedMotion = useReducedMotion()
diff --git a/source/client/view/structure/authentication/sign-in.tsx b/source/client/view/structure/authentication/sign-in.tsx
index 8af2da3..6dfdd13 100644
--- a/source/client/view/structure/authentication/sign-in.tsx
+++ b/source/client/view/structure/authentication/sign-in.tsx
@@ -1,21 +1,14 @@
import CredentialsForm from "./credentials-form"
import { LinkManagerContext } from "../../contexts"
import usePromise from "@libs/react-promise"
-import useStorage from "@libs/storage-hook"
export default function () {
- const authorization = useStorage("authorization")
-
const linkManager = LinkManagerContext.useValue()
const signIn = usePromise(async function (username: string, password: string) {
- const authorizationToken = await linkManager.signIn(username, password)
-
- if (authorizationToken) authorization.update(authorizationToken)
-
- return !!authorizationToken
+ return await linkManager.signIn(username, password)
})
return <CredentialsForm
diff --git a/source/client/view/structure/authentication/register.tsx b/source/client/view/structure/authentication/sign-up.tsx
similarity index 54%
rename from source/client/view/structure/authentication/register.tsx
rename to source/client/view/structure/authentication/sign-up.tsx
index b4ea61a..305b81d 100644
--- a/source/client/view/structure/authentication/register.tsx
+++ b/source/client/view/structure/authentication/sign-up.tsx
@@ -1,22 +1,17 @@
-import { type AuthenticationState, type RegistrationError } from "@server/core/authentication/authentication"
+import { type AuthenticationState, type SignUpError } from "@server/core/authentication/authentication"
import CredentialsForm from "./credentials-form"
import { LinkManagerContext } from "../../contexts"
import usePromise from "@libs/react-promise"
-import useStorage from "@libs/storage-hook"
-export default function Register({ state, onClosed }: RegisterProps) {
-
- const authorization = useStorage("authorization")
+export default function SignUp({ state, onClosed }: SignUpProps) {
const linkManager = LinkManagerContext.useValue()
- const registration = usePromise(async function (username: string, password: string) {
-
- const response = await linkManager.register(username, password)
+ const signUp = usePromise(async function (username: string, password: string) {
- if ("authorization" in response) authorization.update(response.authorization)
+ const response = await linkManager.signUp(username, password)
- else if (response.error === "registered") onClosed()
+ if ("error" in response && response.error === "signed-up") onClosed()
return "error" in response ? message(response.error, state) : null
})
@@ -27,26 +22,26 @@ export default function Register({ state, onClosed }: RegisterProps) {
description="Create the credentials for this system's sole owner."
- submitLabel="Register"
+ submitLabel="Sign up"
passwordAutocomplete="new-password"
requirements={state.requirements}
- error={registration.exception ? String(registration.exception.current) : registration.solve?.current}
+ error={signUp.exception ? String(signUp.exception.current) : signUp.solve?.current}
- pending={registration.isPending}
+ pending={signUp.isPending}
- onSubmit={registration.safeExecute}
+ onSubmit={signUp.safeExecute}
/>
}
-function message(error: RegistrationError, state: AuthenticationState) {
+function message(error: SignUpError, state: AuthenticationState) {
switch (error) {
- case "registered": return "Registration is already complete."
+ case "signed-up": return "Sign-up is already complete."
case "username-required": return "Enter a username."
@@ -60,7 +55,7 @@ function message(error: RegistrationError, state: AuthenticationState) {
}
}
-interface RegisterProps {
+interface SignUpProps {
state: AuthenticationState
diff --git a/source/client/view/structure/desktop/taskbar/system/sign-out.tsx b/source/client/view/structure/desktop/taskbar/system/sign-out.tsx
index c5eef2d..102f2d1 100644
--- a/source/client/view/structure/desktop/taskbar/system/sign-out.tsx
+++ b/source/client/view/structure/desktop/taskbar/system/sign-out.tsx
@@ -1,16 +1,21 @@
-import useStorage from "@libs/storage-hook"
+import { AuthManagerContext } from "@client/view/contexts"
+import usePromise from "@libs/react-promise"
import { ComponentProps, memo } from "react"
import TaskbarButton from "../taskbar-button"
export default memo(function (props: ComponentProps<typeof TaskbarButton>) {
- const authorization = useStorage("authorization")
+ const authManager = AuthManagerContext.useValue()
+
+ const signOut = usePromise(() => authManager.signOut())
return <TaskbarButton
aria-label="Sign out"
- onPress={authorization.remove}
+ disabled={signOut.isPending}
+
+ onPress={signOut.safeExecute}
{...props}
diff --git a/source/libs/encryptor.ts b/source/libs/encryptor.ts
deleted file mode 100644
index d8efd83..0000000
--- a/source/libs/encryptor.ts
+++ /dev/null
@@ -1,145 +0,0 @@
-/**
- * # Encryptor: Secure Token Generation and Verification System
- *
- * Encryptor provides RSA-based cryptographic utilities for creating and verifying
- * secure tokens. It extends NodeRSA to offer simplified token generation and validation
- * for authentication and authorization workflows.
- *
- * The system uses asymmetric cryptography for:
- * - Creating signed tokens containing arbitrary payloads
- * - Verifying token authenticity through signature validation
- * - Managing RSA key pairs with automatic key generation
- *
- * This implementation is ideal for stateless authentication systems, API authorization,
- * secure data exchange between services, or any scenario requiring cryptographic
- * verification of data integrity and origin.
- */
-import { readFile, writeFile } from "fs/promises"
-import { existsSync } from "node:fs"
-import NodeRSA from "node-rsa"
-
-/**
- * Cryptographic utility for token generation and verification using RSA.
- * Extends NodeRSA to provide higher-level functions for working with signed tokens
- * that can contain any serializable data payload.
- */
-export default class Encryptor extends NodeRSA {
-
- /**
- * Creates and initializes an Encryptor instance with an existing private key or generates a new one.
- * This factory method handles key generation, persistence, and instance creation in one operation.
- *
- * If a key exists at the specified path, it loads and uses that key.
- * If no key exists, it generates a new 2048-bit RSA key and saves it to the provided path.
- *
- * @param privateKeyPath The filesystem path where the private key is stored or should be created
- * @returns A configured Encryptor instance ready for token operations
- *
- * @example
- *
- * const encryptor = await Encryptor.initialize("/path/to/private-key.pem")
- * // The encryptor is now ready to create and verify tokens
- */
- public static async initialize(privateKeyPath: string) {
-
- let encryptor: Encryptor
-
- // Check if the private key file already exists
- if (existsSync(privateKeyPath)) {
-
- // Load the existing key from the file
- encryptor = new this(await readFile(privateKeyPath, "utf-8"))
- }
-
- else {
-
- // No key exists, so generate a new 2048-bit RSA key
- encryptor = new this({ b: 2048 })
-
- // Save the newly generated key to the specified path
- await writeFile(privateKeyPath, encryptor.exportKey("pkcs1-private-pem"))
- }
-
- // Return the configured encryptor instance
- return encryptor
- }
-
- /**
- * Creates a signed token containing the provided payload.
- * The token format follows a simplified JWT-like structure of "{encoded_payload}.{signature}"
- * where the payload is base64-encoded JSON and the signature is a base64-encoded RSA signature.
- *
- * This method:
- * 1. Serializes and encodes the payload
- * 2. Creates a cryptographic signature of the encoded payload
- * 3. Combines them into a portable, verifiable token string
- *
- * @param payload Any serializable data to include in the token
- * @returns A signed token string in the format "encoded_payload.signature"
- *
- * @example
- *
- * const token = encryptor.createToken({ userId: 123, role: "admin" })
- * // Returns a string like "eyJwYXlsb2FkIjp7InVzZX...FyTxp4n2K0="
- */
- public createToken(payload: unknown): string {
-
- // Serialize the payload to JSON and encode it to base64
- const encode = btoa(JSON.stringify({ payload }))
-
- // Generate a cryptographic signature for the encoded payload
- const signature = this.sign(encode, "base64")
-
- // Combine the encoded payload and signature with a dot separator
- return `${encode}.${signature}`
- }
-
- /**
- * Verifies a token's authenticity and extracts its payload.
- * This method validates that the token was created by a system with the corresponding private key
- * and has not been tampered with since creation.
- *
- * The verification process:
- * 1. Splits the token into payload and signature components
- * 2. Verifies the signature against the payload using RSA
- * 3. Decodes and deserializes the full token structure if verification succeeds
- *
- * @param token A token string previously generated by createToken()
- * @returns A Reference object containing the payload, or false if verification fails
- *
- * @example
- *
- * const result = encryptor.verifyToken<UserData>(token)
- * if (result) {
- * // result.payload contains the original data: { userId: 123, role: "admin" }
- * } else {
- * // Handle invalid token
- * }
- */
- public verifyToken<Payload>(token: string): Reference<Payload> | false {
-
- // Split the token into its two components: encoded payload and signature
- const [encode, signature] = token.split(".")
-
- // Convert the base64 signature to a Buffer for verification
- const bufferSignature = Buffer.from(signature, "base64")
-
- // Verify that the signature matches the encoded payload
- // If verification fails, return false to indicate an invalid token
- if (!this.verify(encode, bufferSignature)) return false
-
- return JSON.parse(atob(encode))
- }
-}
-
-/**
- * Represents the structure of a verified token containing the original payload.
- * This interface wraps the decoded token payload to maintain type safety
- * and provide a consistent return format from the verifyToken method.
- *
- * @template Payload The type of the original data that was encoded in the token
- */
-export interface Reference<Payload> {
- /** The original payload data that was encoded in the token */
- payload: Payload
-}
\ No newline at end of file
diff --git a/source/libs/sqlite-store.ts b/source/libs/sqlite-store.ts
index 294b405..69fcda6 100644
--- a/source/libs/sqlite-store.ts
+++ b/source/libs/sqlite-store.ts
@@ -62,6 +62,22 @@ export default class SqliteStore extends EventEmitter implements KeyvStoreAdapte
return this.database.prepare("select 1 from keyv where key = ?").get(key) !== undefined
}
+ public async *iterator<Value>(namespace = this.namespace) {
+
+ const prefix = namespace ? `${namespace}:` : ""
+
+ const rows = prefix
+
+ ? this.database.prepare("select key, value from keyv where substr(key, 1, ?) = ? order by key").all(prefix.length, prefix)
+
+ : this.database.prepare("select key, value from keyv order by key").all()
+
+ for (const row of rows as { key: string, value: string }[]) {
+
+ yield [row.key, row.value as Awaited<Value>] as Array<string | Awaited<Value> | undefined>
+ }
+ }
+
public async disconnect() {
this.database.close()
diff --git a/source/server/core/application.ts b/source/server/core/application.ts
index 436a98d..9e3a473 100644
--- a/source/server/core/application.ts
+++ b/source/server/core/application.ts
@@ -1,7 +1,6 @@
import LinkManager from "./link-manager/link-manager"
import Authentication from "./authentication/authentication"
import FileManager from "@libs/file-manager"
-import Encryptor from "@libs/encryptor"
import UploadManager from "./upload-manager"
import DialogManager from "./dialog-manager"
import AppearanceManager from "./appearance-manager"
@@ -32,8 +31,6 @@ export default class Application {
/** Internal application persistence, reached publicly through named methods. */
public readonly store: Keyv
- public readonly encryptor: Encryptor
-
public readonly authentication: Authentication
public readonly uploads: UploadManager
@@ -64,8 +61,6 @@ export default class Application {
this.home = payload.home
- this.encryptor = payload.encryptor
-
this.store = payload.store
this.authentication = payload.authentication
@@ -91,15 +86,13 @@ export default class Application {
const store = openStore(storage.path)
- const encryptor = await Encryptor.initialize(storage.join("private.pem"))
-
const authentication = await Authentication.open(storage.join("credentials.json"), store)
const uploads = new UploadManager(storage.navigateTo("uploads"))
const appearanceManager = await AppearanceManager.open(store, uploads)
- const application = new Application({ name, displayName, version, defaultProgramIcon, storage, home, store, encryptor, authentication, appearanceManager, uploads, createServerRuntime })
+ const application = new Application({ name, displayName, version, defaultProgramIcon, storage, home, store, authentication, appearanceManager, uploads, createServerRuntime })
await application.linkManager.authManager.programManager.initialize()
@@ -123,8 +116,6 @@ interface ApplicationPayload {
store: Keyv
- encryptor: Encryptor
-
authentication: Authentication
appearanceManager: AppearanceManager
diff --git a/source/server/core/authentication/authentication.ts b/source/server/core/authentication/authentication.ts
index fc20248..d7af87e 100644
--- a/source/server/core/authentication/authentication.ts
+++ b/source/server/core/authentication/authentication.ts
@@ -75,15 +75,15 @@ export default class Authentication {
return {
- registered: this.owner !== null,
+ signedUp: this.owner !== null,
requirements
}
}
- public async register(username: string, password: string): Promise<RegistrationResult> {
+ public async signUp(username: string, password: string): Promise<SignUpResult> {
- if (this.owner) return { error: "registered" }
+ if (this.owner) return { error: "signed-up" }
const normalizedUsername = normalizeUsername(username)
@@ -119,18 +119,18 @@ export default class Authentication {
this.owner = owner
- return { registered: true }
+ return { signedUp: true }
}
catch (exception) {
if (!isExisting(exception)) throw exception
- // Another registration won the exclusive write. Load that owner
+ // Another sign-up won the exclusive write. Load that owner
// before reporting the closed state so this instance cannot reopen it.
this.owner = parse(await readFile(this.path, "utf8"))
- return { error: "registered" }
+ return { error: "signed-up" }
}
}
@@ -151,16 +151,40 @@ export default class Authentication {
&& timingSafeEqual(candidate, expected)
}
- /** Creates a session with the authority assigned by its trusted boundary. */
- public createSession(owner = false) {
+ /** Creates a Session and returns its Client-owned raw token exactly once. */
+ public createSession() {
- return this.sessions.create(owner)
+ return this.sessions.create()
}
- /** Whether a valid session belongs to a trusted owner-local connection. */
- public sessionOwner(identity: string) {
+ /** Resolves one Client-owned raw token to a valid Session identity. */
+ public resolveSession(token: string) {
- return this.sessions.owner(identity)
+ return this.sessions.resolve(token)
+ }
+
+ /** Returns every valid browser Session identity. */
+ public sessionsList() {
+
+ return this.sessions.list()
+ }
+
+ /** Resolves one valid browser Session identity. */
+ public sessionFind(identity: string) {
+
+ return this.sessions.find(identity)
+ }
+
+ /** Publishes a newly delivered browser Session into the authoritative registry. */
+ public exposeSession(identity: string) {
+
+ return this.sessions.expose(identity)
+ }
+
+ /** Observes browser Sessions removed by disconnected-lifetime expiration. */
+ public onSessionExpire(listener: (identity: string) => void) {
+
+ return this.sessions.onExpire(listener)
}
/** Whether a session is still within its connection-bound lifetime. */
@@ -169,19 +193,19 @@ export default class Authentication {
return this.sessions.valid(identity)
}
- /** Attaches a live connection and renews the session without a timer. */
+ /** Attaches one live Connection to a Session. */
public connectSession(identity: string) {
- return this.sessions.connect(identity)
+ return this.sessions.attach(identity)
}
- /** Records when the final live connection to a session disappears. */
+ /** Detaches one live Connection and records its normal disconnection time. */
public disconnectSession(identity: string) {
- return this.sessions.disconnect(identity)
+ return this.sessions.detach(identity)
}
- /** Revokes a session explicitly when its owner signs out. */
+ /** Revokes a Session through an explicit sign-out operation. */
public removeSession(identity: string) {
return this.sessions.remove(identity)
@@ -193,7 +217,7 @@ function normalizeUsername(username: string) {
return username.trim().normalize("NFKC")
}
-function validate(username: string, password: string): RegistrationError | null {
+function validate(username: string, password: string): SignUpError | null {
const usernameLength = [...username].length
@@ -290,7 +314,7 @@ function isFileError(exception: unknown, code: string) {
export interface AuthenticationState {
- registered: boolean
+ signedUp: boolean
requirements: {
@@ -310,16 +334,16 @@ export interface AuthenticationState {
}
}
-export type RegistrationResult = {
+export type SignUpResult = {
- registered: true
+ signedUp: true
} | {
- error: RegistrationError
+ error: SignUpError
}
-export type RegistrationError = "registered" | "username-required" | "username-invalid" | "password-too-short" | "password-too-long" | "password-matches-username"
+export type SignUpError = "signed-up" | "username-required" | "username-invalid" | "password-too-short" | "password-too-long" | "password-matches-username"
interface Owner {
diff --git a/source/server/core/authentication/sessions.ts b/source/server/core/authentication/sessions.ts
index 0a9c23a..a656437 100644
--- a/source/server/core/authentication/sessions.ts
+++ b/source/server/core/authentication/sessions.ts
@@ -1,192 +1,293 @@
import Keyv from "keyv"
-import { randomUUID } from "node:crypto"
+import { createHash, randomBytes, randomUUID } from "node:crypto"
-const storageKey = "authentication:sessions"
+const storagePrefix = "authentication:sessions:"
-/** How long an authentication session survives without a live connection. */
+/** How long a Session remains valid without an attached Connection. */
export const disconnectedSessionLifetime = 24 * 60 * 60 * 1_000
-/**
- * Durable authentication sessions, independent of transient desktop links.
- *
- * A session remains valid while at least one connection holds it. Ordinary
- * sessions receive a reconnecting grace period; owner-local sessions are
- * removed with their final connection because no reusable token leaves that
- * boundary.
- */
+/** Persistent Session state and its transient live-connection count. */
export default class Sessions {
- private readonly store: Keyv
+ private readonly identities = new Map<string, StoredSession>()
- private readonly sessions: Map<string, StoredSession>
+ private readonly hashes = new Map<string, StoredSession>()
- private writing: Promise<unknown> = Promise.resolve()
+ private readonly expirationListeners = new Set<(identity: string) => void>()
- private constructor(store: Keyv, sessions: Map<string, StoredSession>) {
-
- this.store = store
-
- this.sessions = sessions
- }
+ private constructor(private readonly store: Keyv) {}
public static async open(store: Keyv) {
- const stored = parse(await store.get(storageKey))
-
- const now = Date.now()
+ if (!store.iterator) throw new Error("The System store cannot enumerate authentication Sessions")
- const sessions = new Map<string, StoredSession>()
+ const sessions = new Sessions(store)
- let changed = false
+ for await (const [key, value] of store.iterator(store.namespace)) {
- for (const record of stored) {
+ if (typeof key !== "string" || !key.startsWith(storagePrefix)) continue
- // No connections survive a host restart. A record that was live
- // when the host stopped becomes disconnected when this host opens.
- const disconnectedAt = record.disconnectedAt ?? now
+ const hash = key.slice(storagePrefix.length)
- if (disconnectedAt !== record.disconnectedAt) changed = true
+ const record = parse(value, hash)
- if (now - disconnectedAt > disconnectedSessionLifetime) {
+ if (sessions.expired(record, Date.now())) {
- changed = true
+ await store.delete(key)
continue
}
- const owner = record.owner === true
+ sessions.identities.set(record.identity, record)
+ sessions.hashes.set(record.hash, record)
+ }
+
+ return sessions
+ }
+
+ /** Creates one Session and returns the raw token exactly once. */
+ public async create(): Promise<CreatedSession> {
+
+ await this.prune()
- if (record.owner === undefined) changed = true
+ const token = randomBytes(32).toString("base64url")
- sessions.set(record.identity, { identity: record.identity, owner, disconnectedAt })
+ const record: StoredSession = {
+
+ identity: randomUUID(),
+
+ hash: hashToken(token),
+
+ exposed: false,
+
+ disconnectedAt: Date.now(),
+
+ connections: 0
}
- const opened = new Sessions(store, sessions)
+ this.identities.set(record.identity, record)
+ this.hashes.set(record.hash, record)
- if (changed) await opened.persist()
+ await this.persist(record)
- return opened
+ return { identity: record.identity, token }
}
- /** Creates a session which has not yet acquired a connection. */
- public async create(owner = false) {
+ /** Resolves a Client-owned raw token to a valid Session identity. */
+ public resolve(token: string) {
- this.prune(Date.now())
+ const record = this.hashes.get(hashToken(token))
- const identity = randomUUID()
+ if (!record || !this.valid(record.identity)) return null
- this.sessions.set(identity, { identity, owner, disconnectedAt: Date.now() })
+ return record.identity
+ }
+
+ /** Returns every valid browser Session. */
+ public list() {
- await this.persist()
+ return [...this.identities.values()]
- return identity
+ .filter(record => record.exposed && this.valid(record.identity))
+
+ .map(record => record.identity)
}
- /** Whether the session exists and has not exhausted its disconnected day. */
- public valid(identity: string) {
+ /** Resolves one valid browser Session by its public identity. */
+ public find(identity: string) {
- const session = this.sessions.get(identity)
+ const record = this.identities.get(identity)
- if (!session) return false
+ return record && record.exposed && this.valid(identity) ? identity : null
+ }
+
+ /** Makes one completely established browser Session publicly discoverable. */
+ public async expose(identity: string) {
+
+ const record = this.identities.get(identity)
+
+ if (!record || !this.valid(identity)) return false
+
+ record.exposed = true
+
+ await this.persist(record)
+
+ return true
+ }
- if (session.disconnectedAt === null || Date.now() - session.disconnectedAt <= disconnectedSessionLifetime) return true
+ /** Whether one Session still exists and can authorize a Connection. */
+ public valid(identity: string) {
+
+ const record = this.identities.get(identity)
+
+ if (!record) return false
- this.sessions.delete(identity)
+ if (this.validRecord(record, Date.now())) return true
- this.persist().catch(() => undefined)
+ this.forget(record)
+ this.expiredSession(record.identity)
+ this.store.delete(this.key(record.hash)).catch(() => undefined)
return false
}
- /** Whether this session represents a trusted owner-local connection. */
- public owner(identity: string) {
+ /** Observes browser Sessions removed by disconnected-lifetime expiration. */
+ public onExpire(listener: (identity: string) => void) {
- return this.valid(identity) && this.sessions.get(identity)!.owner
+ this.expirationListeners.add(listener)
+
+ return () => this.expirationListeners.delete(listener)
}
- /** Resumes a valid session and removes its disconnected deadline. */
- public async connect(identity: string) {
+ /** Attaches one live connection to a valid Session. */
+ public async attach(identity: string) {
if (!this.valid(identity)) return false
- const session = this.sessions.get(identity)!
-
- if (session.disconnectedAt === null) return true
+ const record = this.identities.get(identity)!
- session.disconnectedAt = null
+ record.connections += 1
+ record.disconnectedAt = null
- await this.persist()
+ await this.persist(record)
return true
}
- /** Starts the grace period after the session's final connection is lost. */
- public async disconnect(identity: string) {
+ /** Detaches one live connection and records the normal disconnection time. */
+ public async detach(identity: string) {
- const session = this.sessions.get(identity)
+ const record = this.identities.get(identity)
- if (!session) return
+ if (!record) return
- session.disconnectedAt = Date.now()
+ record.connections = Math.max(0, record.connections - 1)
+ record.disconnectedAt = record.connections === 0 ? Date.now() : null
- await this.persist()
+ await this.persist(record)
}
- /** Revokes a session immediately, independently of its connections. */
+ /** Permanently removes one Session. */
public async remove(identity: string) {
- if (!this.sessions.delete(identity)) return
+ const record = this.identities.get(identity)
- await this.persist()
+ if (!record) return false
+
+ this.forget(record)
+
+ await this.store.delete(this.key(record.hash))
+
+ return true
}
- private persist() {
+ private validRecord(record: StoredSession, now: number) {
- const snapshot = [...this.sessions.values()].map(session => ({ ...session }))
+ return record.connections > 0
- const writing = this.writing.catch(() => undefined).then(() => this.store.set(storageKey, snapshot))
+ || record.disconnectedAt === null
- this.writing = writing
+ || now - record.disconnectedAt <= disconnectedSessionLifetime
+ }
+
+ private expired(record: StoredSession, now: number) {
+
+ return record.connections === 0
- return writing
+ && record.disconnectedAt !== null
+
+ && now - record.disconnectedAt > disconnectedSessionLifetime
}
- private prune(now: number) {
+ private async prune() {
- for (const [identity, session] of this.sessions) {
+ const now = Date.now()
- if (session.disconnectedAt !== null && now - session.disconnectedAt > disconnectedSessionLifetime) this.sessions.delete(identity)
+ const expired = [...this.identities.values()].filter(record => this.expired(record, now))
+
+ for (const record of expired) {
+
+ this.forget(record)
+ this.expiredSession(record.identity)
}
+
+ await Promise.all(expired.map(record => this.store.delete(this.key(record.hash))))
+ }
+
+ private persist(record: StoredSession) {
+
+ if (!record.exposed) return Promise.resolve(true)
+
+ return this.store.set(this.key(record.hash), {
+
+ identity: record.identity,
+
+ disconnectedAt: record.disconnectedAt
+ })
+ }
+
+ private forget(record: StoredSession) {
+
+ this.identities.delete(record.identity)
+ this.hashes.delete(record.hash)
}
-}
-function parse(value: unknown): StoredSessionInput[] {
+ private expiredSession(identity: string) {
- if (value === undefined) return []
+ for (const listener of this.expirationListeners) listener(identity)
+ }
+
+ private key(hash: string) { return storagePrefix + hash }
+}
- if (!Array.isArray(value) || !value.every(isStoredSession)) throw new Error("The authentication sessions are invalid")
+function hashToken(token: string) {
- return value
+ return createHash("sha256").update(token).digest("base64url")
}
-function isStoredSession(value: unknown): value is StoredSessionInput {
+function parse(value: unknown, hash: string): StoredSession {
+
+ if (!value || typeof value !== "object") throw new Error("An authentication Session is invalid")
+
+ const record = value as { identity?: unknown, disconnectedAt?: unknown }
+
+ if (typeof record.identity !== "string"
+
+ || record.disconnectedAt !== null && (typeof record.disconnectedAt !== "number" || !Number.isFinite(record.disconnectedAt))) {
+
+ throw new Error("An authentication Session is invalid")
+ }
+
+ return {
+
+ identity: record.identity,
+
+ hash,
- if (!value || typeof value !== "object") return false
+ exposed: true,
- const record = value as Partial<StoredSessionInput>
+ disconnectedAt: record.disconnectedAt,
- return typeof record.identity === "string"
- && (record.owner === undefined || typeof record.owner === "boolean")
- && (record.disconnectedAt === null || typeof record.disconnectedAt === "number" && Number.isFinite(record.disconnectedAt))
+ connections: 0
+ }
}
interface StoredSession {
identity: string
- owner: boolean
+ hash: string
+
+ exposed: boolean
disconnectedAt: number | null
+
+ connections: number
}
-type StoredSessionInput = Omit<StoredSession, "owner"> & { owner?: boolean }
+export type CreatedSession = Readonly<{
+
+ identity: string
+
+ token: string
+}>
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 8da78e5..5957710 100644
--- a/source/server/core/link-manager/auth-manager/auth-manager.ts
+++ b/source/server/core/link-manager/auth-manager/auth-manager.ts
@@ -50,9 +50,9 @@ export default class AuthManager extends TheLink {
// What being authorized means, decided once. Every road in asks
// here: the link before it carries a message, and the uploads door
// before it accepts bytes.
- public verify(authorization: unknown) {
+ public verify(sessionToken: unknown) {
- const session = typeof authorization === "string" ? this.linkManager.resolveAuthorization(authorization) : null
+ const session = typeof sessionToken === "string" ? this.linkManager.resolveSessionToken(sessionToken) : null
if (!session) throw new Error("Unauthorized")
}
@@ -70,18 +70,22 @@ export default class AuthManager extends TheLink {
}
@Intercept("inbound")
- protected authenticate(authorization: string, ...values: unknown[]) {
+ protected authenticate(...values: unknown[]) {
- this.verify(authorization)
+ if (this.linkManager.connection().external) return values
- return values
+ const [sessionToken, ...authenticated] = values
+
+ this.verify(sessionToken)
+
+ return authenticated
}
// Writing a public value is authorized here; the uploads door is only the
// Client transport that brings its bytes to this operation.
- public async upload(authorization: unknown, content: ReadableStream<Uint8Array> | null, extension: string, signal?: AbortSignal) {
+ public async upload(sessionToken: unknown, content: ReadableStream<Uint8Array> | null, extension: string, signal?: AbortSignal) {
- this.verify(authorization)
+ this.verify(sessionToken)
const file = await this.uploads.write(extension, content, signal)
@@ -89,16 +93,16 @@ export default class AuthManager extends TheLink {
}
/** Perform a server-side request after the desktop door proves authorization. */
- public fetch(authorization: unknown, input: string | URL | Request, init?: RequestInit) {
+ public fetch(sessionToken: unknown, input: string | URL | Request, init?: RequestInit) {
- this.verify(authorization)
+ this.verify(sessionToken)
return fetch(input, init)
}
- public streamArea(authorization: unknown, program: unknown, area: "data" | "cache", path: string[], options: [offset?: number, length?: number] = []) {
+ public streamArea(sessionToken: unknown, program: unknown, area: "data" | "cache", path: string[], options: [offset?: number, length?: number] = []) {
- this.verify(authorization)
+ this.verify(sessionToken)
return this.programManager.streamArea(program, area, path, options)
}
@@ -222,6 +226,92 @@ export default class AuthManager extends TheLink {
return await this.updateAppearance(value)
}
+ @Connect("/session/sign-out-current")
+ protected async signOutCurrentSession() {
+
+ const session = this.linkManager.connection().session
+
+ if (!session) throw new Error("The Connection has no Session")
+
+ await this.linkManager.signOutSession(session)
+ }
+
+ @Connect("/connection/list")
+ protected async connections() {
+
+ return this.linkManager.application.system.listConnections()
+
+ .map(connection => this.linkManager.connectionSnapshot(connection))
+ }
+
+ @Connect("/connection/current")
+ protected async currentConnection() {
+
+ return this.linkManager.connectionSnapshot(this.linkManager.connection())
+ }
+
+ @Connect("/connection/find")
+ protected async connectionFind(identity: unknown) {
+
+ const connection = this.linkManager.application.system.findConnection(domainIdentity(identity, "Connection"))
+
+ return connection ? this.linkManager.connectionSnapshot(connection) : null
+ }
+
+ @Connect("/connection/state")
+ protected async connectionState(identity: unknown) {
+
+ return this.linkManager.application.system.connectionSnapshot(domainIdentity(identity, "Connection"))
+ }
+
+ @Connect("/connection/session")
+ protected async connectionSession(identity: unknown) {
+
+ return this.linkManager.application.system.connectionSession(domainIdentity(identity, "Connection"))
+ }
+
+ @Connect("/connection/sign-in")
+ protected async connectionSignIn(identity: unknown) {
+
+ return this.linkManager.application.system.signInConnection(domainIdentity(identity, "Connection"))
+ }
+
+ @Connect("/session/list")
+ protected async sessions() {
+
+ return this.linkManager.application.system.listSessions()
+
+ .map(identity => this.linkManager.sessionSnapshot(identity))
+ }
+
+ @Connect("/session/find")
+ protected async sessionFind(identity: unknown) {
+
+ const session = this.linkManager.application.system.findSession(domainIdentity(identity, "Session"))
+
+ return session ? this.linkManager.sessionSnapshot(session) : null
+ }
+
+ @Connect("/session/state")
+ protected async sessionState(identity: unknown) {
+
+ return this.linkManager.application.system.sessionSnapshot(domainIdentity(identity, "Session"))
+ }
+
+ @Connect("/session/connections")
+ protected async sessionConnections(identity: unknown) {
+
+ return this.linkManager.application.system.sessionConnections(domainIdentity(identity, "Session"))
+
+ .map(connection => this.linkManager.connectionSnapshot(connection))
+ }
+
+ @Connect("/session/sign-out")
+ protected async sessionSignOut(identity: unknown) {
+
+ return this.linkManager.application.system.signOutSession(domainIdentity(identity, "Session"))
+ }
+
/** Replace System Appearance through the authenticated boundary. */
public async updateAppearance(value: unknown) {
@@ -279,16 +369,16 @@ export default class AuthManager extends TheLink {
if (typeof request === "string" && typeof process === "string") await this.processManager.cancelPermission(process, request)
}
- public async writeArea(authorization: unknown, program: unknown, area: "data" | "cache", path: string[], content: ReadableStream<Uint8Array> | null, signal?: AbortSignal, overwrite = true) {
+ public async writeArea(sessionToken: unknown, program: unknown, area: "data" | "cache", path: string[], content: ReadableStream<Uint8Array> | null, signal?: AbortSignal, overwrite = true) {
- this.verify(authorization)
+ this.verify(sessionToken)
await this.programManager.writeArea(program, area, path, content, signal, overwrite)
}
- public async appendArea(authorization: unknown, program: unknown, area: "data" | "cache", path: string[], content: ReadableStream<Uint8Array> | null, signal?: AbortSignal) {
+ public async appendArea(sessionToken: unknown, program: unknown, area: "data" | "cache", path: string[], content: ReadableStream<Uint8Array> | null, signal?: AbortSignal) {
- this.verify(authorization)
+ this.verify(sessionToken)
await this.programManager.appendArea(program, area, path, content, signal)
}
@@ -298,7 +388,7 @@ export default class AuthManager extends TheLink {
// broadcast and would widen one frame's interest to every session.
public async publishToConnection(connectionIdentity: string, event: string, ...values: unknown[]) {
- const connection = this.linkManager.connections.get(connectionIdentity)
+ const connection = this.linkManager.findConnection(connectionIdentity)
if (!connection?.session) return
@@ -306,11 +396,11 @@ export default class AuthManager extends TheLink {
}
@Forward("outbound", undefined, "/auth")
- protected async broadcastToConnections(event: string, ...values: unknown[]) {
+ protected async broadcastToAuthorizedBoundaries(event: string, ...values: unknown[]) {
- for (const connection of this.linkManager.connections.values()) {
+ for (const connection of this.linkManager.boundaries.values()) {
- if (!connection.session) continue
+ if (!connection.external && !connection.session) continue
await connection.link.$outbound.publish(event, ...values)
}
@@ -348,6 +438,13 @@ function storageListOptions(value: unknown) {
return { recursive: options.recursive === true, depth: options.depth as number | undefined }
}
+function domainIdentity(value: unknown, domain: "Connection" | "Session") {
+
+ if (typeof value !== "string") throw new Error(`A ${domain} identity is required`)
+
+ return value
+}
+
function storageWatchTarget(value: unknown) {
if (!value || typeof value !== "object") throw new Error("A Storage watch target is required")
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 7abba4e..38babd6 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"
+type Domain = "program" | "process" | "window" | "connection" | "session"
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 12435f8..64232ae 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
@@ -177,7 +177,7 @@ export default class ProcessManager extends TheLink {
}
/** Observe one authoritative host fact without creating a Program boundary. */
- public observeHost(domain: "program" | "process" | "window", event: string, subject: string | null, subscriber: (event: string, ...values: unknown[]) => void) {
+ public observeHost(domain: "program" | "process" | "window" | "connection" | "session", event: string, subject: string | null, subscriber: (event: string, ...values: unknown[]) => void) {
return this.hostTraffic.observe(domain, event, subject, (_delivery, word, ...values) => subscriber(word, ...values))
}
@@ -378,7 +378,7 @@ export default class ProcessManager extends TheLink {
private ownClient(connection: string, pane: string, owner: string) {
- if (!this.authManager.linkManager.connections.has(connection) || !this.processes.get(pane)?.client) return
+ if (!this.authManager.linkManager.boundaries.has(connection) || !this.processes.get(pane)?.client) return
const key = this.clientOwnerKey(connection, pane)
@@ -1010,7 +1010,12 @@ export default class ProcessManager extends TheLink {
//
// An unscoped listener — `host` — is built for no subject and so
// receives the subject as its first value.
- await this.announce("process", "create", program.identity, program.reference, processReference(process))
+ await Promise.all([
+
+ this.announceHost("process", "create", program.identity, processReference(process)),
+
+ this.announceSubject("program", "processCreate", program.reference, processReference(process))
+ ])
await this.$outbound.publish("/created", process.hosted())
@@ -1099,7 +1104,12 @@ export default class ProcessManager extends TheLink {
// the process, whole, not an identity a listener would have to look
// up. It is already gone, which is what `exited()` answers and
// why holding it is legitimate.
- () => this.announce("process", "exit", process.program.identity, process.program.reference, processReference(process), code, signal),
+ () => Promise.all([
+
+ this.announceHost("process", "exit", process.program.identity, processReference(process), code, signal),
+
+ this.announceSubject("program", "processExit", process.program.reference, processReference(process), code, signal)
+ ]),
// The same ending, said to whoever holds this one process rather
// than to whoever watches the program. A launcher wants the
@@ -1538,21 +1548,14 @@ export default class ProcessManager extends TheLink {
this.authManager.programManager.record(process.program, process.identity, "client", kind, content)
}
- // Host facts enter only the Process boundaries whose endpoint subscriptions
- // established a matching the-link route.
- public async announce(domain: "program" | "process", event: string, publicSubject: string, scopedSubject: string, ...values: unknown[]) {
-
- await this.hostTraffic.emit(domain, event, publicSubject, scopedSubject, ...values)
- }
-
/** Announces one fact only through an authoritative Host registry. */
- public async announceHost(domain: "program" | "process", event: string, subject: string, ...values: unknown[]) {
+ public async announceHost(domain: "program" | "process" | "connection" | "session", 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", event: string, subject: string, ...values: unknown[]) {
+ public async announceSubject(domain: "program" | "process" | "connection" | "session", event: string, subject: string, ...values: unknown[]) {
await this.hostTraffic.emitSubject(domain, event, subject, ...values)
}
@@ -1656,6 +1659,53 @@ export default class ProcessManager extends TheLink {
if (word === "host-program-list") return [this.system.listPrograms(rest[0] === true)]
+ if (typeof word === "string" && (word.startsWith("host-connection-") || word.startsWith("host-session-"))) {
+
+ if (word === "host-connection-list") {
+
+ return [this.system.listConnections().map(connection => this.authManager.linkManager.connectionSnapshot(connection))]
+ }
+
+ if (word === "host-connection-find") {
+
+ const connection = this.system.findConnection(String(rest[0]))
+
+ return [connection ? this.authManager.linkManager.connectionSnapshot(connection) : null]
+ }
+
+ if (word === "host-connection-state") return [this.system.connectionSnapshot(String(rest[0]))]
+
+ if (word === "host-connection-session") return [this.system.connectionSession(String(rest[0]))]
+
+ if (word === "host-connection-sign-in") return [await this.system.signInConnection(String(rest[0]))]
+
+ if (word === "host-session-list") {
+
+ return [this.system.listSessions().map(identity => this.authManager.linkManager.sessionSnapshot(identity))]
+ }
+
+ if (word === "host-session-find") {
+
+ const session = this.system.findSession(String(rest[0]))
+
+ return [session ? this.authManager.linkManager.sessionSnapshot(session) : null]
+ }
+
+ if (word === "host-session-state") return [this.system.sessionSnapshot(String(rest[0]))]
+
+ if (word === "host-session-connections") {
+
+ return [this.system.sessionConnections(String(rest[0])).map(connection => this.authManager.linkManager.connectionSnapshot(connection))]
+ }
+
+ if (word === "host-session-sign-out") {
+
+ await this.system.signOutSession(String(rest[0]))
+
+ return []
+ }
+ }
+
if (word === "host-program-find") {
const identity = String(rest[0])
@@ -1728,7 +1778,7 @@ export default class ProcessManager extends TheLink {
return [await this.system.programStartup(program, String(rest[1]), rest[2])]
}
- // Which exact process made this one through `program.process.create()`.
+ // Which exact process made this one through `program.createProcess()`.
// Parentage is immutable lineage; liveness belongs to the returned
// Process handle rather than to this relationship.
if (word === "parent") {
@@ -1786,7 +1836,7 @@ export default class ProcessManager extends TheLink {
return [await this.system.forgetProgram(program, process.identity)]
}
- if (word === "program-process-create") {
+ if (word === "program-create-process") {
const program = this.system.holdProgram(rest[0])
@@ -1798,7 +1848,7 @@ export default class ProcessManager extends TheLink {
return [processReference(this.system.requireProcess(await this.system.createProcess(program, rest[1] as Launch, process)))]
}
- if (word === "program-process-find-or-create") {
+ if (word === "program-find-or-create-process") {
const program = this.system.holdProgram(rest[0])
@@ -1806,7 +1856,7 @@ export default class ProcessManager extends TheLink {
}
// Named, only that program's instances; unnamed, every one.
- if (word === "host-process-list" || word === "program-process-list") {
+ if (word === "host-process-list" || word === "program-processes") {
const living = this.system.listProcesses()
@@ -1823,7 +1873,7 @@ export default class ProcessManager extends TheLink {
return [this.system.listProcesses(program).map(processReference)]
}
- if (word === "program-process-find") {
+ if (word === "program-find-process") {
const program = this.system.holdProgram(rest[0])
@@ -2054,7 +2104,7 @@ export default class ProcessManager extends TheLink {
return [target.identity]
}
- if (word === "program-process-exit-all") return [await this.system.exitProgramProcesses(this.system.holdProgram(rest[0]), process.identity)]
+ if (word === "program-exit-processes") return [await this.system.exitProgramProcesses(this.system.holdProgram(rest[0]), process.identity)]
if (word === "observe") {
diff --git a/source/server/core/link-manager/auth-manager/process-manager/process.ts b/source/server/core/link-manager/auth-manager/process-manager/process.ts
index 04ca633..14a1b66 100644
--- a/source/server/core/link-manager/auth-manager/process-manager/process.ts
+++ b/source/server/core/link-manager/auth-manager/process-manager/process.ts
@@ -65,7 +65,7 @@ export default class Process {
// lifetime originate here. Stopping the client destroys this value whole.
public client: ClientState | null = null
- // The process whose call to `program.process.create()` created this
+ // The process whose call to `program.createProcess()` created this
// one. Lineage only: keeping this handle neither owns nor prolongs
// either life.
public readonly parent: Process | null
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 2747ccd..f86de9a 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
@@ -350,9 +350,11 @@ export default class ServerProcessBoundary extends TheLink {
}
const hostDomain = route === "host-program" || route === "program-host" ? "program"
- : route === "host-process" || route === "program-process" || route === "process-host" ? "process"
- : route === "host-end" ? "window"
- : null
+ : route === "host-process" || route === "process-host" ? "process"
+ : route === "host-connection" || route === "connection-host" ? "connection"
+ : route === "host-session" || route === "session-host" ? "session"
+ : route === "host-end" ? "window"
+ : null
if (hostDomain) {
diff --git a/source/server/core/link-manager/link-manager.ts b/source/server/core/link-manager/link-manager.ts
index 3f1ff9f..b8ab4ec 100644
--- a/source/server/core/link-manager/link-manager.ts
+++ b/source/server/core/link-manager/link-manager.ts
@@ -1,20 +1,20 @@
import { Forward, Subscribe } from "@the-link/core/decorators"
import AuthManager from "./auth-manager/auth-manager"
-import { TheLink } from "@the-link/core"
-import { Property } from "@the-link/core"
+import { Property, TheLink } from "@the-link/core"
import Application from "../application"
-import { type Appearance } from "@phreshos/core"
-import { type AuthenticationState, type RegistrationError } from "../authentication/authentication"
+import type { Appearance, ConnectionSnapshot, SessionEndReason, SessionSnapshot } from "@phreshos/core"
+import { type AuthenticationState, type SignUpError } from "../authentication/authentication"
import { AsyncLocalStorage } from "node:async_hooks"
+/** Owns live Link boundaries and their browser Connection and Session relationships. */
export default class LinkManager extends TheLink {
public readonly application: Application
- /** Live boundary connections. Ordinary authentication sessions outlive them. */
- public readonly connections = new Map<string, Connection>()
+ /** Every live transport boundary, including the external owner Gateway. */
+ public readonly boundaries = new Map<string, LinkBoundary>()
- private readonly connectionContext = new AsyncLocalStorage<Connection>()
+ private readonly connectionContext = new AsyncLocalStorage<LinkBoundary>()
public readonly authManager: AuthManager
@@ -32,32 +32,62 @@ export default class LinkManager extends TheLink {
this.appearance = Property.private(this, this.application.appearanceManager.value)
this.authManager = new AuthManager(this)
+
+ this.application.authentication.onSessionExpire(identity => {
+
+ this.announceSessionEnd(identity, "expired").catch(() => undefined)
+ })
}
+ /** Creates an unclassified browser boundary. */
public addConnection(link: TheLink) {
- const connection = new Connection(this, link)
+ return this.addBoundary(link, false)
+ }
+
+ /** Creates a trusted transport boundary excluded from the Connection domain. */
+ public addExternalConnection(link: TheLink) {
- this.connections.set(connection.identity, connection)
+ return this.addBoundary(link, true)
+ }
+
+ private addBoundary(link: TheLink, external: boolean) {
+
+ const connection = new LinkBoundary(this, link, external)
+
+ this.boundaries.set(connection.identity, connection)
return connection
}
- /** Create and bind a new authenticated session to a live connection. */
- public async addSession(connection: Connection, owner = false) {
+ /** Creates an unpublished browser Session and binds it to one live Connection. */
+ private async addSession(connection: LinkBoundary) {
- if (this.connections.get(connection.identity) !== connection) throw new Error("Connection not found")
- if (connection.session) throw new Error("The connection already has a session")
+ this.requireConnection(connection)
- const session = await this.application.authentication.createSession(owner)
+ if (connection.session) throw new Error("The Connection already has a Session")
- if (!await this.application.authentication.connectSession(session)) throw new Error("The created session is unavailable")
+ if (connection.external) throw new Error("External boundaries do not own browser Sessions")
- connection.session = session
+ const created = await this.application.authentication.createSession()
+
+ try {
+
+ await this.attach(connection, created.identity, false)
+ }
+
+ catch (error) {
+
+ await this.application.authentication.removeSession(created.identity)
+
+ throw error
+ }
return {
- authorization: this.application.encryptor.createToken({ version: 1, session }),
+ identity: created.identity,
+
+ token: created.token,
linkManager: this,
@@ -65,22 +95,43 @@ export default class LinkManager extends TheLink {
}
}
- public async removeConnection(connection: Connection) {
+ /** Removes a boundary after its Client or transport has disconnected. */
+ public removeConnection(connection: LinkBoundary) {
+
+ return connection.transition(() => this.removeConnectionNow(connection))
+ }
+
+ private async removeConnectionNow(connection: LinkBoundary) {
- if (this.connections.get(connection.identity) !== connection) return
+ if (this.boundaries.get(connection.identity) !== connection) return
+
+ const exposed = connection.exposed && !connection.external
+
+ await this.detach(connection)
connection.close()
this.authManager.processManager.releaseConnection(connection.identity)
- this.connections.delete(connection.identity)
+ this.boundaries.delete(connection.identity)
+
+ if (!exposed) return
+
+ const snapshot = this.connectionSnapshot(connection)
+
+ await Promise.all([
+
+ this.authManager.processManager.announceSubject("connection", "disconnect", connection.identity),
- if (connection.session && !this.connected(connection.session)) await this.releaseSession(connection.session)
+ this.authManager.processManager.announceHost("connection", "disconnect", connection.identity, snapshot),
+
+ this.authManager.$outbound.publish("/connection/disconnect", snapshot)
+ ])
}
- public receive(connection: Connection, event: string, ...values: unknown[]) {
+ public receive(connection: LinkBoundary, event: string, ...values: unknown[]) {
- if (this.connections.get(connection.identity) !== connection) throw new Error("Connection not found")
+ this.requireConnection(connection)
return this.connectionContext.run(connection, () => this.$inbound.publish(event, ...values))
}
@@ -89,136 +140,177 @@ export default class LinkManager extends TheLink {
const connection = this.connectionContext.getStore()
- if (!connection || this.connections.get(connection.identity) !== connection) throw new Error("This operation requires a live connection")
+ if (!connection) throw new Error("This operation requires a live Connection")
+
+ this.requireConnection(connection)
return connection
}
- @Subscribe("/owner/state")
- protected authenticationState(): AuthenticationState {
+ /** Every currently exposed browser Connection. */
+ public connections() {
- return this.application.authentication.state()
+ return [...this.boundaries.values()].filter(connection => connection.exposed && !connection.external)
}
- @Subscribe("/owner/register")
- protected async register(username: string, password: string): Promise<RegistrationResponse> {
+ public findConnection(identity: string) {
- const result = await this.application.authentication.register(username, password)
+ const connection = this.boundaries.get(identity)
- if ("error" in result) return result
-
- return { authorization: await this.createAuthorization() }
+ return connection?.exposed && !connection.external ? connection : null
}
- @Subscribe("/owner/sign-in")
- protected async signIn(username: string, password: string) {
+ public sessionOf(connection: LinkBoundary) {
- if (!await this.application.authentication.verify(username, password)) return false
+ this.requirePublicConnection(connection)
- return await this.createAuthorization()
+ return connection.session && this.application.authentication.sessionFind(connection.session)
}
- private async createAuthorization() {
+ public sessionConnections(identity: string) {
- const session = await this.application.authentication.createSession()
+ this.requireSession(identity)
- return this.application.encryptor.createToken({ version: 1, session })
+ return this.connections().filter(connection => connection.session === identity)
}
- public resolveAuthorization(authorization: string) {
+ /** Creates, attaches, and delivers a Client-owned token to one Connection. */
+ public signInConnection(connection: LinkBoundary) {
+
+ return connection.transition(() => this.signInConnectionNow(connection))
+ }
+
+ private async signInConnectionNow(connection: LinkBoundary) {
+
+ this.requirePublicConnection(connection)
+
+ const result = await this.addSession(connection)
- // Anything that is not a token at all makes the verifier throw
- // about buffers. What that means is "not authorized", and that
- // is what a caller should be told.
try {
- const result = this.application.encryptor.verifyToken<unknown>(authorization)
+ await connection.link.$outbound.publish("/session/signed-in", result.token)
+ }
+
+ catch (error) {
+
+ connection.session = null
- if (!result || !isAuthorization(result.payload)) return false
+ await this.application.authentication.removeSession(result.identity)
- return this.application.authentication.sessionValid(result.payload.session) ? result.payload.session : false
+ throw error
}
- catch {
+ if (!await this.application.authentication.exposeSession(result.identity)) {
+
+ connection.session = null
- return false
+ await this.application.authentication.removeSession(result.identity)
+
+ throw new Error("The Session could not enter the System registry")
}
+
+ await this.announceSessionCreate(result.identity)
+ await this.announceConnectionSession(connection, this.sessionSnapshot(result.identity))
+ await this.announceSessionConnection(result.identity, connection, true)
+
+ return this.sessionSnapshot(result.identity)
}
- @Subscribe("/session-authenticate")
- protected async sessionAuthenticate(authorization: string | null) {
+ /** Explicitly ends one browser Session without closing any Connections. */
+ public async signOutSession(identity: string) {
- const connection = this.connection()
+ this.requireSession(identity)
- if (!authorization) {
+ const connections = this.sessionConnections(identity)
- await this.releaseAuthorization(connection, true)
+ for (const connection of connections) connection.session = null
- return false
- }
+ await this.application.authentication.removeSession(identity)
- const session = this.resolveAuthorization(authorization)
+ await Promise.allSettled(connections.map(connection => connection.link.$outbound.publish("/session/signed-out")))
- if (!session) {
+ for (const connection of connections) {
- await this.releaseAuthorization(connection)
+ await this.announceConnectionSession(connection, null)
- return false
+ await this.announceSessionConnection(identity, connection, false)
}
- if (connection.session !== session) await this.releaseAuthorization(connection)
+ await this.announceSessionEnd(identity, "signedOut", connections)
+ }
+
+ @Subscribe("/owner/state")
+ protected authenticationState(): AuthenticationState {
+
+ return this.application.authentication.state()
+ }
- if (!await this.application.authentication.connectSession(session)) return false
+ @Subscribe("/owner/sign-up")
+ protected async signUp(username: string, password: string): Promise<SignUpResponse> {
- connection.session = session
+ const result = await this.application.authentication.signUp(username, password)
- return [authorization, this.authManager]
+ if ("error" in result) return result
+
+ await this.signInConnection(this.connection())
+
+ return { signedUp: true }
}
- @Forward("outbound")
- protected async broadcastToConnections(event: string, ...values: unknown[]) {
+ @Subscribe("/owner/sign-in")
+ protected async signIn(username: string, password: string) {
- for (const { link } of this.connections.values()) {
+ if (!await this.application.authentication.verify(username, password)) return false
- await link.$outbound.publish(event, ...values)
- }
+ await this.signInConnection(this.connection())
+
+ return true
}
- private connected(session: string) {
+ /** Resolves a Client-owned raw token to one valid Session identity. */
+ public resolveSessionToken(token: string) {
- return [...this.connections.values()].some(connection => connection.session === session)
+ return this.application.authentication.resolveSession(token) ?? false
}
- private async releaseAuthorization(connection: Connection, remove = false) {
+ @Subscribe("/session-authenticate")
+ protected sessionAuthenticate(token: string | null) {
- const session = connection.session
+ const connection = this.connection()
- connection.session = null
+ return connection.transition(() => this.authenticateConnection(connection, token))
+ }
- if (!session) return
+ private async authenticateConnection(connection: LinkBoundary, token: string | null) {
- if (remove) {
+ if (connection.external) throw new Error("External boundaries do not enter the browser Connection domain")
- for (const current of this.connections.values()) {
+ const session = token ? this.resolveSessionToken(token) : false
- if (current.session === session) current.session = null
- }
+ let attached = false
- await this.application.authentication.removeSession(session)
+ if (connection.session !== (session || null)) {
- return
+ await this.detach(connection)
+
+ if (session) {
+
+ await this.attach(connection, session, false)
+ attached = true
+ }
}
- if (!this.connected(session)) await this.releaseSession(session)
- }
+ await this.expose(connection)
- private releaseSession(session: string) {
+ if (session && attached) await this.announceSessionConnection(session, connection, true)
- return this.application.authentication.sessionOwner(session)
+ return session ? [token, this.authManager] : false
+ }
- ? this.application.authentication.removeSession(session)
+ @Forward("outbound")
+ protected async broadcastToBoundaries(event: string, ...values: unknown[]) {
- : this.application.authentication.disconnectSession(session)
+ for (const { link } of this.boundaries.values()) await link.$outbound.publish(event, ...values)
}
/** Persist and publish one authorized Appearance replacement in call order. */
@@ -238,16 +330,155 @@ export default class LinkManager extends TheLink {
return update
}
- // Nothing about the link itself crosses. The declaration stays, so
- // what a session is born with is stated rather than inferred from
- // whatever the object happens to hold.
- public toJSON() {
+ public connectionSnapshot(connection: LinkBoundary): ConnectionSnapshot {
- return {
+ return Object.freeze({
+
+ identity: connection.identity,
- appearance: this.appearance
+ connected: this.boundaries.get(connection.identity) === connection && !connection.signal.aborted,
+
+ session: connection.session && this.application.authentication.sessionFind(connection.session)
+ })
+ }
+
+ public sessionSnapshot(identity: string, valid = this.application.authentication.sessionFind(identity) !== null): SessionSnapshot {
+
+ return Object.freeze({ identity, valid })
+ }
+
+ private async expose(connection: LinkBoundary) {
+
+ if (connection.exposed) return
+
+ connection.exposed = true
+
+ const snapshot = this.connectionSnapshot(connection)
+
+ await Promise.all([
+
+ this.authManager.processManager.announceHost("connection", "create", connection.identity, snapshot),
+
+ this.authManager.$outbound.publish("/connection/create", snapshot)
+ ])
+ }
+
+ private async attach(connection: LinkBoundary, session: string, announce = true) {
+
+ if (connection.session === session) return
+
+ if (connection.session) await this.detach(connection)
+
+ if (!await this.application.authentication.connectSession(session)) throw new Error("The Session is unavailable")
+
+ connection.session = session
+
+ if (connection.external) return
+
+ if (announce) {
+
+ await this.announceConnectionSession(connection, this.sessionSnapshot(session))
+ await this.announceSessionConnection(session, connection, true)
}
}
+
+ private async detach(connection: LinkBoundary) {
+
+ const session = connection.session
+
+ if (!session) return
+
+ connection.session = null
+
+ await this.application.authentication.disconnectSession(session)
+
+ if (connection.external) return
+
+ await this.announceConnectionSession(connection, null)
+ await this.announceSessionConnection(session, connection, false)
+ }
+
+ private async announceConnectionSession(connection: LinkBoundary, session: SessionSnapshot | null) {
+
+ await Promise.all([
+
+ this.authManager.processManager.announceSubject("connection", "sessionChange", connection.identity, session),
+
+ this.authManager.$outbound.publish("/connection/session-change", this.connectionSnapshot(connection), session)
+ ])
+ }
+
+ private async announceSessionCreate(identity: string) {
+
+ const session = this.sessionSnapshot(identity)
+
+ await Promise.all([
+
+ this.authManager.processManager.announceHost("session", "create", identity, session),
+
+ this.authManager.$outbound.publish("/session/create", session)
+ ])
+ }
+
+ private async announceSessionConnection(identity: string, connection: LinkBoundary, attached: boolean) {
+
+ const session = this.sessionSnapshot(identity, attached || this.application.authentication.sessionValid(identity))
+
+ const snapshot = this.connectionSnapshot(connection)
+
+ const event = attached ? "connectionAttach" : "connectionDetach"
+
+ const route = attached ? "/session/connection-attach" : "/session/connection-detach"
+
+ await Promise.all([
+
+ this.authManager.processManager.announceSubject("session", event, identity, snapshot),
+
+ this.authManager.$outbound.publish(route, session, snapshot)
+ ])
+ }
+
+ private async announceSessionEnd(identity: string, reason: SessionEndReason, previousConnections: readonly LinkBoundary[] = []) {
+
+ const session = this.sessionSnapshot(identity, false)
+
+ await Promise.all([
+
+ this.authManager.processManager.announceSubject("session", "end", identity, reason),
+
+ this.authManager.processManager.announceHost("session", "end", identity, session, reason),
+
+ this.authManager.$outbound.publish(
+ "/session/end",
+ session,
+ reason,
+ previousConnections.map(connection => this.connectionSnapshot(connection))
+ )
+ ])
+ }
+
+ private requireConnection(connection: LinkBoundary) {
+
+ if (this.boundaries.get(connection.identity) !== connection || connection.signal.aborted) throw new Error("Connection not found")
+ }
+
+ private requirePublicConnection(connection: LinkBoundary) {
+
+ this.requireConnection(connection)
+
+ if (connection.external || !connection.exposed) throw new Error("Connection not found")
+ }
+
+ private requireSession(identity: string) {
+
+ if (!this.application.authentication.sessionFind(identity)) throw new Error("Session not found")
+ }
+
+ // The transport stays internal. Only public state is represented.
+ public toJSON() {
+
+ return { appearance: this.appearance }
+ }
}
export interface LinkManagerSnapshot {
@@ -255,36 +486,50 @@ export interface LinkManagerSnapshot {
appearance: ReturnType<Property<Appearance>["toJSON"]>
}
-export type RegistrationResponse = { authorization: string } | { error: RegistrationError }
+export type SignUpResponse = { signedUp: true } | { error: SignUpError }
-export class Connection {
+/** One internal Link boundary. Only browser boundaries enter the public Connection registry. */
+export class LinkBoundary {
public readonly identity = crypto.randomUUID()
public session: string | null = null
+ public exposed = false
+
private readonly lifetime = new AbortController()
+ private transitioning: Promise<void> = Promise.resolve()
+
public readonly signal = this.lifetime.signal
- public constructor(private readonly manager: LinkManager, public readonly link: TheLink) {}
+ public constructor(
+
+ private readonly manager: LinkManager,
+
+ public readonly link: TheLink,
+
+ public readonly external: boolean
+
+ ) {}
public publish(event: string, ...values: unknown[]) {
return this.manager.receive(this, event, ...values)
}
- public close() {
+ /** Serializes Session and lifecycle mutations belonging to this Connection. */
+ public transition<Value>(work: () => Promise<Value>): Promise<Value> {
- this.lifetime.abort(new Error("The System representation disconnected"))
- }
-}
+ const result = this.transitioning.then(work, work)
-function isAuthorization(value: unknown): value is { version: 1, session: string } {
+ this.transitioning = result.then(() => undefined, () => undefined)
- if (!value || typeof value !== "object") return false
+ return result
+ }
- const authorization = value as { version?: unknown, session?: unknown }
+ public close() {
- return authorization.version === 1 && typeof authorization.session === "string"
+ this.lifetime.abort(new Error("The System representation disconnected"))
+ }
}
diff --git a/source/server/core/permissions.ts b/source/server/core/permissions.ts
index 1fa21fb..7668c70 100644
--- a/source/server/core/permissions.ts
+++ b/source/server/core/permissions.ts
@@ -187,6 +187,11 @@ export class PermissionCatalog {
return false
}
+ if (name === "desktopConnection") {
+
+ if (this.allows("connections", [], permissions)) return true
+ }
+
const assigned = permissions[name]
// An exact assignment is the owner's final decision for that
@@ -339,5 +344,15 @@ export const permissionCatalog = new PermissionCatalog({
default: [],
title: "Desktop preferences",
description: "Change this Desktop's preferences."
+ },
+ desktopConnection: {
+ default: [],
+ title: "Desktop connection",
+ description: "Access the browser Connection carrying this Desktop and its Session."
+ },
+ connections: {
+ default: [],
+ title: "Connections",
+ description: "Access every browser Connection and its Session."
}
})
diff --git a/source/server/core/system.ts b/source/server/core/system.ts
index f298913..316c53a 100644
--- a/source/server/core/system.ts
+++ b/source/server/core/system.ts
@@ -217,11 +217,81 @@ export default class System {
})
}
- public observe(domain: "program" | "process" | "window", event: string, subject: string | null, subscriber: (event: string, ...values: unknown[]) => void) {
+ public observe(domain: "program" | "process" | "window" | "connection" | "session", event: string, subject: string | null, subscriber: (event: string, ...values: unknown[]) => void) {
return this.processManager.observeHost(domain, event, subject, subscriber)
}
+ public listConnections() {
+
+ return this.application.linkManager.connections()
+ }
+
+ public findConnection(identity: string) {
+
+ return this.application.linkManager.findConnection(identity)
+ }
+
+ public connectionSnapshot(identity: string) {
+
+ const connection = this.findConnection(identity)
+
+ return connection
+
+ ? this.application.linkManager.connectionSnapshot(connection)
+
+ : Object.freeze({ identity, connected: false, session: null })
+ }
+
+ public connectionSession(identity: string) {
+
+ const connection = this.findConnection(identity)
+
+ if (!connection) return null
+
+ const session = this.application.linkManager.sessionOf(connection)
+
+ return session ? this.application.linkManager.sessionSnapshot(session) : null
+ }
+
+ public signInConnection(identity: string) {
+
+ const connection = this.findConnection(identity)
+
+ if (!connection) throw new Error("Connection not found")
+
+ return this.application.linkManager.signInConnection(connection)
+ }
+
+ public listSessions() {
+
+ return this.application.authentication.sessionsList()
+ }
+
+ public findSession(identity: string) {
+
+ return this.application.authentication.sessionFind(identity)
+ }
+
+ public sessionSnapshot(identity: string) {
+
+ return this.application.linkManager.sessionSnapshot(identity)
+ }
+
+ public sessionConnections(identity: string) {
+
+ return this.findSession(identity)
+
+ ? this.application.linkManager.sessionConnections(identity)
+
+ : []
+ }
+
+ public signOutSession(identity: string) {
+
+ return this.application.linkManager.signOutSession(identity)
+ }
+
public observeEndpoint(process: Process, endpoint: Half, event: string | null, subscriber: (payload: unknown, event: string) => void, impossible?: (reason: string) => void) {
return this.processManager.observeEndpoint(process.identity, endpoint, event, subscriber, impossible)
diff --git a/source/server/view/gateway/gateway.ts b/source/server/view/gateway/gateway.ts
index e478fd5..33b02d2 100644
--- a/source/server/view/gateway/gateway.ts
+++ b/source/server/view/gateway/gateway.ts
@@ -16,7 +16,7 @@ export default function gateway(linkManager: LinkManager, path: string) {
async function connect(linkManager: LinkManager, peer: GatewayPeer) {
- const connection = linkManager.addConnection(peer)
+ const connection = linkManager.addExternalConnection(peer)
let closed = false
const close = async () => {
@@ -34,9 +34,12 @@ async function connect(linkManager: LinkManager, peer: GatewayPeer) {
try {
- const session = await linkManager.addSession(connection, true)
+ await peer.$outbound.publish("/gateway/ready", {
- await peer.$outbound.publish("/gateway/ready", session)
+ linkManager: linkManager.toJSON(),
+
+ authManager: linkManager.authManager.toJSON()
+ })
}
catch (error) {
diff --git a/tests/authentication-domains.test.ts b/tests/authentication-domains.test.ts
new file mode 100644
index 0000000..1062e8a
--- /dev/null
+++ b/tests/authentication-domains.test.ts
@@ -0,0 +1,79 @@
+import { mkdtemp, rm } from "node:fs/promises"
+import { tmpdir } from "node:os"
+import { join } from "node:path"
+import { TheLink } from "@the-link/core"
+import { expect, test } from "vitest"
+import Application from "@server/core/application"
+
+test("browser Connections and Sessions form one authoritative lifecycle", async () => {
+ const home = await mkdtemp(join(tmpdir(), "phreshos-authentication-"))
+ const application = await Application.initialize(
+ "phreshos",
+ "PhreshOS",
+ "test",
+ home,
+ join(home, "icon.png"),
+ () => { throw new Error("The test does not launch Server Endpoints") }
+ )
+ const link = new TheLink()
+ const connection = application.linkManager.addConnection(link)
+ const secondLink = new TheLink()
+ const secondConnection = application.linkManager.addConnection(secondLink)
+ let token: string | null = null
+ let signedOut = 0
+ const stopToken = link.$outbound.subscribe("/session/signed-in", value => {
+ if (typeof value === "string") token = value
+ })
+ const stopFirstSignOut = link.$outbound.subscribe("/session/signed-out", () => { signedOut += 1 })
+ const stopSecondSignOut = secondLink.$outbound.subscribe("/session/signed-out", () => { signedOut += 1 })
+ let secondRemoved = false
+
+ try {
+ expect(await connection.publish("/session-authenticate", null)).toEqual([false])
+ expect(application.system.listConnections()).toEqual([connection])
+ expect(application.system.connectionSession(connection.identity)).toBeNull()
+
+ const created = await application.system.signInConnection(connection.identity)
+
+ expect(token).toEqual(expect.any(String))
+ expect(application.system.listSessions()).toEqual([created.identity])
+ expect(application.system.connectionSession(connection.identity)).toEqual(created)
+ expect(application.system.sessionConnections(created.identity)).toEqual([connection])
+ await expect(application.system.signInConnection(connection.identity)).rejects.toThrow("already has a Session")
+
+ await secondConnection.publish("/session-authenticate", token)
+
+ expect(application.system.connectionSession(secondConnection.identity)).toEqual(created)
+ expect(application.system.sessionConnections(created.identity)).toEqual([connection, secondConnection])
+
+ await application.system.signOutSession(created.identity)
+
+ expect(signedOut).toBe(2)
+ expect(application.system.listSessions()).toEqual([])
+ expect(application.system.connectionSession(connection.identity)).toBeNull()
+ expect(application.system.connectionSession(secondConnection.identity)).toBeNull()
+ expect(application.system.listConnections()).toEqual([connection, secondConnection])
+ expect(application.system.sessionSnapshot(created.identity)).toEqual({ identity: created.identity, valid: false })
+ expect(application.system.sessionConnections(created.identity)).toEqual([])
+ await expect(application.system.signOutSession(created.identity)).rejects.toThrow("Session not found")
+
+ await application.linkManager.removeConnection(secondConnection)
+ secondRemoved = true
+
+ expect(application.system.connectionSnapshot(secondConnection.identity)).toEqual({
+ identity: secondConnection.identity,
+ connected: false,
+ session: null
+ })
+ expect(application.system.connectionSession(secondConnection.identity)).toBeNull()
+ expect(() => application.system.signInConnection(secondConnection.identity)).toThrow("Connection not found")
+ } finally {
+ stopToken()
+ stopFirstSignOut()
+ stopSecondSignOut()
+ await application.linkManager.removeConnection(connection)
+ if (!secondRemoved) await application.linkManager.removeConnection(secondConnection)
+ await application.store.disconnect()
+ await rm(home, { recursive: true, force: true })
+ }
+})
diff --git a/tests/client-layer-permissions.test.ts b/tests/client-layer-permissions.test.ts
index 97abd63..24920ea 100644
--- a/tests/client-layer-permissions.test.ts
+++ b/tests/client-layer-permissions.test.ts
@@ -19,15 +19,39 @@ function fixture() {
const startup = vi.fn()
const savedLaunch = vi.fn()
const startEndpoint = vi.fn()
+ const connections = [
+ { identity: "desktop-connection", connected: true, session: "desktop-session" },
+ { identity: "outside-connection", connected: true, session: "outside-session" }
+ ]
+ const sessions = [
+ { identity: "desktop-session", valid: true },
+ { identity: "outside-session", valid: true }
+ ]
+ const connection = vi.fn(async (operation: string, identity?: string) => {
+
+ if (operation === "current") return connections[0]
+ if (operation === "list") return connections
+ if (operation === "find") return connections.find(value => value.identity === identity) ?? null
+ if (operation === "session") return sessions.find(value => value.identity === connections.find(connection => connection.identity === identity)?.session) ?? null
+ return connections.find(value => value.identity === identity) ?? null
+ })
+ const session = vi.fn(async (operation: string, identity?: string) => {
+
+ if (operation === "list") return sessions
+ if (operation === "find") return sessions.find(value => value.identity === identity) ?? null
+ if (operation === "connections") return connections.filter(value => value.session === identity)
+ return sessions.find(value => value.identity === identity) ?? null
+ })
const command = vi.fn(async function* () {})
const auth = {
programManager: { programs: new Map([[program.identity, program]]), createProcess, findOrCreateProcess, startup, launch: savedLaunch, command },
processManager: { processes: new Map([[process.identity, process]]), startEndpoint, ownFrame: vi.fn(), releaseFrame: vi.fn() },
+ connection, session,
grantsPermission: async <Name extends PermissionName>(_pane: string, name: Name, values: readonly PermissionValue<Name>[]) => permissionCatalog.allows(name, values, permissions)
} as unknown as AuthManager
const answer = host(auth, process.identity, () => ({ size: { width: 100, height: 100 } }), () => "frame", {} as never)
return {
- auth, program, process, answer, createProcess, findOrCreateProcess, startup, savedLaunch, startEndpoint, command,
+ auth, program, process, answer, createProcess, findOrCreateProcess, startup, savedLaunch, startEndpoint, command, connection,
permissions(value: Permissions) { permissions = value }
}
}
@@ -38,8 +62,8 @@ test.each(["under", "over", "wallpaper"] as const)("Client launch routes check %
const process = { identity: f.process.identity, reference: f.process.reference }
const launch = { name: "main", client: { layer } }
const operations = [
- ["program-process-create", program, launch],
- ["program-process-find-or-create", program, launch],
+ ["program-create-process", program, launch],
+ ["program-find-or-create-process", program, launch],
["startup", program, "enable", launch],
["launch", program, "set", launch],
["start-endpoint", process, "client", { layer }]
@@ -60,6 +84,40 @@ test.each(["under", "over", "wallpaper"] as const)("Client launch routes check %
for (const delegate of delegates) expect(delegate).toHaveBeenCalledTimes(3)
})
+test("Connection permissions define one opaque accessible scope", async () => {
+
+ const f = fixture()
+
+ await expect(f.answer("desktop-connection")).rejects.toThrow("Execution is not permitted")
+ await expect(f.answer("host-connection-list")).resolves.toEqual([[]])
+ await expect(f.answer("host-session-list")).resolves.toEqual([[]])
+ await expect(f.answer("host-connection-find", "desktop-connection")).resolves.toEqual([null])
+ await expect(f.answer("host-session-find", "desktop-session")).resolves.toEqual([null])
+ await expect(f.answer("host-connection-state", "desktop-connection")).rejects.toThrow("Connection not found")
+ await expect(f.answer("host-session-state", "desktop-session")).rejects.toThrow("Session not found")
+
+ f.permissions({ desktopConnection: [] })
+
+ await expect(f.answer("desktop-connection")).resolves.toEqual([expect.objectContaining({ identity: "desktop-connection" })])
+ await expect(f.answer("host-connection-list")).resolves.toEqual([[expect.objectContaining({ identity: "desktop-connection" })]])
+ await expect(f.answer("host-session-list")).resolves.toEqual([[expect.objectContaining({ identity: "desktop-session" })]])
+ await expect(f.answer("host-connection-find", "outside-connection")).resolves.toEqual([null])
+ await expect(f.answer("host-session-find", "outside-session")).resolves.toEqual([null])
+ await expect(f.answer("host-session-connections", "desktop-session")).resolves.toEqual([[expect.objectContaining({ identity: "desktop-connection" })]])
+
+ f.permissions({ connections: [] })
+
+ await expect(f.answer("desktop-connection")).resolves.toEqual([expect.objectContaining({ identity: "desktop-connection" })])
+ await expect(f.answer("host-connection-list")).resolves.toEqual([connectionsNamed("desktop-connection", "outside-connection")])
+ await expect(f.answer("host-session-list")).resolves.toEqual([connectionsNamed("desktop-session", "outside-session")])
+ expect(f.connection).toHaveBeenCalledWith("current")
+})
+
+function connectionsNamed(...identities: string[]) {
+
+ return identities.map(identity => expect.objectContaining({ identity }))
+}
+
test("Client layer authorization validates explicit choices without reinterpreting defaults", async () => {
const f = fixture()
const access = new SystemAccess(f.auth, f.process.identity)
@@ -72,7 +130,7 @@ test("Client layer authorization validates explicit choices without reinterpreti
await f.answer("startup", null, "get")
await f.answer("startup", null, "disable")
await f.answer("start-endpoint", null, "server")
- await f.answer("program-process-create", null, {})
+ await f.answer("program-create-process", null, {})
expect(f.createProcess).toHaveBeenCalledOnce()
})
diff --git a/tests/client-permission-boundary.test.ts b/tests/client-permission-boundary.test.ts
index cfef4de..85f310e 100644
--- a/tests/client-permission-boundary.test.ts
+++ b/tests/client-permission-boundary.test.ts
@@ -32,6 +32,41 @@ test("Client Program creation requires all before reaching the creation boundary
expect(forceCreate).toHaveBeenCalledWith(source, "caller")
})
+test("Program and Process discovery exposes only the accessible scope", async () => {
+
+ let permissions: Permissions = {}
+ const owner = program("owner")
+ const outside = program("outside")
+ const current = process("current", owner)
+ const hidden = process("hidden", outside)
+ const auth = {
+ programManager: { programs: new Map([[owner.identity, owner], [outside.identity, outside]]) },
+ processManager: { processes: new Map([[current.identity, current], [hidden.identity, hidden]]) },
+ 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, {} as never)
+
+ await expect(answer("host-program-list")).resolves.toEqual([[expect.objectContaining({ identity: owner.identity })]])
+ await expect(answer("host-process-list")).resolves.toEqual([[expect.objectContaining({ identity: current.identity })]])
+ await expect(answer("host-program-find", outside.identity)).resolves.toEqual([null])
+ await expect(answer("host-process-find", hidden.identity)).resolves.toEqual([null])
+ await expect(answer("installed", { identity: outside.identity, reference: outside.reference })).rejects.toThrow("Program represented by this handle does not exist")
+ await expect(answer("window", { identity: hidden.identity, reference: hidden.reference })).rejects.toThrow("Process represented by this handle does not exist")
+
+ permissions = { programs: [outside.identity] }
+
+ await expect(answer("host-program-list")).resolves.toEqual([[
+ expect.objectContaining({ identity: owner.identity }),
+ expect.objectContaining({ identity: outside.identity })
+ ]])
+ await expect(answer("host-process-list")).resolves.toEqual([[
+ expect.objectContaining({ identity: current.identity }),
+ expect.objectContaining({ identity: hidden.identity })
+ ]])
+ await expect(answer("host-program-find", outside.identity)).resolves.toEqual([expect.objectContaining({ identity: outside.identity })])
+ await expect(answer("host-process-find", hidden.identity)).resolves.toEqual([expect.objectContaining({ identity: hidden.identity })])
+})
+
test.each([
{ owningProgram: "owner", denied: [], granted: [{}] },
{
@@ -54,7 +89,7 @@ test.each([
owningProgram: string
denied: Permissions[]
granted: Permissions[]
-}>)("Service operations follow the authority hierarchy for $owningProgram", async ({ owningProgram, denied, granted }) => {
+}>)("Service operations expose only Services in the accessible scope for $owningProgram", async ({ owningProgram, denied, granted }) => {
const destination = "6d138083-7a51-44ec-9abe-ff0194ad1e5b"
let permissions: Permissions = {}
const serviceExists = vi.fn(async () => true)
@@ -85,7 +120,7 @@ test.each([
for (const assignment of denied) {
permissions = assignment
for (const [operation, ...args] of operations) {
- await expect(answer(operation, ...args)).rejects.toThrow("Execution is not permitted")
+ await expect(answer(operation, ...args)).rejects.toThrow("The Service represented by this key does not exist")
}
}
for (const assignment of granted) {
@@ -97,3 +132,32 @@ test.each([
expect(call).toHaveBeenCalledTimes(granted.length * 2)
}
})
+
+function program(identity: string): ProgramSnapshot {
+
+ return {
+ identity,
+ reference: `${identity}-reference`,
+ assetId: `${identity}-assets`,
+ name: identity,
+ version: null,
+ description: null,
+ hasAgent: false,
+ server: null,
+ client: null
+ }
+}
+
+function process(identity: string, owner: ProgramSnapshot) {
+
+ return {
+ identity,
+ reference: `${identity}-reference`,
+ program: owner.identity,
+ name: null,
+ startedAt: new Date(0),
+ options: {},
+ server: null,
+ client: null
+ }
+}
diff --git a/tests/client-system-access.test.ts b/tests/client-system-access.test.ts
index 04ac894..77b8538 100644
--- a/tests/client-system-access.test.ts
+++ b/tests/client-system-access.test.ts
@@ -30,6 +30,12 @@ test("client system access contract", async () => {
assert.equal(process, owner.identity)
return permissionCatalog.allowsStorage(permissions.all ?? null, permissions.storage ?? null, path, operation)
+ },
+ async connection(operation: string) {
+
+ assert.equal(operation, "current")
+
+ return { identity: "desktop-connection", connected: true, session: "desktop-session" }
}
} as unknown as AuthManager
@@ -47,21 +53,25 @@ test("client system access contract", async () => {
assert.equal(await access.program(ownProgram as never), ownProgram)
assert.equal(await access.service(ownService), ownService)
assert.equal(await access.service(ownExactService), ownExactService)
- await assert.rejects(access.program(outsideProgram as never), /Execution is not permitted/)
- await assert.rejects(access.process(outside), /Execution is not permitted/)
- await assert.rejects(access.service(outsideService), /Execution is not permitted/)
+ await assert.rejects(access.program(outsideProgram as never), /Program represented by this handle does not exist/)
+ await assert.rejects(access.process(outside), /Process represented by this handle does not exist/)
+ await assert.rejects(access.service(outsideService), /Service represented by this key does not exist/)
await assert.rejects(access.requireAll(), /Execution is not permitted/)
await assert.rejects(access.requireNetwork("https://api.example.com/v1/users"), /Execution is not permitted/)
await assert.rejects(access.requireStorage("/Users/person/Documents/report.txt", "read"), /Execution is not permitted/)
await assert.rejects(access.require("uploads", []), /Execution is not permitted/)
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/)
+ await assert.rejects(access.require("connections", []), /Execution is not permitted/)
+ assert.equal(await access.canConnection("desktop-connection"), false)
+ assert.equal(await access.canSession("desktop-session"), false)
permissions = { services: ["outside"] }
assert.equal(await access.service(outsideService), outsideService)
- await assert.rejects(access.program(outsideProgram as never), /Execution is not permitted/)
- await assert.rejects(access.process(outside), /Execution is not permitted/)
+ await assert.rejects(access.program(outsideProgram as never), /Program represented by this handle does not exist/)
+ await assert.rejects(access.process(outside), /Process represented by this handle does not exist/)
await assert.rejects(access.requireAll(), /Execution is not permitted/)
permissions = { services: [] }
@@ -69,7 +79,7 @@ test("client system access contract", async () => {
assert.equal(await access.service(outsideService), outsideService)
assert.equal(await access.service(ownService), ownService)
assert.equal(await access.service(ownExactService), ownExactService)
- await assert.rejects(access.program(outsideProgram as never), /Execution is not permitted/)
+ await assert.rejects(access.program(outsideProgram as never), /Program represented by this handle does not exist/)
await assert.rejects(access.requireAll(), /Execution is not permitted/)
permissions = { programs: ["outside"] }
@@ -86,11 +96,26 @@ test("client system access contract", async () => {
assert.equal(await access.program(outsideProgram as never), outsideProgram)
assert.equal(await access.service(outsideService), outsideService)
- permissions = { appearance: [], desktopPreferences: [] }
+ permissions = { appearance: [], desktopPreferences: [], connections: [] }
await access.require("appearance", [])
await access.require("desktopPreferences", [])
- await assert.rejects(access.program(outsideProgram as never), /Execution is not permitted/)
+ await access.require("connections", [])
+ await access.require("desktopConnection", [])
+ assert.equal(await access.canConnection("desktop-connection"), true)
+ assert.equal(await access.canConnection("another-connection"), true)
+ assert.equal(await access.canSession("desktop-session"), true)
+ assert.equal(await access.canSession("another-session"), true)
+ await assert.rejects(access.program(outsideProgram as never), /Program represented by this handle does not exist/)
+
+ permissions = { desktopConnection: [] }
+
+ await access.require("desktopConnection", [])
+ await assert.rejects(access.require("connections", []), /Execution is not permitted/)
+ assert.equal(await access.canConnection("desktop-connection"), true)
+ assert.equal(await access.canConnection("another-connection"), false)
+ assert.equal(await access.canSession("desktop-session"), true)
+ assert.equal(await access.canSession("another-session"), false)
permissions = { uploads: [] }
@@ -123,6 +148,7 @@ test("client system access contract", async () => {
assert.equal(await access.service(outsideService), outsideService)
await access.require("appearance", [])
await access.require("desktopPreferences", [])
+ await access.require("connections", [])
await access.requireNetwork("wss://events.example.com/socket")
await access.requireStorage("/any/native/path", "delete")
await access.require("uploads", [])
@@ -132,12 +158,12 @@ test("client system access contract", async () => {
permissions = { all: [], services: false }
assert.equal(await access.service(ownService), ownService)
assert.equal(await access.service(ownExactService), ownExactService)
- await assert.rejects(access.service(unresolvedService), /Execution is not permitted/)
+ await assert.rejects(access.service(unresolvedService), /Service represented by this key does not exist/)
permissions = { services: [] }
assert.equal(await access.service(unresolvedService), unresolvedService)
permissions = { services: ["owner"] }
assert.equal(await access.service(ownService), ownService)
assert.equal(await access.service(ownExactService), ownExactService)
- await assert.rejects(access.service(outsideService), /Execution is not permitted/)
- await assert.rejects(access.service(unresolvedService), /Execution is not permitted/)
+ await assert.rejects(access.service(outsideService), /Service represented by this key does not exist/)
+ await assert.rejects(access.service(unresolvedService), /Service represented by this key does not exist/)
}, 120_000)
diff --git a/tests/gateway.test.ts b/tests/gateway.test.ts
index f384f50..fe6b907 100644
--- a/tests/gateway.test.ts
+++ b/tests/gateway.test.ts
@@ -13,8 +13,7 @@ test("gateway contract", async () => {
const path = gatewayAddress(directory)
const received: unknown[][] = []
let removed = false
- const session = {
- authorization: "owner",
+ const snapshot = {
linkManager: { appearance: { key: "appearance", value: {} } },
authManager: {
programManager: { programs: [] },
@@ -22,7 +21,7 @@ test("gateway contract", async () => {
}
}
const linkManager = {
- addConnection() {
+ addExternalConnection() {
return {
async publish(event: string, ...values: unknown[]) {
received.push([event, ...values])
@@ -30,10 +29,8 @@ test("gateway contract", async () => {
}
}
},
- async addSession(_connection: unknown, owner: boolean) {
- assert.equal(owner, true)
- return session
- },
+ authManager: { ...snapshot.authManager, toJSON() { return snapshot.authManager } },
+ toJSON() { return snapshot.linkManager },
async removeConnection() { removed = true }
}
const listener = await gateway(linkManager as unknown as LinkManager, path)
@@ -47,7 +44,7 @@ test("gateway contract", async () => {
try {
await client.connect()
- assert.deepEqual(await ready, session)
+ assert.deepEqual(await ready, snapshot)
assert.deepEqual(
await client.$outbound.publishFirst("/auth/example", "authorization", { binary: new Uint8Array([1, 2, 3]) }),
{ event: "/auth/example", values: ["authorization", { binary: new Uint8Array([1, 2, 3]) }] }
diff --git a/tests/host-traffic.test.ts b/tests/host-traffic.test.ts
index f522471..1420859 100644
--- a/tests/host-traffic.test.ts
+++ b/tests/host-traffic.test.ts
@@ -8,11 +8,15 @@ test("host traffic contract", async () => {
const ownProgram: unknown[][] = []
const hostProcess: unknown[][] = []
const programProcess: unknown[][] = []
+ const hostConnection: unknown[][] = []
+ const ownSession: 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]))
traffic.observe("process", "create", null, (_delivery, event, ...values) => hostProcess.push([event, ...values]))
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]))
const program = { identity: "counter", reference: "program-reference" }
const process = { identity: "worker", reference: "process-reference" }
@@ -30,4 +34,10 @@ test("host traffic contract", async () => {
assert.deepEqual(hostProcess, [["create", program.identity, process]])
assert.deepEqual(programProcess, [["create", program.reference, process]])
+
+ await traffic.emitHost("connection", "create", "connection-identity", { identity: "connection-identity" })
+ await traffic.emitSubject("session", "connectionAttach", "session-identity", { identity: "connection-identity" })
+
+ assert.deepEqual(hostConnection, [["create", "connection-identity", { identity: "connection-identity" }]])
+ assert.deepEqual(ownSession, [["connectionAttach", "session-identity", { identity: "connection-identity" }]])
}, 120_000)
diff --git a/tests/permissions.test.ts b/tests/permissions.test.ts
index 785eb50..195e93d 100644
--- a/tests/permissions.test.ts
+++ b/tests/permissions.test.ts
@@ -49,6 +49,16 @@ test("permissions contract", async () => {
default: [],
title: "Desktop preferences",
description: "Change this Desktop's preferences."
+ },
+ desktopConnection: {
+ default: [],
+ title: "Desktop connection",
+ description: "Access the browser Connection carrying this Desktop and its Session."
+ },
+ connections: {
+ default: [],
+ title: "Connections",
+ description: "Access every browser Connection and its Session."
}
})
@@ -125,6 +135,12 @@ test("permissions contract", async () => {
assert(!catalog.allows("services", [], { programs: ["browser"] }))
assert(!catalog.allows("programs", ["browser"], { services: [] }))
assert(catalog.allows("services", ["browser"], { programs: [], services: false }))
+ assert(catalog.allows("desktopConnection", [], { desktopConnection: [] }))
+ assert(catalog.allows("desktopConnection", [], { connections: [] }))
+ assert(catalog.allows("desktopConnection", [], { connections: [], desktopConnection: false }))
+ assert(!catalog.allows("connections", [], { desktopConnection: [] }))
+ assert(catalog.allows("desktopConnection", [], { all: [], connections: false }))
+ assert(!catalog.allows("desktopConnection", [], { all: [], connections: false, desktopConnection: false }))
assert(!catalog.allows("network", ["https://elsewhere.example"], { all: [], network: ["https://api.example.com"] }))
assert(catalog.allows("network", ["https://api.example.com/v1"], { all: [], network: ["https://api.example.com"] }))
assert(catalog.allowsStorage([], null, "Documents/report.txt", "read"))
@@ -157,7 +173,9 @@ test("permissions contract", async () => {
storage: catalog.definition("storage"),
uploads: catalog.definition("uploads"),
appearance: catalog.definition("appearance"),
- desktopPreferences: catalog.definition("desktopPreferences")
+ desktopPreferences: catalog.definition("desktopPreferences"),
+ desktopConnection: catalog.definition("desktopConnection"),
+ connections: catalog.definition("connections")
} as never), /invalid default/)
assert.deepEqual(permissionCatalog.resolve("all", true), [])
diff --git a/tests/sessions.test.ts b/tests/sessions.test.ts
new file mode 100644
index 0000000..f39d7c2
--- /dev/null
+++ b/tests/sessions.test.ts
@@ -0,0 +1,87 @@
+import { createHash } from "node:crypto"
+import { mkdtemp, rm } from "node:fs/promises"
+import { tmpdir } from "node:os"
+import { join } from "node:path"
+import Keyv from "keyv"
+import { afterEach, describe, expect, test, vi } from "vitest"
+import SqliteStore from "@libs/sqlite-store"
+import Sessions, { disconnectedSessionLifetime } from "@server/core/authentication/sessions"
+
+const directories: string[] = []
+
+afterEach(async () => {
+ vi.useRealTimers()
+ await Promise.all(directories.splice(0).map(path => rm(path, { recursive: true, force: true })))
+})
+
+describe("Session persistence and connection-bound lifetime", () => {
+ test("persists only a token hash and resolves the Client-owned token", async () => {
+ const { sessions, store } = await fixture()
+ const created = await sessions.create()
+ const hash = createHash("sha256").update(created.token).digest("base64url")
+
+ expect(created.identity).not.toBe(created.token)
+ expect(sessions.resolve(created.token)).toBe(created.identity)
+ expect(sessions.find(created.identity)).toBeNull()
+ expect(await store.get(`authentication:sessions:${hash}`)).toBeUndefined()
+ expect(await sessions.expose(created.identity)).toBe(true)
+ expect(sessions.find(created.identity)).toBe(created.identity)
+ expect(await store.get(`authentication:sessions:${hash}`)).toEqual({
+ identity: created.identity,
+ disconnectedAt: expect.any(Number)
+ })
+ expect(await store.get(`authentication:sessions:${created.token}`)).toBeUndefined()
+
+ await store.disconnect()
+ })
+
+ test("keeps a Session valid while any Connection remains attached", async () => {
+ vi.useFakeTimers()
+ vi.setSystemTime(new Date("2026-01-01T00:00:00Z"))
+ const { sessions, store } = await fixture()
+ const created = await sessions.create()
+
+ await sessions.attach(created.identity)
+ await sessions.expose(created.identity)
+ await sessions.attach(created.identity)
+ await sessions.detach(created.identity)
+ vi.advanceTimersByTime(disconnectedSessionLifetime * 2)
+
+ expect(sessions.valid(created.identity)).toBe(true)
+ expect(await persisted(store, created.token)).toEqual({
+ identity: created.identity,
+ disconnectedAt: null
+ })
+
+ await sessions.detach(created.identity)
+ vi.advanceTimersByTime(disconnectedSessionLifetime + 1)
+
+ expect(sessions.valid(created.identity)).toBe(false)
+ expect(sessions.resolve(created.token)).toBeNull()
+
+ await store.disconnect()
+ })
+
+ test("removes an explicitly signed-out Session", async () => {
+ const { sessions, store } = await fixture()
+ const created = await sessions.create()
+
+ expect(await sessions.remove(created.identity)).toBe(true)
+ expect(sessions.find(created.identity)).toBeNull()
+ expect(sessions.resolve(created.token)).toBeNull()
+
+ await store.disconnect()
+ })
+})
+
+async function fixture() {
+ const directory = await mkdtemp(join(tmpdir(), "phreshos-sessions-"))
+ directories.push(directory)
+ const store = new Keyv(new SqliteStore(join(directory, "store.sqlite")))
+ return { sessions: await Sessions.open(store), store }
+}
+
+function persisted(store: Keyv, token: string) {
+ const hash = createHash("sha256").update(token).digest("base64url")
+ return store.get(`authentication:sessions:${hash}`)
+}