lemonldap-ng-handler 0.7.1 → 0.8.0
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/README.md +1 -1
- package/lib/cda.d.ts +64 -0
- package/lib/handlerAuthBasic.d.ts +53 -0
- package/lib/handlerCDA.d.ts +58 -0
- package/lib/handlerMain.d.ts +8 -0
- package/lib/handlerOAuth2.d.ts +29 -0
- package/lib/index-DXlSn3sb.js +2 -0
- package/lib/index-DXlSn3sb.js.map +1 -0
- package/lib/index.d.ts +5 -0
- package/lib/index.js +1 -1
- package/lib/index.js.map +1 -1
- package/lib/index.mjs +886 -23
- package/lib/index.mjs.map +1 -1
- package/lib/init.d.ts +48 -4
- package/lib/msgActions.d.ts +34 -0
- package/lib/tsv.d.ts +23 -0
- package/package.json +13 -8
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
|
-
|
|
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,170 @@ 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
|
+
}
|
|
281
556
|
}
|
|
282
557
|
|
|
558
|
+
/**
|
|
559
|
+
* Default internal cache timeout in seconds
|
|
560
|
+
*/
|
|
561
|
+
const DEFAULT_INTERNAL_CACHE_TIMEOUT = 15;
|
|
283
562
|
class LemonldapNGHandler extends HandlerInit {
|
|
563
|
+
constructor() {
|
|
564
|
+
super(...arguments);
|
|
565
|
+
/* Internal handler cache for session data */
|
|
566
|
+
this.lastSessionId = null;
|
|
567
|
+
this.lastSessionData = null;
|
|
568
|
+
this.lastSessionTime = 0;
|
|
569
|
+
}
|
|
284
570
|
init() {
|
|
285
571
|
return this.reload();
|
|
286
572
|
}
|
|
@@ -301,8 +587,14 @@ class LemonldapNGHandler extends HandlerInit {
|
|
|
301
587
|
return this.setError(res, "/", 503, "Service Temporarily Unavailable");
|
|
302
588
|
/* 3 - check if current URI is protected */
|
|
303
589
|
const protection = this.isUnprotected(req, uri);
|
|
304
|
-
if (protection === 2)
|
|
590
|
+
if (protection === 2) {
|
|
591
|
+
// SKIP: Clear internal session data
|
|
592
|
+
this.lastSessionId = null;
|
|
593
|
+
this.lastSessionData = null;
|
|
594
|
+
this.lastSessionTime = 0;
|
|
595
|
+
this.hideCookie(req);
|
|
305
596
|
return next();
|
|
597
|
+
}
|
|
306
598
|
/* 4 - search for LLNG cookie */
|
|
307
599
|
const id = this.fetchId(req);
|
|
308
600
|
if (id !== "") {
|
|
@@ -324,12 +616,11 @@ class LemonldapNGHandler extends HandlerInit {
|
|
|
324
616
|
}
|
|
325
617
|
})
|
|
326
618
|
.catch((e) => {
|
|
327
|
-
|
|
619
|
+
this.userLogger.error(`Authorization check failed: ${e}`);
|
|
328
620
|
this.setError(res, "/", 503, "Service Unavailable");
|
|
329
621
|
});
|
|
330
622
|
})
|
|
331
|
-
|
|
332
|
-
.catch((e) => {
|
|
623
|
+
.catch((_e) => {
|
|
333
624
|
/* Expired session */
|
|
334
625
|
this.goToPortal(res, this.selfUri(vhost, uri));
|
|
335
626
|
});
|
|
@@ -395,8 +686,8 @@ class LemonldapNGHandler extends HandlerInit {
|
|
|
395
686
|
resolveAlias(req) {
|
|
396
687
|
var _a;
|
|
397
688
|
// @ts-ignore: req.headers.host has already been tested
|
|
398
|
-
const vhost = (_a = req.headers.host) === null || _a === void 0 ? void 0 : _a.split(
|
|
399
|
-
return vhost ?
|
|
689
|
+
const vhost = (_a = req.headers.host) === null || _a === void 0 ? void 0 : _a.split(":")[0];
|
|
690
|
+
return vhost ? this.tsv.vhostAlias[vhost] || vhost : "undef";
|
|
400
691
|
}
|
|
401
692
|
fetchId(req) {
|
|
402
693
|
if (req.headers.cookie) {
|
|
@@ -411,10 +702,21 @@ class LemonldapNGHandler extends HandlerInit {
|
|
|
411
702
|
if (this.sessionAcc === undefined)
|
|
412
703
|
// istanbul ignore next
|
|
413
704
|
return reject("Server not ready, please wait");
|
|
705
|
+
const now = (Date.now() / 1000) | 0;
|
|
706
|
+
const internalCacheTimeout = this.tsv.handlerInternalCache || DEFAULT_INTERNAL_CACHE_TIMEOUT;
|
|
707
|
+
// Check internal handler cache first (efficient for persistent connections)
|
|
708
|
+
if (this.lastSessionId === id &&
|
|
709
|
+
this.lastSessionData &&
|
|
710
|
+
now - this.lastSessionTime < internalCacheTimeout) {
|
|
711
|
+
this.userLogger.debug(`Get session ${id} from internal cache`);
|
|
712
|
+
return resolve(this.lastSessionData);
|
|
713
|
+
}
|
|
714
|
+
// Clear stale internal cache
|
|
715
|
+
this.lastSessionId = null;
|
|
716
|
+
this.lastSessionData = null;
|
|
414
717
|
this.sessionAcc
|
|
415
718
|
.get(id)
|
|
416
719
|
.then((session) => {
|
|
417
|
-
const now = (Date.now() / 1000) | 0;
|
|
418
720
|
if (now - session._utime > this.tsv.timeout ||
|
|
419
721
|
(this.tsv.timeoutActivity &&
|
|
420
722
|
session._lastSeen &&
|
|
@@ -430,6 +732,10 @@ class LemonldapNGHandler extends HandlerInit {
|
|
|
430
732
|
// @ts-ignore this.sessionAcc is defined here
|
|
431
733
|
this.sessionAcc.update(session);
|
|
432
734
|
}
|
|
735
|
+
// Update internal cache
|
|
736
|
+
this.lastSessionId = id;
|
|
737
|
+
this.lastSessionData = session;
|
|
738
|
+
this.lastSessionTime = now;
|
|
433
739
|
resolve(session);
|
|
434
740
|
}
|
|
435
741
|
})
|
|
@@ -438,6 +744,24 @@ class LemonldapNGHandler extends HandlerInit {
|
|
|
438
744
|
});
|
|
439
745
|
});
|
|
440
746
|
}
|
|
747
|
+
/**
|
|
748
|
+
* Local unlog - clear session from all local caches
|
|
749
|
+
* @param sessionId - Optional session ID to clear (uses last cached if not provided)
|
|
750
|
+
*/
|
|
751
|
+
localUnlog(sessionId) {
|
|
752
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
753
|
+
this.userLogger.debug("Local handler logout");
|
|
754
|
+
const id = sessionId || this.lastSessionId;
|
|
755
|
+
// Clear internal handler cache
|
|
756
|
+
this.lastSessionId = null;
|
|
757
|
+
this.lastSessionData = null;
|
|
758
|
+
this.lastSessionTime = 0;
|
|
759
|
+
if (id && this.sessionAcc) {
|
|
760
|
+
this.sessionAcc.clearMemoryCache(id);
|
|
761
|
+
yield this.sessionAcc.clearLocalCache(id);
|
|
762
|
+
}
|
|
763
|
+
});
|
|
764
|
+
}
|
|
441
765
|
grant(req, uri, session) {
|
|
442
766
|
return new Promise((resolve, reject) => {
|
|
443
767
|
const vhost = this.resolveAlias(req);
|
|
@@ -445,12 +769,12 @@ class LemonldapNGHandler extends HandlerInit {
|
|
|
445
769
|
return reject(`No configuration found for ${vhost} (or not listed in Node.js virtualHosts)`);
|
|
446
770
|
}
|
|
447
771
|
if (this.tsv.locationRegexp[vhost]) {
|
|
448
|
-
let i = 0;
|
|
449
|
-
|
|
450
|
-
if (regex.test(uri))
|
|
772
|
+
for (let i = 0; i < this.tsv.locationRegexp[vhost].length; i++) {
|
|
773
|
+
const regex = this.tsv.locationRegexp[vhost][i];
|
|
774
|
+
if (regex.test(uri)) {
|
|
451
775
|
return resolve(this.tsv.locationCondition[vhost][i](req, session));
|
|
452
|
-
|
|
453
|
-
}
|
|
776
|
+
}
|
|
777
|
+
}
|
|
454
778
|
}
|
|
455
779
|
this.tsv.defaultCondition[vhost](req, session)
|
|
456
780
|
? resolve(true)
|
|
@@ -478,7 +802,7 @@ class LemonldapNGHandler extends HandlerInit {
|
|
|
478
802
|
});
|
|
479
803
|
}
|
|
480
804
|
catch (e) {
|
|
481
|
-
|
|
805
|
+
this.userLogger.error(`Headers maybe not sent: ${e}`);
|
|
482
806
|
// istanbul ignore next
|
|
483
807
|
return;
|
|
484
808
|
}
|
|
@@ -488,6 +812,10 @@ class LemonldapNGHandler extends HandlerInit {
|
|
|
488
812
|
req.headers.cookie = req.headers.cookie.replace(this.tsv.cookieDetect, "");
|
|
489
813
|
}
|
|
490
814
|
forbidden(req, res, session) {
|
|
815
|
+
// Clear local cache on forbidden (fire and forget, but catch errors)
|
|
816
|
+
this.localUnlog(session._session_id).catch((e) => {
|
|
817
|
+
this.userLogger.error(`Failed to clear local cache: ${e}`);
|
|
818
|
+
});
|
|
491
819
|
if (session._logout) {
|
|
492
820
|
this.goToPortal(res, session._logout, "logout=1");
|
|
493
821
|
}
|
|
@@ -561,7 +889,7 @@ class LemonldapNGHandlerDevOps extends LemonldapNGHandler {
|
|
|
561
889
|
.catch((e) => reject(e));
|
|
562
890
|
})
|
|
563
891
|
.catch((err) => {
|
|
564
|
-
|
|
892
|
+
this.userLogger.error(`Session retrieval error: ${err}`);
|
|
565
893
|
this.grant(req, uri, session)
|
|
566
894
|
.then((res) => {
|
|
567
895
|
resolve(res);
|
|
@@ -664,9 +992,8 @@ class LemonldapNGHandlerServiceToken extends LemonldapNGHandler {
|
|
|
664
992
|
let tokenElement;
|
|
665
993
|
try {
|
|
666
994
|
tokenElement = this.tsv.cipher.decrypt(token).split(":");
|
|
667
|
-
// eslint-disable-next-line no-unused-vars
|
|
668
995
|
}
|
|
669
|
-
catch (
|
|
996
|
+
catch (_e) {
|
|
670
997
|
this.userLogger.error("Invalid token");
|
|
671
998
|
return "";
|
|
672
999
|
}
|
|
@@ -685,7 +1012,7 @@ class LemonldapNGHandlerServiceToken extends LemonldapNGHandler {
|
|
|
685
1012
|
// Is vhost listed in token ?
|
|
686
1013
|
const vhost = this.resolveAlias(req);
|
|
687
1014
|
if (tokenElement.indexOf(vhost) < 2) {
|
|
688
|
-
|
|
1015
|
+
this.userLogger.warn(`${vhost} not authorizated in token`);
|
|
689
1016
|
return "";
|
|
690
1017
|
}
|
|
691
1018
|
// Then use token sessionId
|
|
@@ -701,6 +1028,530 @@ class LemonldapNGHandlerDevOpsST extends LemonldapNGHandlerDevOps {
|
|
|
701
1028
|
}
|
|
702
1029
|
}
|
|
703
1030
|
|
|
1031
|
+
/**
|
|
1032
|
+
* OAuth2/OIDC Handler for LemonLDAP::NG
|
|
1033
|
+
* Port of Lemonldap::NG::Handler::OAuth2
|
|
1034
|
+
*
|
|
1035
|
+
* This handler validates OAuth2/OIDC access tokens and retrieves
|
|
1036
|
+
* the associated session from the OIDC session storage.
|
|
1037
|
+
*/
|
|
1038
|
+
class LemonldapNGHandlerOAuth2 extends LemonldapNGHandler {
|
|
1039
|
+
/**
|
|
1040
|
+
* Override init to also initialize OIDC session storage
|
|
1041
|
+
*/
|
|
1042
|
+
init() {
|
|
1043
|
+
return new Promise((resolve, reject) => {
|
|
1044
|
+
super
|
|
1045
|
+
.init()
|
|
1046
|
+
.then(() => {
|
|
1047
|
+
// Initialize OIDC session storage if configured
|
|
1048
|
+
if (this.tsv.oidcStorageModule) {
|
|
1049
|
+
try {
|
|
1050
|
+
this.oidcSessionAcc = new Session({
|
|
1051
|
+
storageModule: this.tsv.oidcStorageModule,
|
|
1052
|
+
storageModuleOptions: this.tsv.oidcStorageOptions || {},
|
|
1053
|
+
});
|
|
1054
|
+
this.oidcSessionAcc.ready
|
|
1055
|
+
.then(() => {
|
|
1056
|
+
this.userLogger.debug("OAuth2 OIDC session storage initialized");
|
|
1057
|
+
resolve(true);
|
|
1058
|
+
})
|
|
1059
|
+
.catch((e) => {
|
|
1060
|
+
this.userLogger.error(`Failed to initialize OIDC session storage: ${e}`);
|
|
1061
|
+
reject(e);
|
|
1062
|
+
});
|
|
1063
|
+
}
|
|
1064
|
+
catch (e) {
|
|
1065
|
+
this.userLogger.error(`Failed to create OIDC session accessor: ${e}`);
|
|
1066
|
+
reject(e);
|
|
1067
|
+
}
|
|
1068
|
+
}
|
|
1069
|
+
else {
|
|
1070
|
+
// Use default session storage for OIDC tokens
|
|
1071
|
+
this.userLogger.debug("OAuth2 handler using default session storage for OIDC");
|
|
1072
|
+
resolve(true);
|
|
1073
|
+
}
|
|
1074
|
+
})
|
|
1075
|
+
.catch(reject);
|
|
1076
|
+
});
|
|
1077
|
+
}
|
|
1078
|
+
/**
|
|
1079
|
+
* Override fetchId to check for OAuth2 Bearer token
|
|
1080
|
+
* @param req - HTTP request
|
|
1081
|
+
*/
|
|
1082
|
+
fetchId(req) {
|
|
1083
|
+
// Check for Authorization header with Bearer token
|
|
1084
|
+
const authHeader = req.headers.authorization;
|
|
1085
|
+
if (authHeader && authHeader.toLowerCase().startsWith("bearer ")) {
|
|
1086
|
+
const accessToken = authHeader.substring(7).trim();
|
|
1087
|
+
if (accessToken) {
|
|
1088
|
+
// Try to extract session ID from the access token
|
|
1089
|
+
const sessionId = getAccessTokenSessionId(accessToken);
|
|
1090
|
+
if (sessionId) {
|
|
1091
|
+
this.userLogger.debug(`OAuth2: extracted session ID from token`);
|
|
1092
|
+
return sessionId;
|
|
1093
|
+
}
|
|
1094
|
+
else {
|
|
1095
|
+
this.userLogger.warn("OAuth2: could not extract session ID from token");
|
|
1096
|
+
return "";
|
|
1097
|
+
}
|
|
1098
|
+
}
|
|
1099
|
+
}
|
|
1100
|
+
// Fall back to cookie-based authentication
|
|
1101
|
+
return super.fetchId(req);
|
|
1102
|
+
}
|
|
1103
|
+
/**
|
|
1104
|
+
* Override retrieveSession to use OIDC session storage if token-based
|
|
1105
|
+
* @param id - Session ID
|
|
1106
|
+
*/
|
|
1107
|
+
retrieveSession(id) {
|
|
1108
|
+
// Check if we should use OIDC session storage
|
|
1109
|
+
// For now, use the same logic as parent class
|
|
1110
|
+
// The OIDC sessions are typically in the same format
|
|
1111
|
+
if (this.oidcSessionAcc) {
|
|
1112
|
+
return new Promise((resolve, reject) => {
|
|
1113
|
+
// @ts-ignore: oidcSessionAcc is defined
|
|
1114
|
+
this.oidcSessionAcc
|
|
1115
|
+
.get(id)
|
|
1116
|
+
.then((session) => {
|
|
1117
|
+
const now = (Date.now() / 1000) | 0;
|
|
1118
|
+
if (now - session._utime > this.tsv.timeout ||
|
|
1119
|
+
(this.tsv.timeoutActivity &&
|
|
1120
|
+
session._lastSeen &&
|
|
1121
|
+
// @ts-ignore: session._lastSeen is defined
|
|
1122
|
+
now - session._lastSeen > this.tsv.timeoutActivity)) {
|
|
1123
|
+
reject(`OAuth2 session ${id} expired`);
|
|
1124
|
+
}
|
|
1125
|
+
else {
|
|
1126
|
+
resolve(session);
|
|
1127
|
+
}
|
|
1128
|
+
})
|
|
1129
|
+
.catch((_e) => {
|
|
1130
|
+
// If not found in OIDC storage, try main storage
|
|
1131
|
+
super.retrieveSession(id).then(resolve).catch(reject);
|
|
1132
|
+
});
|
|
1133
|
+
});
|
|
1134
|
+
}
|
|
1135
|
+
return super.retrieveSession(id);
|
|
1136
|
+
}
|
|
1137
|
+
}
|
|
1138
|
+
|
|
1139
|
+
/**
|
|
1140
|
+
* AuthBasic Handler for LemonLDAP::NG
|
|
1141
|
+
* Port of Lemonldap::NG::Handler::Lib::AuthBasic
|
|
1142
|
+
*
|
|
1143
|
+
* This handler supports HTTP Basic Authentication by:
|
|
1144
|
+
* 1. Computing a deterministic session ID from credentials
|
|
1145
|
+
* 2. Checking if session exists
|
|
1146
|
+
* 3. If not, asking the portal to create it via REST API
|
|
1147
|
+
* 4. Sending WWW-Authenticate challenge when needed
|
|
1148
|
+
*/
|
|
1149
|
+
class LemonldapNGHandlerAuthBasic extends LemonldapNGHandler {
|
|
1150
|
+
constructor() {
|
|
1151
|
+
super(...arguments);
|
|
1152
|
+
// Store pending authentication data keyed by session ID
|
|
1153
|
+
this.pendingAuth = new Map();
|
|
1154
|
+
}
|
|
1155
|
+
/**
|
|
1156
|
+
* Override fetchId to compute session ID from Basic Auth credentials
|
|
1157
|
+
* Session ID = sha256(base64_creds + pepper)
|
|
1158
|
+
* pepper = int(time / timeout) + keyH (changes daily)
|
|
1159
|
+
* @param req - HTTP request
|
|
1160
|
+
*/
|
|
1161
|
+
fetchId(req) {
|
|
1162
|
+
var _a;
|
|
1163
|
+
const authHeader = req.headers.authorization;
|
|
1164
|
+
if (authHeader && authHeader.toLowerCase().startsWith("basic ")) {
|
|
1165
|
+
const credentials = authHeader.substring(6).trim();
|
|
1166
|
+
if (credentials) {
|
|
1167
|
+
// Compute deterministic session ID from credentials
|
|
1168
|
+
// This changes daily based on timeout to limit exposure
|
|
1169
|
+
// pepper = int(time / timeout) + keyH (same as Perl implementation)
|
|
1170
|
+
const pepper = Math.floor(Date.now() / 1000 / this.tsv.timeout) +
|
|
1171
|
+
(this.tsv.keyH || "");
|
|
1172
|
+
const sessionId = crypto
|
|
1173
|
+
.createHash("sha256")
|
|
1174
|
+
.update(credentials + pepper)
|
|
1175
|
+
.digest("hex");
|
|
1176
|
+
// Decode and store credentials for potential session creation
|
|
1177
|
+
try {
|
|
1178
|
+
const decoded = Buffer.from(credentials, "base64").toString("utf-8");
|
|
1179
|
+
const colonIndex = decoded.indexOf(":");
|
|
1180
|
+
if (colonIndex > 0) {
|
|
1181
|
+
const username = decoded.substring(0, colonIndex);
|
|
1182
|
+
const password = decoded.substring(colonIndex + 1);
|
|
1183
|
+
// Build X-Forwarded-For
|
|
1184
|
+
const existingXff = req.headers["x-forwarded-for"];
|
|
1185
|
+
const clientIp = req.ip || ((_a = req.socket) === null || _a === void 0 ? void 0 : _a.remoteAddress) || "";
|
|
1186
|
+
const xff = existingXff ? `${existingXff}, ${clientIp}` : clientIp;
|
|
1187
|
+
// Store for use in retrieveSession
|
|
1188
|
+
this.pendingAuth.set(sessionId, { username, password, xff });
|
|
1189
|
+
}
|
|
1190
|
+
}
|
|
1191
|
+
catch (_b) {
|
|
1192
|
+
// Ignore decode errors, will be handled in retrieveSession
|
|
1193
|
+
}
|
|
1194
|
+
this.userLogger.debug(`AuthBasic: computed session ID for credentials`);
|
|
1195
|
+
return sessionId;
|
|
1196
|
+
}
|
|
1197
|
+
}
|
|
1198
|
+
// Fall back to cookie-based authentication
|
|
1199
|
+
return super.fetchId(req);
|
|
1200
|
+
}
|
|
1201
|
+
/**
|
|
1202
|
+
* Override retrieveSession to create session via portal if needed
|
|
1203
|
+
* @param id - Session ID
|
|
1204
|
+
*/
|
|
1205
|
+
retrieveSession(id) {
|
|
1206
|
+
const _super = Object.create(null, {
|
|
1207
|
+
retrieveSession: { get: () => super.retrieveSession }
|
|
1208
|
+
});
|
|
1209
|
+
return new Promise((resolve, reject) => {
|
|
1210
|
+
// First try to get existing session
|
|
1211
|
+
_super.retrieveSession.call(this, id)
|
|
1212
|
+
.then((session) => {
|
|
1213
|
+
// Session exists, clean up pending auth
|
|
1214
|
+
this.pendingAuth.delete(id);
|
|
1215
|
+
resolve(session);
|
|
1216
|
+
})
|
|
1217
|
+
.catch(() => __awaiter(this, void 0, void 0, function* () {
|
|
1218
|
+
// Session doesn't exist, try to create it via portal
|
|
1219
|
+
const pending = this.pendingAuth.get(id);
|
|
1220
|
+
if (!pending) {
|
|
1221
|
+
reject("No session and no pending authentication");
|
|
1222
|
+
return;
|
|
1223
|
+
}
|
|
1224
|
+
// Clean up pending auth
|
|
1225
|
+
this.pendingAuth.delete(id);
|
|
1226
|
+
// Try to create session via portal
|
|
1227
|
+
const created = yield this.createSession(id, pending.username, pending.password, pending.xff);
|
|
1228
|
+
if (created) {
|
|
1229
|
+
// Session was created, now retrieve it
|
|
1230
|
+
_super.retrieveSession.call(this, id).then(resolve).catch(reject);
|
|
1231
|
+
}
|
|
1232
|
+
else {
|
|
1233
|
+
reject("Authentication failed");
|
|
1234
|
+
}
|
|
1235
|
+
}));
|
|
1236
|
+
});
|
|
1237
|
+
}
|
|
1238
|
+
/**
|
|
1239
|
+
* Create session via portal REST API
|
|
1240
|
+
* POST to portal/sessions/global/{id}?auth
|
|
1241
|
+
* @param id - Session ID to create
|
|
1242
|
+
* @param username - Username from Basic auth
|
|
1243
|
+
* @param password - Password from Basic auth
|
|
1244
|
+
* @param xff - X-Forwarded-For header value
|
|
1245
|
+
* @returns true if session created successfully
|
|
1246
|
+
*/
|
|
1247
|
+
createSession(id, username, password, xff) {
|
|
1248
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
1249
|
+
var _a;
|
|
1250
|
+
// Validate session ID to mitigate SSRF
|
|
1251
|
+
if (!/^[a-fA-F0-9]{1,64}$/.test(id)) {
|
|
1252
|
+
this.userLogger.error(`AuthBasic: Invalid session ID format: ${id}`);
|
|
1253
|
+
return false;
|
|
1254
|
+
}
|
|
1255
|
+
const portal = this.tsv.portal();
|
|
1256
|
+
if (!portal) {
|
|
1257
|
+
this.userLogger.error("AuthBasic: portal URL not configured");
|
|
1258
|
+
return false;
|
|
1259
|
+
}
|
|
1260
|
+
// Build URL: portal/sessions/global/{id}?auth
|
|
1261
|
+
let url = `${portal}/sessions/global/${id}?auth`;
|
|
1262
|
+
url = url.replace(/\/\/sessions\//, "/sessions/");
|
|
1263
|
+
// Build request body
|
|
1264
|
+
const bodyParams = {
|
|
1265
|
+
user: username,
|
|
1266
|
+
password: password,
|
|
1267
|
+
secret: ((_a = this.tsv.cipher) === null || _a === void 0 ? void 0 : _a.encrypt(Date.now().toString())) || "",
|
|
1268
|
+
};
|
|
1269
|
+
// Add auth choice if configured
|
|
1270
|
+
if (this.tsv.authChoiceAuthBasic) {
|
|
1271
|
+
const paramName = this.tsv.authChoiceParam || "lmAuth";
|
|
1272
|
+
bodyParams[paramName] = this.tsv.authChoiceAuthBasic;
|
|
1273
|
+
}
|
|
1274
|
+
const body = new URLSearchParams(bodyParams).toString();
|
|
1275
|
+
this.userLogger.debug(`AuthBasic: authenticating ${username} via portal`);
|
|
1276
|
+
try {
|
|
1277
|
+
const response = yield fetch(url, {
|
|
1278
|
+
method: "POST",
|
|
1279
|
+
headers: {
|
|
1280
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
1281
|
+
Accept: "application/json",
|
|
1282
|
+
"X-Forwarded-For": xff,
|
|
1283
|
+
},
|
|
1284
|
+
body: body,
|
|
1285
|
+
});
|
|
1286
|
+
if (response.ok) {
|
|
1287
|
+
this.userLogger.info(`AuthBasic: authentication successful for ${username}`);
|
|
1288
|
+
return true;
|
|
1289
|
+
}
|
|
1290
|
+
else {
|
|
1291
|
+
this.userLogger.warn(`AuthBasic: authentication failed for ${username}: ${response.status} ${response.statusText}`);
|
|
1292
|
+
return false;
|
|
1293
|
+
}
|
|
1294
|
+
}
|
|
1295
|
+
catch (e) {
|
|
1296
|
+
this.userLogger.error(`AuthBasic: portal request failed: ${e}`);
|
|
1297
|
+
return false;
|
|
1298
|
+
}
|
|
1299
|
+
});
|
|
1300
|
+
}
|
|
1301
|
+
/**
|
|
1302
|
+
* Hide Authorization header from protected application
|
|
1303
|
+
* Called after successful authentication
|
|
1304
|
+
* @param req - HTTP request
|
|
1305
|
+
*/
|
|
1306
|
+
hideCookie(req) {
|
|
1307
|
+
this.userLogger.debug("AuthBasic: removing Authorization header");
|
|
1308
|
+
delete req.headers.authorization;
|
|
1309
|
+
}
|
|
1310
|
+
/**
|
|
1311
|
+
* Override goToPortal to send Basic challenge instead of redirect
|
|
1312
|
+
* @param res - HTTP response
|
|
1313
|
+
* @param uri - Original URI
|
|
1314
|
+
* @param args - Additional arguments
|
|
1315
|
+
*/
|
|
1316
|
+
goToPortal(res, uri, args = "") {
|
|
1317
|
+
if (args) {
|
|
1318
|
+
// If there's an argument, redirect to portal with message
|
|
1319
|
+
super.goToPortal(res, uri, args);
|
|
1320
|
+
}
|
|
1321
|
+
else {
|
|
1322
|
+
// Otherwise, send WWW-Authenticate challenge
|
|
1323
|
+
res.setHeader("WWW-Authenticate", 'Basic realm="LemonLDAP::NG"');
|
|
1324
|
+
this.setError(res, uri, 401, "Authentication required");
|
|
1325
|
+
}
|
|
1326
|
+
}
|
|
1327
|
+
}
|
|
1328
|
+
|
|
1329
|
+
/**
|
|
1330
|
+
* CDA (Cross-Domain Authentication) utilities for LemonLDAP::NG
|
|
1331
|
+
* Port of Lemonldap::NG::Handler::Main::CDA
|
|
1332
|
+
*
|
|
1333
|
+
* CDA allows authentication to be shared across different domains
|
|
1334
|
+
* by using encrypted cookies or URL parameters.
|
|
1335
|
+
*/
|
|
1336
|
+
/**
|
|
1337
|
+
* Maximum allowed clock skew in seconds for timestamp validation
|
|
1338
|
+
*/
|
|
1339
|
+
const MAX_CLOCK_SKEW_SECONDS = 10;
|
|
1340
|
+
/**
|
|
1341
|
+
* Parse and validate a CDA cookie value
|
|
1342
|
+
* @param cipher - Crypto instance for decryption
|
|
1343
|
+
* @param cookieValue - Encrypted cookie value
|
|
1344
|
+
* @param maxAge - Maximum age in seconds (default: 120)
|
|
1345
|
+
* @returns Parsed CDA value or null if invalid
|
|
1346
|
+
*/
|
|
1347
|
+
function parseCDACookie(cipher, cookieValue, maxAge = 120) {
|
|
1348
|
+
try {
|
|
1349
|
+
const decrypted = cipher.decrypt(cookieValue);
|
|
1350
|
+
const parts = decrypted.split(":");
|
|
1351
|
+
if (parts.length < 2) {
|
|
1352
|
+
return null;
|
|
1353
|
+
}
|
|
1354
|
+
const sessionId = parts[0];
|
|
1355
|
+
const timestamp = parseInt(parts[1], 10);
|
|
1356
|
+
if (!sessionId || isNaN(timestamp)) {
|
|
1357
|
+
return null;
|
|
1358
|
+
}
|
|
1359
|
+
// Check timestamp validity
|
|
1360
|
+
const now = Math.floor(Date.now() / 1000);
|
|
1361
|
+
if (now - timestamp > maxAge || timestamp > now + MAX_CLOCK_SKEW_SECONDS) {
|
|
1362
|
+
// Cookie too old or too far in the future (clock skew)
|
|
1363
|
+
return null;
|
|
1364
|
+
}
|
|
1365
|
+
return {
|
|
1366
|
+
sessionId,
|
|
1367
|
+
timestamp,
|
|
1368
|
+
domain: parts[2],
|
|
1369
|
+
};
|
|
1370
|
+
}
|
|
1371
|
+
catch (_a) {
|
|
1372
|
+
return null;
|
|
1373
|
+
}
|
|
1374
|
+
}
|
|
1375
|
+
/**
|
|
1376
|
+
* Extract CDA value from URL
|
|
1377
|
+
* @param url - URL potentially containing CDA parameter
|
|
1378
|
+
* @returns CDA parameter value or null
|
|
1379
|
+
*/
|
|
1380
|
+
function extractCDAFromUrl(url) {
|
|
1381
|
+
try {
|
|
1382
|
+
const urlObj = new URL(url, "http://localhost");
|
|
1383
|
+
return urlObj.searchParams.get("lemonldapcda");
|
|
1384
|
+
}
|
|
1385
|
+
catch (_a) {
|
|
1386
|
+
return null;
|
|
1387
|
+
}
|
|
1388
|
+
}
|
|
1389
|
+
/**
|
|
1390
|
+
* Build Set-Cookie header for CDA
|
|
1391
|
+
* @param cookieName - Cookie name
|
|
1392
|
+
* @param value - Cookie value
|
|
1393
|
+
* @param domain - Cookie domain
|
|
1394
|
+
* @param expiration - Expiration in seconds (0 for session cookie)
|
|
1395
|
+
* @param secure - Whether to set Secure flag
|
|
1396
|
+
* @param httpOnly - Whether to set HttpOnly flag
|
|
1397
|
+
* @returns Cookie header string
|
|
1398
|
+
*/
|
|
1399
|
+
function buildCDACookieHeader(cookieName, value, domain, expiration = 0, secure = false, httpOnly = true) {
|
|
1400
|
+
let cookie = `${cookieName}=${value}`;
|
|
1401
|
+
if (domain) {
|
|
1402
|
+
cookie += `; Domain=${domain}`;
|
|
1403
|
+
}
|
|
1404
|
+
cookie += "; Path=/";
|
|
1405
|
+
if (expiration > 0) {
|
|
1406
|
+
const expires = new Date(Date.now() + expiration * 1000);
|
|
1407
|
+
cookie += `; Expires=${expires.toUTCString()}`;
|
|
1408
|
+
}
|
|
1409
|
+
if (secure) {
|
|
1410
|
+
cookie += "; Secure";
|
|
1411
|
+
}
|
|
1412
|
+
if (httpOnly) {
|
|
1413
|
+
cookie += "; HttpOnly";
|
|
1414
|
+
}
|
|
1415
|
+
cookie += "; SameSite=None";
|
|
1416
|
+
return cookie;
|
|
1417
|
+
}
|
|
1418
|
+
|
|
1419
|
+
/**
|
|
1420
|
+
* CDA (Cross-Domain Authentication) Handler for LemonLDAP::NG
|
|
1421
|
+
* Port of Lemonldap::NG::Handler::Main with CDA support
|
|
1422
|
+
*
|
|
1423
|
+
* This handler enables cross-domain authentication by:
|
|
1424
|
+
* 1. Checking for CDA cookies/parameters on incoming requests
|
|
1425
|
+
* 2. Setting CDA cookies when users authenticate
|
|
1426
|
+
* 3. Propagating authentication across configured domains
|
|
1427
|
+
*/
|
|
1428
|
+
class LemonldapNGHandlerCDA extends LemonldapNGHandler {
|
|
1429
|
+
/**
|
|
1430
|
+
* Override fetchId to check for CDA cookie/parameter first
|
|
1431
|
+
* @param req - HTTP request
|
|
1432
|
+
*/
|
|
1433
|
+
fetchId(req) {
|
|
1434
|
+
// Check if CDA is enabled
|
|
1435
|
+
if (!this.tsv.cda) {
|
|
1436
|
+
return super.fetchId(req);
|
|
1437
|
+
}
|
|
1438
|
+
// 1. Check for CDA URL parameter (from redirect)
|
|
1439
|
+
const url = req.url || "/";
|
|
1440
|
+
const cdaParam = extractCDAFromUrl(url);
|
|
1441
|
+
if (cdaParam) {
|
|
1442
|
+
const cdaValue = parseCDACookie(this.tsv.cipher, cdaParam);
|
|
1443
|
+
if (cdaValue) {
|
|
1444
|
+
this.userLogger.debug(`CDA: extracted session from URL parameter`);
|
|
1445
|
+
// Set the CDA cookie for future requests
|
|
1446
|
+
this.setCDACookie(req, cdaValue.sessionId);
|
|
1447
|
+
return cdaValue.sessionId;
|
|
1448
|
+
}
|
|
1449
|
+
else {
|
|
1450
|
+
this.userLogger.warn("CDA: invalid or expired URL parameter");
|
|
1451
|
+
}
|
|
1452
|
+
}
|
|
1453
|
+
// 2. Check for CDA cookie
|
|
1454
|
+
const cdaCookieName = `${this.tsv.cookieName}cda`;
|
|
1455
|
+
const cdaCookie = this.getCDACookie(req, cdaCookieName);
|
|
1456
|
+
if (cdaCookie) {
|
|
1457
|
+
const cdaValue = parseCDACookie(this.tsv.cipher, cdaCookie);
|
|
1458
|
+
if (cdaValue) {
|
|
1459
|
+
this.userLogger.debug(`CDA: extracted session from cookie`);
|
|
1460
|
+
return cdaValue.sessionId;
|
|
1461
|
+
}
|
|
1462
|
+
else {
|
|
1463
|
+
this.userLogger.warn("CDA: invalid or expired cookie");
|
|
1464
|
+
}
|
|
1465
|
+
}
|
|
1466
|
+
// 3. Fall back to standard cookie
|
|
1467
|
+
return super.fetchId(req);
|
|
1468
|
+
}
|
|
1469
|
+
/**
|
|
1470
|
+
* Get CDA cookie value from request
|
|
1471
|
+
* @param req - HTTP request
|
|
1472
|
+
* @param cookieName - Cookie name to look for
|
|
1473
|
+
*/
|
|
1474
|
+
getCDACookie(req, cookieName) {
|
|
1475
|
+
const cookies = req.headers.cookie;
|
|
1476
|
+
if (!cookies) {
|
|
1477
|
+
return null;
|
|
1478
|
+
}
|
|
1479
|
+
const regex = new RegExp(`${cookieName}=([^;]+)`);
|
|
1480
|
+
const match = regex.exec(cookies);
|
|
1481
|
+
return match ? match[1] : null;
|
|
1482
|
+
}
|
|
1483
|
+
/**
|
|
1484
|
+
* Set CDA cookie on response (placeholder for middleware integration)
|
|
1485
|
+
*
|
|
1486
|
+
* TODO: Implement full CDA cookie setting mechanism. Options include:
|
|
1487
|
+
* 1. Store the value in req.llngCdaInfo and set in sendHeaders via response
|
|
1488
|
+
* 2. Use express middleware to intercept and set the cookie
|
|
1489
|
+
* 3. Pass response object through the call chain
|
|
1490
|
+
*
|
|
1491
|
+
* Currently a no-op as we don't have access to the response object here.
|
|
1492
|
+
*
|
|
1493
|
+
* @param _req - HTTP request (unused)
|
|
1494
|
+
* @param _sessionId - Session ID to set (unused)
|
|
1495
|
+
*/
|
|
1496
|
+
setCDACookie(_req, _sessionId) {
|
|
1497
|
+
// Placeholder - see TODO in JSDoc above
|
|
1498
|
+
}
|
|
1499
|
+
/**
|
|
1500
|
+
* Override sendHeaders to also set CDA cookie
|
|
1501
|
+
* @param req - HTTP request
|
|
1502
|
+
* @param session - User session
|
|
1503
|
+
*/
|
|
1504
|
+
sendHeaders(req, session) {
|
|
1505
|
+
super.sendHeaders(req, session);
|
|
1506
|
+
// If CDA is enabled, prepare CDA cookie header
|
|
1507
|
+
// Store in a custom property for middleware to process
|
|
1508
|
+
if (this.tsv.cda) {
|
|
1509
|
+
const cdaCookieName = `${this.tsv.cookieName}cda`;
|
|
1510
|
+
const domain = this.getCDACookieDomain(req);
|
|
1511
|
+
if (domain) {
|
|
1512
|
+
// Store CDA cookie info as a custom property on the request object
|
|
1513
|
+
// Middleware can read this and set the cookie on the response
|
|
1514
|
+
req.llngCdaCookie = buildCDACookieHeader(cdaCookieName, session._session_id, domain, this.tsv.cookieExpiration || 0, this.tsv.securedCookie > 0, this.tsv.httpOnly);
|
|
1515
|
+
}
|
|
1516
|
+
}
|
|
1517
|
+
}
|
|
1518
|
+
/**
|
|
1519
|
+
* Get domain for CDA cookie
|
|
1520
|
+
* @param req - HTTP request
|
|
1521
|
+
*/
|
|
1522
|
+
getCDACookieDomain(req) {
|
|
1523
|
+
const host = req.headers.host;
|
|
1524
|
+
if (!host) {
|
|
1525
|
+
return "";
|
|
1526
|
+
}
|
|
1527
|
+
// Extract domain from host (remove port)
|
|
1528
|
+
const hostname = host.split(":")[0];
|
|
1529
|
+
// For CDA, we typically want to set the cookie on a parent domain
|
|
1530
|
+
// This is a simplified implementation - full implementation would
|
|
1531
|
+
// use configured CDA domains
|
|
1532
|
+
const parts = hostname.split(".");
|
|
1533
|
+
if (parts.length >= 2) {
|
|
1534
|
+
// Return parent domain (e.g., .example.com from www.example.com)
|
|
1535
|
+
return "." + parts.slice(-2).join(".");
|
|
1536
|
+
}
|
|
1537
|
+
return hostname;
|
|
1538
|
+
}
|
|
1539
|
+
/**
|
|
1540
|
+
* Override goToPortal to include CDA parameter
|
|
1541
|
+
* @param res - HTTP response
|
|
1542
|
+
* @param uri - Original URI
|
|
1543
|
+
* @param args - Additional arguments
|
|
1544
|
+
*/
|
|
1545
|
+
goToPortal(res, uri, args = "") {
|
|
1546
|
+
// Add CDA parameter if enabled
|
|
1547
|
+
if (this.tsv.cda) {
|
|
1548
|
+
const cdaArg = "cda=1";
|
|
1549
|
+
args = args ? `${args}&${cdaArg}` : cdaArg;
|
|
1550
|
+
}
|
|
1551
|
+
super.goToPortal(res, uri, args);
|
|
1552
|
+
}
|
|
1553
|
+
}
|
|
1554
|
+
|
|
704
1555
|
let currentHandler;
|
|
705
1556
|
let currentClass;
|
|
706
1557
|
const knownHandlers = {
|
|
@@ -708,6 +1559,9 @@ const knownHandlers = {
|
|
|
708
1559
|
DevOps: LemonldapNGHandlerDevOps,
|
|
709
1560
|
ServiceToken: LemonldapNGHandlerServiceToken,
|
|
710
1561
|
ServiceTokenST: LemonldapNGHandlerDevOpsST,
|
|
1562
|
+
OAuth2: LemonldapNGHandlerOAuth2,
|
|
1563
|
+
AuthBasic: LemonldapNGHandlerAuthBasic,
|
|
1564
|
+
CDA: LemonldapNGHandlerCDA,
|
|
711
1565
|
};
|
|
712
1566
|
const init = (args) => {
|
|
713
1567
|
return new Promise((resolve, reject) => {
|
|
@@ -741,6 +1595,15 @@ const run = (req, res, next) => {
|
|
|
741
1595
|
const nginxServer = (args) => {
|
|
742
1596
|
currentHandler.nginxServer(args);
|
|
743
1597
|
};
|
|
1598
|
+
/**
|
|
1599
|
+
* Shutdown the handler (stops event loop and cleanup)
|
|
1600
|
+
* Call this in tests' afterAll to prevent Jest from hanging
|
|
1601
|
+
*/
|
|
1602
|
+
const shutdown = () => __awaiter(void 0, void 0, void 0, function* () {
|
|
1603
|
+
if (currentHandler) {
|
|
1604
|
+
yield currentHandler.stopEventLoop();
|
|
1605
|
+
}
|
|
1606
|
+
});
|
|
744
1607
|
|
|
745
|
-
export { currentClass as class, init, nginxServer, run };
|
|
1608
|
+
export { currentClass as class, init, nginxServer, run, shutdown };
|
|
746
1609
|
//# sourceMappingURL=index.mjs.map
|