cynx-lib 1.3.110 → 1.3.112

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/gen.js +77 -77
  2. package/package.json +1 -1
  3. package/ui/components/ActionsMenu.jsx +357 -357
  4. package/ui/components/Drawer.jsx +208 -208
  5. package/ui/components/Globe.jsx +764 -764
  6. package/ui/components/HoverCard.jsx +85 -85
  7. package/ui/components/PrivacyBlur.jsx +603 -603
  8. package/ui/components/Sidebar.jsx +10 -47
  9. package/ui/components/useRuler.jsx +0 -1
  10. package/ui/index.cjs +0 -2
  11. package/ui/index.js +1 -2
  12. package/utils/index.js +24 -24
  13. package/utils/utils/duration.js +139 -139
  14. package/utils/utils/oidc.js +214 -214
  15. package/utils/utils/realtime.js +1634 -1634
  16. package/utils/utils/server.js +371 -371
  17. package/utils/utils/session.js +131 -131
  18. package/utils/utils/session_manager.js +580 -580
  19. package/utils/utils/sso_manager.js +702 -702
  20. package/utils/utils/storage.js +393 -393
  21. package/utils/utils/ui.js +111 -111
  22. package/vue/components/Badge.vue +79 -79
  23. package/vue/components/Button.vue +209 -209
  24. package/vue/components/Checkbox.vue +103 -103
  25. package/vue/components/CircularProgress.vue +383 -383
  26. package/vue/components/Divider.vue +94 -94
  27. package/vue/components/Drawer.vue +243 -243
  28. package/vue/components/InfoBadge.vue +223 -223
  29. package/vue/components/Input.vue +341 -341
  30. package/vue/components/LinearProgress.vue +268 -268
  31. package/vue/components/Modal.vue +226 -226
  32. package/vue/components/Pagination.vue +199 -199
  33. package/vue/components/Select.vue +713 -713
  34. package/vue/components/Sidebar.vue +955 -955
  35. package/vue/components/Skeleton.vue +91 -91
  36. package/vue/components/Spinner.vue +263 -263
  37. package/vue/components/StatusTag.vue +89 -89
  38. package/vue/components/TabBar.vue +176 -176
  39. package/vue/components/Table.vue +388 -388
  40. package/vue/components/TimePicker.vue +399 -399
  41. package/vue/components/Toggle.vue +115 -115
  42. package/vue/components/XTable.vue +140 -140
  43. package/vue/composables/useAutoSkeletonRows.ts +71 -71
  44. package/vue/index.d.ts +67 -67
  45. package/vue/index.js +86 -86
@@ -1,580 +1,580 @@
1
- /**
2
- * cynx/utils — Universal Enterprise Session Manager (session_manager.js)
3
- *
4
- * Universal PostgreSQL and in-memory session management engine with dual-token architecture:
5
- * - v2: Compound token format (`st_${sessionId}$${secretCode}`) for O(1) indexed lookups
6
- * and safe non-secret Real-Time / WebSocket event targeting.
7
- * - v1: Legacy flat token format (`st_${hex}`) for seamless backward compatibility.
8
- *
9
- * STRICT NO EMOJIS!
10
- */
11
-
12
- import { genUid, getRandomBytes } from './uid.js';
13
- import { parseDurationMs } from './duration.js';
14
- import { deriveDeviceName, genSessionToken } from './session.js';
15
-
16
- /**
17
- * Format a compound v2 token: prefix + sessionId + '$' + secretCode
18
- * Example: "st_2SuO33NNKhXd$d9e1807390014a5b6c7d8e9f01234567"
19
- *
20
- * @param {string} sessionId Unique session row identifier (ID)
21
- * @param {string} secret Cryptographically secure random secret
22
- * @param {string} [prefix='st_'] Token prefix
23
- * @returns {string}
24
- */
25
- export function formatToken(sessionId, secret, prefix = 'st_') {
26
- return `${prefix}${sessionId}$${secret}`;
27
- }
28
-
29
- /**
30
- * Parse an incoming token string.
31
- * Automatically recognizes v2 compound tokens and legacy v1 flat tokens.
32
- *
33
- * @param {string} token Raw token string or Bearer header
34
- * @param {string} [prefix='st_'] Expected token prefix
35
- * @returns {{ version: number, sessionId: string|null, secret: string|null, prefix: string, raw: string, isValid: boolean }}
36
- */
37
- export function parseToken(token, prefix = 'st_') {
38
- if (!token || typeof token !== 'string') {
39
- return { version: 0, sessionId: null, secret: null, prefix, raw: '', isValid: false };
40
- }
41
- const clean = token.replace(/^Bearer\s+/i, '').trim();
42
- if (!clean) {
43
- return { version: 0, sessionId: null, secret: null, prefix, raw: '', isValid: false };
44
- }
45
-
46
- if (clean.includes('$')) {
47
- const parts = clean.split('$');
48
- const head = parts[0];
49
- const secret = parts.slice(1).join('$');
50
- const sessionId = head.startsWith(prefix) ? head.slice(prefix.length) : head;
51
- return {
52
- version: 2,
53
- sessionId,
54
- secret,
55
- prefix,
56
- raw: clean,
57
- isValid: Boolean(sessionId && secret),
58
- };
59
- }
60
-
61
- // Legacy v1 token (flat string without '$')
62
- return {
63
- version: 1,
64
- sessionId: null,
65
- secret: clean,
66
- prefix,
67
- raw: clean,
68
- isValid: true,
69
- };
70
- }
71
-
72
- /**
73
- * Extract public sessionId from token if available.
74
- * Returns null for legacy v1 tokens.
75
- *
76
- * @param {string} token
77
- * @param {string} [prefix='st_']
78
- * @returns {string|null}
79
- */
80
- export function getSessionId(token, prefix = 'st_') {
81
- const parsed = parseToken(token, prefix);
82
- return parsed.sessionId;
83
- }
84
-
85
- /**
86
- * Universally extract session token from HTTP Request object (Express, Fastify, Next.js, Node).
87
- * Inspects Authorization Bearer header, x-auth-token, x-session-token, and query parameter.
88
- *
89
- * @param {object} req HTTP request object
90
- * @returns {string} Clean session token string or empty string
91
- */
92
- export function extractToken(req) {
93
- if (!req) return '';
94
- const headers = req.headers || {};
95
- const auth = headers.authorization || headers.Authorization || '';
96
- if (typeof auth === 'string' && auth.startsWith('Bearer ')) {
97
- return auth.split(' ')[1].trim();
98
- }
99
- const custom = headers['x-auth-token'] || headers['x-session-token'] || headers['x-token'] || '';
100
- if (typeof custom === 'string' && custom.trim()) {
101
- return custom.trim();
102
- }
103
- if (req.query && req.query.token) {
104
- return String(req.query.token).trim();
105
- }
106
- return '';
107
- }
108
-
109
- /**
110
- * Universal Session Manager Engine.
111
- */
112
- export class SessionManager {
113
- constructor(queryOrOptions = {}, sessionsTable, usersTable, rolesTable, settingsTable) {
114
- let opts = {};
115
- if (typeof queryOrOptions === 'function') {
116
- opts = {
117
- query: queryOrOptions,
118
- ...(typeof sessionsTable === 'string' ? { sessionsTable } : (typeof sessionsTable === 'object' && sessionsTable !== null ? sessionsTable : {})),
119
- ...(typeof usersTable === 'string' ? { usersTable } : {}),
120
- ...(typeof rolesTable === 'string' ? { rolesTable } : {}),
121
- ...(typeof settingsTable === 'string' ? { settingsTable } : {}),
122
- };
123
- } else if (typeof queryOrOptions === 'string') {
124
- opts = { sessionsTable: queryOrOptions };
125
- } else if (queryOrOptions && typeof queryOrOptions === 'object') {
126
- opts = {
127
- ...queryOrOptions,
128
- ...(typeof sessionsTable === 'string' ? { sessionsTable } : {}),
129
- };
130
- }
131
-
132
- this.options = {
133
- query: opts.query || null,
134
- sessionsTable: opts.sessionsTable || 'sessions',
135
- usersTable: opts.usersTable || 'users',
136
- rolesTable: opts.rolesTable || 'roles',
137
- settingsTable: opts.settingsTable || 'settings',
138
- employeeColumn: opts.employeeColumn || 'employee',
139
- superRole: (opts.superRole || 'superadmin').toLowerCase(),
140
- tokenPrefix: opts.tokenPrefix || 'st_',
141
- tokenVersion: opts.tokenVersion || 2,
142
- secretBytes: opts.secretBytes || 32,
143
- idLength: opts.idLength || 12,
144
- defaultAbsoluteTimeoutMs: opts.defaultAbsoluteTimeoutMs || 30 * 24 * 60 * 60 * 1000,
145
- inactivityCacheTtlMs: opts.inactivityCacheTtlMs || 30000,
146
- jwtSecret: opts.jwtSecret || (typeof process !== 'undefined' ? process.env.JWT_SECRET : ''),
147
- ...opts,
148
- };
149
-
150
- this._inactTimeoutMs = null;
151
- this._inactFetchedAt = 0;
152
- }
153
-
154
- async _query(sql, params = []) {
155
- if (typeof this.options.query !== 'function') {
156
- throw new Error('[cynx/session] Database query function not configured in SessionManager.');
157
- }
158
- return this.options.query(sql, params);
159
- }
160
-
161
- parseToken(token) {
162
- return parseToken(token, this.options.tokenPrefix);
163
- }
164
-
165
- getSessionId(token) {
166
- return getSessionId(token, this.options.tokenPrefix);
167
- }
168
-
169
- extractToken(req) {
170
- return extractToken(req);
171
- }
172
-
173
- formatToken(sessionId, secret) {
174
- return formatToken(sessionId, secret, this.options.tokenPrefix);
175
- }
176
-
177
- async getInactivityTimeoutMs() {
178
- const now = Date.now();
179
- if (this._inactTimeoutMs !== null && now - this._inactFetchedAt < this.options.inactivityCacheTtlMs) {
180
- return this._inactTimeoutMs;
181
- }
182
- try {
183
- const sql = `SELECT value FROM ${this.options.settingsTable} WHERE key = 'session_inactivity_timeout'`;
184
- const sRes = await this._query(sql).catch(() => ({ rows: [] }));
185
- if (sRes.rows && sRes.rows.length > 0) {
186
- let val = sRes.rows[0].value;
187
- if (typeof val === 'string') {
188
- try { val = JSON.parse(val); } catch {}
189
- }
190
- this._inactTimeoutMs = parseDurationMs(val, 0);
191
- } else {
192
- this._inactTimeoutMs = 0;
193
- }
194
- } catch {
195
- this._inactTimeoutMs = 0;
196
- }
197
- this._inactFetchedAt = now;
198
- return this._inactTimeoutMs;
199
- }
200
-
201
- clearSettingsCache() {
202
- this._inactTimeoutMs = null;
203
- this._inactFetchedAt = 0;
204
- }
205
-
206
- /**
207
- * Create and persist a new session for a user.
208
- *
209
- * @param {string|number} userId
210
- * @param {object} [req] HTTP request object for device and IP detection
211
- * @param {object} [options]
212
- * @returns {Promise<string>} Generated session token
213
- */
214
- async createSession(userId, req = null, options = {}) {
215
- const id = genUid(this.options.idLength);
216
- const userAgent = (req?.headers ? req.headers['user-agent'] || '' : '').slice(0, 500);
217
- const ipAddress = (req?.headers ? req.headers['x-forwarded-for'] || req.socket?.remoteAddress || '' : '').slice(0, 45);
218
- const deviceName = deriveDeviceName(req, userAgent);
219
-
220
- let token;
221
- if (this.options.tokenVersion === 2) {
222
- const bytes = getRandomBytes(this.options.secretBytes);
223
- let hex = '';
224
- for (let i = 0; i < bytes.length; i++) {
225
- hex += bytes[i].toString(16).padStart(2, '0');
226
- }
227
- token = formatToken(id, hex, this.options.tokenPrefix);
228
- } else {
229
- token = genSessionToken(this.options.secretBytes);
230
- }
231
-
232
- let absoluteMs = this.options.defaultAbsoluteTimeoutMs;
233
- try {
234
- const sRes = await this._query(`SELECT value FROM ${this.options.settingsTable} WHERE key = 'session_absolute_timeout'`);
235
- if (sRes.rows && sRes.rows.length > 0) {
236
- let val = sRes.rows[0].value;
237
- if (typeof val === 'string') {
238
- try { val = JSON.parse(val); } catch {}
239
- }
240
- const parsed = parseDurationMs(val, absoluteMs);
241
- if (parsed > 0) absoluteMs = parsed;
242
- }
243
- } catch {}
244
-
245
- const expiresAt = new Date(Date.now() + absoluteMs);
246
-
247
- const insertSql = `
248
- INSERT INTO ${this.options.sessionsTable} (id, user_id, token, user_agent, device_name, ip_address, is_active, expires_at)
249
- VALUES ($1, $2, $3, $4, $5, $6, true, $7)
250
- `;
251
- await this._query(insertSql, [id, userId, token, userAgent, deviceName, ipAddress, expiresAt]);
252
-
253
- return token;
254
- }
255
-
256
- /**
257
- * Validate a session token against PostgreSQL database and users table.
258
- * Seamlessly resolves v2 compound tokens (O(1) lookup by primary key id) and v1 tokens.
259
- *
260
- * @param {string} token
261
- * @param {object} [options] Options: { updateActivity: boolean }
262
- * @returns {Promise<object|null>}
263
- */
264
- async validateSession(token, options = {}) {
265
- if (!token || typeof token !== 'string') return null;
266
- const cleanToken = token.replace(/^Bearer\s+/i, '').trim();
267
- if (!cleanToken) return null;
268
-
269
- try {
270
- const parsed = parseToken(cleanToken, this.options.tokenPrefix);
271
- const empCol = this.options.employeeColumn || 'employee';
272
- let sessionRes;
273
-
274
- if (parsed.version === 2 && parsed.sessionId) {
275
- // v2: Ultra-fast O(1) Primary Key lookup by id
276
- const sql = `
277
- SELECT s.id as session_id, s.user_id, s.token, s.is_active as session_active,
278
- s.expires_at, s.last_activity, s.device_name, s.ip_address,
279
- u.id as user_id, u.username, u.full_name, u.role, u.is_active as user_active,
280
- COALESCE(u.is_disabled, false) as user_disabled,
281
- u.${empCol} as employee,
282
- u.permissions as user_permissions,
283
- r.permissions as role_permissions
284
- FROM ${this.options.sessionsTable} s
285
- JOIN ${this.options.usersTable} u ON u.id = s.user_id
286
- LEFT JOIN ${this.options.rolesTable} r ON r.id = u.role OR r.name = u.role OR LOWER(r.name) = LOWER(u.role)
287
- WHERE s.id = $1
288
- `;
289
- sessionRes = await this._query(sql, [parsed.sessionId]).catch(() => ({ rows: [] }));
290
- } else {
291
- // v1 (legacy): Direct token string matching
292
- const sql = `
293
- SELECT s.id as session_id, s.user_id, s.token, s.is_active as session_active,
294
- s.expires_at, s.last_activity, s.device_name, s.ip_address,
295
- u.id as user_id, u.username, u.full_name, u.role, u.is_active as user_active,
296
- COALESCE(u.is_disabled, false) as user_disabled,
297
- u.${empCol} as employee,
298
- u.permissions as user_permissions,
299
- r.permissions as role_permissions
300
- FROM ${this.options.sessionsTable} s
301
- JOIN ${this.options.usersTable} u ON u.id = s.user_id
302
- LEFT JOIN ${this.options.rolesTable} r ON r.id = u.role OR r.name = u.role OR LOWER(r.name) = LOWER(u.role)
303
- WHERE s.token = $1
304
- `;
305
- sessionRes = await this._query(sql, [cleanToken]).catch(() => ({ rows: [] }));
306
- }
307
-
308
- if (sessionRes.rows && sessionRes.rows.length > 0) {
309
- const row = sessionRes.rows[0];
310
-
311
- // Security check: verify that row.token matches cleanToken
312
- if (row.token !== cleanToken) {
313
- return null;
314
- }
315
-
316
- const now = new Date();
317
-
318
- // Check active status & expiration
319
- if (!row.session_active || !row.user_active || row.user_disabled || new Date(row.expires_at) < now) {
320
- return null;
321
- }
322
-
323
- // Check inactivity timeout
324
- const inactTimeoutMs = await this.getInactivityTimeoutMs();
325
- if (inactTimeoutMs > 0 && row.last_activity) {
326
- const lastAct = new Date(row.last_activity).getTime();
327
- if (now.getTime() - lastAct > inactTimeoutMs) {
328
- this._query(`UPDATE ${this.options.sessionsTable} SET is_active = false WHERE id = $1`, [row.session_id]).catch(() => {});
329
- return null;
330
- }
331
- }
332
-
333
- // Asynchronously update last_activity
334
- if (options.updateActivity !== false) {
335
- this._query(`UPDATE ${this.options.sessionsTable} SET last_activity = NOW() WHERE id = $1`, [row.session_id]).catch(() => {});
336
- }
337
-
338
- return {
339
- valid: true,
340
- userId: row.user_id,
341
- sessionId: row.session_id,
342
- token: cleanToken,
343
- role: row.role,
344
- employee: row.employee || null,
345
- employeeId: row.employee || null,
346
- leaderId: null,
347
- userPermissions: row.user_permissions || {},
348
- rolePermissions: row.role_permissions || {},
349
- user: {
350
- id: row.user_id,
351
- username: row.username,
352
- fullName: row.full_name,
353
- role: row.role,
354
- employee: row.employee || null,
355
- employeeId: row.employee || null,
356
- leaderId: null,
357
- },
358
- };
359
- }
360
-
361
- // Legacy JWT fallback if enabled
362
- if (this.options.jwtSecret) {
363
- try {
364
- const jwtModule = typeof require === 'function' ? require('jsonwebtoken') : null;
365
- if (jwtModule) {
366
- const decoded = jwtModule.verify(cleanToken, this.options.jwtSecret);
367
- if (decoded && (decoded.userId || decoded.id)) {
368
- const uId = decoded.userId || decoded.id;
369
- const uRes = await this._query(
370
- `SELECT u.id, u.username, u.full_name, u.role, u.is_active, COALESCE(u.is_disabled, false) as is_disabled,
371
- u.${empCol} as employee, u.permissions as user_permissions, r.permissions as role_permissions
372
- FROM ${this.options.usersTable} u
373
- LEFT JOIN ${this.options.rolesTable} r ON r.id = u.role OR r.name = u.role OR LOWER(r.name) = LOWER(u.role)
374
- WHERE u.id = $1`,
375
- [uId]
376
- ).catch(() => ({ rows: [] }));
377
-
378
- if (uRes.rows && uRes.rows.length > 0 && uRes.rows[0].is_active && !uRes.rows[0].is_disabled) {
379
- const uRow = uRes.rows[0];
380
- return {
381
- valid: true,
382
- userId: uRow.id,
383
- sessionId: null,
384
- token: cleanToken,
385
- role: uRow.role || decoded.role,
386
- employee: uRow.employee || null,
387
- employeeId: uRow.employee || null,
388
- leaderId: null,
389
- userPermissions: uRow.user_permissions || {},
390
- rolePermissions: uRow.role_permissions || {},
391
- user: {
392
- id: uRow.id,
393
- username: uRow.username,
394
- fullName: uRow.full_name,
395
- role: uRow.role || decoded.role,
396
- employee: uRow.employee || null,
397
- employeeId: uRow.employee || null,
398
- leaderId: null,
399
- },
400
- };
401
- }
402
- }
403
- }
404
- } catch {}
405
- }
406
-
407
- return null;
408
- } catch (err) {
409
- console.warn('[SessionManager validateSession error]:', err.message);
410
- return null;
411
- }
412
- }
413
-
414
- /**
415
- * Lock a session screen.
416
- *
417
- * @param {string} sessionIdOrToken Session ID or Token
418
- * @returns {Promise<{ ok: boolean, sessionId: string, userId: string, token: string } | null>}
419
- */
420
- async lockSession(sessionIdOrToken) {
421
- if (!sessionIdOrToken) return null;
422
- const parsed = parseToken(sessionIdOrToken, this.options.tokenPrefix);
423
- const idToUse = parsed.sessionId || sessionIdOrToken;
424
-
425
- const sql = `
426
- UPDATE ${this.options.sessionsTable}
427
- SET is_locked = true, locked_at = NOW()
428
- WHERE (id = $1 OR token = $1) AND is_active = true
429
- RETURNING id, user_id, token
430
- `;
431
- const r = await this._query(sql, [idToUse]);
432
- if (r.rows && r.rows.length > 0) {
433
- const row = r.rows[0];
434
- return { ok: true, sessionId: row.id, userId: row.user_id, token: row.token };
435
- }
436
- return null;
437
- }
438
-
439
- /**
440
- * Unlock a session screen.
441
- *
442
- * @param {string} sessionIdOrToken Session ID or Token
443
- * @returns {Promise<{ ok: boolean, sessionId: string, userId: string, token: string } | null>}
444
- */
445
- async unlockSession(sessionIdOrToken) {
446
- if (!sessionIdOrToken) return null;
447
- const parsed = parseToken(sessionIdOrToken, this.options.tokenPrefix);
448
- const idToUse = parsed.sessionId || sessionIdOrToken;
449
-
450
- const sql = `
451
- UPDATE ${this.options.sessionsTable}
452
- SET is_locked = false, locked_at = NULL
453
- WHERE (id = $1 OR token = $1) AND is_active = true
454
- RETURNING id, user_id, token
455
- `;
456
- const r = await this._query(sql, [idToUse]);
457
- if (r.rows && r.rows.length > 0) {
458
- const row = r.rows[0];
459
- return { ok: true, sessionId: row.id, userId: row.user_id, token: row.token };
460
- }
461
- return null;
462
- }
463
-
464
- /**
465
- * Terminate/revoke a single session.
466
- *
467
- * @param {string} sessionIdOrToken Session ID or Token
468
- * @returns {Promise<{ ok: boolean, sessionId: string, userId: string, token: string } | null>}
469
- */
470
- async terminateSession(sessionIdOrToken) {
471
- if (!sessionIdOrToken) return null;
472
- const parsed = parseToken(sessionIdOrToken, this.options.tokenPrefix);
473
- const idToUse = parsed.sessionId || sessionIdOrToken;
474
-
475
- const sql = `
476
- UPDATE ${this.options.sessionsTable}
477
- SET is_active = false
478
- WHERE id = $1 OR token = $1
479
- RETURNING id, user_id, token
480
- `;
481
- const r = await this._query(sql, [idToUse]);
482
- if (r.rows && r.rows.length > 0) {
483
- const row = r.rows[0];
484
- return { ok: true, sessionId: row.id, userId: row.user_id, token: row.token };
485
- }
486
- return null;
487
- }
488
-
489
- /**
490
- * Terminate all other sessions except the current one.
491
- *
492
- * @param {string} currentSessionIdOrToken Current session ID or token to preserve
493
- * @param {string|number} [currentUserId]
494
- * @param {boolean} [protectSuperAdmin=true]
495
- * @returns {Promise<Array<{ sessionId: string, userId: string, token: string }>>}
496
- */
497
- async terminateOtherSessions(currentSessionIdOrToken, currentUserId = null, protectSuperAdmin = true) {
498
- const parsed = parseToken(currentSessionIdOrToken, this.options.tokenPrefix);
499
- const preserveId = parsed.sessionId || currentSessionIdOrToken;
500
-
501
- let whereClause = `id != $1 AND token != $1`;
502
- let params = [preserveId];
503
-
504
- if (currentUserId) {
505
- whereClause += ` AND user_id = $2`;
506
- params.push(currentUserId);
507
- } else if (protectSuperAdmin) {
508
- whereClause += ` AND user_id NOT IN (SELECT id FROM ${this.options.usersTable} WHERE LOWER(COALESCE(role, '')) = '${this.options.superRole}' OR LOWER(username) = '${this.options.superRole}')`;
509
- }
510
-
511
- const sql = `
512
- UPDATE ${this.options.sessionsTable}
513
- SET is_active = false
514
- WHERE ${whereClause} AND is_active = true
515
- RETURNING id, user_id, token
516
- `;
517
- const r = await this._query(sql, params);
518
- return (r.rows || []).map(row => ({
519
- sessionId: row.id,
520
- userId: row.user_id,
521
- token: row.token,
522
- }));
523
- }
524
-
525
- /**
526
- * Terminate all active sessions for a specific user.
527
- *
528
- * @param {string|number} userId
529
- * @returns {Promise<Array<{ sessionId: string, userId: string, token: string }>>}
530
- */
531
- async terminateUserSessions(userId) {
532
- if (!userId) return [];
533
- const sql = `
534
- UPDATE ${this.options.sessionsTable}
535
- SET is_active = false
536
- WHERE user_id = $1 AND is_active = true
537
- RETURNING id, user_id, token
538
- `;
539
- const r = await this._query(sql, [userId]);
540
- return (r.rows || []).map(row => ({
541
- sessionId: row.id,
542
- userId: row.user_id,
543
- token: row.token,
544
- }));
545
- }
546
-
547
- /**
548
- * Aliases for backward compatibility.
549
- */
550
- async revokeSession(tokenOrId) {
551
- return this.terminateSession(tokenOrId);
552
- }
553
-
554
- async revokeAllUserSessions(userId) {
555
- return this.terminateUserSessions(userId);
556
- }
557
- }
558
-
559
- /**
560
- * Universal Factory.
561
- */
562
- export function createSessionManager(queryOrOptions = {}, sessionsTable, usersTable, rolesTable, settingsTable) {
563
- return new SessionManager(queryOrOptions, sessionsTable, usersTable, rolesTable, settingsTable);
564
- }
565
-
566
- export {
567
- genSessionToken,
568
- getDeviceLabel,
569
- parseUserAgent,
570
- deriveDeviceName,
571
- } from './session.js';
572
-
573
- export default {
574
- SessionManager,
575
- createSessionManager,
576
- formatToken,
577
- parseToken,
578
- getSessionId,
579
- extractToken,
580
- };
1
+ /**
2
+ * cynx/utils — Universal Enterprise Session Manager (session_manager.js)
3
+ *
4
+ * Universal PostgreSQL and in-memory session management engine with dual-token architecture:
5
+ * - v2: Compound token format (`st_${sessionId}$${secretCode}`) for O(1) indexed lookups
6
+ * and safe non-secret Real-Time / WebSocket event targeting.
7
+ * - v1: Legacy flat token format (`st_${hex}`) for seamless backward compatibility.
8
+ *
9
+ * STRICT NO EMOJIS!
10
+ */
11
+
12
+ import { genUid, getRandomBytes } from './uid.js';
13
+ import { parseDurationMs } from './duration.js';
14
+ import { deriveDeviceName, genSessionToken } from './session.js';
15
+
16
+ /**
17
+ * Format a compound v2 token: prefix + sessionId + '$' + secretCode
18
+ * Example: "st_2SuO33NNKhXd$d9e1807390014a5b6c7d8e9f01234567"
19
+ *
20
+ * @param {string} sessionId Unique session row identifier (ID)
21
+ * @param {string} secret Cryptographically secure random secret
22
+ * @param {string} [prefix='st_'] Token prefix
23
+ * @returns {string}
24
+ */
25
+ export function formatToken(sessionId, secret, prefix = 'st_') {
26
+ return `${prefix}${sessionId}$${secret}`;
27
+ }
28
+
29
+ /**
30
+ * Parse an incoming token string.
31
+ * Automatically recognizes v2 compound tokens and legacy v1 flat tokens.
32
+ *
33
+ * @param {string} token Raw token string or Bearer header
34
+ * @param {string} [prefix='st_'] Expected token prefix
35
+ * @returns {{ version: number, sessionId: string|null, secret: string|null, prefix: string, raw: string, isValid: boolean }}
36
+ */
37
+ export function parseToken(token, prefix = 'st_') {
38
+ if (!token || typeof token !== 'string') {
39
+ return { version: 0, sessionId: null, secret: null, prefix, raw: '', isValid: false };
40
+ }
41
+ const clean = token.replace(/^Bearer\s+/i, '').trim();
42
+ if (!clean) {
43
+ return { version: 0, sessionId: null, secret: null, prefix, raw: '', isValid: false };
44
+ }
45
+
46
+ if (clean.includes('$')) {
47
+ const parts = clean.split('$');
48
+ const head = parts[0];
49
+ const secret = parts.slice(1).join('$');
50
+ const sessionId = head.startsWith(prefix) ? head.slice(prefix.length) : head;
51
+ return {
52
+ version: 2,
53
+ sessionId,
54
+ secret,
55
+ prefix,
56
+ raw: clean,
57
+ isValid: Boolean(sessionId && secret),
58
+ };
59
+ }
60
+
61
+ // Legacy v1 token (flat string without '$')
62
+ return {
63
+ version: 1,
64
+ sessionId: null,
65
+ secret: clean,
66
+ prefix,
67
+ raw: clean,
68
+ isValid: true,
69
+ };
70
+ }
71
+
72
+ /**
73
+ * Extract public sessionId from token if available.
74
+ * Returns null for legacy v1 tokens.
75
+ *
76
+ * @param {string} token
77
+ * @param {string} [prefix='st_']
78
+ * @returns {string|null}
79
+ */
80
+ export function getSessionId(token, prefix = 'st_') {
81
+ const parsed = parseToken(token, prefix);
82
+ return parsed.sessionId;
83
+ }
84
+
85
+ /**
86
+ * Universally extract session token from HTTP Request object (Express, Fastify, Next.js, Node).
87
+ * Inspects Authorization Bearer header, x-auth-token, x-session-token, and query parameter.
88
+ *
89
+ * @param {object} req HTTP request object
90
+ * @returns {string} Clean session token string or empty string
91
+ */
92
+ export function extractToken(req) {
93
+ if (!req) return '';
94
+ const headers = req.headers || {};
95
+ const auth = headers.authorization || headers.Authorization || '';
96
+ if (typeof auth === 'string' && auth.startsWith('Bearer ')) {
97
+ return auth.split(' ')[1].trim();
98
+ }
99
+ const custom = headers['x-auth-token'] || headers['x-session-token'] || headers['x-token'] || '';
100
+ if (typeof custom === 'string' && custom.trim()) {
101
+ return custom.trim();
102
+ }
103
+ if (req.query && req.query.token) {
104
+ return String(req.query.token).trim();
105
+ }
106
+ return '';
107
+ }
108
+
109
+ /**
110
+ * Universal Session Manager Engine.
111
+ */
112
+ export class SessionManager {
113
+ constructor(queryOrOptions = {}, sessionsTable, usersTable, rolesTable, settingsTable) {
114
+ let opts = {};
115
+ if (typeof queryOrOptions === 'function') {
116
+ opts = {
117
+ query: queryOrOptions,
118
+ ...(typeof sessionsTable === 'string' ? { sessionsTable } : (typeof sessionsTable === 'object' && sessionsTable !== null ? sessionsTable : {})),
119
+ ...(typeof usersTable === 'string' ? { usersTable } : {}),
120
+ ...(typeof rolesTable === 'string' ? { rolesTable } : {}),
121
+ ...(typeof settingsTable === 'string' ? { settingsTable } : {}),
122
+ };
123
+ } else if (typeof queryOrOptions === 'string') {
124
+ opts = { sessionsTable: queryOrOptions };
125
+ } else if (queryOrOptions && typeof queryOrOptions === 'object') {
126
+ opts = {
127
+ ...queryOrOptions,
128
+ ...(typeof sessionsTable === 'string' ? { sessionsTable } : {}),
129
+ };
130
+ }
131
+
132
+ this.options = {
133
+ query: opts.query || null,
134
+ sessionsTable: opts.sessionsTable || 'sessions',
135
+ usersTable: opts.usersTable || 'users',
136
+ rolesTable: opts.rolesTable || 'roles',
137
+ settingsTable: opts.settingsTable || 'settings',
138
+ employeeColumn: opts.employeeColumn || 'employee',
139
+ superRole: (opts.superRole || 'superadmin').toLowerCase(),
140
+ tokenPrefix: opts.tokenPrefix || 'st_',
141
+ tokenVersion: opts.tokenVersion || 2,
142
+ secretBytes: opts.secretBytes || 32,
143
+ idLength: opts.idLength || 12,
144
+ defaultAbsoluteTimeoutMs: opts.defaultAbsoluteTimeoutMs || 30 * 24 * 60 * 60 * 1000,
145
+ inactivityCacheTtlMs: opts.inactivityCacheTtlMs || 30000,
146
+ jwtSecret: opts.jwtSecret || (typeof process !== 'undefined' ? process.env.JWT_SECRET : ''),
147
+ ...opts,
148
+ };
149
+
150
+ this._inactTimeoutMs = null;
151
+ this._inactFetchedAt = 0;
152
+ }
153
+
154
+ async _query(sql, params = []) {
155
+ if (typeof this.options.query !== 'function') {
156
+ throw new Error('[cynx/session] Database query function not configured in SessionManager.');
157
+ }
158
+ return this.options.query(sql, params);
159
+ }
160
+
161
+ parseToken(token) {
162
+ return parseToken(token, this.options.tokenPrefix);
163
+ }
164
+
165
+ getSessionId(token) {
166
+ return getSessionId(token, this.options.tokenPrefix);
167
+ }
168
+
169
+ extractToken(req) {
170
+ return extractToken(req);
171
+ }
172
+
173
+ formatToken(sessionId, secret) {
174
+ return formatToken(sessionId, secret, this.options.tokenPrefix);
175
+ }
176
+
177
+ async getInactivityTimeoutMs() {
178
+ const now = Date.now();
179
+ if (this._inactTimeoutMs !== null && now - this._inactFetchedAt < this.options.inactivityCacheTtlMs) {
180
+ return this._inactTimeoutMs;
181
+ }
182
+ try {
183
+ const sql = `SELECT value FROM ${this.options.settingsTable} WHERE key = 'session_inactivity_timeout'`;
184
+ const sRes = await this._query(sql).catch(() => ({ rows: [] }));
185
+ if (sRes.rows && sRes.rows.length > 0) {
186
+ let val = sRes.rows[0].value;
187
+ if (typeof val === 'string') {
188
+ try { val = JSON.parse(val); } catch {}
189
+ }
190
+ this._inactTimeoutMs = parseDurationMs(val, 0);
191
+ } else {
192
+ this._inactTimeoutMs = 0;
193
+ }
194
+ } catch {
195
+ this._inactTimeoutMs = 0;
196
+ }
197
+ this._inactFetchedAt = now;
198
+ return this._inactTimeoutMs;
199
+ }
200
+
201
+ clearSettingsCache() {
202
+ this._inactTimeoutMs = null;
203
+ this._inactFetchedAt = 0;
204
+ }
205
+
206
+ /**
207
+ * Create and persist a new session for a user.
208
+ *
209
+ * @param {string|number} userId
210
+ * @param {object} [req] HTTP request object for device and IP detection
211
+ * @param {object} [options]
212
+ * @returns {Promise<string>} Generated session token
213
+ */
214
+ async createSession(userId, req = null, options = {}) {
215
+ const id = genUid(this.options.idLength);
216
+ const userAgent = (req?.headers ? req.headers['user-agent'] || '' : '').slice(0, 500);
217
+ const ipAddress = (req?.headers ? req.headers['x-forwarded-for'] || req.socket?.remoteAddress || '' : '').slice(0, 45);
218
+ const deviceName = deriveDeviceName(req, userAgent);
219
+
220
+ let token;
221
+ if (this.options.tokenVersion === 2) {
222
+ const bytes = getRandomBytes(this.options.secretBytes);
223
+ let hex = '';
224
+ for (let i = 0; i < bytes.length; i++) {
225
+ hex += bytes[i].toString(16).padStart(2, '0');
226
+ }
227
+ token = formatToken(id, hex, this.options.tokenPrefix);
228
+ } else {
229
+ token = genSessionToken(this.options.secretBytes);
230
+ }
231
+
232
+ let absoluteMs = this.options.defaultAbsoluteTimeoutMs;
233
+ try {
234
+ const sRes = await this._query(`SELECT value FROM ${this.options.settingsTable} WHERE key = 'session_absolute_timeout'`);
235
+ if (sRes.rows && sRes.rows.length > 0) {
236
+ let val = sRes.rows[0].value;
237
+ if (typeof val === 'string') {
238
+ try { val = JSON.parse(val); } catch {}
239
+ }
240
+ const parsed = parseDurationMs(val, absoluteMs);
241
+ if (parsed > 0) absoluteMs = parsed;
242
+ }
243
+ } catch {}
244
+
245
+ const expiresAt = new Date(Date.now() + absoluteMs);
246
+
247
+ const insertSql = `
248
+ INSERT INTO ${this.options.sessionsTable} (id, user_id, token, user_agent, device_name, ip_address, is_active, expires_at)
249
+ VALUES ($1, $2, $3, $4, $5, $6, true, $7)
250
+ `;
251
+ await this._query(insertSql, [id, userId, token, userAgent, deviceName, ipAddress, expiresAt]);
252
+
253
+ return token;
254
+ }
255
+
256
+ /**
257
+ * Validate a session token against PostgreSQL database and users table.
258
+ * Seamlessly resolves v2 compound tokens (O(1) lookup by primary key id) and v1 tokens.
259
+ *
260
+ * @param {string} token
261
+ * @param {object} [options] Options: { updateActivity: boolean }
262
+ * @returns {Promise<object|null>}
263
+ */
264
+ async validateSession(token, options = {}) {
265
+ if (!token || typeof token !== 'string') return null;
266
+ const cleanToken = token.replace(/^Bearer\s+/i, '').trim();
267
+ if (!cleanToken) return null;
268
+
269
+ try {
270
+ const parsed = parseToken(cleanToken, this.options.tokenPrefix);
271
+ const empCol = this.options.employeeColumn || 'employee';
272
+ let sessionRes;
273
+
274
+ if (parsed.version === 2 && parsed.sessionId) {
275
+ // v2: Ultra-fast O(1) Primary Key lookup by id
276
+ const sql = `
277
+ SELECT s.id as session_id, s.user_id, s.token, s.is_active as session_active,
278
+ s.expires_at, s.last_activity, s.device_name, s.ip_address,
279
+ u.id as user_id, u.username, u.full_name, u.role, u.is_active as user_active,
280
+ COALESCE(u.is_disabled, false) as user_disabled,
281
+ u.${empCol} as employee,
282
+ u.permissions as user_permissions,
283
+ r.permissions as role_permissions
284
+ FROM ${this.options.sessionsTable} s
285
+ JOIN ${this.options.usersTable} u ON u.id = s.user_id
286
+ LEFT JOIN ${this.options.rolesTable} r ON r.id = u.role OR r.name = u.role OR LOWER(r.name) = LOWER(u.role)
287
+ WHERE s.id = $1
288
+ `;
289
+ sessionRes = await this._query(sql, [parsed.sessionId]).catch(() => ({ rows: [] }));
290
+ } else {
291
+ // v1 (legacy): Direct token string matching
292
+ const sql = `
293
+ SELECT s.id as session_id, s.user_id, s.token, s.is_active as session_active,
294
+ s.expires_at, s.last_activity, s.device_name, s.ip_address,
295
+ u.id as user_id, u.username, u.full_name, u.role, u.is_active as user_active,
296
+ COALESCE(u.is_disabled, false) as user_disabled,
297
+ u.${empCol} as employee,
298
+ u.permissions as user_permissions,
299
+ r.permissions as role_permissions
300
+ FROM ${this.options.sessionsTable} s
301
+ JOIN ${this.options.usersTable} u ON u.id = s.user_id
302
+ LEFT JOIN ${this.options.rolesTable} r ON r.id = u.role OR r.name = u.role OR LOWER(r.name) = LOWER(u.role)
303
+ WHERE s.token = $1
304
+ `;
305
+ sessionRes = await this._query(sql, [cleanToken]).catch(() => ({ rows: [] }));
306
+ }
307
+
308
+ if (sessionRes.rows && sessionRes.rows.length > 0) {
309
+ const row = sessionRes.rows[0];
310
+
311
+ // Security check: verify that row.token matches cleanToken
312
+ if (row.token !== cleanToken) {
313
+ return null;
314
+ }
315
+
316
+ const now = new Date();
317
+
318
+ // Check active status & expiration
319
+ if (!row.session_active || !row.user_active || row.user_disabled || new Date(row.expires_at) < now) {
320
+ return null;
321
+ }
322
+
323
+ // Check inactivity timeout
324
+ const inactTimeoutMs = await this.getInactivityTimeoutMs();
325
+ if (inactTimeoutMs > 0 && row.last_activity) {
326
+ const lastAct = new Date(row.last_activity).getTime();
327
+ if (now.getTime() - lastAct > inactTimeoutMs) {
328
+ this._query(`UPDATE ${this.options.sessionsTable} SET is_active = false WHERE id = $1`, [row.session_id]).catch(() => {});
329
+ return null;
330
+ }
331
+ }
332
+
333
+ // Asynchronously update last_activity
334
+ if (options.updateActivity !== false) {
335
+ this._query(`UPDATE ${this.options.sessionsTable} SET last_activity = NOW() WHERE id = $1`, [row.session_id]).catch(() => {});
336
+ }
337
+
338
+ return {
339
+ valid: true,
340
+ userId: row.user_id,
341
+ sessionId: row.session_id,
342
+ token: cleanToken,
343
+ role: row.role,
344
+ employee: row.employee || null,
345
+ employeeId: row.employee || null,
346
+ leaderId: null,
347
+ userPermissions: row.user_permissions || {},
348
+ rolePermissions: row.role_permissions || {},
349
+ user: {
350
+ id: row.user_id,
351
+ username: row.username,
352
+ fullName: row.full_name,
353
+ role: row.role,
354
+ employee: row.employee || null,
355
+ employeeId: row.employee || null,
356
+ leaderId: null,
357
+ },
358
+ };
359
+ }
360
+
361
+ // Legacy JWT fallback if enabled
362
+ if (this.options.jwtSecret) {
363
+ try {
364
+ const jwtModule = typeof require === 'function' ? require('jsonwebtoken') : null;
365
+ if (jwtModule) {
366
+ const decoded = jwtModule.verify(cleanToken, this.options.jwtSecret);
367
+ if (decoded && (decoded.userId || decoded.id)) {
368
+ const uId = decoded.userId || decoded.id;
369
+ const uRes = await this._query(
370
+ `SELECT u.id, u.username, u.full_name, u.role, u.is_active, COALESCE(u.is_disabled, false) as is_disabled,
371
+ u.${empCol} as employee, u.permissions as user_permissions, r.permissions as role_permissions
372
+ FROM ${this.options.usersTable} u
373
+ LEFT JOIN ${this.options.rolesTable} r ON r.id = u.role OR r.name = u.role OR LOWER(r.name) = LOWER(u.role)
374
+ WHERE u.id = $1`,
375
+ [uId]
376
+ ).catch(() => ({ rows: [] }));
377
+
378
+ if (uRes.rows && uRes.rows.length > 0 && uRes.rows[0].is_active && !uRes.rows[0].is_disabled) {
379
+ const uRow = uRes.rows[0];
380
+ return {
381
+ valid: true,
382
+ userId: uRow.id,
383
+ sessionId: null,
384
+ token: cleanToken,
385
+ role: uRow.role || decoded.role,
386
+ employee: uRow.employee || null,
387
+ employeeId: uRow.employee || null,
388
+ leaderId: null,
389
+ userPermissions: uRow.user_permissions || {},
390
+ rolePermissions: uRow.role_permissions || {},
391
+ user: {
392
+ id: uRow.id,
393
+ username: uRow.username,
394
+ fullName: uRow.full_name,
395
+ role: uRow.role || decoded.role,
396
+ employee: uRow.employee || null,
397
+ employeeId: uRow.employee || null,
398
+ leaderId: null,
399
+ },
400
+ };
401
+ }
402
+ }
403
+ }
404
+ } catch {}
405
+ }
406
+
407
+ return null;
408
+ } catch (err) {
409
+ console.warn('[SessionManager validateSession error]:', err.message);
410
+ return null;
411
+ }
412
+ }
413
+
414
+ /**
415
+ * Lock a session screen.
416
+ *
417
+ * @param {string} sessionIdOrToken Session ID or Token
418
+ * @returns {Promise<{ ok: boolean, sessionId: string, userId: string, token: string } | null>}
419
+ */
420
+ async lockSession(sessionIdOrToken) {
421
+ if (!sessionIdOrToken) return null;
422
+ const parsed = parseToken(sessionIdOrToken, this.options.tokenPrefix);
423
+ const idToUse = parsed.sessionId || sessionIdOrToken;
424
+
425
+ const sql = `
426
+ UPDATE ${this.options.sessionsTable}
427
+ SET is_locked = true, locked_at = NOW()
428
+ WHERE (id = $1 OR token = $1) AND is_active = true
429
+ RETURNING id, user_id, token
430
+ `;
431
+ const r = await this._query(sql, [idToUse]);
432
+ if (r.rows && r.rows.length > 0) {
433
+ const row = r.rows[0];
434
+ return { ok: true, sessionId: row.id, userId: row.user_id, token: row.token };
435
+ }
436
+ return null;
437
+ }
438
+
439
+ /**
440
+ * Unlock a session screen.
441
+ *
442
+ * @param {string} sessionIdOrToken Session ID or Token
443
+ * @returns {Promise<{ ok: boolean, sessionId: string, userId: string, token: string } | null>}
444
+ */
445
+ async unlockSession(sessionIdOrToken) {
446
+ if (!sessionIdOrToken) return null;
447
+ const parsed = parseToken(sessionIdOrToken, this.options.tokenPrefix);
448
+ const idToUse = parsed.sessionId || sessionIdOrToken;
449
+
450
+ const sql = `
451
+ UPDATE ${this.options.sessionsTable}
452
+ SET is_locked = false, locked_at = NULL
453
+ WHERE (id = $1 OR token = $1) AND is_active = true
454
+ RETURNING id, user_id, token
455
+ `;
456
+ const r = await this._query(sql, [idToUse]);
457
+ if (r.rows && r.rows.length > 0) {
458
+ const row = r.rows[0];
459
+ return { ok: true, sessionId: row.id, userId: row.user_id, token: row.token };
460
+ }
461
+ return null;
462
+ }
463
+
464
+ /**
465
+ * Terminate/revoke a single session.
466
+ *
467
+ * @param {string} sessionIdOrToken Session ID or Token
468
+ * @returns {Promise<{ ok: boolean, sessionId: string, userId: string, token: string } | null>}
469
+ */
470
+ async terminateSession(sessionIdOrToken) {
471
+ if (!sessionIdOrToken) return null;
472
+ const parsed = parseToken(sessionIdOrToken, this.options.tokenPrefix);
473
+ const idToUse = parsed.sessionId || sessionIdOrToken;
474
+
475
+ const sql = `
476
+ UPDATE ${this.options.sessionsTable}
477
+ SET is_active = false
478
+ WHERE id = $1 OR token = $1
479
+ RETURNING id, user_id, token
480
+ `;
481
+ const r = await this._query(sql, [idToUse]);
482
+ if (r.rows && r.rows.length > 0) {
483
+ const row = r.rows[0];
484
+ return { ok: true, sessionId: row.id, userId: row.user_id, token: row.token };
485
+ }
486
+ return null;
487
+ }
488
+
489
+ /**
490
+ * Terminate all other sessions except the current one.
491
+ *
492
+ * @param {string} currentSessionIdOrToken Current session ID or token to preserve
493
+ * @param {string|number} [currentUserId]
494
+ * @param {boolean} [protectSuperAdmin=true]
495
+ * @returns {Promise<Array<{ sessionId: string, userId: string, token: string }>>}
496
+ */
497
+ async terminateOtherSessions(currentSessionIdOrToken, currentUserId = null, protectSuperAdmin = true) {
498
+ const parsed = parseToken(currentSessionIdOrToken, this.options.tokenPrefix);
499
+ const preserveId = parsed.sessionId || currentSessionIdOrToken;
500
+
501
+ let whereClause = `id != $1 AND token != $1`;
502
+ let params = [preserveId];
503
+
504
+ if (currentUserId) {
505
+ whereClause += ` AND user_id = $2`;
506
+ params.push(currentUserId);
507
+ } else if (protectSuperAdmin) {
508
+ whereClause += ` AND user_id NOT IN (SELECT id FROM ${this.options.usersTable} WHERE LOWER(COALESCE(role, '')) = '${this.options.superRole}' OR LOWER(username) = '${this.options.superRole}')`;
509
+ }
510
+
511
+ const sql = `
512
+ UPDATE ${this.options.sessionsTable}
513
+ SET is_active = false
514
+ WHERE ${whereClause} AND is_active = true
515
+ RETURNING id, user_id, token
516
+ `;
517
+ const r = await this._query(sql, params);
518
+ return (r.rows || []).map(row => ({
519
+ sessionId: row.id,
520
+ userId: row.user_id,
521
+ token: row.token,
522
+ }));
523
+ }
524
+
525
+ /**
526
+ * Terminate all active sessions for a specific user.
527
+ *
528
+ * @param {string|number} userId
529
+ * @returns {Promise<Array<{ sessionId: string, userId: string, token: string }>>}
530
+ */
531
+ async terminateUserSessions(userId) {
532
+ if (!userId) return [];
533
+ const sql = `
534
+ UPDATE ${this.options.sessionsTable}
535
+ SET is_active = false
536
+ WHERE user_id = $1 AND is_active = true
537
+ RETURNING id, user_id, token
538
+ `;
539
+ const r = await this._query(sql, [userId]);
540
+ return (r.rows || []).map(row => ({
541
+ sessionId: row.id,
542
+ userId: row.user_id,
543
+ token: row.token,
544
+ }));
545
+ }
546
+
547
+ /**
548
+ * Aliases for backward compatibility.
549
+ */
550
+ async revokeSession(tokenOrId) {
551
+ return this.terminateSession(tokenOrId);
552
+ }
553
+
554
+ async revokeAllUserSessions(userId) {
555
+ return this.terminateUserSessions(userId);
556
+ }
557
+ }
558
+
559
+ /**
560
+ * Universal Factory.
561
+ */
562
+ export function createSessionManager(queryOrOptions = {}, sessionsTable, usersTable, rolesTable, settingsTable) {
563
+ return new SessionManager(queryOrOptions, sessionsTable, usersTable, rolesTable, settingsTable);
564
+ }
565
+
566
+ export {
567
+ genSessionToken,
568
+ getDeviceLabel,
569
+ parseUserAgent,
570
+ deriveDeviceName,
571
+ } from './session.js';
572
+
573
+ export default {
574
+ SessionManager,
575
+ createSessionManager,
576
+ formatToken,
577
+ parseToken,
578
+ getSessionId,
579
+ extractToken,
580
+ };