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