lemonldap-ng-handler 0.5.4 → 0.6.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 ADDED
@@ -0,0 +1,744 @@
1
+ import Conf from '@lemonldap-ng/conf';
2
+ import Session from '@lemonldap-ng/session';
3
+ import SafeLib from '@lemonldap-ng/safelib';
4
+ import Logger from '@lemonldap-ng/logger';
5
+ import vm from 'vm';
6
+ import RE2 from 're2';
7
+ import http from 'http';
8
+ import normalizeUrl from 'normalize-url';
9
+
10
+ const condMatch = new RE2('^logout(?:_sso|_app|_app_sso|)(?:s+(.*))?$', 'i');
11
+ let sid = 0;
12
+ const requiredFields = [
13
+ 'cda',
14
+ 'cookieExpiration',
15
+ 'cipher',
16
+ 'cookieName',
17
+ 'customFunctions',
18
+ 'httpOnly',
19
+ 'securedCookie',
20
+ 'timeout',
21
+ 'timeoutActivity',
22
+ 'useRedirectOnError',
23
+ 'useRedirectOnForbidden',
24
+ 'whatToTrace',
25
+ 'loopBackUrl'
26
+ ];
27
+ class HandlerInit {
28
+ constructor(args) {
29
+ this.safe = {};
30
+ // @ts-ignore: some values will be initialized later
31
+ this.tsv = {
32
+ defaultCondition: {},
33
+ defaultProtection: {},
34
+ forgeHeaders: {},
35
+ headerList: {},
36
+ https: {},
37
+ locationCondition: {},
38
+ locationCount: {},
39
+ locationProtection: {},
40
+ locationRegexp: {},
41
+ maintenance: {},
42
+ port: {},
43
+ portal: () => '',
44
+ vhostAlias: {}
45
+ };
46
+ this.localConf = args;
47
+ if (!args.configStorage)
48
+ args.configStorage = {};
49
+ args.configStorage.localStorage ||
50
+ (args.configStorage.localStorage = args.localStorage);
51
+ args.configStorage.localStorageOptions ||
52
+ (args.configStorage.localStorageOptions = args.localStorageOptions);
53
+ this.confAcc = new Conf(args.configStorage);
54
+ const handlerConf = this.confAcc.getLocalConf('handler', true);
55
+ const nodeHandlerConf = (this.confAcc.getLocalConf('node-handler', false));
56
+ [handlerConf, nodeHandlerConf].forEach(iniSection => {
57
+ Object.keys(iniSection).forEach((k) => {
58
+ if (!this.localConf)
59
+ throw new Error('undef');
60
+ if (this.localConf[k] === undefined)
61
+ this.localConf[k] = iniSection[k];
62
+ });
63
+ });
64
+ if (this.localConf.nodeVhosts === undefined)
65
+ // istanbul ignore next
66
+ throw new Error('No Virtualhosts configured for Node.js');
67
+ this.vhostList = this.localConf.nodeVhosts.split(/[,\s]+/);
68
+ }
69
+ reload() {
70
+ return new Promise((resolve, reject) => {
71
+ const ucFirst = (s) => {
72
+ return s.charAt(0).toUpperCase() + s.slice(1);
73
+ };
74
+ this.confAcc.ready.then(() => {
75
+ this.confAcc
76
+ .getConf({})
77
+ .then((conf) => {
78
+ requiredFields.forEach(k => {
79
+ // @ts-ignore: all fields not declared
80
+ this.tsv[k] = conf[k];
81
+ });
82
+ Object.keys(this.localConf).forEach(k => {
83
+ conf[k] = this.localConf[k];
84
+ });
85
+ ['https', 'port', 'maintenance'].forEach(k => {
86
+ if (conf[k] !== undefined) {
87
+ // @ts-ignore; k is in TSV type
88
+ this.tsv[k] = { _: conf[k] };
89
+ if (conf.vhostOptions) {
90
+ const name = `vhost${ucFirst(k)}`;
91
+ Object.keys(conf.vhostOptions).forEach((vhost) => {
92
+ // @ts-ignore: val is a number
93
+ const val = conf.vhostOptions[vhost][name];
94
+ // @ts-ignore; k is in TSV type
95
+ if (val > 0)
96
+ this.tsv[k][vhost] = val;
97
+ });
98
+ }
99
+ }
100
+ });
101
+ if (!conf.portal)
102
+ throw new Error('portal should be defined');
103
+ //if ( conf.portal.match(/[\$\(&\|"']/) ) {
104
+ // this.tsv.portal = self.conditionSubs(conf.portal)[0];
105
+ //} else {
106
+ this.tsv.portal = () => conf.portal;
107
+ //}
108
+ /**
109
+ * Sessions storage initialization
110
+ */
111
+ //['global','oidc'].forEach
112
+ if (!conf['globalStorage'] || !conf['globalStorageOptions'])
113
+ // istanbul ignore next
114
+ throw new Error('Missing session storage configuration');
115
+ try {
116
+ this.sessionAcc = new Session({
117
+ storageModule: conf['globalStorage'],
118
+ storageModuleOptions: conf['globalStorageOptions']
119
+ });
120
+ }
121
+ catch (e) {
122
+ // istanbul ignore next
123
+ throw new Error(`Unable to load session module: ${e}`);
124
+ }
125
+ /**
126
+ * Location rules initialization
127
+ */
128
+ Object.keys(conf.locationRules).forEach((vhost) => {
129
+ if (this.vhostList.indexOf(vhost) == -1)
130
+ return;
131
+ this.tsv.locationCount[vhost] = 0;
132
+ [
133
+ 'locationRegexp',
134
+ 'locationProtection',
135
+ 'locationCondition'
136
+ ].forEach(k => {
137
+ // @ts-ignore: fields declared in TSV type
138
+ if (this.tsv[k][vhost] === undefined)
139
+ this.tsv[k][vhost] = [];
140
+ });
141
+ if (!this.safe[vhost])
142
+ this.safe[vhost] = new SafeLib(conf);
143
+ // @ts-ignore conf.locationRules[vhost] exists
144
+ const rules = conf.locationRules[vhost];
145
+ Object.keys(rules).forEach(url => {
146
+ const [cond, prot] = this.conditionSub(rules[url], this.safe[vhost]);
147
+ if (url === 'default') {
148
+ this.tsv.defaultCondition[vhost] = cond;
149
+ this.tsv.defaultProtection[vhost] = prot;
150
+ }
151
+ else {
152
+ this.tsv.locationCondition[vhost].push(cond);
153
+ this.tsv.locationProtection[vhost].push(prot);
154
+ this.tsv.locationRegexp[vhost].push(new RE2(url.replace(/\(\?#.*?\)/, '')));
155
+ this.tsv.locationCount[vhost]++;
156
+ }
157
+ });
158
+ if (!this.tsv.defaultCondition[vhost]) {
159
+ // istanbul ignore next
160
+ this.tsv.defaultCondition[vhost] = () => true;
161
+ // istanbul ignore next
162
+ this.tsv.defaultProtection[vhost] = 0;
163
+ }
164
+ });
165
+ /**
166
+ * Headers initialization
167
+ */
168
+ if (conf.exportedHeaders !== undefined) {
169
+ Object.keys(conf.exportedHeaders).forEach((vhost) => {
170
+ // @ts-ignore
171
+ const headers = (
172
+ // @ts-ignore: conf.exportedHeaders[vhost] is defined
173
+ conf.exportedHeaders[vhost]);
174
+ if (this.vhostList.indexOf(vhost) == -1)
175
+ return;
176
+ if (!this.tsv.headerList[vhost])
177
+ this.tsv.headerList[vhost] = [];
178
+ let sub = '';
179
+ Object.keys(headers).forEach((name) => {
180
+ this.tsv.headerList[vhost].push(name);
181
+ sub += `'${name}': ${this.substitute(headers[name])},`;
182
+ });
183
+ sub = sub.replace(/,$/, '');
184
+ vm.runInContext(`fg = function(session) {return {${sub}};}`, this.safe[vhost]);
185
+ // @ts-ignore: fg is now defined
186
+ this.tsv.forgeHeaders[vhost] = this.safe[vhost].fg;
187
+ });
188
+ }
189
+ // TODO: post url initialization
190
+ /**
191
+ * Alias initialization
192
+ */
193
+ if (conf.vhostOptions !== undefined) {
194
+ Object.keys(conf.vhostOptions).forEach((vhost) => {
195
+ // @ts-ignore: conf.vhostOptions[vhost] is defined
196
+ if (conf.vhostOptions[vhost].aliases) {
197
+ // @ts-ignore: conf.vhostOptions[vhost] is defined
198
+ conf.vhostOptions[vhost].aliases.forEach((alias) => {
199
+ this.tsv.vhostAlias[alias] = vhost;
200
+ });
201
+ }
202
+ });
203
+ }
204
+ this.tsv.cookieDetect = new RE2(`\\b${this.tsv.cookieName}=([^;]+)`);
205
+ this.sessionAcc.ready.then(() => {
206
+ resolve(true);
207
+ Logger(conf, true)
208
+ .then(logger => {
209
+ this.userLogger = logger;
210
+ resolve(true);
211
+ })
212
+ .catch(e => {
213
+ console.error('Logger error', e);
214
+ // istanbul ignore next
215
+ throw new Error(e);
216
+ });
217
+ });
218
+ })
219
+ .catch((e) => {
220
+ // istanbul ignore next
221
+ reject(`Unable to get configuration: ${e}`);
222
+ });
223
+ });
224
+ });
225
+ }
226
+ conditionSub(cond, ctx) {
227
+ const OK = () => true;
228
+ const NOK = () => false;
229
+ if (cond === 'accept')
230
+ return [OK, 0];
231
+ if (cond === 'deny')
232
+ return [NOK, 0];
233
+ if (cond === 'unprotect')
234
+ return [OK, 1];
235
+ if (cond === 'skip')
236
+ return [OK, 2];
237
+ // TODO: manage app logout
238
+ const res = condMatch.exec(cond);
239
+ if (res && res[1]) {
240
+ const url = res[1];
241
+ if (url) {
242
+ return [
243
+ (session) => {
244
+ session._logout = url;
245
+ return false;
246
+ },
247
+ 0
248
+ ];
249
+ }
250
+ else {
251
+ return [
252
+ (session) => {
253
+ session._logout = this.tsv.portal();
254
+ return false;
255
+ },
256
+ 0
257
+ ];
258
+ }
259
+ }
260
+ cond = this.substitute(cond);
261
+ if (ctx) {
262
+ sid++;
263
+ vm.runInContext(`sub${sid.toString()} = function(req,session) {return (${cond});}`, ctx);
264
+ // @ts-ignore: cts is also a context
265
+ return [ctx[`sub${sid.toString()}`], 0];
266
+ }
267
+ else {
268
+ // istanbul ignore next
269
+ throw new Error('Disabling safeJail is not supported');
270
+ }
271
+ }
272
+ substitute(expr) {
273
+ return (expr
274
+ // Special macros
275
+ .replace(/\$date\b/g, 'this.date()')
276
+ .replace(/\$vhost\b/g, 'this.hostname(req)')
277
+ .replace(/\$ip\b/g, 'this.remote_ip(req)')
278
+ // Session attributes: $xx is replaced by session.xx
279
+ .replace(/\$(_*[a-zA-Z]\w*)/g, 'session.$1'));
280
+ }
281
+ }
282
+
283
+ class LemonldapNGHandler extends HandlerInit {
284
+ init() {
285
+ return this.reload();
286
+ }
287
+ /**
288
+ * run(), the access control function
289
+ */
290
+ run(req, res, next) {
291
+ const vhost = req.headers.host;
292
+ if (vhost === undefined) {
293
+ this.userLogger.error('Request without Host header');
294
+ this.setError(res, '/', 400, 'Bad request');
295
+ return;
296
+ }
297
+ /* 1 - get data */
298
+ const uri = new URL(normalizeUrl(vhost + req.url)).pathname || '/';
299
+ /* 2 - check for maintenance mode */
300
+ if (this.tsv.maintenance[vhost])
301
+ return this.setError(res, '/', 503, 'Service Temporarily Unavailable');
302
+ /* 3 - check if current URI is protected */
303
+ const protection = this.isUnprotected(req, uri);
304
+ if (protection === 2)
305
+ return next();
306
+ /* 4 - search for LLNG cookie */
307
+ const id = this.fetchId(req);
308
+ if (id !== '') {
309
+ this.retrieveSession(id)
310
+ .then(session => {
311
+ const user = session[this.tsv.whatToTrace];
312
+ this.userLogger.debug(`User ${user} identified`);
313
+ this.grant(req, uri, session)
314
+ .then(grantResult => {
315
+ if (grantResult) {
316
+ this.sendHeaders(req, session);
317
+ this.hideCookie(req);
318
+ next();
319
+ this.userLogger.info(`${vhost}: user ${user} was granted access to ${uri}`);
320
+ }
321
+ else {
322
+ this.forbidden(req, res, session);
323
+ this.userLogger.notice(`${vhost}: user ${user} was denied access to ${uri}`);
324
+ }
325
+ })
326
+ .catch(e => {
327
+ console.error(e);
328
+ this.setError(res, '/', 503, 'Service Unavailable');
329
+ });
330
+ })
331
+ .catch(e => {
332
+ /* Expired session */
333
+ this.goToPortal(res, this.selfUri(vhost, uri));
334
+ });
335
+ }
336
+ else {
337
+ this.goToPortal(res, this.selfUri(vhost, uri));
338
+ }
339
+ }
340
+ selfUri(vhost, uri) {
341
+ return ((this.tsv.https && this.tsv.https[vhost] ? 'https' : 'http') +
342
+ '://' +
343
+ vhost +
344
+ uri);
345
+ }
346
+ nginxServer(fcgiOpt) {
347
+ fcgiOpt.mode || (fcgiOpt.mode = 'fcgi');
348
+ fcgiOpt.port || (fcgiOpt.port = 9090);
349
+ fcgiOpt.ip || (fcgiOpt.ip = 'localhost');
350
+ const srv = fcgiOpt.mode === 'fcgi' ? require('node-fastcgi') : http;
351
+ srv
352
+ .createServer((req, res) => {
353
+ const next = () => {
354
+ res.writeHead(200, req.headers);
355
+ };
356
+ this.run(req, res, next);
357
+ })
358
+ .listen(fcgiOpt.port, fcgiOpt.ip);
359
+ }
360
+ setError(res, uri, code, txt) {
361
+ if (this.tsv.useRedirectOnError) {
362
+ const url = this.tsv.portal() + `?lmError=${code.toString()}&url=`;
363
+ //+ (new Buffer.from(encodeURI(uri))).toString('base64');
364
+ // @ts-ignore: res.redirect may exist
365
+ if (res.redirect) {
366
+ // @ts-ignore: res.redirect may exist
367
+ res.redirect(url);
368
+ }
369
+ else {
370
+ res.writeHead(401, { Location: url });
371
+ }
372
+ }
373
+ else {
374
+ // @ts-ignore: res.redirect may exist
375
+ if (res.redirect) {
376
+ // @ts-ignore: res.status may exist
377
+ res.status(code).send(txt);
378
+ }
379
+ else {
380
+ res.writeHead(code, txt);
381
+ }
382
+ }
383
+ }
384
+ isUnprotected(req, uri) {
385
+ const vhost = this.resolveAlias(req);
386
+ if (!this.tsv.defaultCondition[vhost])
387
+ return false;
388
+ for (let i = 0; i < this.tsv.locationRegexp[vhost].length; i++) {
389
+ if (this.tsv.locationRegexp[vhost][i].test(uri))
390
+ return this.tsv.locationProtection[vhost][i];
391
+ }
392
+ return this.tsv.defaultProtection[vhost];
393
+ }
394
+ resolveAlias(req) {
395
+ // @ts-ignore: req.headers.host has already been tested
396
+ const vhost = req.headers.host.replace(/:.*$/, '');
397
+ return this.tsv.vhostAlias[vhost] || vhost;
398
+ }
399
+ fetchId(req) {
400
+ if (req.headers.cookie) {
401
+ const res = this.tsv.cookieDetect.exec(req.headers.cookie);
402
+ if (res && res[1] != '0')
403
+ return res[1];
404
+ }
405
+ return '';
406
+ }
407
+ retrieveSession(id) {
408
+ return new Promise((resolve, reject) => {
409
+ if (this.sessionAcc === undefined)
410
+ // istanbul ignore next
411
+ return reject('Server not ready, please wait');
412
+ this.sessionAcc
413
+ .get(id)
414
+ .then((session) => {
415
+ const now = (Date.now() / 1000) | 0;
416
+ if (now - session._utime > this.tsv.timeout ||
417
+ (this.tsv.timeoutActivity &&
418
+ session._lastSeen &&
419
+ // @ts-ignore: session._lastSeen is defined
420
+ now - session._lastSeen > this.tsv.timeoutActivity)) {
421
+ reject(`Session ${id} expired`);
422
+ }
423
+ else {
424
+ if (this.tsv.timeoutActivity &&
425
+ // @ts-ignore: session._lastSeen is defined
426
+ now - session._lastSeen > 60) {
427
+ session._lastSeen = now;
428
+ // @ts-ignore this.sessionAcc is defined here
429
+ this.sessionAcc.update(session);
430
+ }
431
+ resolve(session);
432
+ }
433
+ })
434
+ .catch((e) => {
435
+ reject(`Session ${id} can't be found in store: ${e}`);
436
+ });
437
+ });
438
+ }
439
+ grant(req, uri, session) {
440
+ return new Promise((resolve, reject) => {
441
+ const vhost = this.resolveAlias(req);
442
+ if (!this.tsv.defaultCondition[vhost]) {
443
+ return reject(`No configuration found for ${vhost} (or not listed in Node.js virtualHosts)`);
444
+ }
445
+ if (this.tsv.locationRegexp[vhost]) {
446
+ let i = 0;
447
+ this.tsv.locationRegexp[vhost].forEach((regex) => {
448
+ if (regex.test(uri))
449
+ return resolve(this.tsv.locationCondition[vhost][i](req, session));
450
+ i++;
451
+ });
452
+ }
453
+ this.tsv.defaultCondition[vhost](req, session)
454
+ ? resolve(true)
455
+ : reject('Unauthorized');
456
+ });
457
+ }
458
+ sendHeaders(req, session) {
459
+ const vhost = this.resolveAlias(req);
460
+ try {
461
+ let i = 0;
462
+ // @ts-ignore
463
+ req.headers['Lm-Remote-User'] = session[this.tsv.whatToTrace];
464
+ const map = this.tsv.forgeHeaders[vhost](session);
465
+ Object.keys(map).forEach((k) => {
466
+ i++;
467
+ req.headers[k] = map[k];
468
+ req.rawHeaders.push(k, map[k]);
469
+ // req.redirect is defined when running under express. If not
470
+ // we are running as FastCGI server
471
+ // @ts-ignore
472
+ if (!req.redirect) {
473
+ req.headers[`Headername${i}`] = k;
474
+ req.headers[`Headervalue${i}`] = map[k];
475
+ }
476
+ });
477
+ }
478
+ catch (e) {
479
+ console.error(`Headers maybe not sent: ${e}`);
480
+ // istanbul ignore next
481
+ return;
482
+ }
483
+ }
484
+ hideCookie(req) {
485
+ if (req.headers.cookie)
486
+ req.headers.cookie = req.headers.cookie.replace(this.tsv.cookieDetect, '');
487
+ }
488
+ forbidden(req, res, session) {
489
+ if (session._logout) {
490
+ this.goToPortal(res, session._logout, 'logout=1');
491
+ }
492
+ else {
493
+ this.setError(res, '/', 403, 'Forbidden');
494
+ }
495
+ }
496
+ goToPortal(res, uri, args = '') {
497
+ if (typeof this.tsv.portal !== 'function') {
498
+ this.setError(res, uri, 503, 'Waiting for configuration');
499
+ // istanbul ignore next
500
+ return;
501
+ }
502
+ const urlc = this.tsv.portal() +
503
+ (uri
504
+ ? // @ts-ignore
505
+ '?url=' + new Buffer.from(encodeURI(uri)).toString('base64')
506
+ : '') +
507
+ (args ? (uri ? '&' : '?') + args : '');
508
+ // req.redirect is defined when running under express. If not
509
+ // we are running as FastCGI server
510
+ // @ts-ignore
511
+ if (res.redirect) {
512
+ // @ts-ignore
513
+ res.redirect(urlc);
514
+ }
515
+ else {
516
+ // Nginx doesn't accept 302 from a auth request. LLNG Nginx configuration
517
+ // maps 401 to 302 when "Location" is set
518
+ res.writeHead(401, { Location: urlc });
519
+ }
520
+ }
521
+ }
522
+
523
+ class LemonldapNGHandlerDevOps extends LemonldapNGHandler {
524
+ constructor(args) {
525
+ super(args);
526
+ this.tsv.lastVhostUpdate = {};
527
+ }
528
+ grant(req, uri, session) {
529
+ const vhost = this.resolveAlias(req);
530
+ if (this.tsv.defaultCondition[vhost] &&
531
+ Date.now() / 1000 - this.tsv.lastVhostUpdate[vhost] < 600) {
532
+ // @ts-ignore
533
+ return super.grant(req, uri, session);
534
+ }
535
+ const base =
536
+ // @ts-ignore: cgiParams is tested
537
+ req.cgiParams && req.cgiParams.RULES_URL
538
+ ? // @ts-ignore: same
539
+ req.cgiParams.RULES_URL
540
+ : (this.tsv.loopBackUrl || 'http://127.0.0.1') + '/rules.json';
541
+ if (!/^(https?):\/\/([^/:]+)(?::(\d+))?(.*)$/.test(base)) {
542
+ return new Promise((resolve, reject) => reject(`Bad loopBackUrl ${base}`));
543
+ }
544
+ const lvOpts = {
545
+ prot: RegExp.$1,
546
+ host: RegExp.$2,
547
+ path: RegExp.$4,
548
+ port: RegExp.$3 || (RegExp.$1 == 'https' ? '443' : '80'),
549
+ // @ts-ignore: cgiParams is tested
550
+ lb: !(req.cgiParams && req.cgiParams.RULES_URL)
551
+ };
552
+ return new Promise((resolve, reject) => {
553
+ this.loadVhostConfig(req, vhost, lvOpts)
554
+ .then(() => {
555
+ this.grant(req, uri, session)
556
+ .then(res => {
557
+ resolve(res);
558
+ })
559
+ .catch(e => reject(e));
560
+ })
561
+ .catch(err => {
562
+ console.error(err);
563
+ this.grant(req, uri, session)
564
+ .then(res => {
565
+ resolve(res);
566
+ })
567
+ .catch(e => reject(e));
568
+ });
569
+ });
570
+ }
571
+ loadVhostConfig(req, vhost, lvOpts) {
572
+ return new Promise((resolve, reject) => {
573
+ if (!lvOpts.lb)
574
+ vhost = lvOpts.host;
575
+ delete lvOpts.lb;
576
+ lvOpts.headers = { Host: vhost };
577
+ const http = require(lvOpts.prot);
578
+ // @ts-ignore, property no more needed but required before
579
+ delete lvOpts.prot;
580
+ const req = http.request(lvOpts, (resp) => {
581
+ let str = '';
582
+ resp.on('data', chunk => {
583
+ str += chunk;
584
+ });
585
+ resp.on('end', () => {
586
+ // Blank vhost
587
+ this.tsv.locationCondition[vhost] = [];
588
+ this.tsv.locationProtection[vhost] = [];
589
+ this.tsv.locationRegexp[vhost] = [];
590
+ this.tsv.locationCount[vhost] = 0;
591
+ this.tsv.headerList[vhost] = [];
592
+ if (str === '') {
593
+ this.tsv.defaultCondition[vhost] = () => {
594
+ return true;
595
+ };
596
+ this.tsv.defaultProtection[vhost] = 0;
597
+ this.tsv.lastVhostUpdate[vhost] = Date.now() / 1000;
598
+ return resolve(true);
599
+ }
600
+ try {
601
+ const vhostConfig = JSON.parse(str);
602
+ // @ts-expect-error: TODO
603
+ this.safe[vhost] = new SafeLib({ cipher: this.tsv.cipher });
604
+ if (vhostConfig.rules && typeof vhostConfig.rules === 'object') {
605
+ Object.keys(vhostConfig.rules).forEach((url) => {
606
+ const rule = new String(vhostConfig.rules[url]).valueOf();
607
+ let cond, prot;
608
+ [cond, prot] = this.conditionSub(rule, this.safe[vhost]);
609
+ if (url === 'default') {
610
+ this.tsv.defaultCondition[vhost] = cond;
611
+ this.tsv.defaultProtection[vhost] = prot;
612
+ }
613
+ else {
614
+ this.tsv.locationCondition[vhost].push(cond);
615
+ this.tsv.locationProtection[vhost].push(prot);
616
+ this.tsv.locationRegexp[vhost].push(new RE2(url.replace(/\(\?#.*?\)/, '')));
617
+ this.tsv.locationCount[vhost]++;
618
+ }
619
+ });
620
+ if (!this.tsv.defaultCondition[vhost]) {
621
+ this.tsv.defaultCondition[vhost] = () => true;
622
+ this.tsv.defaultProtection[vhost] = 0;
623
+ }
624
+ }
625
+ if (vhostConfig.headers &&
626
+ typeof vhostConfig.headers === 'object') {
627
+ const sub = Object.keys(vhostConfig.headers)
628
+ .map(name => {
629
+ this.tsv.headerList[vhost].push(name);
630
+ return `'${name}': ${this.substitute(vhostConfig.headers[name])}`;
631
+ })
632
+ .join(',');
633
+ vm.runInContext(`fg = function(session) {return {${sub}}}`, this.safe[vhost]);
634
+ // @ts-ignore; fg is defined now
635
+ this.tsv.forgeHeaders[vhost] = this.safe[vhost].fg;
636
+ }
637
+ this.tsv.lastVhostUpdate[vhost] = Date.now() / 1000;
638
+ resolve(true);
639
+ }
640
+ catch (e) {
641
+ reject('Unable to getremote config: ' + e);
642
+ }
643
+ });
644
+ req.on('error', (e) => {
645
+ reject(e);
646
+ });
647
+ req.end();
648
+ });
649
+ });
650
+ }
651
+ }
652
+
653
+ class LemonldapNGHandlerServiceToken extends LemonldapNGHandler {
654
+ fetchId(req) {
655
+ // @ts-ignore: node-fastcgi has no ts declarations
656
+ const token = req.cgiParams
657
+ ? // @ts-ignore: node-fastcgi has no ts declarations
658
+ req.cgiParams.HTTP_X_LLNG_TOKEN
659
+ : req.headers['x-llng-token'];
660
+ if (token) {
661
+ // Decrypt token
662
+ // Format: encrypt(time:_session_id:vhost1:vhost2,...)
663
+ let tokenElement;
664
+ try {
665
+ tokenElement = this.tsv.cipher.decrypt(token).split(':');
666
+ }
667
+ catch (e) {
668
+ this.userLogger.error('Invalid token');
669
+ return '';
670
+ }
671
+ // At least one vhost is required
672
+ if (!tokenElement[2]) {
673
+ this.userLogger.error('Bad service token');
674
+ return '';
675
+ }
676
+ // Is token in good interval ? [ now - 30s, now ]
677
+ const now = Date.now() / 1000;
678
+ const tokenTime = parseInt(tokenElement[0]);
679
+ if (tokenTime < now - 30 || tokenTime > now) {
680
+ this.userLogger.warn('Expired service token');
681
+ return '';
682
+ }
683
+ // Is vhost listed in token ?
684
+ const vhost = this.resolveAlias(req);
685
+ if (tokenElement.indexOf(vhost) < 2) {
686
+ console.warn(`${vhost} not authorizated in token`);
687
+ return '';
688
+ }
689
+ // Then use token sessionId
690
+ return tokenElement[1];
691
+ }
692
+ return super.fetchId(req);
693
+ }
694
+ }
695
+
696
+ class LemonldapNGHandlerDevOpsST extends LemonldapNGHandlerDevOps {
697
+ fetchId(req) {
698
+ return LemonldapNGHandlerServiceToken.prototype.fetchId.call(this, req);
699
+ }
700
+ }
701
+
702
+ let currentHandler;
703
+ let currentClass;
704
+ const knownHandlers = {
705
+ Main: LemonldapNGHandler,
706
+ DevOps: LemonldapNGHandlerDevOps,
707
+ ServiceToken: LemonldapNGHandlerServiceToken,
708
+ ServiceTokenST: LemonldapNGHandlerDevOpsST
709
+ };
710
+ const init = (args) => {
711
+ return new Promise((resolve, reject) => {
712
+ if (!args.type)
713
+ args.type = 'Main';
714
+ // @ts-ignore: args.type is defined now
715
+ if (knownHandlers[args.type]) {
716
+ // @ts-ignore
717
+ currentClass = knownHandlers[args.type];
718
+ // @ts-ignore
719
+ currentHandler = new knownHandlers[args.type](args);
720
+ currentHandler
721
+ .init()
722
+ .then(() => resolve(currentHandler))
723
+ .catch(e => reject(e));
724
+ }
725
+ else {
726
+ import('@lemonldap-ng/handler-' + args.type.toLowerCase())
727
+ .then(mod => {
728
+ currentClass = mod.default;
729
+ currentHandler = new currentClass(args);
730
+ currentHandler.init().then(() => resolve(currentHandler));
731
+ })
732
+ .catch(e => reject(e));
733
+ }
734
+ });
735
+ };
736
+ const run = (req, res, next) => {
737
+ return currentHandler.run(req, res, next);
738
+ };
739
+ const nginxServer = (args) => {
740
+ currentHandler.nginxServer(args);
741
+ };
742
+
743
+ export { currentClass as class, init, nginxServer, run };
744
+ //# sourceMappingURL=index.mjs.map