An open-source, self-hosted system for apps built with web technologies.
Connections and Sessions keep a short description of the browser that opened them
zohayrslileh2587a4a3619f
diff --git a/source/libs/device-description.ts b/source/libs/device-description.tsnew file mode 100644index 0000000..038dad1--- /dev/null+++ b/source/libs/device-description.ts@@ -0,0 +1,36 @@+/**+ * A short description of the browser and system a User-Agent names, such as "Chrome on macOS", or+ * `null` when it names no browser this recognizes. Only the description is kept: the full text+ * says more about the machine than anyone reading a list of Sessions needs.+ */+export default function deviceDescription(userAgent: string | null): string | null {++ if (!userAgent) return null++ const browser = browsers.find(([, pattern]) => pattern.test(userAgent))?.[0]++ if (!browser) return null++ const system = systems.find(([, pattern]) => pattern.test(userAgent))?.[0]++ return system ? `${browser} on ${system}` : browser+}++// Order matters: browsers built on Chromium also name Chrome, and Chrome also names Safari.+const browsers: readonly (readonly [string, RegExp])[] = [+ ["Edge", /\bEdg(?:e|A|iOS)?\//],+ ["Opera", /\bOPR\/|\bOpera\b/],+ ["Firefox", /\bFirefox\/|\bFxiOS\//],+ ["Chrome", /\bChrome\/|\bCriOS\//],+ ["Safari", /\bSafari\//]+]++// iOS and Android name other systems too, so they come first.+const systems: readonly (readonly [string, RegExp])[] = [+ ["iOS", /\biPhone\b|\biPad\b|\biPod\b/],+ ["Android", /\bAndroid\b/],+ ["ChromeOS", /\bCrOS\b/],+ ["Windows", /\bWindows\b/],+ ["macOS", /\bMacintosh\b|\bMac OS X\b/],+ ["Linux", /\bLinux\b/]+]diff --git a/source/server/core/authentication/authentication.ts b/source/server/core/authentication/authentication.tsindex e3ec07d..d475e19 100644--- a/source/server/core/authentication/authentication.ts+++ b/source/server/core/authentication/authentication.ts@@ -1,7 +1,7 @@import { readFile, rename, rm, writeFile } from "node:fs/promises"import { randomBytes, randomUUID, scrypt as derive, timingSafeEqual } from "node:crypto"import { parseAuthenticationCredentials, type AuthenticationRequirements } from "@phreshos/core"-import Sessions from "./sessions"+import Sessions, { type SessionRecord } from "./sessions"import Keyv from "keyv"const parameters = {@@ -194,9 +194,9 @@ export default class Authentication {}/** Creates a Session and returns its Client-owned raw token exactly once. */- public createSession() {+ public createSession(device: string | null) {- return this.sessions.create()+ return this.sessions.create(device)}/** Resolves one Client-owned raw token to a valid Session identity. */@@ -224,7 +224,7 @@ export default class Authentication {}/** Observes browser Sessions removed by disconnected-lifetime expiration. */- public onSessionExpire(listener: (identity: string, createdAt: Date) => void) {+ public onSessionExpire(listener: (identity: string, record: SessionRecord) => void) {return this.sessions.onExpire(listener)}diff --git a/source/server/core/authentication/sessions.ts b/source/server/core/authentication/sessions.tsindex d803231..dabeb11 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, createdAt: Date) => void>()+ private readonly expirationListeners = new Set<(identity: string, record: SessionRecord) => void>()private constructor(private readonly store: Keyv) {}@@ -32,8 +32,8 @@ export default class Sessions {const record = parse(value, hash)- // A Session stored without its sign-in time is not one this System can describe; the- // owner signs in again.+ // A Session stored without its sign-in time and device is not one this System can+ // describe; the owner signs in again.if (!record || sessions.expired(record, Date.now())) {await store.delete(key)@@ -48,8 +48,8 @@ export default class Sessions {return sessions}- /** Creates one Session and returns the raw token exactly once. */- public async create(): Promise<CreatedSession> {+ /** Creates one Session for the device it signs in from, and returns the raw token exactly once. */+ public async create(device: string | null): Promise<CreatedSession> {await this.prune()@@ -65,6 +65,8 @@ export default class Sessions {createdAt: Date.now(),+ device,+disconnectedAt: Date.now(),connections: 0@@ -127,7 +129,10 @@ export default class Sessions {if (!record) return null- return { createdAt: new Date(record.createdAt), lastActiveAt: new Date(record.connections > 0 ? Date.now() : record.disconnectedAt ?? Date.now()) }+ return {+ ...recordOf(record),+ lastActiveAt: new Date(record.connections > 0 ? Date.now() : record.disconnectedAt ?? Date.now())+ }}/** Whether one Session still exists and can authorize a Connection. */@@ -147,7 +152,7 @@ export default class Sessions {}/** Observes browser Sessions removed by disconnected-lifetime expiration. */- public onExpire(listener: (identity: string, createdAt: Date) => void) {+ public onExpire(listener: (identity: string, record: SessionRecord) => void) {this.expirationListeners.add(listener)@@ -182,7 +187,7 @@ export default class Sessions {await this.persist(record)}- /** Permanently removes one Session and returns when it signed in, or `null` when it was unknown. */+ /** Permanently removes one Session and returns what described it, or `null` when it was unknown. */public async remove(identity: string) {const record = this.identities.get(identity)@@ -193,7 +198,7 @@ export default class Sessions {await this.store.delete(this.key(record.hash))- return new Date(record.createdAt)+ return recordOf(record)}private validRecord(record: StoredSession, now: number) {@@ -239,6 +244,8 @@ export default class Sessions {createdAt: record.createdAt,+ device: record.device,+disconnectedAt: record.disconnectedAt})}@@ -251,7 +258,7 @@ export default class Sessions {private expiredSession(record: StoredSession) {- for (const listener of this.expirationListeners) listener(record.identity, new Date(record.createdAt))+ for (const listener of this.expirationListeners) listener(record.identity, recordOf(record))}private key(hash: string) { return storagePrefix + hash }@@ -266,14 +273,16 @@ 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, createdAt?: unknown, disconnectedAt?: unknown }+ const record = value as { identity?: unknown, createdAt?: unknown, device?: unknown, disconnectedAt?: unknown }- if (record.createdAt === undefined) return null+ if (record.createdAt === undefined || record.device === undefined) return nullif (typeof record.identity !== "string"|| typeof record.createdAt !== "number" || !Number.isFinite(record.createdAt)+ || record.device !== null && typeof record.device !== "string"+|| record.disconnectedAt !== null && (typeof record.disconnectedAt !== "number" || !Number.isFinite(record.disconnectedAt))) {throw new Error("An authentication Session is invalid")@@ -289,6 +298,8 @@ function parse(value: unknown, hash: string): StoredSession | null {createdAt: record.createdAt,+ device: record.device,+disconnectedAt: record.disconnectedAt,connections: 0@@ -305,11 +316,21 @@ interface StoredSession {createdAt: number+ device: string | null+disconnectedAt: number | nullconnections: number}+/** What describes one Session, also after it ended. */+export type SessionRecord = Readonly<{ createdAt: Date, device: string | null }>++function recordOf(record: StoredSession): SessionRecord {++ return { createdAt: new Date(record.createdAt), device: record.device }+}+export type CreatedSession = Readonly<{identity: stringdiff --git a/source/server/core/link-manager/link-manager.ts b/source/server/core/link-manager/link-manager.tsindex 0a12db1..dcaa4fe 100644--- a/source/server/core/link-manager/link-manager.ts+++ b/source/server/core/link-manager/link-manager.ts@@ -34,27 +34,27 @@ export default class LinkManager extends TheLink {this.authManager = new AuthManager(this)- this.application.authentication.onSessionExpire((identity, createdAt) => {+ this.application.authentication.onSessionExpire((identity, record) => {- this.announceSessionEnd(identity, createdAt, "expired").catch(() => undefined)+ this.announceSessionEnd(identity, record, "expired").catch(() => undefined)})}- /** Creates an unclassified browser boundary. */- public addConnection(link: TheLink) {+ /** Creates an unclassified browser boundary; `device` describes the browser that opened it. */+ public addConnection(link: TheLink, device: string | null) {- return this.addBoundary(link, false)+ return this.addBoundary(link, false, device)}/** Creates a trusted transport boundary excluded from the Connection domain. */public addExternalConnection(link: TheLink) {- return this.addBoundary(link, true)+ return this.addBoundary(link, true, null)}- private addBoundary(link: TheLink, external: boolean) {+ private addBoundary(link: TheLink, external: boolean, device: string | null) {- const connection = new LinkBoundary(this, link, external)+ const connection = new LinkBoundary(this, link, external, device)this.boundaries.set(connection.identity, connection)@@ -70,7 +70,7 @@ export default class LinkManager extends TheLink {if (connection.external) throw new Error("External boundaries do not own browser Sessions")- const created = await this.application.authentication.createSession()+ const created = await this.application.authentication.createSession(connection.device)try {@@ -226,10 +226,10 @@ export default class LinkManager extends TheLink {for (const connection of connections) connection.session = null- // Removal returns when it signed in, so the ended Session is still described as it was.- const createdAt = await this.application.authentication.removeSession(identity)+ // Removal returns what described it, so the ended Session is still described as it was.+ const record = await this.application.authentication.removeSession(identity)- if (!createdAt) throw new Error("Session not found")+ if (!record) throw new Error("Session not found")await Promise.allSettled(connections.map(connection => connection.link.$outbound.publish("/session/signed-out")))@@ -237,10 +237,10 @@ export default class LinkManager extends TheLink {await this.announceConnectionSession(connection, null)- await this.announceSessionConnection(identity, connection, false, createdAt)+ await this.announceSessionConnection(identity, connection, false, record)}- await this.announceSessionEnd(identity, createdAt, "signedOut", connections)+ await this.announceSessionEnd(identity, record, "signedOut", connections)}/** Ends the Sessions present at this operation's authoritative snapshot. */@@ -356,7 +356,9 @@ export default class LinkManager extends TheLink {session: connection.session && this.application.authentication.sessionFind(connection.session),- connectedAt: connection.connectedAt+ connectedAt: connection.connectedAt,++ device: connection.device})}@@ -376,10 +378,10 @@ export default class LinkManager extends TheLink {public sessionSnapshot(identity: string,valid = this.application.authentication.sessionFind(identity) !== null,- createdAt = this.sessionCreatedAt(identity)+ record: SessionRecord = this.sessionRecord(identity)): SessionSnapshot {- return Object.freeze({ identity, valid, createdAt })+ return Object.freeze({ identity, valid, createdAt: record.createdAt, device: record.device })}/** What may change about one Session, also after it ended. */@@ -390,13 +392,13 @@ export default class LinkManager extends TheLink {return Object.freeze({ valid, lastActiveAt: valid ? this.application.authentication.describeSession(identity)!.lastActiveAt : null })}- private sessionCreatedAt(identity: string) {+ private sessionRecord(identity: string): SessionRecord {const described = this.application.authentication.describeSession(identity)if (!described) throw new Error("Session not found")- return described.createdAt+ return described}private async expose(connection: LinkBoundary) {@@ -472,9 +474,9 @@ export default class LinkManager extends TheLink {])}- private async announceSessionConnection(identity: string, connection: LinkBoundary, attached: boolean, createdAt?: Date) {+ private async announceSessionConnection(identity: string, connection: LinkBoundary, attached: boolean, record?: SessionRecord) {- const session = this.sessionSnapshot(identity, attached || this.application.authentication.sessionValid(identity), createdAt)+ const session = this.sessionSnapshot(identity, attached || this.application.authentication.sessionValid(identity), record)const snapshot = this.connectionSnapshot(connection)@@ -490,9 +492,9 @@ export default class LinkManager extends TheLink {])}- private async announceSessionEnd(identity: string, createdAt: Date, reason: SessionEndReason, previousConnections: readonly LinkBoundary[] = []) {+ private async announceSessionEnd(identity: string, record: SessionRecord, reason: SessionEndReason, previousConnections: readonly LinkBoundary[] = []) {- const session = this.sessionSnapshot(identity, false, createdAt)+ const session = this.sessionSnapshot(identity, false, record)await Promise.all([@@ -538,6 +540,9 @@ export interface LinkManagerSnapshot {appearance: ReturnType<Property<Appearance>["toJSON"]>}+/** What describes one Session, also after it ended. */+type SessionRecord = Readonly<{ createdAt: Date, device: string | null }>+export type SignUpResponse = { signedUp: true } | { error: SignUpError }/** One internal Link boundary. Only browser boundaries enter the public Connection registry. */@@ -564,7 +569,10 @@ export class LinkBoundary {public readonly link: TheLink,- public readonly external: boolean+ public readonly external: boolean,++ /** The browser and system that opened it, such as "Chrome on macOS". */+ public readonly device: string | null) {}diff --git a/source/server/view/http/link.ts b/source/server/view/http/link.tsindex 770e206..e52c35b 100644--- a/source/server/view/http/link.ts+++ b/source/server/view/http/link.ts@@ -3,6 +3,7 @@ import { upgradeWebSocket } from "@hono/node-server"import Application from "@server/core/application"import { HttpServer } from "@the-link/http/server"import messagepack from "@the-link/messagepack"+import deviceDescription from "@libs/device-description"export default function (application: Application, debugging: boolean) {@@ -16,7 +17,7 @@ export default function (application: Application, debugging: boolean) {http.onSubscribe(function (socketLink) {- const connection = application.linkManager.addConnection(socketLink)+ const connection = application.linkManager.addConnection(socketLink, deviceDescription(socketLink.request.headers.get("user-agent")))const stopForwarding = socketLink.$inbound.forwardTo(async function (event, responseUuid: string | null, ...values: unknown[]) {diff --git a/tests/authentication-domains.test.ts b/tests/authentication-domains.test.tsindex 04421ef..0702b38 100644--- a/tests/authentication-domains.test.ts+++ b/tests/authentication-domains.test.ts@@ -12,9 +12,9 @@ test("browser Connections and Sessions form one authoritative lifecycle", async{ system: join(home, "logo.png"), defaultProgram: join(home, "icon.png") })const link = new TheLink()- const connection = application.linkManager.addConnection(link)+ const connection = application.linkManager.addConnection(link, "Chrome on macOS")const secondLink = new TheLink()- const secondConnection = application.linkManager.addConnection(secondLink)+ const secondConnection = application.linkManager.addConnection(secondLink, null)let token: string | null = nulllet signedOut = 0const stopToken = link.$outbound.subscribe("/session/signed-in", value => {diff --git a/tests/device-description.test.ts b/tests/device-description.test.tsnew file mode 100644index 0000000..b05eaeb--- /dev/null+++ b/tests/device-description.test.ts@@ -0,0 +1,12 @@+import { expect, test } from "vitest"+import deviceDescription from "@libs/device-description"++test("a User-Agent becomes a short browser and system description", () => {+ expect(deviceDescription("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/155.0.0.0 Safari/537.36")).toBe("Chrome on macOS")+ expect(deviceDescription("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/154.0.0.0 Safari/537.36 Edg/154.0.0.0")).toBe("Edge on Windows")+ expect(deviceDescription("Mozilla/5.0 (X11; Linux x86_64; rv:140.0) Gecko/20100101 Firefox/140.0")).toBe("Firefox on Linux")+ expect(deviceDescription("Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Mobile/15E148 Safari/604.1")).toBe("Safari on iOS")+ expect(deviceDescription("Mozilla/5.0 (Linux; Android 15) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/154.0.0.0 Mobile Safari/537.36")).toBe("Chrome on Android")+ expect(deviceDescription("curl/8.7.1")).toBeNull()+ expect(deviceDescription(null)).toBeNull()+})diff --git a/tests/sessions.test.ts b/tests/sessions.test.tsindex c6742d1..2686a94 100644--- a/tests/sessions.test.ts+++ b/tests/sessions.test.ts@@ -17,7 +17,7 @@ afterEach(async () => {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 created = await sessions.create("Chrome on macOS")const hash = createHash("sha256").update(created.token).digest("base64url")expect(created.identity).not.toBe(created.token)@@ -29,6 +29,7 @@ describe("Session persistence and connection-bound lifetime", () => {expect(await store.get(`authentication:sessions:${hash}`)).toEqual({identity: created.identity,createdAt: expect.any(Number),+ device: "Chrome on macOS",disconnectedAt: expect.any(Number)})expect(await store.get(`authentication:sessions:${created.token}`)).toBeUndefined()@@ -40,7 +41,7 @@ describe("Session persistence and connection-bound lifetime", () => {vi.useFakeTimers()vi.setSystemTime(new Date("2026-01-01T00:00:00Z"))const { sessions, store } = await fixture()- const created = await sessions.create()+ const created = await sessions.create("Chrome on macOS")await sessions.attach(created.identity)await sessions.expose(created.identity)@@ -52,6 +53,7 @@ describe("Session persistence and connection-bound lifetime", () => {expect(await persisted(store, created.token)).toEqual({identity: created.identity,createdAt: expect.any(Number),+ device: "Chrome on macOS",disconnectedAt: null})@@ -68,21 +70,21 @@ describe("Session persistence and connection-bound lifetime", () => {vi.useFakeTimers()vi.setSystemTime(new Date("2026-01-01T00:00:00Z"))const { sessions, store } = await fixture()- const created = await sessions.create()+ const created = await sessions.create("Chrome on macOS")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") })+ expect(sessions.describe(created.identity)).toEqual({ createdAt: new Date("2026-01-01T00:00:00Z"), device: "Chrome on macOS", 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") })+ expect(sessions.describe(created.identity)).toEqual({ createdAt: new Date("2026-01-01T00:00:00Z"), device: "Chrome on macOS", 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 () => {+ test("a stored Session without its sign-in time or device is removed when the System opens", async () => {const { store } = await fixture()await store.set("authentication:sessions:old-hash", { identity: "old", disconnectedAt: Date.now() })@@ -95,9 +97,9 @@ describe("Session persistence and connection-bound lifetime", () => {test("removes an explicitly signed-out Session", async () => {const { sessions, store } = await fixture()- const created = await sessions.create()+ const created = await sessions.create("Chrome on macOS")- expect(await sessions.remove(created.identity)).toBeInstanceOf(Date)+ expect(await sessions.remove(created.identity)).toEqual({ createdAt: expect.any(Date), device: "Chrome on macOS" })expect(sessions.find(created.identity)).toBeNull()expect(sessions.resolve(created.token)).toBeNull()