lemonldap-ng-handler 0.7.3 → 0.8.1

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/lib/index.mjs CHANGED
@@ -3,9 +3,104 @@ import Session from '@lemonldap-ng/session';
3
3
  import SafeLib from '@lemonldap-ng/safelib';
4
4
  import Logger from '@lemonldap-ng/logger';
5
5
  import vm from 'vm';
6
+ import crypto from 'crypto';
6
7
  import RE2 from 're2';
7
8
  import http from 'http';
8
9
  import normalizeUrl from 'normalize-url';
10
+ import { getAccessTokenSessionId } from '@lemonldap-ng/jwt';
11
+
12
+ /******************************************************************************
13
+ Copyright (c) Microsoft Corporation.
14
+
15
+ Permission to use, copy, modify, and/or distribute this software for any
16
+ purpose with or without fee is hereby granted.
17
+
18
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
19
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
20
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
21
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
22
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
23
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
24
+ PERFORMANCE OF THIS SOFTWARE.
25
+ ***************************************************************************** */
26
+ /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
27
+
28
+
29
+ function __awaiter(thisArg, _arguments, P, generator) {
30
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
31
+ return new (P || (P = Promise))(function (resolve, reject) {
32
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
33
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
34
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
35
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
36
+ });
37
+ }
38
+
39
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
40
+ var e = new Error(message);
41
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
42
+ };
43
+
44
+ /**
45
+ * Message Broker Actions for LemonLDAP::NG handler
46
+ * Port of Lemonldap::NG::Handler::Main::Msg
47
+ *
48
+ * Handles event messages from the message broker (config reload, session purge, etc.)
49
+ */
50
+ /**
51
+ * Process a message from the broker
52
+ * @param handler - Handler instance to call actions on
53
+ * @param msg - Message from broker
54
+ * @returns true if message was processed, false if unknown action
55
+ */
56
+ function processMessage(handler, msg) {
57
+ return __awaiter(this, void 0, void 0, function* () {
58
+ const logger = handler.userLogger;
59
+ switch (msg.action) {
60
+ case "reload":
61
+ logger.debug("Message broker: reload configuration requested");
62
+ try {
63
+ yield handler.reload();
64
+ logger.info("Configuration reloaded via message broker");
65
+ return true;
66
+ }
67
+ catch (e) {
68
+ logger.error(`Failed to reload configuration: ${e}`);
69
+ return false;
70
+ }
71
+ case "unlog":
72
+ if (msg.id) {
73
+ logger.debug(`Message broker: unlog session ${msg.id}`);
74
+ yield handler.localUnlog(msg.id);
75
+ return true;
76
+ }
77
+ else {
78
+ logger.warn("Message broker: unlog without session id");
79
+ return false;
80
+ }
81
+ case "newSession":
82
+ // New session notification - currently no action needed for handler
83
+ // This is mainly used by portals to notify other instances
84
+ logger.debug(`Message broker: new session notification (id: ${msg.id})`);
85
+ return true;
86
+ case "delSession":
87
+ // Session deleted - clear from cache
88
+ if (msg.id) {
89
+ logger.debug(`Message broker: session ${msg.id} deleted`);
90
+ yield handler.localUnlog(msg.id);
91
+ return true;
92
+ }
93
+ return false;
94
+ case "ping":
95
+ // Ping message for health checks
96
+ logger.debug("Message broker: ping received");
97
+ return true;
98
+ default:
99
+ logger.debug(`Message broker: unknown action '${msg.action}'`);
100
+ return false;
101
+ }
102
+ });
103
+ }
9
104
 
10
105
  const condMatch = new RE2("^logout(?:_sso|_app|_app_sso|)(?:s+(.*))?$", "i");
11
106
  let sid = 0;
@@ -23,10 +118,23 @@ const requiredFields = [
23
118
  "useRedirectOnForbidden",
24
119
  "whatToTrace",
25
120
  "loopBackUrl",
121
+ "handlerInternalCache",
122
+ "authChoiceAuthBasic",
123
+ "authChoiceParam",
26
124
  ];
125
+ /**
126
+ * Default message broker options
127
+ */
128
+ const DEFAULT_CHECK_TIME = 600; // seconds
129
+ const MIN_CHECK_INTERVAL_MS = 1000; // minimum 1 second
130
+ const DEFAULT_EVENT_QUEUE = "llng-events";
131
+ const DEFAULT_STATUS_QUEUE = "llng-status";
27
132
  class HandlerInit {
28
133
  constructor(args) {
29
134
  this.safe = {};
135
+ /* Message Broker properties */
136
+ this.eventLoopInterval = null;
137
+ this.lastConfigCheck = 0;
30
138
  // @ts-ignore: some values will be initialized later
31
139
  this.tsv = {
32
140
  defaultCondition: {},
@@ -42,6 +150,10 @@ class HandlerInit {
42
150
  port: {},
43
151
  portal: () => "",
44
152
  vhostAlias: {},
153
+ eventQueueName: DEFAULT_EVENT_QUEUE,
154
+ statusQueueName: DEFAULT_STATUS_QUEUE,
155
+ checkMsg: 0,
156
+ checkTime: DEFAULT_CHECK_TIME,
45
157
  };
46
158
  this.localConf = args;
47
159
  if (!args.configStorage)
@@ -79,6 +191,13 @@ class HandlerInit {
79
191
  // @ts-ignore: all fields not declared
80
192
  this.tsv[k] = conf[k];
81
193
  });
194
+ // Compute keyH for AuthBasic session ID generation
195
+ if (conf.key) {
196
+ this.tsv.keyH = crypto
197
+ .createHash("sha256")
198
+ .update(conf.key)
199
+ .digest("hex");
200
+ }
82
201
  Object.keys(this.localConf).forEach((k) => {
83
202
  conf[k] = this.localConf[k];
84
203
  });
@@ -203,16 +322,22 @@ class HandlerInit {
203
322
  }
204
323
  this.tsv.cookieDetect = new RE2(`\\b${this.tsv.cookieName}=([^;]+)`);
205
324
  this.sessionAcc.ready.then(() => {
206
- resolve(true);
207
325
  Logger(conf, true)
208
- .then((logger) => {
326
+ .then((logger) => __awaiter(this, void 0, void 0, function* () {
209
327
  this.userLogger = logger;
328
+ // Initialize message broker after logger is ready
329
+ const brokerInitialized = yield this.msgBrokerInit(conf);
330
+ if (!brokerInitialized) {
331
+ this.userLogger.info("Handler initialized without message broker (real-time events disabled)");
332
+ }
333
+ // Start event loop for checking broker messages
334
+ this.startEventLoop();
210
335
  resolve(true);
211
- })
336
+ }))
212
337
  .catch((e) => {
213
- console.error("Logger error", e);
338
+ // Logger initialization failed, throw error
214
339
  // istanbul ignore next
215
- throw new Error(e);
340
+ throw new Error(`Logger error: ${e}`);
216
341
  });
217
342
  });
218
343
  })
@@ -278,9 +403,177 @@ class HandlerInit {
278
403
  // Session attributes: $xx is replaced by session.xx
279
404
  .replace(/\$(_*[a-zA-Z]\w*)/g, "session.$1"));
280
405
  }
406
+ /**
407
+ * Parse Perl-style message broker module name
408
+ * Handles formats:
409
+ * - "::Redis" -> "redis"
410
+ * - "Lemonldap::NG::Common::MessageBroker::Redis" -> "redis"
411
+ * - "Redis" -> "redis"
412
+ * - "redis" -> "redis"
413
+ */
414
+ parseBrokerType(brokerType) {
415
+ if (!brokerType)
416
+ return "nobroker";
417
+ // Extract the last part after ::
418
+ const match = brokerType.match(/::(\w+)$/);
419
+ if (match) {
420
+ return match[1].toLowerCase();
421
+ }
422
+ // Already a simple name
423
+ return brokerType.toLowerCase();
424
+ }
425
+ /**
426
+ * Initialize message broker from configuration
427
+ * @param conf - LemonLDAP::NG configuration
428
+ * @returns true if broker was successfully initialized, false if using fallback/none
429
+ */
430
+ msgBrokerInit(conf) {
431
+ return __awaiter(this, void 0, void 0, function* () {
432
+ // Get message broker configuration
433
+ // Parse Perl-style module name (::Redis, Lemonldap::NG::Common::MessageBroker::Redis)
434
+ const brokerType = this.parseBrokerType(conf.messageBroker || "nobroker");
435
+ const brokerOptions = conf.messageBrokerOptions || {};
436
+ // Set queue names from config
437
+ this.tsv.eventQueueName =
438
+ brokerOptions.eventQueueName || DEFAULT_EVENT_QUEUE;
439
+ this.tsv.statusQueueName =
440
+ brokerOptions.statusQueueName || DEFAULT_STATUS_QUEUE;
441
+ this.tsv.checkTime = brokerOptions.checkTime || DEFAULT_CHECK_TIME;
442
+ // Dynamic import of message broker module
443
+ const moduleName = `@lemonldap-ng/message-broker-${brokerType.toLowerCase()}`;
444
+ try {
445
+ const BrokerModule = yield import(moduleName);
446
+ const BrokerClass = BrokerModule.default;
447
+ // Create reader and writer instances
448
+ this.tsv.msgBrokerReader = new BrokerClass(brokerOptions, this.userLogger);
449
+ this.tsv.msgBrokerWriter = new BrokerClass(brokerOptions, this.userLogger);
450
+ // Subscribe to event queue
451
+ if (this.tsv.msgBrokerReader) {
452
+ yield this.tsv.msgBrokerReader.subscribe(this.tsv.eventQueueName);
453
+ this.userLogger.debug(`Message broker ${brokerType} initialized, subscribed to ${this.tsv.eventQueueName}`);
454
+ return true;
455
+ }
456
+ return false;
457
+ }
458
+ catch (e) {
459
+ this.userLogger.warn(`Failed to load message broker ${moduleName}: ${e}. Using NoBroker fallback.`);
460
+ // Fallback to NoBroker
461
+ try {
462
+ const NoBroker = (yield import('@lemonldap-ng/message-broker-nobroker'))
463
+ .default;
464
+ this.tsv.msgBrokerReader = new NoBroker({}, this.userLogger);
465
+ this.tsv.msgBrokerWriter = new NoBroker({}, this.userLogger);
466
+ return false; // Using fallback, not the configured broker
467
+ }
468
+ catch (_a) {
469
+ // No broker available at all
470
+ this.userLogger.debug("No message broker available");
471
+ return false;
472
+ }
473
+ }
474
+ });
475
+ }
476
+ /**
477
+ * Start the event loop to check for broker messages
478
+ * Uses setInterval for non-blocking periodic checks
479
+ */
480
+ startEventLoop() {
481
+ if (this.eventLoopInterval) {
482
+ // Already running
483
+ return;
484
+ }
485
+ // Check interval (convert seconds to ms, minimum 1 second)
486
+ const intervalMs = Math.max(MIN_CHECK_INTERVAL_MS, (this.tsv.checkTime || DEFAULT_CHECK_TIME) * 1000);
487
+ this.eventLoopInterval = setInterval(() => __awaiter(this, void 0, void 0, function* () {
488
+ try {
489
+ yield this.checkEvents();
490
+ }
491
+ catch (e) {
492
+ this.userLogger.error(`Event loop error: ${e}`);
493
+ }
494
+ }), intervalMs);
495
+ this.userLogger.debug(`Event loop started with ${intervalMs}ms interval`);
496
+ }
497
+ /**
498
+ * Stop the event loop and close all connections
499
+ * Called to cleanly shutdown the handler (useful for tests)
500
+ */
501
+ stopEventLoop() {
502
+ return __awaiter(this, void 0, void 0, function* () {
503
+ if (this.eventLoopInterval) {
504
+ clearInterval(this.eventLoopInterval);
505
+ this.eventLoopInterval = null;
506
+ this.userLogger.debug("Event loop stopped");
507
+ }
508
+ // Close session storage to stop background processes
509
+ if (this.sessionAcc && typeof this.sessionAcc.close === "function") {
510
+ yield this.sessionAcc.close();
511
+ this.userLogger.debug("Session storage closed");
512
+ }
513
+ });
514
+ }
515
+ /**
516
+ * Check for pending events from the message broker
517
+ * Called periodically by the event loop
518
+ */
519
+ checkEvents() {
520
+ return __awaiter(this, void 0, void 0, function* () {
521
+ if (!this.tsv.msgBrokerReader) {
522
+ return;
523
+ }
524
+ try {
525
+ const msg = yield this.tsv.msgBrokerReader.getNextMessage(this.tsv.eventQueueName, 0);
526
+ if (msg) {
527
+ this.tsv.checkMsg++;
528
+ yield processMessage(this, msg);
529
+ }
530
+ }
531
+ catch (e) {
532
+ this.userLogger.error(`Error checking events: ${e}`);
533
+ }
534
+ });
535
+ }
536
+ /**
537
+ * Publish an event to the message broker
538
+ * @param action - Action type
539
+ * @param data - Additional data to include
540
+ */
541
+ publishEvent(action_1) {
542
+ return __awaiter(this, arguments, void 0, function* (action, data = {}) {
543
+ if (!this.tsv.msgBrokerWriter) {
544
+ return;
545
+ }
546
+ const msg = Object.assign({ action, channel: this.tsv.eventQueueName }, data);
547
+ try {
548
+ yield this.tsv.msgBrokerWriter.publish(this.tsv.eventQueueName, msg);
549
+ this.userLogger.debug(`Published event: ${action}`);
550
+ }
551
+ catch (e) {
552
+ this.userLogger.error(`Failed to publish event ${action}: ${e}`);
553
+ }
554
+ });
555
+ }
556
+ /**
557
+ * Returns the portal URL from configuration
558
+ * @returns Portal URL string
559
+ */
560
+ portal() {
561
+ return this.tsv.portal();
562
+ }
281
563
  }
282
564
 
565
+ /**
566
+ * Default internal cache timeout in seconds
567
+ */
568
+ const DEFAULT_INTERNAL_CACHE_TIMEOUT = 15;
283
569
  class LemonldapNGHandler extends HandlerInit {
570
+ constructor() {
571
+ super(...arguments);
572
+ /* Internal handler cache for session data */
573
+ this.lastSessionId = null;
574
+ this.lastSessionData = null;
575
+ this.lastSessionTime = 0;
576
+ }
284
577
  init() {
285
578
  return this.reload();
286
579
  }
@@ -301,8 +594,14 @@ class LemonldapNGHandler extends HandlerInit {
301
594
  return this.setError(res, "/", 503, "Service Temporarily Unavailable");
302
595
  /* 3 - check if current URI is protected */
303
596
  const protection = this.isUnprotected(req, uri);
304
- if (protection === 2)
597
+ if (protection === 2) {
598
+ // SKIP: Clear internal session data
599
+ this.lastSessionId = null;
600
+ this.lastSessionData = null;
601
+ this.lastSessionTime = 0;
602
+ this.hideCookie(req);
305
603
  return next();
604
+ }
306
605
  /* 4 - search for LLNG cookie */
307
606
  const id = this.fetchId(req);
308
607
  if (id !== "") {
@@ -324,12 +623,11 @@ class LemonldapNGHandler extends HandlerInit {
324
623
  }
325
624
  })
326
625
  .catch((e) => {
327
- console.error(e);
626
+ this.userLogger.error(`Authorization check failed: ${e}`);
328
627
  this.setError(res, "/", 503, "Service Unavailable");
329
628
  });
330
629
  })
331
- // eslint-disable-next-line no-unused-vars
332
- .catch((e) => {
630
+ .catch((_e) => {
333
631
  /* Expired session */
334
632
  this.goToPortal(res, this.selfUri(vhost, uri));
335
633
  });
@@ -395,8 +693,8 @@ class LemonldapNGHandler extends HandlerInit {
395
693
  resolveAlias(req) {
396
694
  var _a;
397
695
  // @ts-ignore: req.headers.host has already been tested
398
- const vhost = (_a = req.headers.host) === null || _a === void 0 ? void 0 : _a.split(':')[0];
399
- return vhost ? (this.tsv.vhostAlias[vhost] || vhost) : 'undef';
696
+ const vhost = (_a = req.headers.host) === null || _a === void 0 ? void 0 : _a.split(":")[0];
697
+ return vhost ? this.tsv.vhostAlias[vhost] || vhost : "undef";
400
698
  }
401
699
  fetchId(req) {
402
700
  if (req.headers.cookie) {
@@ -411,10 +709,21 @@ class LemonldapNGHandler extends HandlerInit {
411
709
  if (this.sessionAcc === undefined)
412
710
  // istanbul ignore next
413
711
  return reject("Server not ready, please wait");
712
+ const now = (Date.now() / 1000) | 0;
713
+ const internalCacheTimeout = this.tsv.handlerInternalCache || DEFAULT_INTERNAL_CACHE_TIMEOUT;
714
+ // Check internal handler cache first (efficient for persistent connections)
715
+ if (this.lastSessionId === id &&
716
+ this.lastSessionData &&
717
+ now - this.lastSessionTime < internalCacheTimeout) {
718
+ this.userLogger.debug(`Get session ${id} from internal cache`);
719
+ return resolve(this.lastSessionData);
720
+ }
721
+ // Clear stale internal cache
722
+ this.lastSessionId = null;
723
+ this.lastSessionData = null;
414
724
  this.sessionAcc
415
725
  .get(id)
416
726
  .then((session) => {
417
- const now = (Date.now() / 1000) | 0;
418
727
  if (now - session._utime > this.tsv.timeout ||
419
728
  (this.tsv.timeoutActivity &&
420
729
  session._lastSeen &&
@@ -430,6 +739,10 @@ class LemonldapNGHandler extends HandlerInit {
430
739
  // @ts-ignore this.sessionAcc is defined here
431
740
  this.sessionAcc.update(session);
432
741
  }
742
+ // Update internal cache
743
+ this.lastSessionId = id;
744
+ this.lastSessionData = session;
745
+ this.lastSessionTime = now;
433
746
  resolve(session);
434
747
  }
435
748
  })
@@ -438,6 +751,24 @@ class LemonldapNGHandler extends HandlerInit {
438
751
  });
439
752
  });
440
753
  }
754
+ /**
755
+ * Local unlog - clear session from all local caches
756
+ * @param sessionId - Optional session ID to clear (uses last cached if not provided)
757
+ */
758
+ localUnlog(sessionId) {
759
+ return __awaiter(this, void 0, void 0, function* () {
760
+ this.userLogger.debug("Local handler logout");
761
+ const id = sessionId || this.lastSessionId;
762
+ // Clear internal handler cache
763
+ this.lastSessionId = null;
764
+ this.lastSessionData = null;
765
+ this.lastSessionTime = 0;
766
+ if (id && this.sessionAcc) {
767
+ this.sessionAcc.clearMemoryCache(id);
768
+ yield this.sessionAcc.clearLocalCache(id);
769
+ }
770
+ });
771
+ }
441
772
  grant(req, uri, session) {
442
773
  return new Promise((resolve, reject) => {
443
774
  const vhost = this.resolveAlias(req);
@@ -445,12 +776,12 @@ class LemonldapNGHandler extends HandlerInit {
445
776
  return reject(`No configuration found for ${vhost} (or not listed in Node.js virtualHosts)`);
446
777
  }
447
778
  if (this.tsv.locationRegexp[vhost]) {
448
- let i = 0;
449
- this.tsv.locationRegexp[vhost].forEach((regex) => {
450
- if (regex.test(uri))
779
+ for (let i = 0; i < this.tsv.locationRegexp[vhost].length; i++) {
780
+ const regex = this.tsv.locationRegexp[vhost][i];
781
+ if (regex.test(uri)) {
451
782
  return resolve(this.tsv.locationCondition[vhost][i](req, session));
452
- i++;
453
- });
783
+ }
784
+ }
454
785
  }
455
786
  this.tsv.defaultCondition[vhost](req, session)
456
787
  ? resolve(true)
@@ -478,7 +809,7 @@ class LemonldapNGHandler extends HandlerInit {
478
809
  });
479
810
  }
480
811
  catch (e) {
481
- console.error(`Headers maybe not sent: ${e}`);
812
+ this.userLogger.error(`Headers maybe not sent: ${e}`);
482
813
  // istanbul ignore next
483
814
  return;
484
815
  }
@@ -488,6 +819,10 @@ class LemonldapNGHandler extends HandlerInit {
488
819
  req.headers.cookie = req.headers.cookie.replace(this.tsv.cookieDetect, "");
489
820
  }
490
821
  forbidden(req, res, session) {
822
+ // Clear local cache on forbidden (fire and forget, but catch errors)
823
+ this.localUnlog(session._session_id).catch((e) => {
824
+ this.userLogger.error(`Failed to clear local cache: ${e}`);
825
+ });
491
826
  if (session._logout) {
492
827
  this.goToPortal(res, session._logout, "logout=1");
493
828
  }
@@ -561,7 +896,7 @@ class LemonldapNGHandlerDevOps extends LemonldapNGHandler {
561
896
  .catch((e) => reject(e));
562
897
  })
563
898
  .catch((err) => {
564
- console.error(err);
899
+ this.userLogger.error(`Session retrieval error: ${err}`);
565
900
  this.grant(req, uri, session)
566
901
  .then((res) => {
567
902
  resolve(res);
@@ -664,9 +999,8 @@ class LemonldapNGHandlerServiceToken extends LemonldapNGHandler {
664
999
  let tokenElement;
665
1000
  try {
666
1001
  tokenElement = this.tsv.cipher.decrypt(token).split(":");
667
- // eslint-disable-next-line no-unused-vars
668
1002
  }
669
- catch (e) {
1003
+ catch (_e) {
670
1004
  this.userLogger.error("Invalid token");
671
1005
  return "";
672
1006
  }
@@ -685,7 +1019,7 @@ class LemonldapNGHandlerServiceToken extends LemonldapNGHandler {
685
1019
  // Is vhost listed in token ?
686
1020
  const vhost = this.resolveAlias(req);
687
1021
  if (tokenElement.indexOf(vhost) < 2) {
688
- console.warn(`${vhost} not authorizated in token`);
1022
+ this.userLogger.warn(`${vhost} not authorizated in token`);
689
1023
  return "";
690
1024
  }
691
1025
  // Then use token sessionId
@@ -701,6 +1035,530 @@ class LemonldapNGHandlerDevOpsST extends LemonldapNGHandlerDevOps {
701
1035
  }
702
1036
  }
703
1037
 
1038
+ /**
1039
+ * OAuth2/OIDC Handler for LemonLDAP::NG
1040
+ * Port of Lemonldap::NG::Handler::OAuth2
1041
+ *
1042
+ * This handler validates OAuth2/OIDC access tokens and retrieves
1043
+ * the associated session from the OIDC session storage.
1044
+ */
1045
+ class LemonldapNGHandlerOAuth2 extends LemonldapNGHandler {
1046
+ /**
1047
+ * Override init to also initialize OIDC session storage
1048
+ */
1049
+ init() {
1050
+ return new Promise((resolve, reject) => {
1051
+ super
1052
+ .init()
1053
+ .then(() => {
1054
+ // Initialize OIDC session storage if configured
1055
+ if (this.tsv.oidcStorageModule) {
1056
+ try {
1057
+ this.oidcSessionAcc = new Session({
1058
+ storageModule: this.tsv.oidcStorageModule,
1059
+ storageModuleOptions: this.tsv.oidcStorageOptions || {},
1060
+ });
1061
+ this.oidcSessionAcc.ready
1062
+ .then(() => {
1063
+ this.userLogger.debug("OAuth2 OIDC session storage initialized");
1064
+ resolve(true);
1065
+ })
1066
+ .catch((e) => {
1067
+ this.userLogger.error(`Failed to initialize OIDC session storage: ${e}`);
1068
+ reject(e);
1069
+ });
1070
+ }
1071
+ catch (e) {
1072
+ this.userLogger.error(`Failed to create OIDC session accessor: ${e}`);
1073
+ reject(e);
1074
+ }
1075
+ }
1076
+ else {
1077
+ // Use default session storage for OIDC tokens
1078
+ this.userLogger.debug("OAuth2 handler using default session storage for OIDC");
1079
+ resolve(true);
1080
+ }
1081
+ })
1082
+ .catch(reject);
1083
+ });
1084
+ }
1085
+ /**
1086
+ * Override fetchId to check for OAuth2 Bearer token
1087
+ * @param req - HTTP request
1088
+ */
1089
+ fetchId(req) {
1090
+ // Check for Authorization header with Bearer token
1091
+ const authHeader = req.headers.authorization;
1092
+ if (authHeader && authHeader.toLowerCase().startsWith("bearer ")) {
1093
+ const accessToken = authHeader.substring(7).trim();
1094
+ if (accessToken) {
1095
+ // Try to extract session ID from the access token
1096
+ const sessionId = getAccessTokenSessionId(accessToken);
1097
+ if (sessionId) {
1098
+ this.userLogger.debug(`OAuth2: extracted session ID from token`);
1099
+ return sessionId;
1100
+ }
1101
+ else {
1102
+ this.userLogger.warn("OAuth2: could not extract session ID from token");
1103
+ return "";
1104
+ }
1105
+ }
1106
+ }
1107
+ // Fall back to cookie-based authentication
1108
+ return super.fetchId(req);
1109
+ }
1110
+ /**
1111
+ * Override retrieveSession to use OIDC session storage if token-based
1112
+ * @param id - Session ID
1113
+ */
1114
+ retrieveSession(id) {
1115
+ // Check if we should use OIDC session storage
1116
+ // For now, use the same logic as parent class
1117
+ // The OIDC sessions are typically in the same format
1118
+ if (this.oidcSessionAcc) {
1119
+ return new Promise((resolve, reject) => {
1120
+ // @ts-ignore: oidcSessionAcc is defined
1121
+ this.oidcSessionAcc
1122
+ .get(id)
1123
+ .then((session) => {
1124
+ const now = (Date.now() / 1000) | 0;
1125
+ if (now - session._utime > this.tsv.timeout ||
1126
+ (this.tsv.timeoutActivity &&
1127
+ session._lastSeen &&
1128
+ // @ts-ignore: session._lastSeen is defined
1129
+ now - session._lastSeen > this.tsv.timeoutActivity)) {
1130
+ reject(`OAuth2 session ${id} expired`);
1131
+ }
1132
+ else {
1133
+ resolve(session);
1134
+ }
1135
+ })
1136
+ .catch((_e) => {
1137
+ // If not found in OIDC storage, try main storage
1138
+ super.retrieveSession(id).then(resolve).catch(reject);
1139
+ });
1140
+ });
1141
+ }
1142
+ return super.retrieveSession(id);
1143
+ }
1144
+ }
1145
+
1146
+ /**
1147
+ * AuthBasic Handler for LemonLDAP::NG
1148
+ * Port of Lemonldap::NG::Handler::Lib::AuthBasic
1149
+ *
1150
+ * This handler supports HTTP Basic Authentication by:
1151
+ * 1. Computing a deterministic session ID from credentials
1152
+ * 2. Checking if session exists
1153
+ * 3. If not, asking the portal to create it via REST API
1154
+ * 4. Sending WWW-Authenticate challenge when needed
1155
+ */
1156
+ class LemonldapNGHandlerAuthBasic extends LemonldapNGHandler {
1157
+ constructor() {
1158
+ super(...arguments);
1159
+ // Store pending authentication data keyed by session ID
1160
+ this.pendingAuth = new Map();
1161
+ }
1162
+ /**
1163
+ * Override fetchId to compute session ID from Basic Auth credentials
1164
+ * Session ID = sha256(base64_creds + pepper)
1165
+ * pepper = int(time / timeout) + keyH (changes daily)
1166
+ * @param req - HTTP request
1167
+ */
1168
+ fetchId(req) {
1169
+ var _a;
1170
+ const authHeader = req.headers.authorization;
1171
+ if (authHeader && authHeader.toLowerCase().startsWith("basic ")) {
1172
+ const credentials = authHeader.substring(6).trim();
1173
+ if (credentials) {
1174
+ // Compute deterministic session ID from credentials
1175
+ // This changes daily based on timeout to limit exposure
1176
+ // pepper = int(time / timeout) + keyH (same as Perl implementation)
1177
+ const pepper = Math.floor(Date.now() / 1000 / this.tsv.timeout) +
1178
+ (this.tsv.keyH || "");
1179
+ const sessionId = crypto
1180
+ .createHash("sha256")
1181
+ .update(credentials + pepper)
1182
+ .digest("hex");
1183
+ // Decode and store credentials for potential session creation
1184
+ try {
1185
+ const decoded = Buffer.from(credentials, "base64").toString("utf-8");
1186
+ const colonIndex = decoded.indexOf(":");
1187
+ if (colonIndex > 0) {
1188
+ const username = decoded.substring(0, colonIndex);
1189
+ const password = decoded.substring(colonIndex + 1);
1190
+ // Build X-Forwarded-For
1191
+ const existingXff = req.headers["x-forwarded-for"];
1192
+ const clientIp = req.ip || ((_a = req.socket) === null || _a === void 0 ? void 0 : _a.remoteAddress) || "";
1193
+ const xff = existingXff ? `${existingXff}, ${clientIp}` : clientIp;
1194
+ // Store for use in retrieveSession
1195
+ this.pendingAuth.set(sessionId, { username, password, xff });
1196
+ }
1197
+ }
1198
+ catch (_b) {
1199
+ // Ignore decode errors, will be handled in retrieveSession
1200
+ }
1201
+ this.userLogger.debug(`AuthBasic: computed session ID for credentials`);
1202
+ return sessionId;
1203
+ }
1204
+ }
1205
+ // Fall back to cookie-based authentication
1206
+ return super.fetchId(req);
1207
+ }
1208
+ /**
1209
+ * Override retrieveSession to create session via portal if needed
1210
+ * @param id - Session ID
1211
+ */
1212
+ retrieveSession(id) {
1213
+ const _super = Object.create(null, {
1214
+ retrieveSession: { get: () => super.retrieveSession }
1215
+ });
1216
+ return new Promise((resolve, reject) => {
1217
+ // First try to get existing session
1218
+ _super.retrieveSession.call(this, id)
1219
+ .then((session) => {
1220
+ // Session exists, clean up pending auth
1221
+ this.pendingAuth.delete(id);
1222
+ resolve(session);
1223
+ })
1224
+ .catch(() => __awaiter(this, void 0, void 0, function* () {
1225
+ // Session doesn't exist, try to create it via portal
1226
+ const pending = this.pendingAuth.get(id);
1227
+ if (!pending) {
1228
+ reject("No session and no pending authentication");
1229
+ return;
1230
+ }
1231
+ // Clean up pending auth
1232
+ this.pendingAuth.delete(id);
1233
+ // Try to create session via portal
1234
+ const created = yield this.createSession(id, pending.username, pending.password, pending.xff);
1235
+ if (created) {
1236
+ // Session was created, now retrieve it
1237
+ _super.retrieveSession.call(this, id).then(resolve).catch(reject);
1238
+ }
1239
+ else {
1240
+ reject("Authentication failed");
1241
+ }
1242
+ }));
1243
+ });
1244
+ }
1245
+ /**
1246
+ * Create session via portal REST API
1247
+ * POST to portal/sessions/global/{id}?auth
1248
+ * @param id - Session ID to create
1249
+ * @param username - Username from Basic auth
1250
+ * @param password - Password from Basic auth
1251
+ * @param xff - X-Forwarded-For header value
1252
+ * @returns true if session created successfully
1253
+ */
1254
+ createSession(id, username, password, xff) {
1255
+ return __awaiter(this, void 0, void 0, function* () {
1256
+ var _a;
1257
+ // Validate session ID to mitigate SSRF
1258
+ if (!/^[a-fA-F0-9]{1,64}$/.test(id)) {
1259
+ this.userLogger.error(`AuthBasic: Invalid session ID format: ${id}`);
1260
+ return false;
1261
+ }
1262
+ const portal = this.tsv.portal();
1263
+ if (!portal) {
1264
+ this.userLogger.error("AuthBasic: portal URL not configured");
1265
+ return false;
1266
+ }
1267
+ // Build URL: portal/sessions/global/{id}?auth
1268
+ let url = `${portal}/sessions/global/${id}?auth`;
1269
+ url = url.replace(/\/\/sessions\//, "/sessions/");
1270
+ // Build request body
1271
+ const bodyParams = {
1272
+ user: username,
1273
+ password: password,
1274
+ secret: ((_a = this.tsv.cipher) === null || _a === void 0 ? void 0 : _a.encrypt(Date.now().toString())) || "",
1275
+ };
1276
+ // Add auth choice if configured
1277
+ if (this.tsv.authChoiceAuthBasic) {
1278
+ const paramName = this.tsv.authChoiceParam || "lmAuth";
1279
+ bodyParams[paramName] = this.tsv.authChoiceAuthBasic;
1280
+ }
1281
+ const body = new URLSearchParams(bodyParams).toString();
1282
+ this.userLogger.debug(`AuthBasic: authenticating ${username} via portal`);
1283
+ try {
1284
+ const response = yield fetch(url, {
1285
+ method: "POST",
1286
+ headers: {
1287
+ "Content-Type": "application/x-www-form-urlencoded",
1288
+ Accept: "application/json",
1289
+ "X-Forwarded-For": xff,
1290
+ },
1291
+ body: body,
1292
+ });
1293
+ if (response.ok) {
1294
+ this.userLogger.info(`AuthBasic: authentication successful for ${username}`);
1295
+ return true;
1296
+ }
1297
+ else {
1298
+ this.userLogger.warn(`AuthBasic: authentication failed for ${username}: ${response.status} ${response.statusText}`);
1299
+ return false;
1300
+ }
1301
+ }
1302
+ catch (e) {
1303
+ this.userLogger.error(`AuthBasic: portal request failed: ${e}`);
1304
+ return false;
1305
+ }
1306
+ });
1307
+ }
1308
+ /**
1309
+ * Hide Authorization header from protected application
1310
+ * Called after successful authentication
1311
+ * @param req - HTTP request
1312
+ */
1313
+ hideCookie(req) {
1314
+ this.userLogger.debug("AuthBasic: removing Authorization header");
1315
+ delete req.headers.authorization;
1316
+ }
1317
+ /**
1318
+ * Override goToPortal to send Basic challenge instead of redirect
1319
+ * @param res - HTTP response
1320
+ * @param uri - Original URI
1321
+ * @param args - Additional arguments
1322
+ */
1323
+ goToPortal(res, uri, args = "") {
1324
+ if (args) {
1325
+ // If there's an argument, redirect to portal with message
1326
+ super.goToPortal(res, uri, args);
1327
+ }
1328
+ else {
1329
+ // Otherwise, send WWW-Authenticate challenge
1330
+ res.setHeader("WWW-Authenticate", 'Basic realm="LemonLDAP::NG"');
1331
+ this.setError(res, uri, 401, "Authentication required");
1332
+ }
1333
+ }
1334
+ }
1335
+
1336
+ /**
1337
+ * CDA (Cross-Domain Authentication) utilities for LemonLDAP::NG
1338
+ * Port of Lemonldap::NG::Handler::Main::CDA
1339
+ *
1340
+ * CDA allows authentication to be shared across different domains
1341
+ * by using encrypted cookies or URL parameters.
1342
+ */
1343
+ /**
1344
+ * Maximum allowed clock skew in seconds for timestamp validation
1345
+ */
1346
+ const MAX_CLOCK_SKEW_SECONDS = 10;
1347
+ /**
1348
+ * Parse and validate a CDA cookie value
1349
+ * @param cipher - Crypto instance for decryption
1350
+ * @param cookieValue - Encrypted cookie value
1351
+ * @param maxAge - Maximum age in seconds (default: 120)
1352
+ * @returns Parsed CDA value or null if invalid
1353
+ */
1354
+ function parseCDACookie(cipher, cookieValue, maxAge = 120) {
1355
+ try {
1356
+ const decrypted = cipher.decrypt(cookieValue);
1357
+ const parts = decrypted.split(":");
1358
+ if (parts.length < 2) {
1359
+ return null;
1360
+ }
1361
+ const sessionId = parts[0];
1362
+ const timestamp = parseInt(parts[1], 10);
1363
+ if (!sessionId || isNaN(timestamp)) {
1364
+ return null;
1365
+ }
1366
+ // Check timestamp validity
1367
+ const now = Math.floor(Date.now() / 1000);
1368
+ if (now - timestamp > maxAge || timestamp > now + MAX_CLOCK_SKEW_SECONDS) {
1369
+ // Cookie too old or too far in the future (clock skew)
1370
+ return null;
1371
+ }
1372
+ return {
1373
+ sessionId,
1374
+ timestamp,
1375
+ domain: parts[2],
1376
+ };
1377
+ }
1378
+ catch (_a) {
1379
+ return null;
1380
+ }
1381
+ }
1382
+ /**
1383
+ * Extract CDA value from URL
1384
+ * @param url - URL potentially containing CDA parameter
1385
+ * @returns CDA parameter value or null
1386
+ */
1387
+ function extractCDAFromUrl(url) {
1388
+ try {
1389
+ const urlObj = new URL(url, "http://localhost");
1390
+ return urlObj.searchParams.get("lemonldapcda");
1391
+ }
1392
+ catch (_a) {
1393
+ return null;
1394
+ }
1395
+ }
1396
+ /**
1397
+ * Build Set-Cookie header for CDA
1398
+ * @param cookieName - Cookie name
1399
+ * @param value - Cookie value
1400
+ * @param domain - Cookie domain
1401
+ * @param expiration - Expiration in seconds (0 for session cookie)
1402
+ * @param secure - Whether to set Secure flag
1403
+ * @param httpOnly - Whether to set HttpOnly flag
1404
+ * @returns Cookie header string
1405
+ */
1406
+ function buildCDACookieHeader(cookieName, value, domain, expiration = 0, secure = false, httpOnly = true) {
1407
+ let cookie = `${cookieName}=${value}`;
1408
+ if (domain) {
1409
+ cookie += `; Domain=${domain}`;
1410
+ }
1411
+ cookie += "; Path=/";
1412
+ if (expiration > 0) {
1413
+ const expires = new Date(Date.now() + expiration * 1000);
1414
+ cookie += `; Expires=${expires.toUTCString()}`;
1415
+ }
1416
+ if (secure) {
1417
+ cookie += "; Secure";
1418
+ }
1419
+ if (httpOnly) {
1420
+ cookie += "; HttpOnly";
1421
+ }
1422
+ cookie += "; SameSite=None";
1423
+ return cookie;
1424
+ }
1425
+
1426
+ /**
1427
+ * CDA (Cross-Domain Authentication) Handler for LemonLDAP::NG
1428
+ * Port of Lemonldap::NG::Handler::Main with CDA support
1429
+ *
1430
+ * This handler enables cross-domain authentication by:
1431
+ * 1. Checking for CDA cookies/parameters on incoming requests
1432
+ * 2. Setting CDA cookies when users authenticate
1433
+ * 3. Propagating authentication across configured domains
1434
+ */
1435
+ class LemonldapNGHandlerCDA extends LemonldapNGHandler {
1436
+ /**
1437
+ * Override fetchId to check for CDA cookie/parameter first
1438
+ * @param req - HTTP request
1439
+ */
1440
+ fetchId(req) {
1441
+ // Check if CDA is enabled
1442
+ if (!this.tsv.cda) {
1443
+ return super.fetchId(req);
1444
+ }
1445
+ // 1. Check for CDA URL parameter (from redirect)
1446
+ const url = req.url || "/";
1447
+ const cdaParam = extractCDAFromUrl(url);
1448
+ if (cdaParam) {
1449
+ const cdaValue = parseCDACookie(this.tsv.cipher, cdaParam);
1450
+ if (cdaValue) {
1451
+ this.userLogger.debug(`CDA: extracted session from URL parameter`);
1452
+ // Set the CDA cookie for future requests
1453
+ this.setCDACookie(req, cdaValue.sessionId);
1454
+ return cdaValue.sessionId;
1455
+ }
1456
+ else {
1457
+ this.userLogger.warn("CDA: invalid or expired URL parameter");
1458
+ }
1459
+ }
1460
+ // 2. Check for CDA cookie
1461
+ const cdaCookieName = `${this.tsv.cookieName}cda`;
1462
+ const cdaCookie = this.getCDACookie(req, cdaCookieName);
1463
+ if (cdaCookie) {
1464
+ const cdaValue = parseCDACookie(this.tsv.cipher, cdaCookie);
1465
+ if (cdaValue) {
1466
+ this.userLogger.debug(`CDA: extracted session from cookie`);
1467
+ return cdaValue.sessionId;
1468
+ }
1469
+ else {
1470
+ this.userLogger.warn("CDA: invalid or expired cookie");
1471
+ }
1472
+ }
1473
+ // 3. Fall back to standard cookie
1474
+ return super.fetchId(req);
1475
+ }
1476
+ /**
1477
+ * Get CDA cookie value from request
1478
+ * @param req - HTTP request
1479
+ * @param cookieName - Cookie name to look for
1480
+ */
1481
+ getCDACookie(req, cookieName) {
1482
+ const cookies = req.headers.cookie;
1483
+ if (!cookies) {
1484
+ return null;
1485
+ }
1486
+ const regex = new RegExp(`${cookieName}=([^;]+)`);
1487
+ const match = regex.exec(cookies);
1488
+ return match ? match[1] : null;
1489
+ }
1490
+ /**
1491
+ * Set CDA cookie on response (placeholder for middleware integration)
1492
+ *
1493
+ * TODO: Implement full CDA cookie setting mechanism. Options include:
1494
+ * 1. Store the value in req.llngCdaInfo and set in sendHeaders via response
1495
+ * 2. Use express middleware to intercept and set the cookie
1496
+ * 3. Pass response object through the call chain
1497
+ *
1498
+ * Currently a no-op as we don't have access to the response object here.
1499
+ *
1500
+ * @param _req - HTTP request (unused)
1501
+ * @param _sessionId - Session ID to set (unused)
1502
+ */
1503
+ setCDACookie(_req, _sessionId) {
1504
+ // Placeholder - see TODO in JSDoc above
1505
+ }
1506
+ /**
1507
+ * Override sendHeaders to also set CDA cookie
1508
+ * @param req - HTTP request
1509
+ * @param session - User session
1510
+ */
1511
+ sendHeaders(req, session) {
1512
+ super.sendHeaders(req, session);
1513
+ // If CDA is enabled, prepare CDA cookie header
1514
+ // Store in a custom property for middleware to process
1515
+ if (this.tsv.cda) {
1516
+ const cdaCookieName = `${this.tsv.cookieName}cda`;
1517
+ const domain = this.getCDACookieDomain(req);
1518
+ if (domain) {
1519
+ // Store CDA cookie info as a custom property on the request object
1520
+ // Middleware can read this and set the cookie on the response
1521
+ req.llngCdaCookie = buildCDACookieHeader(cdaCookieName, session._session_id, domain, this.tsv.cookieExpiration || 0, this.tsv.securedCookie > 0, this.tsv.httpOnly);
1522
+ }
1523
+ }
1524
+ }
1525
+ /**
1526
+ * Get domain for CDA cookie
1527
+ * @param req - HTTP request
1528
+ */
1529
+ getCDACookieDomain(req) {
1530
+ const host = req.headers.host;
1531
+ if (!host) {
1532
+ return "";
1533
+ }
1534
+ // Extract domain from host (remove port)
1535
+ const hostname = host.split(":")[0];
1536
+ // For CDA, we typically want to set the cookie on a parent domain
1537
+ // This is a simplified implementation - full implementation would
1538
+ // use configured CDA domains
1539
+ const parts = hostname.split(".");
1540
+ if (parts.length >= 2) {
1541
+ // Return parent domain (e.g., .example.com from www.example.com)
1542
+ return "." + parts.slice(-2).join(".");
1543
+ }
1544
+ return hostname;
1545
+ }
1546
+ /**
1547
+ * Override goToPortal to include CDA parameter
1548
+ * @param res - HTTP response
1549
+ * @param uri - Original URI
1550
+ * @param args - Additional arguments
1551
+ */
1552
+ goToPortal(res, uri, args = "") {
1553
+ // Add CDA parameter if enabled
1554
+ if (this.tsv.cda) {
1555
+ const cdaArg = "cda=1";
1556
+ args = args ? `${args}&${cdaArg}` : cdaArg;
1557
+ }
1558
+ super.goToPortal(res, uri, args);
1559
+ }
1560
+ }
1561
+
704
1562
  let currentHandler;
705
1563
  let currentClass;
706
1564
  const knownHandlers = {
@@ -708,6 +1566,9 @@ const knownHandlers = {
708
1566
  DevOps: LemonldapNGHandlerDevOps,
709
1567
  ServiceToken: LemonldapNGHandlerServiceToken,
710
1568
  ServiceTokenST: LemonldapNGHandlerDevOpsST,
1569
+ OAuth2: LemonldapNGHandlerOAuth2,
1570
+ AuthBasic: LemonldapNGHandlerAuthBasic,
1571
+ CDA: LemonldapNGHandlerCDA,
711
1572
  };
712
1573
  const init = (args) => {
713
1574
  return new Promise((resolve, reject) => {
@@ -741,6 +1602,22 @@ const run = (req, res, next) => {
741
1602
  const nginxServer = (args) => {
742
1603
  currentHandler.nginxServer(args);
743
1604
  };
1605
+ /**
1606
+ * Returns the portal URL from LemonLDAP::NG configuration
1607
+ * @returns Portal URL string
1608
+ */
1609
+ const portal = () => {
1610
+ return currentHandler.portal();
1611
+ };
1612
+ /**
1613
+ * Shutdown the handler (stops event loop and cleanup)
1614
+ * Call this in tests' afterAll to prevent Jest from hanging
1615
+ */
1616
+ const shutdown = () => __awaiter(void 0, void 0, void 0, function* () {
1617
+ if (currentHandler) {
1618
+ yield currentHandler.stopEventLoop();
1619
+ }
1620
+ });
744
1621
 
745
- export { currentClass as class, init, nginxServer, run };
1622
+ export { currentClass as class, init, nginxServer, portal, run, shutdown };
746
1623
  //# sourceMappingURL=index.mjs.map