import { randomUUID } from 'node:crypto'; import { Session } from './session-protocol'; /** What JSON.stringify leaves out: a key holding it does not make a session changed. */ function isSerialized(value: unknown): boolean { return value !== undefined && typeof value !== 'function' && typeof value !== 'symbol'; } export class SessionImpl implements Session { /** From node:crypto: a session id must be unguessable on every runtime (Node.js 18 has no global `crypto`). */ readonly id: string; isNew = true; expire: number; maxAge: number; /** The serialized values of a restored session, to tell whether it changed. */ protected _snapshot?: string; /** `expire` and `maxAge` of a new session as created. */ protected _created?: { id: string, expire: number, maxAge: number }; /** * Every request without a session gets a new one, so a new session is cheap: no serialization, and * `changed` compares its few values instead of JSON. A restored session is serialized once to compare. */ constructor(sessionOptions: any, obj?: any) { if (obj) { this.isNew = false; for (const key of Object.keys(obj)) { (this as any)[key] = obj[key]; } this._snapshot = this.serialize(); } else { this.id = randomUUID(); this.expire = sessionOptions.maxAge + Date.now(); this.maxAge = sessionOptions.maxAge; this._created = { id: this.id, expire: this.expire, maxAge: this.maxAge }; } } protected serialize(): string { return JSON.stringify(this.toJSON()); } toJSON(): any { const obj: any = {}; for (const key of Object.keys(this)) { if (key !== 'isNew' && key[0] !== '_') { obj[key] = (this as any)[key]; } } return obj; } /** Whether the serialized session differs from the one created or restored. */ get changed(): boolean { const created = this._created; if (!created) { return this._snapshot !== this.serialize(); } // A new session holds only id, expire and maxAge: anything else that would be serialized is a change. for (const key of Object.keys(this)) { if (key === 'isNew' || key[0] === '_') { continue; } const value = (this as any)[key]; if (key === 'id' || key === 'expire' || key === 'maxAge') { if (value !== created[key]) { return true; } } else if (isSerialized(value)) { return true; } } return false; } }