cynx-lib 1.3.100 → 1.3.102

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