An open-source, self-hosted system for apps built with web technologies.
Sessions keep when they signed in; state reads report last activity and connection, also after an end
zohayrslilehd2976c2a3387
diff --git a/source/server/core/authentication/authentication.ts b/source/server/core/authentication/authentication.tsindex ef76868..e3ec07d 100644--- a/source/server/core/authentication/authentication.ts+++ b/source/server/core/authentication/authentication.ts@@ -224,11 +224,17 @@ export default class Authentication {}/** Observes browser Sessions removed by disconnected-lifetime expiration. */- public onSessionExpire(listener: (identity: string) => void) {+ public onSessionExpire(listener: (identity: string, createdAt: Date) => void) {return this.sessions.onExpire(listener)}+ /** When one known Session signed in and was last used, or `null` when it is unknown. */+ public describeSession(identity: string) {++ return this.sessions.describe(identity)+ }+/** Whether a session is still within its connection-bound lifetime. */public sessionValid(identity: string) {diff --git a/source/server/core/authentication/sessions.ts b/source/server/core/authentication/sessions.tsindex d62593f..d803231 100644--- a/source/server/core/authentication/sessions.ts+++ b/source/server/core/authentication/sessions.ts@@ -14,7 +14,7 @@ export default class Sessions {private readonly hashes = new Map<string, StoredSession>()- private readonly expirationListeners = new Set<(identity: string) => void>()+ private readonly expirationListeners = new Set<(identity: string, createdAt: Date) => void>()private constructor(private readonly store: Keyv) {}@@ -32,7 +32,9 @@ export default class Sessions {const record = parse(value, hash)- if (sessions.expired(record, Date.now())) {+ // A Session stored without its sign-in time is not one this System can describe; the+ // owner signs in again.+ if (!record || sessions.expired(record, Date.now())) {await store.delete(key)@@ -61,6 +63,8 @@ export default class Sessions {exposed: false,+ createdAt: Date.now(),+disconnectedAt: Date.now(),connections: 0@@ -116,6 +120,16 @@ export default class Sessions {return true}+ /** When one known Session signed in, and when it was last used: now while a Connection uses it. */+ public describe(identity: string) {++ const record = this.identities.get(identity)++ if (!record) return null++ return { createdAt: new Date(record.createdAt), lastActiveAt: new Date(record.connections > 0 ? Date.now() : record.disconnectedAt ?? Date.now()) }+ }+/** Whether one Session still exists and can authorize a Connection. */public valid(identity: string) {@@ -126,14 +140,14 @@ export default class Sessions {if (this.validRecord(record, Date.now())) return truethis.forget(record)- this.expiredSession(record.identity)+ this.expiredSession(record)this.store.delete(this.key(record.hash)).catch(() => undefined)return false}/** Observes browser Sessions removed by disconnected-lifetime expiration. */- public onExpire(listener: (identity: string) => void) {+ public onExpire(listener: (identity: string, createdAt: Date) => void) {this.expirationListeners.add(listener)@@ -168,18 +182,18 @@ export default class Sessions {await this.persist(record)}- /** Permanently removes one Session. */+ /** Permanently removes one Session and returns when it signed in, or `null` when it was unknown. */public async remove(identity: string) {const record = this.identities.get(identity)- if (!record) return false+ if (!record) return nullthis.forget(record)await this.store.delete(this.key(record.hash))- return true+ return new Date(record.createdAt)}private validRecord(record: StoredSession, now: number) {@@ -209,7 +223,7 @@ export default class Sessions {for (const record of expired) {this.forget(record)- this.expiredSession(record.identity)+ this.expiredSession(record)}await Promise.all(expired.map(record => this.store.delete(this.key(record.hash))))@@ -223,6 +237,8 @@ export default class Sessions {identity: record.identity,+ createdAt: record.createdAt,+disconnectedAt: record.disconnectedAt})}@@ -233,9 +249,9 @@ export default class Sessions {this.hashes.delete(record.hash)}- private expiredSession(identity: string) {+ private expiredSession(record: StoredSession) {- for (const listener of this.expirationListeners) listener(identity)+ for (const listener of this.expirationListeners) listener(record.identity, new Date(record.createdAt))}private key(hash: string) { return storagePrefix + hash }@@ -246,14 +262,18 @@ function hashToken(token: string) {return createHash("sha256").update(token).digest("base64url")}-function parse(value: unknown, hash: string): StoredSession {+function parse(value: unknown, hash: string): StoredSession | null {if (!value || typeof value !== "object") throw new Error("An authentication Session is invalid")- const record = value as { identity?: unknown, disconnectedAt?: unknown }+ const record = value as { identity?: unknown, createdAt?: unknown, disconnectedAt?: unknown }++ if (record.createdAt === undefined) return nullif (typeof record.identity !== "string"+ || typeof record.createdAt !== "number" || !Number.isFinite(record.createdAt)+|| record.disconnectedAt !== null && (typeof record.disconnectedAt !== "number" || !Number.isFinite(record.disconnectedAt))) {throw new Error("An authentication Session is invalid")@@ -267,6 +287,8 @@ function parse(value: unknown, hash: string): StoredSession {exposed: true,+ createdAt: record.createdAt,+disconnectedAt: record.disconnectedAt,connections: 0@@ -281,6 +303,8 @@ interface StoredSession {exposed: boolean+ createdAt: number+disconnectedAt: number | nullconnections: numberdiff --git a/source/server/core/link-manager/auth-manager/auth-manager.ts b/source/server/core/link-manager/auth-manager/auth-manager.tsindex 9028b9f..3b40017 100644--- a/source/server/core/link-manager/auth-manager/auth-manager.ts+++ b/source/server/core/link-manager/auth-manager/auth-manager.ts@@ -334,7 +334,7 @@ export default class AuthManager extends TheLink {@Subscribe("/connection/state")protected async connectionState(identity: unknown) {- return this.linkManager.application.system.connectionSnapshot(domainIdentity(identity, "Connection"))+ return this.linkManager.application.system.connectionState(domainIdentity(identity, "Connection"))}@Subscribe("/connection/session")@@ -368,7 +368,7 @@ export default class AuthManager extends TheLink {@Subscribe("/session/state")protected async sessionState(identity: unknown) {- return this.linkManager.application.system.sessionSnapshot(domainIdentity(identity, "Session"))+ return this.linkManager.application.system.sessionState(domainIdentity(identity, "Session"))}@Subscribe("/session/connections")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.tsindex 0b92aa5..5adcf5a 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@@ -1929,7 +1929,7 @@ export default class ProcessManager extends TheLink {if (word.startsWith("host-connection-") && !access.canAuthentication()) throw new Error("Connection not found")- if (word === "host-connection-state") return [this.system.connectionSnapshot(String(rest[0]))]+ if (word === "host-connection-state") return [this.system.connectionState(String(rest[0]))]if (word === "host-connection-session") return [this.system.connectionSession(String(rest[0]))]@@ -1937,7 +1937,7 @@ export default class ProcessManager extends TheLink {if (!access.canAuthentication()) throw new Error("Session not found")- if (word === "host-session-state") return [this.system.sessionSnapshot(String(rest[0]))]+ if (word === "host-session-state") return [this.system.sessionState(String(rest[0]))]if (word === "host-session-connections") {diff --git a/source/server/core/link-manager/link-manager.ts b/source/server/core/link-manager/link-manager.tsindex d97521e..0a12db1 100644--- a/source/server/core/link-manager/link-manager.ts+++ b/source/server/core/link-manager/link-manager.ts@@ -2,7 +2,7 @@ import { Forward, Subscribe } from "@the-link/core/decorators"import AuthManager from "./auth-manager/auth-manager"import { Property, TheLink } from "@the-link/core"import Application from "../application"-import type { Appearance, ConnectionSnapshot, SessionEndReason, SessionSnapshot } from "@phreshos/core"+import type { Appearance, ConnectionSnapshot, ConnectionState, SessionEndReason, SessionSnapshot, SessionState } from "@phreshos/core"import { type AuthenticationState, type SignUpError } from "../authentication/authentication"import { AsyncLocalStorage } from "node:async_hooks"import shortIdentity from "@libs/short-identity"@@ -34,9 +34,9 @@ export default class LinkManager extends TheLink {this.authManager = new AuthManager(this)- this.application.authentication.onSessionExpire(identity => {+ this.application.authentication.onSessionExpire((identity, createdAt) => {- this.announceSessionEnd(identity, "expired").catch(() => undefined)+ this.announceSessionEnd(identity, createdAt, "expired").catch(() => undefined)})}@@ -226,7 +226,10 @@ export default class LinkManager extends TheLink {for (const connection of connections) connection.session = null- await this.application.authentication.removeSession(identity)+ // Removal returns when it signed in, so the ended Session is still described as it was.+ const createdAt = await this.application.authentication.removeSession(identity)++ if (!createdAt) throw new Error("Session not found")await Promise.allSettled(connections.map(connection => connection.link.$outbound.publish("/session/signed-out")))@@ -234,10 +237,10 @@ export default class LinkManager extends TheLink {await this.announceConnectionSession(connection, null)- await this.announceSessionConnection(identity, connection, false)+ await this.announceSessionConnection(identity, connection, false, createdAt)}- await this.announceSessionEnd(identity, "signedOut", connections)+ await this.announceSessionEnd(identity, createdAt, "signedOut", connections)}/** Ends the Sessions present at this operation's authoritative snapshot. */@@ -351,13 +354,49 @@ export default class LinkManager extends TheLink {connected: this.boundaries.get(connection.identity) === connection && !connection.signal.aborted,- session: connection.session && this.application.authentication.sessionFind(connection.session)+ session: connection.session && this.application.authentication.sessionFind(connection.session),++ connectedAt: connection.connectedAt+ })+ }++ /** What may change about one Connection, also after it is gone. */+ public connectionState(identity: string): ConnectionState {++ const connection = this.findConnection(identity)++ return Object.freeze({++ connected: connection !== null && this.boundaries.get(identity) === connection && !connection.signal.aborted,++ session: connection?.session ? this.application.authentication.sessionFind(connection.session) : null})}- public sessionSnapshot(identity: string, valid = this.application.authentication.sessionFind(identity) !== null): SessionSnapshot {+ public sessionSnapshot(+ identity: string,+ valid = this.application.authentication.sessionFind(identity) !== null,+ createdAt = this.sessionCreatedAt(identity)+ ): SessionSnapshot {- return Object.freeze({ identity, valid })+ return Object.freeze({ identity, valid, createdAt })+ }++ /** What may change about one Session, also after it ended. */+ public sessionState(identity: string): SessionState {++ const valid = this.application.authentication.sessionFind(identity) !== null++ return Object.freeze({ valid, lastActiveAt: valid ? this.application.authentication.describeSession(identity)!.lastActiveAt : null })+ }++ private sessionCreatedAt(identity: string) {++ const described = this.application.authentication.describeSession(identity)++ if (!described) throw new Error("Session not found")++ return described.createdAt}private async expose(connection: LinkBoundary) {@@ -433,9 +472,9 @@ export default class LinkManager extends TheLink {])}- private async announceSessionConnection(identity: string, connection: LinkBoundary, attached: boolean) {+ private async announceSessionConnection(identity: string, connection: LinkBoundary, attached: boolean, createdAt?: Date) {- const session = this.sessionSnapshot(identity, attached || this.application.authentication.sessionValid(identity))+ const session = this.sessionSnapshot(identity, attached || this.application.authentication.sessionValid(identity), createdAt)const snapshot = this.connectionSnapshot(connection)@@ -451,9 +490,9 @@ export default class LinkManager extends TheLink {])}- private async announceSessionEnd(identity: string, reason: SessionEndReason, previousConnections: readonly LinkBoundary[] = []) {+ private async announceSessionEnd(identity: string, createdAt: Date, reason: SessionEndReason, previousConnections: readonly LinkBoundary[] = []) {- const session = this.sessionSnapshot(identity, false)+ const session = this.sessionSnapshot(identity, false, createdAt)await Promise.all([@@ -506,6 +545,9 @@ export class LinkBoundary {public readonly identity = shortIdentity()+ /** When the browser connected. */+ public readonly connectedAt = new Date()+public session: string | null = nullpublic exposed = falsediff --git a/source/server/core/system.ts b/source/server/core/system.tsindex 7c52def..6bfff6a 100644--- a/source/server/core/system.ts+++ b/source/server/core/system.ts@@ -264,15 +264,9 @@ export default class System {return this.application.linkManager.findConnection(identity)}- public connectionSnapshot(identity: string) {+ public connectionState(identity: string) {- const connection = this.findConnection(identity)-- return connection-- ? this.application.linkManager.connectionSnapshot(connection)-- : Object.freeze({ identity, connected: false, session: null })+ return this.application.linkManager.connectionState(identity)}public connectionSession(identity: string) {@@ -305,9 +299,9 @@ export default class System {return this.application.authentication.sessionFind(identity)}- public sessionSnapshot(identity: string) {+ public sessionState(identity: string) {- return this.application.linkManager.sessionSnapshot(identity)+ return this.application.linkManager.sessionState(identity)}public sessionConnections(identity: string) {diff --git a/tests/authentication-domains.test.ts b/tests/authentication-domains.test.tsindex a6e3de6..04421ef 100644--- a/tests/authentication-domains.test.ts+++ b/tests/authentication-domains.test.ts@@ -62,18 +62,14 @@ test("browser Connections and Sessions form one authoritative lifecycle", asyncexpect(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.sessionState(created.identity)).toEqual({ valid: false, lastActiveAt: null })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.connectionState(secondConnection.identity)).toEqual({ connected: false, session: null })expect(application.system.connectionSession(secondConnection.identity)).toBeNull()expect(() => application.system.signInConnection(secondConnection.identity)).toThrow("Connection not found")} finally {diff --git a/tests/sessions.test.ts b/tests/sessions.test.tsindex f39d7c2..c6742d1 100644--- a/tests/sessions.test.ts+++ b/tests/sessions.test.ts@@ -28,6 +28,7 @@ describe("Session persistence and connection-bound lifetime", () => {expect(sessions.find(created.identity)).toBe(created.identity)expect(await store.get(`authentication:sessions:${hash}`)).toEqual({identity: created.identity,+ createdAt: expect.any(Number),disconnectedAt: expect.any(Number)})expect(await store.get(`authentication:sessions:${created.token}`)).toBeUndefined()@@ -50,6 +51,7 @@ describe("Session persistence and connection-bound lifetime", () => {expect(sessions.valid(created.identity)).toBe(true)expect(await persisted(store, created.token)).toEqual({identity: created.identity,+ createdAt: expect.any(Number),disconnectedAt: null})@@ -62,11 +64,40 @@ describe("Session persistence and connection-bound lifetime", () => {await store.disconnect()})+ test("describes when a Session signed in, and when it was last used", async () => {+ vi.useFakeTimers()+ vi.setSystemTime(new Date("2026-01-01T00:00:00Z"))+ const { sessions, store } = await fixture()+ const created = await sessions.create()+ await sessions.expose(created.identity)+ await sessions.attach(created.identity)++ vi.setSystemTime(new Date("2026-01-01T01:00:00Z"))+ expect(sessions.describe(created.identity)).toEqual({ createdAt: new Date("2026-01-01T00:00:00Z"), lastActiveAt: new Date("2026-01-01T01:00:00Z") })++ await sessions.detach(created.identity)+ vi.setSystemTime(new Date("2026-01-01T02:00:00Z"))+ expect(sessions.describe(created.identity)).toEqual({ createdAt: new Date("2026-01-01T00:00:00Z"), lastActiveAt: new Date("2026-01-01T01:00:00Z") })++ await store.disconnect()+ })++ test("a stored Session without its sign-in time is removed when the System opens", async () => {+ const { store } = await fixture()+ await store.set("authentication:sessions:old-hash", { identity: "old", disconnectedAt: Date.now() })++ const sessions = await Sessions.open(store)++ expect(sessions.find("old")).toBeNull()+ expect(await store.get("authentication:sessions:old-hash")).toBeUndefined()+ 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(await sessions.remove(created.identity)).toBeInstanceOf(Date)expect(sessions.find(created.identity)).toBeNull()expect(sessions.resolve(created.token)).toBeNull()