cynx-lib 1.3.102 → 1.3.103

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 (46) 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/Pagination.jsx +145 -145
  8. package/ui/components/PrivacyBlur.jsx +603 -603
  9. package/ui/components/XTable.jsx +112 -112
  10. package/ui/components/useRuler.jsx +94 -0
  11. package/ui/index.cjs +5 -0
  12. package/ui/index.js +3 -0
  13. package/utils/index.js +24 -24
  14. package/utils/utils/duration.js +139 -139
  15. package/utils/utils/oidc.js +214 -214
  16. package/utils/utils/realtime.js +1634 -1634
  17. package/utils/utils/server.js +371 -371
  18. package/utils/utils/session.js +131 -131
  19. package/utils/utils/session_manager.js +580 -580
  20. package/utils/utils/sso_manager.js +702 -702
  21. package/utils/utils/storage.js +393 -393
  22. package/utils/utils/ui.js +111 -111
  23. package/vue/components/Badge.vue +79 -79
  24. package/vue/components/Button.vue +209 -209
  25. package/vue/components/Checkbox.vue +103 -103
  26. package/vue/components/CircularProgress.vue +383 -383
  27. package/vue/components/Divider.vue +94 -94
  28. package/vue/components/Drawer.vue +243 -243
  29. package/vue/components/InfoBadge.vue +223 -223
  30. package/vue/components/Input.vue +341 -341
  31. package/vue/components/LinearProgress.vue +268 -268
  32. package/vue/components/Modal.vue +226 -226
  33. package/vue/components/Pagination.vue +199 -199
  34. package/vue/components/Select.vue +713 -713
  35. package/vue/components/Sidebar.vue +955 -955
  36. package/vue/components/Skeleton.vue +91 -91
  37. package/vue/components/Spinner.vue +263 -263
  38. package/vue/components/StatusTag.vue +89 -89
  39. package/vue/components/TabBar.vue +176 -176
  40. package/vue/components/Table.vue +388 -388
  41. package/vue/components/TimePicker.vue +399 -399
  42. package/vue/components/Toggle.vue +115 -115
  43. package/vue/components/XTable.vue +140 -140
  44. package/vue/composables/useAutoSkeletonRows.ts +71 -71
  45. package/vue/index.d.ts +67 -67
  46. package/vue/index.js +86 -86
@@ -1,702 +1,702 @@
1
- /**
2
- * cynx/utils — Universal OpenID Connect & SSO Manager (sso_manager.js)
3
- *
4
- * Universal, enterprise-grade OIDC / SSO engine:
5
- * - Internal ID generation via uid(12)
6
- * - Dynamic Schema Reflection (auto-detects existing columns in users table and roles table)
7
- * - Zero-hardcode dynamic tables with smart defaults ('sso_providers', 'users', 'roles')
8
- * - Self-contained provider lifecycle (CRUD, activate, deactivate, test discovery)
9
- * - End-to-end OAuth2/OIDC Authorization Code Flow with PKCE & signed state tokens
10
- * - Claims mapping, automatic user profile synchronization & session generation
11
- *
12
- * STRICT NO EMOJIS!
13
- */
14
-
15
- import crypto from 'crypto';
16
- import { uid, genUid } from './uid.js';
17
- import {
18
- generateState,
19
- consumeState,
20
- generatePKCE,
21
- discover,
22
- buildAuthorizeUrl,
23
- exchangeCode,
24
- getUserInfo,
25
- decodeIdToken,
26
- } from './oidc.js';
27
-
28
- export function getClaimValue(claims, path) {
29
- if (!claims || !path) return undefined;
30
- if (claims[path] !== undefined) return claims[path];
31
- const parts = String(path).split('.');
32
- let curr = claims;
33
- for (const p of parts) {
34
- if (curr === undefined || curr === null || typeof curr !== 'object') return undefined;
35
- curr = curr[p];
36
- }
37
- return curr;
38
- }
39
-
40
- export function applyClaimsMapping(oidcClaims, mapping = [], superRole = 'superadmin', allPermissions = {}) {
41
- let role = '';
42
- let permissions = {};
43
-
44
- if (Array.isArray(mapping) && mapping.length > 0) {
45
- for (const rule of mapping) {
46
- if (!rule || !rule.oidc_claim) continue;
47
- const rawValue = getClaimValue(oidcClaims, rule.oidc_claim);
48
- if (rawValue === undefined || rawValue === null) continue;
49
-
50
- const ruleVal = rule.value ? String(rule.value).trim() : '';
51
-
52
- if (rule.type === 'custom_role' || !ruleVal || ruleVal.toLowerCase() === String(rule.oidc_claim).toLowerCase()) {
53
- const claimValue = Array.isArray(rawValue) ? rawValue[0] : String(rawValue).trim();
54
- if (claimValue) {
55
- role = claimValue;
56
- }
57
- } else if (rule.type === 'role') {
58
- const match = Array.isArray(rawValue)
59
- ? rawValue.some((v) => String(v).toLowerCase() === ruleVal.toLowerCase())
60
- : String(rawValue).toLowerCase() === ruleVal.toLowerCase();
61
-
62
- if (match) {
63
- role = ruleVal;
64
- } else if (typeof rawValue === 'string' && rawValue.trim()) {
65
- role = rawValue.trim();
66
- } else if (Array.isArray(rawValue) && rawValue.length > 0) {
67
- role = String(rawValue[0]).trim();
68
- }
69
- } else if (rule.type === 'permission') {
70
- const match = Array.isArray(rawValue)
71
- ? rawValue.includes(ruleVal)
72
- : String(rawValue) === ruleVal;
73
- if (match && (!allPermissions || allPermissions[ruleVal])) {
74
- permissions[ruleVal] = true;
75
- }
76
- }
77
- }
78
- }
79
-
80
- if (!role) {
81
- const candidates = [
82
- getClaimValue(oidcClaims, 'role'),
83
- getClaimValue(oidcClaims, 'roles'),
84
- getClaimValue(oidcClaims, 'groups'),
85
- getClaimValue(oidcClaims, 'group'),
86
- getClaimValue(oidcClaims, 'realm_access.roles'),
87
- getClaimValue(oidcClaims, 'resource_access.account.roles'),
88
- getClaimValue(oidcClaims, 'https://emp/roles'),
89
- getClaimValue(oidcClaims, 'https://emp/role'),
90
- ];
91
-
92
- for (const c of candidates) {
93
- if (!c) continue;
94
- if (typeof c === 'string' && c.trim()) {
95
- role = c.trim();
96
- break;
97
- }
98
- if (Array.isArray(c) && c.length > 0 && typeof c[0] === 'string') {
99
- role = c[0].trim();
100
- break;
101
- }
102
- }
103
- }
104
-
105
- return { role, permissions };
106
- }
107
-
108
- export class SSOManager {
109
- /**
110
- * @param {object} [options={}]
111
- * @param {Function} options.query Database query function `(sql, params) => Promise<{ rows: any[], rowCount: number }>`
112
- * @param {string} [options.table='sso_providers'] SSO providers table name
113
- * @param {string} [options.usersTable='users'] Users table name
114
- * @param {string} [options.rolesTable='roles'] Roles table name
115
- * @param {string} [options.superRole='superadmin'] Name of super administrative role
116
- * @param {object} [options.allPermissions={}] Map of system permissions
117
- * @param {Function} [options.createSession] Session generation function `async (userId, req) => string`
118
- * @param {string} [options.jwtSecret] State signing secret
119
- */
120
- constructor(options = {}) {
121
- this.query = options.query;
122
- this.table = options.table || options.ssoTable || 'sso_providers';
123
- this.usersTable = options.usersTable || 'users';
124
- this.rolesTable = options.rolesTable || 'roles';
125
- this.superRole = options.superRole || 'superadmin';
126
- this.allPermissions = options.allPermissions || {};
127
- this.createSession = options.createSession || null;
128
- this.jwtSecret =
129
- options.jwtSecret ||
130
- (typeof process !== 'undefined'
131
- ? (process.env?.JWT_SECRET || process.env?.OIDC_STATE_SECRET || 'cynx-sso-state-secret')
132
- : 'cynx-sso-state-secret');
133
-
134
- this._tableColumnsCache = {};
135
- this._tablesCache = {};
136
- }
137
-
138
- /**
139
- * Internal ID generator. Defaults to 12 chars UID from cynx-lib.
140
- * @param {number} [len=12]
141
- * @returns {string}
142
- */
143
- generateId(len = 12) {
144
- return uid(len);
145
- }
146
-
147
- async _getTableColumns(tableName) {
148
- if (this._tableColumnsCache[tableName]) return this._tableColumnsCache[tableName];
149
- if (!this.query) return new Set();
150
- try {
151
- const res = await this.query(
152
- `SELECT column_name FROM information_schema.columns WHERE table_schema = 'public' AND table_name = $1`,
153
- [tableName]
154
- );
155
- const cols = new Set((res.rows || []).map((r) => r.column_name));
156
- this._tableColumnsCache[tableName] = cols;
157
- return cols;
158
- } catch {
159
- return new Set();
160
- }
161
- }
162
-
163
- async _hasTable(tableName) {
164
- if (this._tablesCache[tableName] !== undefined) return this._tablesCache[tableName];
165
- if (!this.query) return false;
166
- try {
167
- const res = await this.query(
168
- `SELECT 1 FROM information_schema.tables WHERE table_schema = 'public' AND table_name = $1 LIMIT 1`,
169
- [tableName]
170
- );
171
- const exists = Boolean(res.rows && res.rows.length > 0);
172
- this._tablesCache[tableName] = exists;
173
- return exists;
174
- } catch {
175
- return false;
176
- }
177
- }
178
-
179
- buildConfig(row) {
180
- if (!row) return null;
181
- let mapping = row.claims_mapping;
182
- if (typeof mapping === 'string') {
183
- try {
184
- mapping = JSON.parse(mapping);
185
- } catch {
186
- mapping = [];
187
- }
188
- }
189
- return {
190
- id: row.id,
191
- name: row.name,
192
- issuer: row.issuer,
193
- clientId: row.client_id,
194
- clientSecret: row.client_secret,
195
- scopes: row.scopes || 'openid profile email',
196
- discoveryPath: row.discovery_path || '/.well-known/openid-configuration',
197
- pkceEnabled: !!row.pkce_enabled,
198
- claimsMapping: Array.isArray(mapping) ? mapping : [],
199
- redirectUri: row.redirect_uri || '',
200
- isActive: !!row.is_active,
201
- createdAt: row.created_at,
202
- };
203
- }
204
-
205
- /**
206
- * Retrieve all SSO providers.
207
- * @returns {Promise<object[]>}
208
- */
209
- async getProviders() {
210
- if (!this.query) throw new Error('[cynx/sso] Database query function is required.');
211
- const r = await this.query(
212
- `SELECT id, name, issuer, client_id, scopes, discovery_path, pkce_enabled, claims_mapping, redirect_uri, is_active, created_at
213
- FROM ${this.table} ORDER BY created_at ASC`
214
- );
215
- return r.rows;
216
- }
217
-
218
- /**
219
- * Retrieve active SSO providers for public login view.
220
- * @returns {Promise<{ id: string, name: string }[]>}
221
- */
222
- async getActiveProviders() {
223
- if (!this.query) return [];
224
- try {
225
- const r = await this.query(
226
- `SELECT id, name FROM ${this.table} WHERE is_active = TRUE ORDER BY created_at ASC`
227
- );
228
- return r.rows;
229
- } catch {
230
- return [];
231
- }
232
- }
233
-
234
- /**
235
- * Create a new SSO provider. Generates internal ID if not provided.
236
- * @param {object} data
237
- * @returns {Promise<object>}
238
- */
239
- async createProvider(data = {}) {
240
- if (!this.query) throw new Error('[cynx/sso] Database query function is required.');
241
- const { name, issuer, client_id, client_secret, scopes, discovery_path, pkce_enabled, claims_mapping, redirect_uri } = data;
242
- if (!name || !issuer || !client_id) {
243
- throw new Error('Name, issuer, and client_id are required');
244
- }
245
-
246
- const providerId = data.id || this.generateId(12);
247
-
248
- const r = await this.query(
249
- `INSERT INTO ${this.table} (id, name, issuer, client_id, client_secret, scopes, discovery_path, pkce_enabled, claims_mapping, redirect_uri)
250
- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
251
- RETURNING id, name, issuer, is_active, created_at`,
252
- [
253
- providerId,
254
- String(name).trim(),
255
- String(issuer).trim(),
256
- String(client_id).trim(),
257
- client_secret || '',
258
- scopes || 'openid profile email',
259
- discovery_path || '/.well-known/openid-configuration',
260
- !!pkce_enabled,
261
- JSON.stringify(claims_mapping || []),
262
- redirect_uri || '',
263
- ]
264
- );
265
-
266
- return r.rows[0];
267
- }
268
-
269
- /**
270
- * Update existing SSO provider.
271
- * @param {string} id
272
- * @param {object} data
273
- * @returns {Promise<object>}
274
- */
275
- async updateProvider(id, data = {}) {
276
- if (!this.query) throw new Error('[cynx/sso] Database query function is required.');
277
- if (!id) throw new Error('Provider ID is required');
278
-
279
- const { name, issuer, client_id, client_secret, scopes, discovery_path, pkce_enabled, claims_mapping, redirect_uri } = data;
280
- const sets = [];
281
- const params = [id];
282
-
283
- if (name !== undefined) {
284
- params.push(String(name).trim());
285
- sets.push(`name = $${params.length}`);
286
- }
287
- if (issuer !== undefined) {
288
- params.push(String(issuer).trim());
289
- sets.push(`issuer = $${params.length}`);
290
- }
291
- if (client_id !== undefined) {
292
- params.push(String(client_id).trim());
293
- sets.push(`client_id = $${params.length}`);
294
- }
295
- if (client_secret !== undefined && client_secret !== '') {
296
- params.push(client_secret);
297
- sets.push(`client_secret = $${params.length}`);
298
- }
299
- if (scopes !== undefined) {
300
- params.push(scopes);
301
- sets.push(`scopes = $${params.length}`);
302
- }
303
- if (discovery_path !== undefined) {
304
- params.push(discovery_path);
305
- sets.push(`discovery_path = $${params.length}`);
306
- }
307
- if (pkce_enabled !== undefined) {
308
- params.push(!!pkce_enabled);
309
- sets.push(`pkce_enabled = $${params.length}`);
310
- }
311
- if (claims_mapping !== undefined) {
312
- params.push(JSON.stringify(claims_mapping));
313
- sets.push(`claims_mapping = $${params.length}`);
314
- }
315
- if (redirect_uri !== undefined) {
316
- params.push(redirect_uri);
317
- sets.push(`redirect_uri = $${params.length}`);
318
- }
319
-
320
- if (!sets.length) throw new Error('Nothing to update');
321
-
322
- const r = await this.query(
323
- `UPDATE ${this.table} SET ${sets.join(', ')} WHERE id = $1 RETURNING id, name, issuer, is_active, created_at`,
324
- params
325
- );
326
-
327
- if (!r.rows.length) throw new Error('SSO provider not found');
328
- return r.rows[0];
329
- }
330
-
331
- /**
332
- * Delete an inactive SSO provider.
333
- * @param {string} id
334
- * @returns {Promise<{ ok: boolean }>}
335
- */
336
- async deleteProvider(id) {
337
- if (!this.query) throw new Error('[cynx/sso] Database query function is required.');
338
- const p = await this.query(`SELECT is_active FROM ${this.table} WHERE id = $1`, [id]);
339
- if (!p.rows.length) throw new Error('Provider not found');
340
- if (p.rows[0].is_active) {
341
- throw new Error('Cannot delete active provider. Deactivate it first.');
342
- }
343
- await this.query(`DELETE FROM ${this.table} WHERE id = $1`, [id]);
344
- return { ok: true };
345
- }
346
-
347
- /**
348
- * Activate an SSO provider.
349
- * @param {string} id
350
- * @returns {Promise<{ ok: boolean }>}
351
- */
352
- async activateProvider(id) {
353
- if (!this.query) throw new Error('[cynx/sso] Database query function is required.');
354
- const p = await this.query(`SELECT id FROM ${this.table} WHERE id = $1`, [id]);
355
- if (!p.rows.length) throw new Error('Provider not found');
356
- await this.query(`UPDATE ${this.table} SET is_active = TRUE WHERE id = $1`, [id]);
357
- return { ok: true };
358
- }
359
-
360
- /**
361
- * Deactivate an SSO provider.
362
- * @param {string} id
363
- * @returns {Promise<{ ok: boolean }>}
364
- */
365
- async deactivateProvider(id) {
366
- if (!this.query) throw new Error('[cynx/sso] Database query function is required.');
367
- const p = await this.query(`SELECT id FROM ${this.table} WHERE id = $1`, [id]);
368
- if (!p.rows.length) throw new Error('Provider not found');
369
- await this.query(`UPDATE ${this.table} SET is_active = FALSE WHERE id = $1`, [id]);
370
- return { ok: true };
371
- }
372
-
373
- /**
374
- * Test OIDC discovery configuration.
375
- * @param {string} issuer
376
- * @param {string} [discoveryPath]
377
- * @returns {Promise<object>}
378
- */
379
- async testConnection(issuer, discoveryPath) {
380
- if (!issuer) throw new Error('Issuer URL is required');
381
- const doc = await discover(issuer, discoveryPath);
382
- return {
383
- ok: true,
384
- issuer: doc.issuer,
385
- authorization_endpoint: doc.authorization_endpoint,
386
- token_endpoint: doc.token_endpoint,
387
- userinfo_endpoint: doc.userinfo_endpoint,
388
- };
389
- }
390
-
391
- /**
392
- * Build authorize redirect URL for client authentication.
393
- * @param {object} params
394
- * @param {string} params.providerId
395
- * @param {string} [params.origin]
396
- * @param {string} [params.customRedirectUri]
397
- * @returns {Promise<{ authorizeUrl: string, state: string }>}
398
- */
399
- async buildAuthorizeUrl({ providerId, origin = '', customRedirectUri = '' }) {
400
- if (!this.query) throw new Error('[cynx/sso] Database query function is required.');
401
- const r = await this.query(`SELECT * FROM ${this.table} WHERE id = $1 AND is_active = TRUE`, [providerId]);
402
- if (!r.rows.length) {
403
- throw new Error('SSO provider not found or inactive');
404
- }
405
-
406
- const config = this.buildConfig(r.rows[0]);
407
- if (!config.issuer || !config.clientId) {
408
- throw new Error('SSO provider is not fully configured');
409
- }
410
-
411
- const effectiveRedirectUri = (config.redirectUri && config.redirectUri.trim())
412
- ? config.redirectUri.trim()
413
- : customRedirectUri || (origin ? `${origin.replace(/\/+$/, '')}/auth/callback` : '/auth/callback');
414
-
415
- let codeVerifier = null;
416
- if (config.pkceEnabled) {
417
- const pkce = generatePKCE();
418
- codeVerifier = pkce.codeVerifier;
419
- }
420
-
421
- const state = generateState(
422
- {
423
- providerId,
424
- redirectUri: effectiveRedirectUri,
425
- origin,
426
- codeVerifier,
427
- },
428
- this.jwtSecret
429
- );
430
-
431
- const codeChallenge = codeVerifier
432
- ? crypto.createHash('sha256').update(codeVerifier).digest('base64url')
433
- : null;
434
-
435
- const authConfig = { ...config, redirectUri: effectiveRedirectUri };
436
- const authorizeUrl = buildAuthorizeUrl(authConfig, state, codeChallenge);
437
-
438
- return { authorizeUrl, state };
439
- }
440
-
441
- /**
442
- * Handle OAuth2 / OIDC callback, exchange code, synchronize user, and issue session.
443
- * @param {object} params
444
- * @param {string} params.code
445
- * @param {string} params.state
446
- * @param {string} [params.error]
447
- * @param {string} [params.errorDescription]
448
- * @param {string} [params.origin]
449
- * @param {object} [params.req] Original HTTP request object (for session creation)
450
- * @returns {Promise<{ redirectUrl: string, sessionToken: string, user: object }>}
451
- */
452
- async handleCallback({ code, state, error, errorDescription, origin = '', req = null }) {
453
- if (error) {
454
- throw new Error(errorDescription || error);
455
- }
456
- if (!code || !state) {
457
- throw new Error('Missing authorization code or state');
458
- }
459
-
460
- const stateEntry = consumeState(state, this.jwtSecret);
461
- if (!stateEntry || !stateEntry.providerId) {
462
- throw new Error('Invalid or expired state parameter');
463
- }
464
-
465
- const r = await this.query(`SELECT * FROM ${this.table} WHERE id = $1 AND is_active = TRUE`, [stateEntry.providerId]);
466
- if (!r.rows.length) {
467
- throw new Error('SSO provider not found or inactive');
468
- }
469
-
470
- const reqOrigin = (stateEntry && stateEntry.origin) || origin;
471
- const effectiveRedirectUri = (stateEntry && stateEntry.redirectUri)
472
- || (r.rows[0].redirect_uri && r.rows[0].redirect_uri.trim())
473
- || `${reqOrigin.replace(/\/+$/, '')}/auth/callback`;
474
-
475
- const config = { ...this.buildConfig(r.rows[0]), redirectUri: effectiveRedirectUri };
476
-
477
- const tokenResult = await exchangeCode(config, code, stateEntry.codeVerifier);
478
-
479
- let claims = {};
480
- if (tokenResult.id_token) {
481
- try {
482
- claims = decodeIdToken(tokenResult.id_token);
483
- } catch (err) {
484
- console.warn('[cynx/sso] ID token decode warning:', err.message);
485
- }
486
- }
487
-
488
- if (tokenResult.access_token) {
489
- try {
490
- const userinfo = await getUserInfo(config, tokenResult.access_token);
491
- claims = { ...claims, ...userinfo };
492
- } catch (err) {
493
- console.warn('[cynx/sso] getUserInfo warning:', err.message);
494
- }
495
- }
496
-
497
- if (!claims || Object.keys(claims).length === 0) {
498
- throw new Error('Failed to retrieve user claims from SSO provider');
499
- }
500
-
501
- const sub = claims.sub || '';
502
- const email = (claims.email || '').toLowerCase().trim();
503
- let username = claims.preferred_username || claims.nickname || (email ? email.split('@')[0] : sub);
504
- username = username ? String(username).trim() : 'sso_user_' + genUid(6);
505
-
506
- let fullName = claims.name;
507
- if (!fullName) {
508
- const parts = [claims.given_name, claims.family_name].filter(Boolean);
509
- fullName = parts.length ? parts.join(' ') : (claims.preferred_username || username);
510
- }
511
- fullName = String(fullName).trim();
512
-
513
- // Inspect user table columns dynamically
514
- const userCols = await this._getTableColumns(this.usersTable);
515
- const selectCols = ['id', 'username', 'role', 'is_active'];
516
- if (userCols.has('full_name')) selectCols.push('full_name');
517
- if (userCols.has('email')) selectCols.push('email');
518
- if (userCols.has('permissions')) selectCols.push('permissions');
519
- if (userCols.has('is_disabled')) selectCols.push('is_disabled');
520
-
521
- let existingUser = null;
522
- let u = await this.query(
523
- `SELECT ${selectCols.join(', ')} FROM ${this.usersTable} WHERE username = $1`,
524
- [username]
525
- );
526
- if (!u.rows.length && email && userCols.has('email')) {
527
- u = await this.query(
528
- `SELECT ${selectCols.join(', ')} FROM ${this.usersTable} WHERE email = $1`,
529
- [email]
530
- );
531
- }
532
- if (u.rows.length) {
533
- existingUser = u.rows[0];
534
- if (existingUser.is_disabled || existingUser.is_active === false) {
535
- throw new Error('Account is disabled or inactive');
536
- }
537
- }
538
-
539
- let { role, permissions } = applyClaimsMapping(claims, config.claimsMapping, this.superRole, this.allPermissions);
540
-
541
- if (!role) {
542
- if (existingUser && existingUser.role) {
543
- role = existingUser.role;
544
- } else if (username.toLowerCase() === this.superRole.toLowerCase() || (email && email.toLowerCase().startsWith(`${this.superRole.toLowerCase()}@`))) {
545
- role = this.superRole;
546
- } else {
547
- const hasRolesTable = await this._hasTable(this.rolesTable);
548
- if (hasRolesTable) {
549
- try {
550
- const rRow = await this.query(`SELECT name FROM ${this.rolesTable} ORDER BY created_at ASC LIMIT 1`);
551
- role = rRow.rows[0]?.name || this.superRole || 'user';
552
- } catch {
553
- role = this.superRole || 'user';
554
- }
555
- } else {
556
- role = this.superRole || 'user';
557
- }
558
- }
559
- }
560
-
561
- if (userCols.has('permissions')) {
562
- if (role.toLowerCase() === this.superRole.toLowerCase()) {
563
- permissions = Object.fromEntries(Object.keys(this.allPermissions || {}).map((k) => [k, true]));
564
- } else if (Object.keys(permissions).length === 0) {
565
- const hasRolesTable = await this._hasTable(this.rolesTable);
566
- if (hasRolesTable) {
567
- try {
568
- const roleRow = await this.query(`SELECT permissions FROM ${this.rolesTable} WHERE name = $1 OR LOWER(name) = LOWER($1)`, [role]);
569
- if (roleRow.rows.length && roleRow.rows[0].permissions) {
570
- permissions = roleRow.rows[0].permissions;
571
- }
572
- } catch (err) {
573
- console.warn('[cynx/sso] Role permissions fetch warning:', err.message);
574
- }
575
- }
576
- }
577
- }
578
-
579
- let userId = null;
580
- if (existingUser) {
581
- userId = existingUser.id;
582
- const updateSets = ['is_active = TRUE'];
583
- const updateParams = [userId];
584
-
585
- if (userCols.has('updated_at')) {
586
- updateSets.push('updated_at = NOW()');
587
- }
588
- if (email && userCols.has('email')) {
589
- updateParams.push(email);
590
- updateSets.push(`email = $${updateParams.length}`);
591
- }
592
- if (fullName && userCols.has('full_name')) {
593
- updateParams.push(fullName);
594
- updateSets.push(`full_name = $${updateParams.length}`);
595
- }
596
- if (role && userCols.has('role')) {
597
- updateParams.push(role);
598
- updateSets.push(`role = $${updateParams.length}`);
599
- }
600
- if (userCols.has('permissions') && permissions && Object.keys(permissions).length > 0) {
601
- updateParams.push(JSON.stringify(permissions));
602
- updateSets.push(`permissions = $${updateParams.length}`);
603
- }
604
-
605
- await this.query(`UPDATE ${this.usersTable} SET ${updateSets.join(', ')} WHERE id = $1`, updateParams);
606
- } else {
607
- userId = this.generateId(16);
608
- const insertCols = ['id', 'username'];
609
- const insertVals = [userId, username];
610
-
611
- if (userCols.has('password_hash')) {
612
- insertCols.push('password_hash');
613
- insertVals.push('SSO_AUTH_EXTERNAL');
614
- }
615
- if (userCols.has('full_name')) {
616
- insertCols.push('full_name');
617
- insertVals.push(fullName || username);
618
- }
619
- if (userCols.has('role')) {
620
- insertCols.push('role');
621
- insertVals.push(role);
622
- }
623
- if (userCols.has('is_active')) {
624
- insertCols.push('is_active');
625
- insertVals.push(true);
626
- }
627
- if (userCols.has('email')) {
628
- insertCols.push('email');
629
- insertVals.push(email || null);
630
- }
631
- if (userCols.has('permissions')) {
632
- insertCols.push('permissions');
633
- insertVals.push(JSON.stringify(permissions || {}));
634
- }
635
-
636
- const placeholders = insertVals.map((_, i) => `$${i + 1}`).join(', ');
637
- await this.query(
638
- `INSERT INTO ${this.usersTable} (${insertCols.join(', ')}) VALUES (${placeholders})`,
639
- insertVals
640
- );
641
- }
642
-
643
- let sessionToken = '';
644
- if (typeof this.createSession === 'function') {
645
- sessionToken = await this.createSession(userId, req);
646
- }
647
-
648
- const frontendBase = (stateEntry && stateEntry.origin) || (config.redirectUri ? new URL(config.redirectUri).origin : reqOrigin);
649
- const redirectUrl = `${frontendBase.replace(/\/+$/, '')}/sso-callback#token=${encodeURIComponent(sessionToken)}`;
650
-
651
- return {
652
- redirectUrl,
653
- sessionToken,
654
- userId,
655
- username,
656
- role,
657
- };
658
- }
659
- }
660
-
661
- /**
662
- * Universal Factory function to create configured SSOManager instance.
663
- * Supports positional arguments and options object.
664
- *
665
- * @param {object|Function} queryOrOptions
666
- * @param {string} [table='sso_providers']
667
- * @param {string} [usersTable='users']
668
- * @param {string} [rolesTable='roles']
669
- * @param {string} [superRole='superadmin']
670
- * @param {object} [allPermissions={}]
671
- * @param {Function} [createSession]
672
- * @returns {SSOManager}
673
- */
674
- export function createSSOManager(
675
- queryOrOptions = {},
676
- table = 'sso_providers',
677
- usersTable = 'users',
678
- rolesTable = 'roles',
679
- superRole = 'superadmin',
680
- allPermissions = {},
681
- createSession = null
682
- ) {
683
- if (typeof queryOrOptions === 'function') {
684
- return new SSOManager({
685
- query: queryOrOptions,
686
- table,
687
- usersTable,
688
- rolesTable,
689
- superRole,
690
- allPermissions,
691
- createSession,
692
- });
693
- }
694
- return new SSOManager(queryOrOptions);
695
- }
696
-
697
- export default {
698
- SSOManager,
699
- createSSOManager,
700
- applyClaimsMapping,
701
- getClaimValue,
702
- };
1
+ /**
2
+ * cynx/utils — Universal OpenID Connect & SSO Manager (sso_manager.js)
3
+ *
4
+ * Universal, enterprise-grade OIDC / SSO engine:
5
+ * - Internal ID generation via uid(12)
6
+ * - Dynamic Schema Reflection (auto-detects existing columns in users table and roles table)
7
+ * - Zero-hardcode dynamic tables with smart defaults ('sso_providers', 'users', 'roles')
8
+ * - Self-contained provider lifecycle (CRUD, activate, deactivate, test discovery)
9
+ * - End-to-end OAuth2/OIDC Authorization Code Flow with PKCE & signed state tokens
10
+ * - Claims mapping, automatic user profile synchronization & session generation
11
+ *
12
+ * STRICT NO EMOJIS!
13
+ */
14
+
15
+ import crypto from 'crypto';
16
+ import { uid, genUid } from './uid.js';
17
+ import {
18
+ generateState,
19
+ consumeState,
20
+ generatePKCE,
21
+ discover,
22
+ buildAuthorizeUrl,
23
+ exchangeCode,
24
+ getUserInfo,
25
+ decodeIdToken,
26
+ } from './oidc.js';
27
+
28
+ export function getClaimValue(claims, path) {
29
+ if (!claims || !path) return undefined;
30
+ if (claims[path] !== undefined) return claims[path];
31
+ const parts = String(path).split('.');
32
+ let curr = claims;
33
+ for (const p of parts) {
34
+ if (curr === undefined || curr === null || typeof curr !== 'object') return undefined;
35
+ curr = curr[p];
36
+ }
37
+ return curr;
38
+ }
39
+
40
+ export function applyClaimsMapping(oidcClaims, mapping = [], superRole = 'superadmin', allPermissions = {}) {
41
+ let role = '';
42
+ let permissions = {};
43
+
44
+ if (Array.isArray(mapping) && mapping.length > 0) {
45
+ for (const rule of mapping) {
46
+ if (!rule || !rule.oidc_claim) continue;
47
+ const rawValue = getClaimValue(oidcClaims, rule.oidc_claim);
48
+ if (rawValue === undefined || rawValue === null) continue;
49
+
50
+ const ruleVal = rule.value ? String(rule.value).trim() : '';
51
+
52
+ if (rule.type === 'custom_role' || !ruleVal || ruleVal.toLowerCase() === String(rule.oidc_claim).toLowerCase()) {
53
+ const claimValue = Array.isArray(rawValue) ? rawValue[0] : String(rawValue).trim();
54
+ if (claimValue) {
55
+ role = claimValue;
56
+ }
57
+ } else if (rule.type === 'role') {
58
+ const match = Array.isArray(rawValue)
59
+ ? rawValue.some((v) => String(v).toLowerCase() === ruleVal.toLowerCase())
60
+ : String(rawValue).toLowerCase() === ruleVal.toLowerCase();
61
+
62
+ if (match) {
63
+ role = ruleVal;
64
+ } else if (typeof rawValue === 'string' && rawValue.trim()) {
65
+ role = rawValue.trim();
66
+ } else if (Array.isArray(rawValue) && rawValue.length > 0) {
67
+ role = String(rawValue[0]).trim();
68
+ }
69
+ } else if (rule.type === 'permission') {
70
+ const match = Array.isArray(rawValue)
71
+ ? rawValue.includes(ruleVal)
72
+ : String(rawValue) === ruleVal;
73
+ if (match && (!allPermissions || allPermissions[ruleVal])) {
74
+ permissions[ruleVal] = true;
75
+ }
76
+ }
77
+ }
78
+ }
79
+
80
+ if (!role) {
81
+ const candidates = [
82
+ getClaimValue(oidcClaims, 'role'),
83
+ getClaimValue(oidcClaims, 'roles'),
84
+ getClaimValue(oidcClaims, 'groups'),
85
+ getClaimValue(oidcClaims, 'group'),
86
+ getClaimValue(oidcClaims, 'realm_access.roles'),
87
+ getClaimValue(oidcClaims, 'resource_access.account.roles'),
88
+ getClaimValue(oidcClaims, 'https://emp/roles'),
89
+ getClaimValue(oidcClaims, 'https://emp/role'),
90
+ ];
91
+
92
+ for (const c of candidates) {
93
+ if (!c) continue;
94
+ if (typeof c === 'string' && c.trim()) {
95
+ role = c.trim();
96
+ break;
97
+ }
98
+ if (Array.isArray(c) && c.length > 0 && typeof c[0] === 'string') {
99
+ role = c[0].trim();
100
+ break;
101
+ }
102
+ }
103
+ }
104
+
105
+ return { role, permissions };
106
+ }
107
+
108
+ export class SSOManager {
109
+ /**
110
+ * @param {object} [options={}]
111
+ * @param {Function} options.query Database query function `(sql, params) => Promise<{ rows: any[], rowCount: number }>`
112
+ * @param {string} [options.table='sso_providers'] SSO providers table name
113
+ * @param {string} [options.usersTable='users'] Users table name
114
+ * @param {string} [options.rolesTable='roles'] Roles table name
115
+ * @param {string} [options.superRole='superadmin'] Name of super administrative role
116
+ * @param {object} [options.allPermissions={}] Map of system permissions
117
+ * @param {Function} [options.createSession] Session generation function `async (userId, req) => string`
118
+ * @param {string} [options.jwtSecret] State signing secret
119
+ */
120
+ constructor(options = {}) {
121
+ this.query = options.query;
122
+ this.table = options.table || options.ssoTable || 'sso_providers';
123
+ this.usersTable = options.usersTable || 'users';
124
+ this.rolesTable = options.rolesTable || 'roles';
125
+ this.superRole = options.superRole || 'superadmin';
126
+ this.allPermissions = options.allPermissions || {};
127
+ this.createSession = options.createSession || null;
128
+ this.jwtSecret =
129
+ options.jwtSecret ||
130
+ (typeof process !== 'undefined'
131
+ ? (process.env?.JWT_SECRET || process.env?.OIDC_STATE_SECRET || 'cynx-sso-state-secret')
132
+ : 'cynx-sso-state-secret');
133
+
134
+ this._tableColumnsCache = {};
135
+ this._tablesCache = {};
136
+ }
137
+
138
+ /**
139
+ * Internal ID generator. Defaults to 12 chars UID from cynx-lib.
140
+ * @param {number} [len=12]
141
+ * @returns {string}
142
+ */
143
+ generateId(len = 12) {
144
+ return uid(len);
145
+ }
146
+
147
+ async _getTableColumns(tableName) {
148
+ if (this._tableColumnsCache[tableName]) return this._tableColumnsCache[tableName];
149
+ if (!this.query) return new Set();
150
+ try {
151
+ const res = await this.query(
152
+ `SELECT column_name FROM information_schema.columns WHERE table_schema = 'public' AND table_name = $1`,
153
+ [tableName]
154
+ );
155
+ const cols = new Set((res.rows || []).map((r) => r.column_name));
156
+ this._tableColumnsCache[tableName] = cols;
157
+ return cols;
158
+ } catch {
159
+ return new Set();
160
+ }
161
+ }
162
+
163
+ async _hasTable(tableName) {
164
+ if (this._tablesCache[tableName] !== undefined) return this._tablesCache[tableName];
165
+ if (!this.query) return false;
166
+ try {
167
+ const res = await this.query(
168
+ `SELECT 1 FROM information_schema.tables WHERE table_schema = 'public' AND table_name = $1 LIMIT 1`,
169
+ [tableName]
170
+ );
171
+ const exists = Boolean(res.rows && res.rows.length > 0);
172
+ this._tablesCache[tableName] = exists;
173
+ return exists;
174
+ } catch {
175
+ return false;
176
+ }
177
+ }
178
+
179
+ buildConfig(row) {
180
+ if (!row) return null;
181
+ let mapping = row.claims_mapping;
182
+ if (typeof mapping === 'string') {
183
+ try {
184
+ mapping = JSON.parse(mapping);
185
+ } catch {
186
+ mapping = [];
187
+ }
188
+ }
189
+ return {
190
+ id: row.id,
191
+ name: row.name,
192
+ issuer: row.issuer,
193
+ clientId: row.client_id,
194
+ clientSecret: row.client_secret,
195
+ scopes: row.scopes || 'openid profile email',
196
+ discoveryPath: row.discovery_path || '/.well-known/openid-configuration',
197
+ pkceEnabled: !!row.pkce_enabled,
198
+ claimsMapping: Array.isArray(mapping) ? mapping : [],
199
+ redirectUri: row.redirect_uri || '',
200
+ isActive: !!row.is_active,
201
+ createdAt: row.created_at,
202
+ };
203
+ }
204
+
205
+ /**
206
+ * Retrieve all SSO providers.
207
+ * @returns {Promise<object[]>}
208
+ */
209
+ async getProviders() {
210
+ if (!this.query) throw new Error('[cynx/sso] Database query function is required.');
211
+ const r = await this.query(
212
+ `SELECT id, name, issuer, client_id, scopes, discovery_path, pkce_enabled, claims_mapping, redirect_uri, is_active, created_at
213
+ FROM ${this.table} ORDER BY created_at ASC`
214
+ );
215
+ return r.rows;
216
+ }
217
+
218
+ /**
219
+ * Retrieve active SSO providers for public login view.
220
+ * @returns {Promise<{ id: string, name: string }[]>}
221
+ */
222
+ async getActiveProviders() {
223
+ if (!this.query) return [];
224
+ try {
225
+ const r = await this.query(
226
+ `SELECT id, name FROM ${this.table} WHERE is_active = TRUE ORDER BY created_at ASC`
227
+ );
228
+ return r.rows;
229
+ } catch {
230
+ return [];
231
+ }
232
+ }
233
+
234
+ /**
235
+ * Create a new SSO provider. Generates internal ID if not provided.
236
+ * @param {object} data
237
+ * @returns {Promise<object>}
238
+ */
239
+ async createProvider(data = {}) {
240
+ if (!this.query) throw new Error('[cynx/sso] Database query function is required.');
241
+ const { name, issuer, client_id, client_secret, scopes, discovery_path, pkce_enabled, claims_mapping, redirect_uri } = data;
242
+ if (!name || !issuer || !client_id) {
243
+ throw new Error('Name, issuer, and client_id are required');
244
+ }
245
+
246
+ const providerId = data.id || this.generateId(12);
247
+
248
+ const r = await this.query(
249
+ `INSERT INTO ${this.table} (id, name, issuer, client_id, client_secret, scopes, discovery_path, pkce_enabled, claims_mapping, redirect_uri)
250
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
251
+ RETURNING id, name, issuer, is_active, created_at`,
252
+ [
253
+ providerId,
254
+ String(name).trim(),
255
+ String(issuer).trim(),
256
+ String(client_id).trim(),
257
+ client_secret || '',
258
+ scopes || 'openid profile email',
259
+ discovery_path || '/.well-known/openid-configuration',
260
+ !!pkce_enabled,
261
+ JSON.stringify(claims_mapping || []),
262
+ redirect_uri || '',
263
+ ]
264
+ );
265
+
266
+ return r.rows[0];
267
+ }
268
+
269
+ /**
270
+ * Update existing SSO provider.
271
+ * @param {string} id
272
+ * @param {object} data
273
+ * @returns {Promise<object>}
274
+ */
275
+ async updateProvider(id, data = {}) {
276
+ if (!this.query) throw new Error('[cynx/sso] Database query function is required.');
277
+ if (!id) throw new Error('Provider ID is required');
278
+
279
+ const { name, issuer, client_id, client_secret, scopes, discovery_path, pkce_enabled, claims_mapping, redirect_uri } = data;
280
+ const sets = [];
281
+ const params = [id];
282
+
283
+ if (name !== undefined) {
284
+ params.push(String(name).trim());
285
+ sets.push(`name = $${params.length}`);
286
+ }
287
+ if (issuer !== undefined) {
288
+ params.push(String(issuer).trim());
289
+ sets.push(`issuer = $${params.length}`);
290
+ }
291
+ if (client_id !== undefined) {
292
+ params.push(String(client_id).trim());
293
+ sets.push(`client_id = $${params.length}`);
294
+ }
295
+ if (client_secret !== undefined && client_secret !== '') {
296
+ params.push(client_secret);
297
+ sets.push(`client_secret = $${params.length}`);
298
+ }
299
+ if (scopes !== undefined) {
300
+ params.push(scopes);
301
+ sets.push(`scopes = $${params.length}`);
302
+ }
303
+ if (discovery_path !== undefined) {
304
+ params.push(discovery_path);
305
+ sets.push(`discovery_path = $${params.length}`);
306
+ }
307
+ if (pkce_enabled !== undefined) {
308
+ params.push(!!pkce_enabled);
309
+ sets.push(`pkce_enabled = $${params.length}`);
310
+ }
311
+ if (claims_mapping !== undefined) {
312
+ params.push(JSON.stringify(claims_mapping));
313
+ sets.push(`claims_mapping = $${params.length}`);
314
+ }
315
+ if (redirect_uri !== undefined) {
316
+ params.push(redirect_uri);
317
+ sets.push(`redirect_uri = $${params.length}`);
318
+ }
319
+
320
+ if (!sets.length) throw new Error('Nothing to update');
321
+
322
+ const r = await this.query(
323
+ `UPDATE ${this.table} SET ${sets.join(', ')} WHERE id = $1 RETURNING id, name, issuer, is_active, created_at`,
324
+ params
325
+ );
326
+
327
+ if (!r.rows.length) throw new Error('SSO provider not found');
328
+ return r.rows[0];
329
+ }
330
+
331
+ /**
332
+ * Delete an inactive SSO provider.
333
+ * @param {string} id
334
+ * @returns {Promise<{ ok: boolean }>}
335
+ */
336
+ async deleteProvider(id) {
337
+ if (!this.query) throw new Error('[cynx/sso] Database query function is required.');
338
+ const p = await this.query(`SELECT is_active FROM ${this.table} WHERE id = $1`, [id]);
339
+ if (!p.rows.length) throw new Error('Provider not found');
340
+ if (p.rows[0].is_active) {
341
+ throw new Error('Cannot delete active provider. Deactivate it first.');
342
+ }
343
+ await this.query(`DELETE FROM ${this.table} WHERE id = $1`, [id]);
344
+ return { ok: true };
345
+ }
346
+
347
+ /**
348
+ * Activate an SSO provider.
349
+ * @param {string} id
350
+ * @returns {Promise<{ ok: boolean }>}
351
+ */
352
+ async activateProvider(id) {
353
+ if (!this.query) throw new Error('[cynx/sso] Database query function is required.');
354
+ const p = await this.query(`SELECT id FROM ${this.table} WHERE id = $1`, [id]);
355
+ if (!p.rows.length) throw new Error('Provider not found');
356
+ await this.query(`UPDATE ${this.table} SET is_active = TRUE WHERE id = $1`, [id]);
357
+ return { ok: true };
358
+ }
359
+
360
+ /**
361
+ * Deactivate an SSO provider.
362
+ * @param {string} id
363
+ * @returns {Promise<{ ok: boolean }>}
364
+ */
365
+ async deactivateProvider(id) {
366
+ if (!this.query) throw new Error('[cynx/sso] Database query function is required.');
367
+ const p = await this.query(`SELECT id FROM ${this.table} WHERE id = $1`, [id]);
368
+ if (!p.rows.length) throw new Error('Provider not found');
369
+ await this.query(`UPDATE ${this.table} SET is_active = FALSE WHERE id = $1`, [id]);
370
+ return { ok: true };
371
+ }
372
+
373
+ /**
374
+ * Test OIDC discovery configuration.
375
+ * @param {string} issuer
376
+ * @param {string} [discoveryPath]
377
+ * @returns {Promise<object>}
378
+ */
379
+ async testConnection(issuer, discoveryPath) {
380
+ if (!issuer) throw new Error('Issuer URL is required');
381
+ const doc = await discover(issuer, discoveryPath);
382
+ return {
383
+ ok: true,
384
+ issuer: doc.issuer,
385
+ authorization_endpoint: doc.authorization_endpoint,
386
+ token_endpoint: doc.token_endpoint,
387
+ userinfo_endpoint: doc.userinfo_endpoint,
388
+ };
389
+ }
390
+
391
+ /**
392
+ * Build authorize redirect URL for client authentication.
393
+ * @param {object} params
394
+ * @param {string} params.providerId
395
+ * @param {string} [params.origin]
396
+ * @param {string} [params.customRedirectUri]
397
+ * @returns {Promise<{ authorizeUrl: string, state: string }>}
398
+ */
399
+ async buildAuthorizeUrl({ providerId, origin = '', customRedirectUri = '' }) {
400
+ if (!this.query) throw new Error('[cynx/sso] Database query function is required.');
401
+ const r = await this.query(`SELECT * FROM ${this.table} WHERE id = $1 AND is_active = TRUE`, [providerId]);
402
+ if (!r.rows.length) {
403
+ throw new Error('SSO provider not found or inactive');
404
+ }
405
+
406
+ const config = this.buildConfig(r.rows[0]);
407
+ if (!config.issuer || !config.clientId) {
408
+ throw new Error('SSO provider is not fully configured');
409
+ }
410
+
411
+ const effectiveRedirectUri = (config.redirectUri && config.redirectUri.trim())
412
+ ? config.redirectUri.trim()
413
+ : customRedirectUri || (origin ? `${origin.replace(/\/+$/, '')}/auth/callback` : '/auth/callback');
414
+
415
+ let codeVerifier = null;
416
+ if (config.pkceEnabled) {
417
+ const pkce = generatePKCE();
418
+ codeVerifier = pkce.codeVerifier;
419
+ }
420
+
421
+ const state = generateState(
422
+ {
423
+ providerId,
424
+ redirectUri: effectiveRedirectUri,
425
+ origin,
426
+ codeVerifier,
427
+ },
428
+ this.jwtSecret
429
+ );
430
+
431
+ const codeChallenge = codeVerifier
432
+ ? crypto.createHash('sha256').update(codeVerifier).digest('base64url')
433
+ : null;
434
+
435
+ const authConfig = { ...config, redirectUri: effectiveRedirectUri };
436
+ const authorizeUrl = buildAuthorizeUrl(authConfig, state, codeChallenge);
437
+
438
+ return { authorizeUrl, state };
439
+ }
440
+
441
+ /**
442
+ * Handle OAuth2 / OIDC callback, exchange code, synchronize user, and issue session.
443
+ * @param {object} params
444
+ * @param {string} params.code
445
+ * @param {string} params.state
446
+ * @param {string} [params.error]
447
+ * @param {string} [params.errorDescription]
448
+ * @param {string} [params.origin]
449
+ * @param {object} [params.req] Original HTTP request object (for session creation)
450
+ * @returns {Promise<{ redirectUrl: string, sessionToken: string, user: object }>}
451
+ */
452
+ async handleCallback({ code, state, error, errorDescription, origin = '', req = null }) {
453
+ if (error) {
454
+ throw new Error(errorDescription || error);
455
+ }
456
+ if (!code || !state) {
457
+ throw new Error('Missing authorization code or state');
458
+ }
459
+
460
+ const stateEntry = consumeState(state, this.jwtSecret);
461
+ if (!stateEntry || !stateEntry.providerId) {
462
+ throw new Error('Invalid or expired state parameter');
463
+ }
464
+
465
+ const r = await this.query(`SELECT * FROM ${this.table} WHERE id = $1 AND is_active = TRUE`, [stateEntry.providerId]);
466
+ if (!r.rows.length) {
467
+ throw new Error('SSO provider not found or inactive');
468
+ }
469
+
470
+ const reqOrigin = (stateEntry && stateEntry.origin) || origin;
471
+ const effectiveRedirectUri = (stateEntry && stateEntry.redirectUri)
472
+ || (r.rows[0].redirect_uri && r.rows[0].redirect_uri.trim())
473
+ || `${reqOrigin.replace(/\/+$/, '')}/auth/callback`;
474
+
475
+ const config = { ...this.buildConfig(r.rows[0]), redirectUri: effectiveRedirectUri };
476
+
477
+ const tokenResult = await exchangeCode(config, code, stateEntry.codeVerifier);
478
+
479
+ let claims = {};
480
+ if (tokenResult.id_token) {
481
+ try {
482
+ claims = decodeIdToken(tokenResult.id_token);
483
+ } catch (err) {
484
+ console.warn('[cynx/sso] ID token decode warning:', err.message);
485
+ }
486
+ }
487
+
488
+ if (tokenResult.access_token) {
489
+ try {
490
+ const userinfo = await getUserInfo(config, tokenResult.access_token);
491
+ claims = { ...claims, ...userinfo };
492
+ } catch (err) {
493
+ console.warn('[cynx/sso] getUserInfo warning:', err.message);
494
+ }
495
+ }
496
+
497
+ if (!claims || Object.keys(claims).length === 0) {
498
+ throw new Error('Failed to retrieve user claims from SSO provider');
499
+ }
500
+
501
+ const sub = claims.sub || '';
502
+ const email = (claims.email || '').toLowerCase().trim();
503
+ let username = claims.preferred_username || claims.nickname || (email ? email.split('@')[0] : sub);
504
+ username = username ? String(username).trim() : 'sso_user_' + genUid(6);
505
+
506
+ let fullName = claims.name;
507
+ if (!fullName) {
508
+ const parts = [claims.given_name, claims.family_name].filter(Boolean);
509
+ fullName = parts.length ? parts.join(' ') : (claims.preferred_username || username);
510
+ }
511
+ fullName = String(fullName).trim();
512
+
513
+ // Inspect user table columns dynamically
514
+ const userCols = await this._getTableColumns(this.usersTable);
515
+ const selectCols = ['id', 'username', 'role', 'is_active'];
516
+ if (userCols.has('full_name')) selectCols.push('full_name');
517
+ if (userCols.has('email')) selectCols.push('email');
518
+ if (userCols.has('permissions')) selectCols.push('permissions');
519
+ if (userCols.has('is_disabled')) selectCols.push('is_disabled');
520
+
521
+ let existingUser = null;
522
+ let u = await this.query(
523
+ `SELECT ${selectCols.join(', ')} FROM ${this.usersTable} WHERE username = $1`,
524
+ [username]
525
+ );
526
+ if (!u.rows.length && email && userCols.has('email')) {
527
+ u = await this.query(
528
+ `SELECT ${selectCols.join(', ')} FROM ${this.usersTable} WHERE email = $1`,
529
+ [email]
530
+ );
531
+ }
532
+ if (u.rows.length) {
533
+ existingUser = u.rows[0];
534
+ if (existingUser.is_disabled || existingUser.is_active === false) {
535
+ throw new Error('Account is disabled or inactive');
536
+ }
537
+ }
538
+
539
+ let { role, permissions } = applyClaimsMapping(claims, config.claimsMapping, this.superRole, this.allPermissions);
540
+
541
+ if (!role) {
542
+ if (existingUser && existingUser.role) {
543
+ role = existingUser.role;
544
+ } else if (username.toLowerCase() === this.superRole.toLowerCase() || (email && email.toLowerCase().startsWith(`${this.superRole.toLowerCase()}@`))) {
545
+ role = this.superRole;
546
+ } else {
547
+ const hasRolesTable = await this._hasTable(this.rolesTable);
548
+ if (hasRolesTable) {
549
+ try {
550
+ const rRow = await this.query(`SELECT name FROM ${this.rolesTable} ORDER BY created_at ASC LIMIT 1`);
551
+ role = rRow.rows[0]?.name || this.superRole || 'user';
552
+ } catch {
553
+ role = this.superRole || 'user';
554
+ }
555
+ } else {
556
+ role = this.superRole || 'user';
557
+ }
558
+ }
559
+ }
560
+
561
+ if (userCols.has('permissions')) {
562
+ if (role.toLowerCase() === this.superRole.toLowerCase()) {
563
+ permissions = Object.fromEntries(Object.keys(this.allPermissions || {}).map((k) => [k, true]));
564
+ } else if (Object.keys(permissions).length === 0) {
565
+ const hasRolesTable = await this._hasTable(this.rolesTable);
566
+ if (hasRolesTable) {
567
+ try {
568
+ const roleRow = await this.query(`SELECT permissions FROM ${this.rolesTable} WHERE name = $1 OR LOWER(name) = LOWER($1)`, [role]);
569
+ if (roleRow.rows.length && roleRow.rows[0].permissions) {
570
+ permissions = roleRow.rows[0].permissions;
571
+ }
572
+ } catch (err) {
573
+ console.warn('[cynx/sso] Role permissions fetch warning:', err.message);
574
+ }
575
+ }
576
+ }
577
+ }
578
+
579
+ let userId = null;
580
+ if (existingUser) {
581
+ userId = existingUser.id;
582
+ const updateSets = ['is_active = TRUE'];
583
+ const updateParams = [userId];
584
+
585
+ if (userCols.has('updated_at')) {
586
+ updateSets.push('updated_at = NOW()');
587
+ }
588
+ if (email && userCols.has('email')) {
589
+ updateParams.push(email);
590
+ updateSets.push(`email = $${updateParams.length}`);
591
+ }
592
+ if (fullName && userCols.has('full_name')) {
593
+ updateParams.push(fullName);
594
+ updateSets.push(`full_name = $${updateParams.length}`);
595
+ }
596
+ if (role && userCols.has('role')) {
597
+ updateParams.push(role);
598
+ updateSets.push(`role = $${updateParams.length}`);
599
+ }
600
+ if (userCols.has('permissions') && permissions && Object.keys(permissions).length > 0) {
601
+ updateParams.push(JSON.stringify(permissions));
602
+ updateSets.push(`permissions = $${updateParams.length}`);
603
+ }
604
+
605
+ await this.query(`UPDATE ${this.usersTable} SET ${updateSets.join(', ')} WHERE id = $1`, updateParams);
606
+ } else {
607
+ userId = this.generateId(16);
608
+ const insertCols = ['id', 'username'];
609
+ const insertVals = [userId, username];
610
+
611
+ if (userCols.has('password_hash')) {
612
+ insertCols.push('password_hash');
613
+ insertVals.push('SSO_AUTH_EXTERNAL');
614
+ }
615
+ if (userCols.has('full_name')) {
616
+ insertCols.push('full_name');
617
+ insertVals.push(fullName || username);
618
+ }
619
+ if (userCols.has('role')) {
620
+ insertCols.push('role');
621
+ insertVals.push(role);
622
+ }
623
+ if (userCols.has('is_active')) {
624
+ insertCols.push('is_active');
625
+ insertVals.push(true);
626
+ }
627
+ if (userCols.has('email')) {
628
+ insertCols.push('email');
629
+ insertVals.push(email || null);
630
+ }
631
+ if (userCols.has('permissions')) {
632
+ insertCols.push('permissions');
633
+ insertVals.push(JSON.stringify(permissions || {}));
634
+ }
635
+
636
+ const placeholders = insertVals.map((_, i) => `$${i + 1}`).join(', ');
637
+ await this.query(
638
+ `INSERT INTO ${this.usersTable} (${insertCols.join(', ')}) VALUES (${placeholders})`,
639
+ insertVals
640
+ );
641
+ }
642
+
643
+ let sessionToken = '';
644
+ if (typeof this.createSession === 'function') {
645
+ sessionToken = await this.createSession(userId, req);
646
+ }
647
+
648
+ const frontendBase = (stateEntry && stateEntry.origin) || (config.redirectUri ? new URL(config.redirectUri).origin : reqOrigin);
649
+ const redirectUrl = `${frontendBase.replace(/\/+$/, '')}/sso-callback#token=${encodeURIComponent(sessionToken)}`;
650
+
651
+ return {
652
+ redirectUrl,
653
+ sessionToken,
654
+ userId,
655
+ username,
656
+ role,
657
+ };
658
+ }
659
+ }
660
+
661
+ /**
662
+ * Universal Factory function to create configured SSOManager instance.
663
+ * Supports positional arguments and options object.
664
+ *
665
+ * @param {object|Function} queryOrOptions
666
+ * @param {string} [table='sso_providers']
667
+ * @param {string} [usersTable='users']
668
+ * @param {string} [rolesTable='roles']
669
+ * @param {string} [superRole='superadmin']
670
+ * @param {object} [allPermissions={}]
671
+ * @param {Function} [createSession]
672
+ * @returns {SSOManager}
673
+ */
674
+ export function createSSOManager(
675
+ queryOrOptions = {},
676
+ table = 'sso_providers',
677
+ usersTable = 'users',
678
+ rolesTable = 'roles',
679
+ superRole = 'superadmin',
680
+ allPermissions = {},
681
+ createSession = null
682
+ ) {
683
+ if (typeof queryOrOptions === 'function') {
684
+ return new SSOManager({
685
+ query: queryOrOptions,
686
+ table,
687
+ usersTable,
688
+ rolesTable,
689
+ superRole,
690
+ allPermissions,
691
+ createSession,
692
+ });
693
+ }
694
+ return new SSOManager(queryOrOptions);
695
+ }
696
+
697
+ export default {
698
+ SSOManager,
699
+ createSSOManager,
700
+ applyClaimsMapping,
701
+ getClaimValue,
702
+ };