cynx-lib 1.3.99 → 1.3.100
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.
- package/package.json +1 -1
- package/utils/utils/session_manager.cjs +17 -11
- package/utils/utils/session_manager.js +562 -556
package/package.json
CHANGED
|
@@ -113,6 +113,7 @@ class SessionManager {
|
|
|
113
113
|
usersTable: opts.usersTable || "users",
|
|
114
114
|
rolesTable: opts.rolesTable || "roles",
|
|
115
115
|
settingsTable: opts.settingsTable || "settings",
|
|
116
|
+
employeeColumn: opts.employeeColumn || "employee",
|
|
116
117
|
superRole: (opts.superRole || "superadmin").toLowerCase(),
|
|
117
118
|
tokenPrefix: opts.tokenPrefix || "st_",
|
|
118
119
|
tokenVersion: opts.tokenVersion || 2,
|
|
@@ -236,6 +237,7 @@ class SessionManager {
|
|
|
236
237
|
if (!cleanToken) return null;
|
|
237
238
|
try {
|
|
238
239
|
const parsed = parseToken(cleanToken, this.options.tokenPrefix);
|
|
240
|
+
const empCol = this.options.employeeColumn || "employee";
|
|
239
241
|
let sessionRes;
|
|
240
242
|
if (parsed.version === 2 && parsed.sessionId) {
|
|
241
243
|
const sql = `
|
|
@@ -243,7 +245,7 @@ class SessionManager {
|
|
|
243
245
|
s.expires_at, s.last_activity, s.device_name, s.ip_address,
|
|
244
246
|
u.id as user_id, u.username, u.full_name, u.role, u.is_active as user_active,
|
|
245
247
|
COALESCE(u.is_disabled, false) as user_disabled,
|
|
246
|
-
u
|
|
248
|
+
u.${empCol} as employee,
|
|
247
249
|
u.permissions as user_permissions,
|
|
248
250
|
r.permissions as role_permissions
|
|
249
251
|
FROM ${this.options.sessionsTable} s
|
|
@@ -258,7 +260,7 @@ class SessionManager {
|
|
|
258
260
|
s.expires_at, s.last_activity, s.device_name, s.ip_address,
|
|
259
261
|
u.id as user_id, u.username, u.full_name, u.role, u.is_active as user_active,
|
|
260
262
|
COALESCE(u.is_disabled, false) as user_disabled,
|
|
261
|
-
u
|
|
263
|
+
u.${empCol} as employee,
|
|
262
264
|
u.permissions as user_permissions,
|
|
263
265
|
r.permissions as role_permissions
|
|
264
266
|
FROM ${this.options.sessionsTable} s
|
|
@@ -296,8 +298,9 @@ class SessionManager {
|
|
|
296
298
|
sessionId: row.session_id,
|
|
297
299
|
token: cleanToken,
|
|
298
300
|
role: row.role,
|
|
299
|
-
|
|
300
|
-
|
|
301
|
+
employee: row.employee || null,
|
|
302
|
+
employeeId: row.employee || null,
|
|
303
|
+
leaderId: null,
|
|
301
304
|
userPermissions: row.user_permissions || {},
|
|
302
305
|
rolePermissions: row.role_permissions || {},
|
|
303
306
|
user: {
|
|
@@ -305,8 +308,9 @@ class SessionManager {
|
|
|
305
308
|
username: row.username,
|
|
306
309
|
fullName: row.full_name,
|
|
307
310
|
role: row.role,
|
|
308
|
-
|
|
309
|
-
|
|
311
|
+
employee: row.employee || null,
|
|
312
|
+
employeeId: row.employee || null,
|
|
313
|
+
leaderId: null
|
|
310
314
|
}
|
|
311
315
|
};
|
|
312
316
|
}
|
|
@@ -319,7 +323,7 @@ class SessionManager {
|
|
|
319
323
|
const uId = decoded.userId || decoded.id;
|
|
320
324
|
const uRes = await this._query(
|
|
321
325
|
`SELECT u.id, u.username, u.full_name, u.role, u.is_active, COALESCE(u.is_disabled, false) as is_disabled,
|
|
322
|
-
u
|
|
326
|
+
u.${empCol} as employee, u.permissions as user_permissions, r.permissions as role_permissions
|
|
323
327
|
FROM ${this.options.usersTable} u
|
|
324
328
|
LEFT JOIN ${this.options.rolesTable} r ON r.id = u.role OR r.name = u.role OR LOWER(r.name) = LOWER(u.role)
|
|
325
329
|
WHERE u.id = $1`,
|
|
@@ -333,8 +337,9 @@ class SessionManager {
|
|
|
333
337
|
sessionId: null,
|
|
334
338
|
token: cleanToken,
|
|
335
339
|
role: uRow.role || decoded.role,
|
|
336
|
-
|
|
337
|
-
|
|
340
|
+
employee: uRow.employee || null,
|
|
341
|
+
employeeId: uRow.employee || null,
|
|
342
|
+
leaderId: null,
|
|
338
343
|
userPermissions: uRow.user_permissions || {},
|
|
339
344
|
rolePermissions: uRow.role_permissions || {},
|
|
340
345
|
user: {
|
|
@@ -342,8 +347,9 @@ class SessionManager {
|
|
|
342
347
|
username: uRow.username,
|
|
343
348
|
fullName: uRow.full_name,
|
|
344
349
|
role: uRow.role || decoded.role,
|
|
345
|
-
|
|
346
|
-
|
|
350
|
+
employee: uRow.employee || null,
|
|
351
|
+
employeeId: uRow.employee || null,
|
|
352
|
+
leaderId: null
|
|
347
353
|
}
|
|
348
354
|
};
|
|
349
355
|
}
|
|
@@ -1,116 +1,116 @@
|
|
|
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) {
|
|
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
114
|
let opts = {};
|
|
115
115
|
if (typeof queryOrOptions === 'function') {
|
|
116
116
|
opts = {
|
|
@@ -129,446 +129,452 @@ export class SessionManager {
|
|
|
129
129
|
};
|
|
130
130
|
}
|
|
131
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
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
this.
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
const
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
this.
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
*
|
|
208
|
-
*
|
|
209
|
-
* @param {
|
|
210
|
-
* @param {object} [
|
|
211
|
-
* @
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
const
|
|
216
|
-
const
|
|
217
|
-
const
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
*
|
|
258
|
-
*
|
|
259
|
-
*
|
|
260
|
-
* @param {
|
|
261
|
-
* @
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
u.
|
|
280
|
-
u.
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
u.
|
|
296
|
-
u.
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
const
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
const
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
const
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
WHERE ${
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
const
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
const
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
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
|
+
};
|