lemonldap-ng-handler 0.10.0 → 0.10.2
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 +27 -0
- package/lib/canonicalUri.d.mts +42 -0
- package/lib/canonicalUri.d.ts +42 -0
- package/lib/handlerMain.d.mts +1 -1
- package/lib/handlerMain.d.ts +1 -1
- package/lib/index.js +1 -1
- package/lib/index.js.map +1 -1
- package/lib/index.mjs +270 -55
- package/lib/index.mjs.map +1 -1
- package/package.json +3 -4
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,32 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.10.2
|
|
4
|
+
|
|
5
|
+
- handler: a user refused by the `default` location rule is answered 403
|
|
6
|
+
instead of 503 (the refusal was rejected as an error, see
|
|
7
|
+
[ldap-rest#855](https://github.com/linagora/ldap-rest/issues/855))
|
|
8
|
+
|
|
9
|
+
## 0.10.1
|
|
10
|
+
|
|
11
|
+
- handler: **security** — rules are matched against a canonical request URI
|
|
12
|
+
(port of `Lemonldap::NG::Handler::Main::canonicalUri()`): decoded until stable
|
|
13
|
+
(`%2f`, `%252f`), duplicate slashes removed, query string kept. This completes
|
|
14
|
+
the CVE-2020-24660 fix (see
|
|
15
|
+
[GHSA-74vj-gq94-gp9r](https://github.com/LemonLDAPNG/lemonldap-ng.js/security/advisories/GHSA-74vj-gq94-gp9r))
|
|
16
|
+
- handler: **security** — a raw or decoded `.`/`..` segment is refused (400) and
|
|
17
|
+
rules are matched case-insensitively (`(?-i:...)` opts out): Node.js routers
|
|
18
|
+
do not normalize dot segments and may ignore case
|
|
19
|
+
- handler: **security** — a rule is tried on path and query, then on the path
|
|
20
|
+
alone (`^/admin$` applies to `/admin?x=1`); a decoded `%3f` stays encoded
|
|
21
|
+
- handler: **security** — the `Host` header is validated (400) and normalized
|
|
22
|
+
(port, IPv6 brackets, trailing dot, case) to resolve the virtual host,
|
|
23
|
+
maintenance mode and HTTPS; configuration keys are normalized the same way
|
|
24
|
+
- handler: redirections use the requested URI, and the portal `url` parameter is
|
|
25
|
+
its base64; the URI is escaped in logs
|
|
26
|
+
- safelib: `hostname()` normalizes the Host header like the handler
|
|
27
|
+
- handler: `normalize-url` is dropped, the obsolete Jest tests are replaced by
|
|
28
|
+
Vitest tests
|
|
29
|
+
|
|
3
30
|
## 0.10.0
|
|
4
31
|
|
|
5
32
|
- All packages: ship `.d.mts` declarations and declare per-condition
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Canonical form of an URI, as web servers do before routing requests to
|
|
3
|
+
* applications: the path is percent-decoded and normalized (duplicate slashes
|
|
4
|
+
* removed). The query string is left untouched since some rules contain GET
|
|
5
|
+
* parameters.
|
|
6
|
+
*
|
|
7
|
+
* This is a port of Lemonldap::NG::Handler::Main::canonicalUri(), with
|
|
8
|
+
* intentional differences for Node.js:
|
|
9
|
+
*
|
|
10
|
+
* - the path is decoded until it is stable, because an application or its
|
|
11
|
+
* framework may decode it more than once ("%252f");
|
|
12
|
+
* - a path containing "." or ".." segments, in its raw or decoded form, is
|
|
13
|
+
* rejected: Node.js routers (Express, Fastify, ...) do not normalize dot
|
|
14
|
+
* segments, so removing them here would make the handler decide on a path
|
|
15
|
+
* the application does not serve ("/admin/..%2Fpublic" would be seen as
|
|
16
|
+
* "/public" by the handler but routed under "/admin" by Express).
|
|
17
|
+
*
|
|
18
|
+
* Location rules must be matched against the path the protected application
|
|
19
|
+
* will serve, otherwise they can be bypassed with an encoded URL: the
|
|
20
|
+
* canonicalization used for CVE-2020-24660 did not decode "%2f", so a deny
|
|
21
|
+
* rule on "/admin/secret" missed "/admin%2fsecret".
|
|
22
|
+
*/
|
|
23
|
+
/**
|
|
24
|
+
* Raised when the request URI can not be matched safely against location rules.
|
|
25
|
+
*/
|
|
26
|
+
export declare class InvalidUriError extends Error {
|
|
27
|
+
readonly uri: string;
|
|
28
|
+
constructor(uri: string);
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Request URI as sent by the client, restricted to its path and query: it
|
|
32
|
+
* identifies the resource for redirections, unlike the canonical URI that is
|
|
33
|
+
* only meant to be matched against rules.
|
|
34
|
+
*/
|
|
35
|
+
export declare function rawRequestUri(uri?: string | null): string;
|
|
36
|
+
/**
|
|
37
|
+
* @param uri URI to canonicalize
|
|
38
|
+
* @returns canonical URI
|
|
39
|
+
* @throws InvalidUriError if the URI can not be matched safely
|
|
40
|
+
*/
|
|
41
|
+
export declare function canonicalUri(uri?: string | null): string;
|
|
42
|
+
export default canonicalUri;
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Canonical form of an URI, as web servers do before routing requests to
|
|
3
|
+
* applications: the path is percent-decoded and normalized (duplicate slashes
|
|
4
|
+
* removed). The query string is left untouched since some rules contain GET
|
|
5
|
+
* parameters.
|
|
6
|
+
*
|
|
7
|
+
* This is a port of Lemonldap::NG::Handler::Main::canonicalUri(), with
|
|
8
|
+
* intentional differences for Node.js:
|
|
9
|
+
*
|
|
10
|
+
* - the path is decoded until it is stable, because an application or its
|
|
11
|
+
* framework may decode it more than once ("%252f");
|
|
12
|
+
* - a path containing "." or ".." segments, in its raw or decoded form, is
|
|
13
|
+
* rejected: Node.js routers (Express, Fastify, ...) do not normalize dot
|
|
14
|
+
* segments, so removing them here would make the handler decide on a path
|
|
15
|
+
* the application does not serve ("/admin/..%2Fpublic" would be seen as
|
|
16
|
+
* "/public" by the handler but routed under "/admin" by Express).
|
|
17
|
+
*
|
|
18
|
+
* Location rules must be matched against the path the protected application
|
|
19
|
+
* will serve, otherwise they can be bypassed with an encoded URL: the
|
|
20
|
+
* canonicalization used for CVE-2020-24660 did not decode "%2f", so a deny
|
|
21
|
+
* rule on "/admin/secret" missed "/admin%2fsecret".
|
|
22
|
+
*/
|
|
23
|
+
/**
|
|
24
|
+
* Raised when the request URI can not be matched safely against location rules.
|
|
25
|
+
*/
|
|
26
|
+
export declare class InvalidUriError extends Error {
|
|
27
|
+
readonly uri: string;
|
|
28
|
+
constructor(uri: string);
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Request URI as sent by the client, restricted to its path and query: it
|
|
32
|
+
* identifies the resource for redirections, unlike the canonical URI that is
|
|
33
|
+
* only meant to be matched against rules.
|
|
34
|
+
*/
|
|
35
|
+
export declare function rawRequestUri(uri?: string | null): string;
|
|
36
|
+
/**
|
|
37
|
+
* @param uri URI to canonicalize
|
|
38
|
+
* @returns canonical URI
|
|
39
|
+
* @throws InvalidUriError if the URI can not be matched safely
|
|
40
|
+
*/
|
|
41
|
+
export declare function canonicalUri(uri?: string | null): string;
|
|
42
|
+
export default canonicalUri;
|
package/lib/handlerMain.d.mts
CHANGED
|
@@ -16,7 +16,7 @@ declare class LemonldapNGHandler extends HandlerInit {
|
|
|
16
16
|
* run(), the access control function
|
|
17
17
|
*/
|
|
18
18
|
run(req: express.Request | http.IncomingMessage, res: http.ServerResponse, next: Function): any;
|
|
19
|
-
selfUri(vhost: string, uri: string): string;
|
|
19
|
+
selfUri(vhost: string, uri: string, host?: string): string;
|
|
20
20
|
nginxServer(fcgiOpt: FastCGI_Opts): void;
|
|
21
21
|
setError(res: http.ServerResponse, uri: string, code: number, txt: string): void;
|
|
22
22
|
isUnprotected(req: express.Request | http.IncomingMessage, uri: string): number | false;
|
package/lib/handlerMain.d.ts
CHANGED
|
@@ -16,7 +16,7 @@ declare class LemonldapNGHandler extends HandlerInit {
|
|
|
16
16
|
* run(), the access control function
|
|
17
17
|
*/
|
|
18
18
|
run(req: express.Request | http.IncomingMessage, res: http.ServerResponse, next: Function): any;
|
|
19
|
-
selfUri(vhost: string, uri: string): string;
|
|
19
|
+
selfUri(vhost: string, uri: string, host?: string): string;
|
|
20
20
|
nginxServer(fcgiOpt: FastCGI_Opts): void;
|
|
21
21
|
setError(res: http.ServerResponse, uri: string, code: number, txt: string): void;
|
|
22
22
|
isUnprotected(req: express.Request | http.IncomingMessage, uri: string): number | false;
|
package/lib/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var e=require("@lemonldap-ng/conf"),t=require("@lemonldap-ng/session"),s=require("@lemonldap-ng/safelib"),o=require("@lemonldap-ng/logger"),i=require("vm"),r=require("crypto"),n=require("re2"),a=require("http");function c(e,t,s,o){return new(s||(s=Promise))(function(i,r){function n(e){try{c(o.next(e))}catch(e){r(e)}}function a(e){try{c(o.throw(e))}catch(e){r(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof s?t:new s(function(e){e(t)})).then(n,a)}c((o=o.apply(e,t||[])).next())})}"function"==typeof SuppressedError&&SuppressedError;const h=new n("^logout(?:_sso|_app|_app_sso|)(?:s+(.*))?$","i");let l=0;const u=["cda","cookieExpiration","cipher","cookieName","customFunctions","httpOnly","securedCookie","timeout","timeoutActivity","useRedirectOnError","useRedirectOnForbidden","whatToTrace","loopBackUrl","handlerInternalCache","authChoiceAuthBasic","authChoiceParam"],d="llng-events",g="llng-status";class p{constructor(t){this.safe={},this.eventLoopInterval=null,this.lastConfigCheck=0,this.tsv={defaultCondition:{},defaultProtection:{},forgeHeaders:{},headerList:{},https:{},locationCondition:{},locationCount:{},locationProtection:{},locationRegexp:{},maintenance:{},port:{},portal:()=>"",vhostAlias:{},eventQueueName:d,statusQueueName:g,checkMsg:0,checkTime:600},this.localConf=t,t.configStorage||(t.configStorage={}),t.configStorage.localStorage||(t.configStorage.localStorage=t.localStorage),t.configStorage.localStorageOptions||(t.configStorage.localStorageOptions=t.localStorageOptions),this.confAcc=new e(t.configStorage);if([this.confAcc.getLocalConf("handler",!0),this.confAcc.getLocalConf("node-handler",!1)].forEach(e=>{Object.keys(e).forEach(t=>{if(!this.localConf)throw new Error("undef");void 0===this.localConf[t]&&(this.localConf[t]=e[t])})}),void 0===this.localConf.nodeVhosts)throw new Error("No Virtualhosts configured for Node.js");this.vhostList=this.localConf.nodeVhosts.split(/[,\s]+/)}reload(){return new Promise((e,a)=>{this.confAcc.ready.then(()=>{this.confAcc.getConf({}).then(a=>{if(u.forEach(e=>{this.tsv[e]=a[e]}),a.key&&(this.tsv.keyH=r.createHash("sha256").update(a.key).digest("hex")),Object.keys(this.localConf).forEach(e=>{a[e]=this.localConf[e]}),["https","port","maintenance"].forEach(e=>{if(void 0!==a[e]&&(this.tsv[e]={_:a[e]},a.vhostOptions)){const s=`vhost${t=e,t.charAt(0).toUpperCase()+t.slice(1)}`;Object.keys(a.vhostOptions).forEach(t=>{const o=a.vhostOptions[t][s];o>0&&(this.tsv[e][t]=o)})}var t}),!a.portal)throw new Error("portal should be defined");if(this.tsv.portal=()=>a.portal,!a.globalStorage||!a.globalStorageOptions)throw new Error("Missing session storage configuration");this.tsv.sessionStorageModule=a.globalStorage,this.tsv.sessionStorageOptions=a.globalStorageOptions;try{this.sessionAcc=new t({storageModule:a.globalStorage,storageModuleOptions:a.globalStorageOptions})}catch(e){throw new Error(`Unable to load session module: ${e}`,{cause:e})}a.oidcStorage?(this.tsv.oidcStorageModule=a.oidcStorage,this.tsv.oidcStorageOptions=a.oidcStorageOptions||{}):(this.tsv.oidcStorageModule=a.globalStorage,this.tsv.oidcStorageOptions=a.globalStorageOptions),this.tsv.oauth2Options={},Object.keys(a.oidcRPMetaDataOptions||{}).forEach(e=>{var t;const s=null===(t=a.oidcRPMetaDataOptions[e])||void 0===t?void 0:t.oidcRPMetaDataOptionsClientID;s&&(this.tsv.oauth2Options[e]={clientId:s})}),Object.keys(a.locationRules).forEach(e=>{if(-1==this.vhostList.indexOf(e))return;this.tsv.locationCount[e]=0,["locationRegexp","locationProtection","locationCondition"].forEach(t=>{void 0===this.tsv[t][e]&&(this.tsv[t][e]=[])}),this.safe[e]||(this.safe[e]=new s(a));const t=a.locationRules[e];Object.keys(t).forEach(s=>{const[o,i]=this.conditionSub(t[s],this.safe[e]);"default"===s?(this.tsv.defaultCondition[e]=o,this.tsv.defaultProtection[e]=i):(this.tsv.locationCondition[e].push(o),this.tsv.locationProtection[e].push(i),this.tsv.locationRegexp[e].push(new n(s.replace(/\(\?#.*?\)/g,""))),this.tsv.locationCount[e]++)}),this.tsv.defaultCondition[e]||(this.tsv.defaultCondition[e]=()=>!0,this.tsv.defaultProtection[e]=0)}),void 0!==a.exportedHeaders&&Object.keys(a.exportedHeaders).forEach(e=>{const t=a.exportedHeaders[e];if(-1==this.vhostList.indexOf(e))return;this.tsv.headerList[e]||(this.tsv.headerList[e]=[]);let s="";Object.keys(t).forEach(o=>{this.tsv.headerList[e].push(o),s+=`'${o}': ${this.substitute(t[o])},`}),s=s.replace(/,$/,""),i.runInContext(`fg = function(session) {return {${s}};}`,this.safe[e]),this.tsv.forgeHeaders[e]=this.safe[e].fg}),void 0!==a.vhostOptions&&Object.keys(a.vhostOptions).forEach(e=>{a.vhostOptions[e].aliases&&a.vhostOptions[e].aliases.forEach(t=>{this.tsv.vhostAlias[t]=e})}),this.tsv.cookieDetect=new n(`\\b${this.tsv.cookieName}=([^;]+)`),this.sessionAcc.ready.then(()=>{o(a,!0).then(t=>c(this,void 0,void 0,function*(){this.userLogger=t;(yield this.msgBrokerInit(a))||this.userLogger.info("Handler initialized without message broker (real-time events disabled)"),this.startEventLoop(),e(!0)})).catch(e=>{throw new Error(`Logger error: ${e}`)})})}).catch(e=>{a(`Unable to get configuration: ${e}`)})})})}conditionSub(e,t){const s=()=>!0;if("accept"===e)return[s,0];if("deny"===e)return[()=>!1,0];if("unprotect"===e)return[s,1];if("skip"===e)return[s,2];const o=h.exec(e);if(o&&o[1]){const e=o[1];return e?[t=>(t._logout=e,!1),0]:[e=>(e._logout=this.tsv.portal(),!1),0]}if(e=this.substitute(e),t)return l++,i.runInContext(`sub${l.toString()} = function(req,session) {return (${e});}`,t),[t[`sub${l.toString()}`],0];throw new Error("Disabling safeJail is not supported")}substitute(e){return e.replace(/\$date\b/g,"this.date()").replace(/\$vhost\b/g,"this.hostname(req)").replace(/\$ip\b/g,"this.remote_ip(req)").replace(/\$(_*[a-zA-Z]\w*)/g,"session.$1")}parseBrokerType(e){if(!e)return"nobroker";const t=e.match(/::(\w+)$/);return t?t[1].toLowerCase():e.toLowerCase()}msgBrokerInit(e){return c(this,void 0,void 0,function*(){const t=this.parseBrokerType(e.messageBroker||"nobroker"),s=e.messageBrokerOptions||{};this.tsv.eventQueueName=s.eventQueueName||d,this.tsv.statusQueueName=s.statusQueueName||g,this.tsv.checkTime=s.checkTime||600;const o=`@lemonldap-ng/message-broker-${t.toLowerCase()}`;try{const e=(yield import(o)).default;return this.tsv.msgBrokerReader=new e(s,this.userLogger),this.tsv.msgBrokerWriter=new e(s,this.userLogger),!!this.tsv.msgBrokerReader&&(yield this.tsv.msgBrokerReader.subscribe(this.tsv.eventQueueName),this.userLogger.debug(`Message broker ${t} initialized, subscribed to ${this.tsv.eventQueueName}`),!0)}catch(e){this.userLogger.warn(`Failed to load message broker ${o}: ${e}. Using NoBroker fallback.`);try{const e=(yield Promise.resolve().then(function(){return require("./index-DXlSn3sb.js")})).default;return this.tsv.msgBrokerReader=new e({},this.userLogger),this.tsv.msgBrokerWriter=new e({},this.userLogger),!1}catch(e){return this.userLogger.debug("No message broker available"),!1}}})}startEventLoop(){if(this.eventLoopInterval)return;const e=Math.max(1e3,1e3*(this.tsv.checkTime||600));this.eventLoopInterval=setInterval(()=>c(this,void 0,void 0,function*(){try{yield this.checkEvents()}catch(e){this.userLogger.error(`Event loop error: ${e}`)}}),e),this.userLogger.debug(`Event loop started with ${e}ms interval`)}stopEventLoop(){return c(this,void 0,void 0,function*(){this.eventLoopInterval&&(clearInterval(this.eventLoopInterval),this.eventLoopInterval=null,this.userLogger.debug("Event loop stopped")),this.sessionAcc&&"function"==typeof this.sessionAcc.close&&(yield this.sessionAcc.close(),this.userLogger.debug("Session storage closed"))})}checkEvents(){return c(this,void 0,void 0,function*(){if(this.tsv.msgBrokerReader)try{const e=yield this.tsv.msgBrokerReader.getNextMessage(this.tsv.eventQueueName,0);e&&(this.tsv.checkMsg++,yield function(e,t){return c(this,void 0,void 0,function*(){const s=e.userLogger;switch(t.action){case"reload":s.debug("Message broker: reload configuration requested");try{return yield e.reload(),s.info("Configuration reloaded via message broker"),!0}catch(e){return s.error(`Failed to reload configuration: ${e}`),!1}case"unlog":return t.id?(s.debug(`Message broker: unlog session ${t.id}`),yield e.localUnlog(t.id),!0):(s.warn("Message broker: unlog without session id"),!1);case"newSession":return s.debug(`Message broker: new session notification (id: ${t.id})`),!0;case"delSession":return!!t.id&&(s.debug(`Message broker: session ${t.id} deleted`),yield e.localUnlog(t.id),!0);case"ping":return s.debug("Message broker: ping received"),!0;default:return s.debug(`Message broker: unknown action '${t.action}'`),!1}})}(this,e))}catch(e){this.userLogger.error(`Error checking events: ${e}`)}})}publishEvent(e){return c(this,arguments,void 0,function*(e,t={}){if(!this.tsv.msgBrokerWriter)return;const s=Object.assign({action:e,channel:this.tsv.eventQueueName},t);try{yield this.tsv.msgBrokerWriter.publish(this.tsv.eventQueueName,s),this.userLogger.debug(`Published event: ${e}`)}catch(t){this.userLogger.error(`Failed to publish event ${e}: ${t}`)}})}portal(){return this.tsv.portal()}}const f=(e,t)=>t.some(t=>t instanceof RegExp?t.test(e):t===e);function v(e,t){if(t={defaultProtocol:"http:",normalizeProtocol:!0,forceHttp:!1,forceHttps:!1,stripAuthentication:!0,stripHash:!1,stripTextFragment:!0,stripWWW:!0,removeQueryParameters:[/^utm_\w+/i],removeTrailingSlash:!0,removeSingleSlash:!0,removeDirectoryIndex:!1,removeExplicitPort:!1,sortQueryParameters:!0,...t},e=e.trim(),/^data:/i.test(e))return((e,{stripHash:t})=>{const s=/^data:(?<type>[^,]*?),(?<data>[^#]*?)(?:#(?<hash>.*))?$/.exec(e);if(!s)throw new Error(`Invalid URL: ${e}`);let{type:o,data:i,hash:r}=s.groups;const n=o.split(";");r=t?"":r;let a=!1;"base64"===n[n.length-1]&&(n.pop(),a=!0);const c=(n.shift()||"").toLowerCase(),h=[...n.map(e=>{let[t,s=""]=e.split("=").map(e=>e.trim());return"charset"===t&&(s=s.toLowerCase(),"us-ascii"===s)?"":`${t}${s?`=${s}`:""}`}).filter(Boolean)];return a&&h.push("base64"),(h.length>0||c&&"text/plain"!==c)&&h.unshift(c),`data:${h.join(";")},${a?i.trim():i}${r?`#${r}`:""}`})(e,t);if(/^view-source:/i.test(e))throw new Error("`view-source:` is not supported as it is a non-standard protocol");const s=e.startsWith("//");!s&&/^\.*\//.test(e)||(e=e.replace(/^(?!(?:\w+:)?\/\/)|^\/\//,t.defaultProtocol));const o=new URL(e);if(t.forceHttp&&t.forceHttps)throw new Error("The `forceHttp` and `forceHttps` options cannot be used together");if(t.forceHttp&&"https:"===o.protocol&&(o.protocol="http:"),t.forceHttps&&"http:"===o.protocol&&(o.protocol="https:"),t.stripAuthentication&&(o.username="",o.password=""),t.stripHash?o.hash="":t.stripTextFragment&&(o.hash=o.hash.replace(/#?:~:text.*?$/i,"")),o.pathname){const e=/\b[a-z][a-z\d+\-.]{1,50}:\/\//g;let t=0,s="";for(;;){const i=e.exec(o.pathname);if(!i)break;const r=i[0],n=i.index;s+=o.pathname.slice(t,n).replace(/\/{2,}/g,"/"),s+=r,t=n+r.length}s+=o.pathname.slice(t,o.pathname.length).replace(/\/{2,}/g,"/"),o.pathname=s}if(o.pathname)try{o.pathname=decodeURI(o.pathname)}catch{}if(!0===t.removeDirectoryIndex&&(t.removeDirectoryIndex=[/^index\.[a-z]+$/]),Array.isArray(t.removeDirectoryIndex)&&t.removeDirectoryIndex.length>0){let e=o.pathname.split("/");const s=e[e.length-1];f(s,t.removeDirectoryIndex)&&(e=e.slice(0,-1),o.pathname=e.slice(1).join("/")+"/")}if(o.hostname&&(o.hostname=o.hostname.replace(/\.$/,""),t.stripWWW&&/^www\.(?!www\.)[a-z\-\d]{1,63}\.[a-z.\-\d]{2,63}$/.test(o.hostname)&&(o.hostname=o.hostname.replace(/^www\./,""))),Array.isArray(t.removeQueryParameters))for(const e of[...o.searchParams.keys()])f(e,t.removeQueryParameters)&&o.searchParams.delete(e);if(Array.isArray(t.keepQueryParameters)||!0!==t.removeQueryParameters||(o.search=""),Array.isArray(t.keepQueryParameters)&&t.keepQueryParameters.length>0)for(const e of[...o.searchParams.keys()])f(e,t.keepQueryParameters)||o.searchParams.delete(e);if(t.sortQueryParameters){o.searchParams.sort();try{o.search=decodeURIComponent(o.search)}catch{}}t.removeTrailingSlash&&(o.pathname=o.pathname.replace(/\/$/,"")),t.removeExplicitPort&&o.port&&(o.port="");const i=e;return e=o.toString(),t.removeSingleSlash||"/"!==o.pathname||i.endsWith("/")||""!==o.hash||(e=e.replace(/\/$/,"")),(t.removeTrailingSlash||"/"===o.pathname)&&""===o.hash&&t.removeSingleSlash&&(e=e.replace(/\/$/,"")),s&&!t.normalizeProtocol&&(e=e.replace(/^http:\/\//,"//")),t.stripProtocol&&(e=e.replace(/^(?:https?:)?\/\//,"")),e}class m extends p{constructor(){super(...arguments),this.lastSessionId=null,this.lastSessionData=null,this.lastSessionTime=0}init(){return this.reload()}run(e,t,s){const o=e.headers.host;if(void 0===o)return this.userLogger.error("Request without Host header"),void this.setError(t,"/",400,"Bad request");const i=new URL(v(o+e.url)).pathname||"/";if(this.tsv.maintenance[o])return this.setError(t,"/",503,"Service Temporarily Unavailable");if(2===this.isUnprotected(e,i))return this.lastSessionId=null,this.lastSessionData=null,this.lastSessionTime=0,this.hideCookie(e),s();Promise.resolve(this.fetchId(e)).then(r=>{if(""===r)return this.goToPortal(t,this.selfUri(o,i));this.retrieveSession(r,e).then(r=>{const n=r[this.tsv.whatToTrace];this.userLogger.debug(`User ${n} identified`),this.grant(e,i,r).then(a=>{a?(this.sendHeaders(e,r),this.hideCookie(e),s(),this.userLogger.info(`${o}: user ${n} was granted access to ${i}`)):(this.forbidden(e,t,r),this.userLogger.notice(`${o}: user ${n} was denied access to ${i}`))}).catch(e=>{this.userLogger.error(`Authorization check failed: ${e}`),this.setError(t,"/",503,"Service Unavailable")})}).catch(e=>{this.goToPortal(t,this.selfUri(o,i))})}).catch(e=>{this.userLogger.error(`Unable to fetch session id: ${e}`),this.goToPortal(t,this.selfUri(o,i))})}selfUri(e,t){return(this.tsv.https&&this.tsv.https[e]?"https":"http")+"://"+e+t}nginxServer(e){e.mode||(e.mode="fcgi"),e.port||(e.port=9090),e.ip||(e.ip="localhost");("fcgi"===e.mode?require("node-fastcgi"):a).createServer((e,t)=>{this.run(e,t,()=>{t.writeHead(200,e.headers)})}).listen(e.port,e.ip)}setError(e,t,s,o){if(this.tsv.useRedirectOnError){const t=this.tsv.portal()+`?lmError=${s.toString()}&url=`;e.redirect?e.redirect(t):e.writeHead(401,{Location:t})}else e.redirect?e.status(s).send(o):e.writeHead(s,o)}isUnprotected(e,t){const s=this.resolveAlias(e);if(!this.tsv.defaultCondition[s])return!1;for(let e=0;e<this.tsv.locationRegexp[s].length;e++)if(this.tsv.locationRegexp[s][e].test(t))return this.tsv.locationProtection[s][e];return this.tsv.defaultProtection[s]}resolveAlias(e){var t;const s=null===(t=e.headers.host)||void 0===t?void 0:t.split(":")[0];return s?this.tsv.vhostAlias[s]||s:"undef"}fetchId(e){if(e.headers.cookie){const t=this.tsv.cookieDetect.exec(e.headers.cookie);if(t&&"0"!=t[1])return t[1]}return""}retrieveSession(e,t){return new Promise((t,s)=>{if(void 0===this.sessionAcc)return s("Server not ready, please wait");const o=Date.now()/1e3|0,i=this.tsv.handlerInternalCache||15;if(this.lastSessionId===e&&this.lastSessionData&&o-this.lastSessionTime<i)return this.userLogger.debug(`Get session ${e} from internal cache`),t(this.lastSessionData);this.lastSessionId=null,this.lastSessionData=null,this.sessionAcc.get(e).then(i=>{o-i._utime>this.tsv.timeout||this.tsv.timeoutActivity&&i._lastSeen&&o-i._lastSeen>this.tsv.timeoutActivity?s(`Session ${e} expired`):(this.tsv.timeoutActivity&&o-i._lastSeen>60&&(i._lastSeen=o,this.sessionAcc.update(i)),this.lastSessionId=e,this.lastSessionData=i,this.lastSessionTime=o,t(i))}).catch(t=>{s(`Session ${e} can't be found in store: ${t}`)})})}localUnlog(e){return c(this,void 0,void 0,function*(){this.userLogger.debug("Local handler logout");const t=e||this.lastSessionId;this.lastSessionId=null,this.lastSessionData=null,this.lastSessionTime=0,t&&this.sessionAcc&&(this.sessionAcc.clearMemoryCache(t),yield this.sessionAcc.clearLocalCache(t))})}grant(e,t,s){return new Promise((o,i)=>{const r=this.resolveAlias(e);if(!Object.prototype.hasOwnProperty.call(this.tsv.defaultCondition,r))return i(`No configuration found for ${r} (or not listed in Node.js virtualHosts)`);if(this.tsv.locationRegexp[r])for(let i=0;i<this.tsv.locationRegexp[r].length;i++){if(this.tsv.locationRegexp[r][i].test(t))return o(this.tsv.locationCondition[r][i](e,s))}this.tsv.defaultCondition[r](e,s)?o(!0):i("Unauthorized")})}sendHeaders(e,t){const s=this.resolveAlias(e);try{let o=0;e.headers["Lm-Remote-User"]=t[this.tsv.whatToTrace];const i=this.tsv.forgeHeaders[s](t);Object.keys(i).forEach(t=>{o++,e.headers[t]=i[t],e.rawHeaders.push(t,i[t]),e.redirect||(e.headers[`Headername${o}`]=t,e.headers[`Headervalue${o}`]=i[t])})}catch(e){return void this.userLogger.error(`Headers maybe not sent: ${e}`)}}hideCookie(e){e.headers.cookie&&(e.headers.cookie=e.headers.cookie.replace(this.tsv.cookieDetect,""))}forbidden(e,t,s){this.localUnlog(s._session_id).catch(e=>{this.userLogger.error(`Failed to clear local cache: ${e}`)}),s._logout?this.goToPortal(t,s._logout,"logout=1"):this.setError(t,"/",403,"Forbidden")}goToPortal(e,t,s=""){if("function"!=typeof this.tsv.portal)return void this.setError(e,t,503,"Waiting for configuration");const o=this.tsv.portal()+(t?"?url="+new Buffer.from(encodeURI(t)).toString("base64"):"")+(s?(t?"&":"?")+s:"");e.redirect?e.redirect(o):e.writeHead(401,{Location:o})}}class k extends m{constructor(e){super(e),this.tsv.lastVhostUpdate={}}grant(e,t,s){const o=this.resolveAlias(e);if(this.tsv.defaultCondition[o]&&Date.now()/1e3-this.tsv.lastVhostUpdate[o]<600)return super.grant(e,t,s);const i=e.cgiParams&&e.cgiParams.RULES_URL?e.cgiParams.RULES_URL:(this.tsv.loopBackUrl||"http://127.0.0.1")+"/rules.json";if(!/^(https?):\/\/([^/:]+)(?::(\d+))?(.*)$/.test(i))return new Promise((e,t)=>t(`Bad loopBackUrl ${i}`));const r={prot:RegExp.$1,host:RegExp.$2,path:RegExp.$4,port:RegExp.$3||("https"==RegExp.$1?"443":"80"),lb:!(e.cgiParams&&e.cgiParams.RULES_URL)};return new Promise((i,n)=>{this.loadVhostConfig(e,o,r).then(()=>{this.grant(e,t,s).then(e=>{i(e)}).catch(e=>n(e))}).catch(o=>{this.userLogger.error(`Session retrieval error: ${o}`),this.grant(e,t,s).then(e=>{i(e)}).catch(e=>n(e))})})}loadVhostConfig(e,t,o){return new Promise((e,r)=>{o.lb||(t=o.host),delete o.lb,o.headers={Host:t};const a=require(o.prot);delete o.prot;const c=a.request(o,o=>{let a="";o.on("data",e=>{a+=e}),o.on("end",()=>{if(this.tsv.locationCondition[t]=[],this.tsv.locationProtection[t]=[],this.tsv.locationRegexp[t]=[],this.tsv.locationCount[t]=0,this.tsv.headerList[t]=[],""===a)return this.tsv.defaultCondition[t]=()=>!0,this.tsv.defaultProtection[t]=0,this.tsv.lastVhostUpdate[t]=Date.now()/1e3,e(!0);try{const o=JSON.parse(a);if(this.safe[t]=new s({cipher:this.tsv.cipher}),o.rules&&"object"==typeof o.rules&&(Object.keys(o.rules).forEach(e=>{const s=new String(o.rules[e]).valueOf(),[i,r]=this.conditionSub(s,this.safe[t]);"default"===e?(this.tsv.defaultCondition[t]=i,this.tsv.defaultProtection[t]=r):(this.tsv.locationCondition[t].push(i),this.tsv.locationProtection[t].push(r),this.tsv.locationRegexp[t].push(new n(e.replace(/\(\?#.*?\)/g,""))),this.tsv.locationCount[t]++)}),this.tsv.defaultCondition[t]||(this.tsv.defaultCondition[t]=()=>!0,this.tsv.defaultProtection[t]=0)),o.headers&&"object"==typeof o.headers){const e=Object.keys(o.headers).map(e=>(this.tsv.headerList[t].push(e),`'${e}': ${this.substitute(o.headers[e])}`)).join(",");i.runInContext(`fg = function(session) {return {${e}}}`,this.safe[t]),this.tsv.forgeHeaders[t]=this.safe[t].fg}this.tsv.lastVhostUpdate[t]=Date.now()/1e3,e(!0)}catch(e){r("Unable to getremote config: "+e)}}),c.on("error",e=>{r(e)}),c.end()})})}}class b extends m{fetchId(e){const t=e.cgiParams?e.cgiParams.HTTP_X_LLNG_TOKEN:e.headers["x-llng-token"];if(t){let s;try{s=this.tsv.cipher.decrypt(t).split(":")}catch(e){return this.userLogger.error("Invalid token"),""}if(!s[2])return this.userLogger.error("Bad service token"),"";const o=Date.now()/1e3,i=parseInt(s[0]);if(i<o-30||i>o)return this.userLogger.warn("Expired service token"),"";const r=this.resolveAlias(e);return s.indexOf(r)<2?(this.userLogger.warn(`${r} not authorizated in token`),""):s[1]}return super.fetchId(e)}}function w(e,t){const s=e.split(".");if(s.length<2)return null;if(t>=s.length)return null;try{const e=function(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");for(;t.length%4;)t+="=";return Buffer.from(t,"base64").toString("utf8")}(s[t]);return JSON.parse(e)}catch(e){return null}}function S(e){if(e.indexOf(".")>0){const t=w(e,1);return t&&"string"==typeof t.jti&&""!==t.jti?t.jti:null}return e}const y="O-",$=/^[A-Za-z0-9_-]+$/;function L(e,t,s=120){try{const o=e.decrypt(t).split(":");if(o.length<2)return null;const i=o[0],r=parseInt(o[1],10);if(!i||isNaN(r))return null;const n=Math.floor(Date.now()/1e3);return n-r>s||r>n+10?null:{sessionId:i,timestamp:r,domain:o[2]}}catch(e){return null}}let A;exports.class=void 0;const C={Main:m,DevOps:k,ServiceToken:b,ServiceTokenST:class extends k{fetchId(e){return b.prototype.fetchId.call(this,e)}},OAuth2:class extends m{constructor(){super(...arguments),this.ownOidcSessionAcc=!1,this.state=new WeakMap}reload(){const e=Object.create(null,{reload:{get:()=>super.reload}});return c(this,void 0,void 0,function*(){const t=yield e.reload.call(this);return yield this.initOidcSessionStorage(),t})}initOidcSessionStorage(){return c(this,void 0,void 0,function*(){const e=this.tsv.oidcStorageModule;if(!e)throw new Error("OAuth2 handler requires a session storage");let s,o;if(e===this.tsv.sessionStorageModule&&JSON.stringify(this.tsv.oidcStorageOptions||{})===JSON.stringify(this.tsv.sessionStorageOptions||{}))this.userLogger.debug("OAuth2 handler shares the main session storage"),s=this.sessionAcc,o=!1;else{try{s=new t({storageModule:e,storageModuleOptions:this.tsv.oidcStorageOptions||{}}),yield s.ready}catch(e){throw new Error(`Unable to load OIDC session module: ${e}`,{cause:e})}o=!0,this.userLogger.debug("OAuth2 OIDC session storage initialized")}const i=this.ownOidcSessionAcc?this.oidcSessionAcc:void 0;this.oidcSessionAcc=s,this.ownOidcSessionAcc=o,i&&i!==s&&(yield i.close())})}localUnlog(e){const t=Object.create(null,{localUnlog:{get:()=>super.localUnlog}});return c(this,void 0,void 0,function*(){const s=e||this.lastSessionId;yield t.localUnlog.call(this,e),s&&this.ownOidcSessionAcc&&this.oidcSessionAcc&&(yield this.oidcSessionAcc.clearAllCaches(s))})}run(e,t,s){const o={};return this.state.set(e,o),this.state.set(t,o),super.run(e,t,s)}fetchId(e){const t=Object.create(null,{fetchId:{get:()=>super.fetchId}});return c(this,void 0,void 0,function*(){const s=e.headers.authorization;if(!s||!/^bearer\s/i.test(s))return t.fetchId.call(this,e);const o=s.replace(/^bearer\s+/i,"").trim();if(!o)return this.userLogger.info("OAuth2: empty Bearer token"),this.fallbackToCookie(e);const i=S(o);if(!i)return this.invalidToken(e,"No session id found in access token");if(!this.isSessionId(i))return this.invalidToken(e,"Malformed access token session id");const r=yield this.getOIDCInfos(i);if("invalid"===r.status)return this.invalidToken(e,"Access token session is not usable");if("notFound"===r.status)return this.userLogger.info(`Unknown access token session ${i}`),this.fallbackToCookie(e);const n=r.data,a=n.rp?this.tokenAttributes(o,n):void 0;if(n.user_session_id){if(!this.isSessionId(n.user_session_id))return this.invalidToken(e,`Malformed user_session_id in access token session ${i}`);const t=this.stateFor(e);return t.viaToken=!0,t.attrs=a,this.userLogger.debug(`OAuth2: get user session ${n.user_session_id}`),n.user_session_id}if(n.offline_session_id){if(!this.isSessionId(n.offline_session_id))return this.invalidToken(e,`Malformed offline_session_id in access token session ${i}`);const t=this.stateFor(e);return t.viaToken=!0,t.attrs=a,this.userLogger.debug(`OAuth2: get offline session ${n.offline_session_id}`),`${y}${n.offline_session_id}`}return this.userLogger.warn(`Access token session ${i} references no session`),this.fallbackToCookie(e)})}retrieveSession(e,t){var s;const o=t?null===(s=this.state.get(t))||void 0===s?void 0:s.attrs:void 0;if(!e.startsWith(y))return super.retrieveSession(e,t).then(e=>this.withTokenAttributes(e,o),e=>{var s;throw t&&(null===(s=this.state.get(t))||void 0===s?void 0:s.viaToken)&&(this.stateFor(t).error="invalid_token"),e});const i=e.substring(2);return this.getOIDCInfos(i).then(e=>{if("ok"!==e.status)throw t&&(this.stateFor(t).error="invalid_token"),`Offline session ${i} can not be retrieved`;return this.withTokenAttributes(e.data,o)},e=>{throw t&&(this.stateFor(t).error="invalid_token"),e})}hideCookie(e){e.headers.authorization&&(this.userLogger.debug("OAuth2: removing Authorization header"),delete e.headers.authorization),super.hideCookie(e)}goToPortal(e,t,s=""){var o;const i=null===(o=this.state.get(e))||void 0===o?void 0:o.error;e.setHeader("WWW-Authenticate","Bearer"+(i?` error="${i}"`:"")),e.status?e.status(401).send("Unauthorized"):e.writeHead(401,"Unauthorized")}stopEventLoop(){const e=Object.create(null,{stopEventLoop:{get:()=>super.stopEventLoop}});return c(this,void 0,void 0,function*(){yield e.stopEventLoop.call(this),this.ownOidcSessionAcc&&this.oidcSessionAcc&&(yield this.oidcSessionAcc.close(),this.userLogger.debug("OIDC session storage closed"))})}getOIDCInfos(e){return void 0===this.oidcSessionAcc?Promise.resolve({status:"invalid"}):this.oidcSessionAcc.get(e).then(t=>{const s=Number(t._utime);if(!t._utime||!Number.isFinite(s))return this.userLogger.error(`_utime missing from OIDC session ${e}`),{status:"invalid"};return(Date.now()/1e3|0)-s>this.tsv.timeout?(this.userLogger.info(`OIDC session ${e} expired`),{status:"invalid"}):(this.userLogger.debug(`Get OIDC session ${e}`),{status:"ok",data:t})},t=>(this.userLogger.info(`OIDC session ${e} can not be retrieved: ${t}`),{status:"notFound"}))}tokenAttributes(e,t){var s,o;const i={_accessToken:e,_clientConfKey:t.rp};void 0!==t.scope&&(i._scope=t.scope),void 0!==t.grant_type&&(i._oidc_grant_type=t.grant_type),void 0!==t.aud&&(i._audiences=t.aud);const r=null===(o=null===(s=this.tsv.oauth2Options)||void 0===s?void 0:s[t.rp])||void 0===o?void 0:o.clientId;return r&&(i._clientId=r),i}withTokenAttributes(e,t){return t?Object.assign(Object.assign({},e),t):e}isSessionId(e){return"string"==typeof e&&$.test(e)}stateFor(e){let t=this.state.get(e);return t||(t={},this.state.set(e,t)),t}invalidToken(e,t){return this.userLogger.warn(`OAuth2: ${t}`),this.stateFor(e).error="invalid_token",""}fallbackToCookie(e){const t=Object.create(null,{fetchId:{get:()=>super.fetchId}});return c(this,void 0,void 0,function*(){const s=yield t.fetchId.call(this,e);return""===s&&(this.stateFor(e).error="invalid_token"),s})}},AuthBasic:class extends m{constructor(){super(...arguments),this.pendingAuth=new Map}fetchId(e){var t;const s=e.headers.authorization;if(s&&s.toLowerCase().startsWith("basic ")){const o=s.substring(6).trim();if(o){const s=Math.floor(Date.now()/1e3/this.tsv.timeout)+(this.tsv.keyH||""),i=r.createHash("sha256").update(o+s).digest("hex");try{const s=Buffer.from(o,"base64").toString("utf-8"),r=s.indexOf(":");if(r>0){const o=s.substring(0,r),n=s.substring(r+1),a=e.headers["x-forwarded-for"],c=e.ip||(null===(t=e.socket)||void 0===t?void 0:t.remoteAddress)||"",h=a?`${a}, ${c}`:c;this.pendingAuth.set(i,{username:o,password:n,xff:h})}}catch(e){}return this.userLogger.debug("AuthBasic: computed session ID for credentials"),i}}return super.fetchId(e)}retrieveSession(e){const t=Object.create(null,{retrieveSession:{get:()=>super.retrieveSession}});return new Promise((s,o)=>{t.retrieveSession.call(this,e).then(t=>{this.pendingAuth.delete(e),s(t)}).catch(()=>c(this,void 0,void 0,function*(){const i=this.pendingAuth.get(e);if(!i)return void o("No session and no pending authentication");this.pendingAuth.delete(e);(yield this.createSession(e,i.username,i.password,i.xff))?t.retrieveSession.call(this,e).then(s).catch(o):o("Authentication failed")}))})}createSession(e,t,s,o){return c(this,void 0,void 0,function*(){var i;if(!/^[a-fA-F0-9]{1,64}$/.test(e))return this.userLogger.error(`AuthBasic: Invalid session ID format: ${e}`),!1;const r=this.tsv.portal();if(!r)return this.userLogger.error("AuthBasic: portal URL not configured"),!1;let n=`${r}/sessions/global/${e}?auth`;n=n.replace(/\/\/sessions\//,"/sessions/");const a={user:t,password:s,secret:(null===(i=this.tsv.cipher)||void 0===i?void 0:i.encrypt(Date.now().toString()))||""};if(this.tsv.authChoiceAuthBasic){a[this.tsv.authChoiceParam||"lmAuth"]=this.tsv.authChoiceAuthBasic}const c=new URLSearchParams(a).toString();this.userLogger.debug(`AuthBasic: authenticating ${t} via portal`);try{const e=yield fetch(n,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json","X-Forwarded-For":o},body:c});return e.ok?(this.userLogger.info(`AuthBasic: authentication successful for ${t}`),!0):(this.userLogger.warn(`AuthBasic: authentication failed for ${t}: ${e.status} ${e.statusText}`),!1)}catch(e){return this.userLogger.error(`AuthBasic: portal request failed: ${e}`),!1}})}hideCookie(e){this.userLogger.debug("AuthBasic: removing Authorization header"),delete e.headers.authorization}goToPortal(e,t,s=""){s?super.goToPortal(e,t,s):(e.setHeader("WWW-Authenticate",'Basic realm="LemonLDAP::NG"'),this.setError(e,t,401,"Authentication required"))}},CDA:class extends m{fetchId(e){if(!this.tsv.cda)return super.fetchId(e);const t=function(e){try{return new URL(e,"http://localhost").searchParams.get("lemonldapcda")}catch(e){return null}}(e.url||"/");if(t){const s=L(this.tsv.cipher,t);if(s)return this.userLogger.debug("CDA: extracted session from URL parameter"),this.setCDACookie(e,s.sessionId),s.sessionId;this.userLogger.warn("CDA: invalid or expired URL parameter")}const s=`${this.tsv.cookieName}cda`,o=this.getCDACookie(e,s);if(o){const e=L(this.tsv.cipher,o);if(e)return this.userLogger.debug("CDA: extracted session from cookie"),e.sessionId;this.userLogger.warn("CDA: invalid or expired cookie")}return super.fetchId(e)}getCDACookie(e,t){const s=e.headers.cookie;if(!s)return null;const o=new RegExp(`${t}=([^;]+)`).exec(s);return o?o[1]:null}setCDACookie(e,t){}sendHeaders(e,t){if(super.sendHeaders(e,t),this.tsv.cda){const s=`${this.tsv.cookieName}cda`,o=this.getCDACookieDomain(e);o&&(e.llngCdaCookie=function(e,t,s,o=0,i=!1,r=!0){let n=`${e}=${t}`;s&&(n+=`; Domain=${s}`),n+="; Path=/",o>0&&(n+=`; Expires=${new Date(Date.now()+1e3*o).toUTCString()}`);return i&&(n+="; Secure"),r&&(n+="; HttpOnly"),n+="; SameSite=None",n}(s,t._session_id,o,this.tsv.cookieExpiration||0,this.tsv.securedCookie>0,this.tsv.httpOnly))}}getCDACookieDomain(e){const t=e.headers.host;if(!t)return"";const s=t.split(":")[0],o=s.split(".");return o.length>=2?"."+o.slice(-2).join("."):s}goToPortal(e,t,s=""){if(this.tsv.cda){const e="cda=1";s=s?`${s}&${e}`:e}super.goToPortal(e,t,s)}}};exports.init=e=>new Promise((t,s)=>{e.type||(e.type="Main"),C[e.type]?(exports.class=C[e.type],A=new C[e.type](e),A.init().then(()=>t(A)).catch(e=>s(e))):import("@lemonldap-ng/handler-"+e.type.toLowerCase()).then(s=>{exports.class=s.default,A=new exports.class(e),A.init().then(()=>t(A))}).catch(e=>s(e))}),exports.nginxServer=e=>{A.nginxServer(e)},exports.portal=()=>A.portal(),exports.run=(e,t,s)=>A.run(e,t,s),exports.shutdown=()=>c(void 0,void 0,void 0,function*(){A&&(yield A.stopEventLoop())});
|
|
1
|
+
"use strict";var t=require("@lemonldap-ng/conf"),e=require("@lemonldap-ng/session"),s=require("@lemonldap-ng/safelib"),o=require("@lemonldap-ng/logger"),i=require("vm"),r=require("crypto"),n=require("re2"),a=require("http");function c(t,e,s,o){return new(s||(s=Promise))(function(i,r){function n(t){try{c(o.next(t))}catch(t){r(t)}}function a(t){try{c(o.throw(t))}catch(t){r(t)}}function c(t){var e;t.done?i(t.value):(e=t.value,e instanceof s?e:new s(function(t){t(e)})).then(n,a)}c((o=o.apply(t,e||[])).next())})}"function"==typeof SuppressedError&&SuppressedError;const h=new n("^logout(?:_sso|_app|_app_sso|)(?:s+(.*))?$","i");let u=0;const l=["cda","cookieExpiration","cipher","cookieName","customFunctions","httpOnly","securedCookie","timeout","timeoutActivity","useRedirectOnError","useRedirectOnForbidden","whatToTrace","loopBackUrl","handlerInternalCache","authChoiceAuthBasic","authChoiceParam"],d="llng-events",g="llng-status";class f{constructor(e){this.safe={},this.eventLoopInterval=null,this.lastConfigCheck=0,this.tsv={defaultCondition:{},defaultProtection:{},forgeHeaders:{},headerList:{},https:{},locationCondition:{},locationCount:{},locationProtection:{},locationRegexp:{},maintenance:{},port:{},portal:()=>"",vhostAlias:{},eventQueueName:d,statusQueueName:g,checkMsg:0,checkTime:600},this.localConf=e,e.configStorage||(e.configStorage={}),e.configStorage.localStorage||(e.configStorage.localStorage=e.localStorage),e.configStorage.localStorageOptions||(e.configStorage.localStorageOptions=e.localStorageOptions),this.confAcc=new t(e.configStorage);if([this.confAcc.getLocalConf("handler",!0),this.confAcc.getLocalConf("node-handler",!1)].forEach(t=>{Object.keys(t).forEach(e=>{if(!this.localConf)throw new Error("undef");void 0===this.localConf[e]&&(this.localConf[e]=t[e])})}),void 0===this.localConf.nodeVhosts)throw new Error("No Virtualhosts configured for Node.js");this.vhostList=this.localConf.nodeVhosts.split(/[,\s]+/).map(t=>t.toLowerCase())}reload(){return new Promise((t,a)=>{this.confAcc.ready.then(()=>{this.confAcc.getConf({}).then(a=>{if(l.forEach(t=>{this.tsv[t]=a[t]}),a.key&&(this.tsv.keyH=r.createHash("sha256").update(a.key).digest("hex")),Object.keys(this.localConf).forEach(t=>{a[t]=this.localConf[t]}),["https","port","maintenance"].forEach(t=>{if(void 0!==a[t]&&(this.tsv[t]={_:a[t]},a.vhostOptions)){const s=`vhost${e=t,e.charAt(0).toUpperCase()+e.slice(1)}`;Object.keys(a.vhostOptions).forEach(e=>{const o=a.vhostOptions[e][s];o>0&&(this.tsv[t][e.toLowerCase()]=o)})}var e}),!a.portal)throw new Error("portal should be defined");if(this.tsv.portal=()=>a.portal,!a.globalStorage||!a.globalStorageOptions)throw new Error("Missing session storage configuration");this.tsv.sessionStorageModule=a.globalStorage,this.tsv.sessionStorageOptions=a.globalStorageOptions;try{this.sessionAcc=new e({storageModule:a.globalStorage,storageModuleOptions:a.globalStorageOptions})}catch(t){throw new Error(`Unable to load session module: ${t}`,{cause:t})}a.oidcStorage?(this.tsv.oidcStorageModule=a.oidcStorage,this.tsv.oidcStorageOptions=a.oidcStorageOptions||{}):(this.tsv.oidcStorageModule=a.globalStorage,this.tsv.oidcStorageOptions=a.globalStorageOptions),this.tsv.oauth2Options={},Object.keys(a.oidcRPMetaDataOptions||{}).forEach(t=>{var e;const s=null===(e=a.oidcRPMetaDataOptions[t])||void 0===e?void 0:e.oidcRPMetaDataOptionsClientID;s&&(this.tsv.oauth2Options[t]={clientId:s})}),Object.keys(a.locationRules).forEach(t=>{const e=t.toLowerCase();if(-1==this.vhostList.indexOf(e))return;this.tsv.locationCount[e]=0,["locationRegexp","locationProtection","locationCondition"].forEach(t=>{void 0===this.tsv[t][e]&&(this.tsv[t][e]=[])}),this.safe[e]||(this.safe[e]=new s(a));const o=a.locationRules[t];Object.keys(o).forEach(t=>{const[s,i]=this.conditionSub(o[t],this.safe[e]);"default"===t?(this.tsv.defaultCondition[e]=s,this.tsv.defaultProtection[e]=i):(this.tsv.locationCondition[e].push(s),this.tsv.locationProtection[e].push(i),this.tsv.locationRegexp[e].push(new n(t.replace(/\(\?#.*?\)/g,""),"i")),this.tsv.locationCount[e]++)}),this.tsv.defaultCondition[e]||(this.tsv.defaultCondition[e]=()=>!0,this.tsv.defaultProtection[e]=0)}),void 0!==a.exportedHeaders&&Object.keys(a.exportedHeaders).forEach(t=>{const e=t.toLowerCase(),s=a.exportedHeaders[t];if(-1==this.vhostList.indexOf(e))return;this.tsv.headerList[e]||(this.tsv.headerList[e]=[]);let o="";Object.keys(s).forEach(t=>{this.tsv.headerList[e].push(t),o+=`'${t}': ${this.substitute(s[t])},`}),o=o.replace(/,$/,""),i.runInContext(`fg = function(session) {return {${o}};}`,this.safe[e]),this.tsv.forgeHeaders[e]=this.safe[e].fg}),void 0!==a.vhostOptions&&Object.keys(a.vhostOptions).forEach(t=>{a.vhostOptions[t].aliases&&a.vhostOptions[t].aliases.forEach(e=>{this.tsv.vhostAlias[e.toLowerCase()]=t.toLowerCase()})}),this.tsv.cookieDetect=new n(`\\b${this.tsv.cookieName}=([^;]+)`),this.sessionAcc.ready.then(()=>{o(a,!0).then(e=>c(this,void 0,void 0,function*(){this.userLogger=e;(yield this.msgBrokerInit(a))||this.userLogger.info("Handler initialized without message broker (real-time events disabled)"),this.startEventLoop(),t(!0)})).catch(t=>{throw new Error(`Logger error: ${t}`)})})}).catch(t=>{a(`Unable to get configuration: ${t}`)})})})}conditionSub(t,e){const s=()=>!0;if("accept"===t)return[s,0];if("deny"===t)return[()=>!1,0];if("unprotect"===t)return[s,1];if("skip"===t)return[s,2];const o=h.exec(t);if(o&&o[1]){const t=o[1];return t?[e=>(e._logout=t,!1),0]:[t=>(t._logout=this.tsv.portal(),!1),0]}if(t=this.substitute(t),e)return u++,i.runInContext(`sub${u.toString()} = function(req,session) {return (${t});}`,e),[e[`sub${u.toString()}`],0];throw new Error("Disabling safeJail is not supported")}substitute(t){return t.replace(/\$date\b/g,"this.date()").replace(/\$vhost\b/g,"this.hostname(req)").replace(/\$ip\b/g,"this.remote_ip(req)").replace(/\$(_*[a-zA-Z]\w*)/g,"session.$1")}parseBrokerType(t){if(!t)return"nobroker";const e=t.match(/::(\w+)$/);return e?e[1].toLowerCase():t.toLowerCase()}msgBrokerInit(t){return c(this,void 0,void 0,function*(){const e=this.parseBrokerType(t.messageBroker||"nobroker"),s=t.messageBrokerOptions||{};this.tsv.eventQueueName=s.eventQueueName||d,this.tsv.statusQueueName=s.statusQueueName||g,this.tsv.checkTime=s.checkTime||600;const o=`@lemonldap-ng/message-broker-${e.toLowerCase()}`;try{const t=(yield import(o)).default;return this.tsv.msgBrokerReader=new t(s,this.userLogger),this.tsv.msgBrokerWriter=new t(s,this.userLogger),!!this.tsv.msgBrokerReader&&(yield this.tsv.msgBrokerReader.subscribe(this.tsv.eventQueueName),this.userLogger.debug(`Message broker ${e} initialized, subscribed to ${this.tsv.eventQueueName}`),!0)}catch(t){this.userLogger.warn(`Failed to load message broker ${o}: ${t}. Using NoBroker fallback.`);try{const t=(yield Promise.resolve().then(function(){return require("./index-DXlSn3sb.js")})).default;return this.tsv.msgBrokerReader=new t({},this.userLogger),this.tsv.msgBrokerWriter=new t({},this.userLogger),!1}catch(t){return this.userLogger.debug("No message broker available"),!1}}})}startEventLoop(){if(this.eventLoopInterval)return;const t=Math.max(1e3,1e3*(this.tsv.checkTime||600));this.eventLoopInterval=setInterval(()=>c(this,void 0,void 0,function*(){try{yield this.checkEvents()}catch(t){this.userLogger.error(`Event loop error: ${t}`)}}),t),this.userLogger.debug(`Event loop started with ${t}ms interval`)}stopEventLoop(){return c(this,void 0,void 0,function*(){this.eventLoopInterval&&(clearInterval(this.eventLoopInterval),this.eventLoopInterval=null,this.userLogger.debug("Event loop stopped")),this.sessionAcc&&"function"==typeof this.sessionAcc.close&&(yield this.sessionAcc.close(),this.userLogger.debug("Session storage closed"))})}checkEvents(){return c(this,void 0,void 0,function*(){if(this.tsv.msgBrokerReader)try{const t=yield this.tsv.msgBrokerReader.getNextMessage(this.tsv.eventQueueName,0);t&&(this.tsv.checkMsg++,yield function(t,e){return c(this,void 0,void 0,function*(){const s=t.userLogger;switch(e.action){case"reload":s.debug("Message broker: reload configuration requested");try{return yield t.reload(),s.info("Configuration reloaded via message broker"),!0}catch(t){return s.error(`Failed to reload configuration: ${t}`),!1}case"unlog":return e.id?(s.debug(`Message broker: unlog session ${e.id}`),yield t.localUnlog(e.id),!0):(s.warn("Message broker: unlog without session id"),!1);case"newSession":return s.debug(`Message broker: new session notification (id: ${e.id})`),!0;case"delSession":return!!e.id&&(s.debug(`Message broker: session ${e.id} deleted`),yield t.localUnlog(e.id),!0);case"ping":return s.debug("Message broker: ping received"),!0;default:return s.debug(`Message broker: unknown action '${e.action}'`),!1}})}(this,t))}catch(t){this.userLogger.error(`Error checking events: ${t}`)}})}publishEvent(t){return c(this,arguments,void 0,function*(t,e={}){if(!this.tsv.msgBrokerWriter)return;const s=Object.assign({action:t,channel:this.tsv.eventQueueName},e);try{yield this.tsv.msgBrokerWriter.publish(this.tsv.eventQueueName,s),this.userLogger.debug(`Published event: ${t}`)}catch(e){this.userLogger.error(`Failed to publish event ${t}: ${e}`)}})}portal(){return this.tsv.portal()}}const v=/(?:%[0-9A-Fa-f]{2})+/g,p=/(?:^|\/)\.{1,2}(?:\/|$)/;class m extends Error{constructor(t){super("Invalid request URI"),this.uri=t,this.name="InvalidUriError"}}function k(t){if(p.test(t))throw new m(t)}function b(t){return t.replace(v,t=>{try{return decodeURIComponent(t)}catch(e){return t.replace(/%([0-9A-Fa-f]{2})/g,(t,e)=>String.fromCharCode(parseInt(e,16)))}})}function S(t){if(null==t)return"/";let e,s=t.replace(/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\/[^/?]*\/?/,"/");/^(?:\?|$)/.test(s)&&(s="/"+s);const o=s.indexOf("?");if(o>=0&&(e=s.slice(o+1),s=s.slice(0,o)),s.startsWith("/")){k(s),s=function(t){for(let e=0;e<5;e++){const e=b(t);if(e===t)break;k(e),t=e}return t}(s),s=s.replace(/\?/g,"%3F");const t=/\/$/.test(s),e=s.split(/\/+/).filter(t=>""!==t);s="/"+e.join("/"),t&&"/"!==s&&(s+="/")}return void 0===e?s:`${s}?${e}`}const w=/^(?:\[[0-9A-Fa-f:.]+\]|[A-Za-z0-9_](?:[A-Za-z0-9_-]*[A-Za-z0-9_])?(?:\.[A-Za-z0-9_](?:[A-Za-z0-9_-]*[A-Za-z0-9_])?)*\.?)(?::[0-9]{1,5})?$/;function L(t){t.writeHead(400,"Bad request"),t.end()}function A(t,e){if(t.test(e))return!0;const s=e.indexOf("?");return s>0&&t.test(e.slice(0,s))}function $(t){return JSON.stringify(t)}class C extends f{constructor(){super(...arguments),this.lastSessionId=null,this.lastSessionData=null,this.lastSessionTime=0}init(){return this.reload()}run(t,e,s){var o;const i=t.headers.host;if(void 0===i||!function(t){return w.test(t)}(i))return this.userLogger.error("Missing or invalid Host header"),void L(e);const r=this.resolveAlias(t),n=function(t){if(!t)return"/";const e=t.replace(/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\/[^/?#]*/,"");return e.startsWith("/")?e:"/"}(t.url);let a;try{a=S(t.url)}catch(t){return t instanceof m?this.userLogger.warn(`Refusing malformed URI ${$(t.uri)}`):this.userLogger.error(`Unable to canonicalize URI: ${$(String(t))}`),void L(e)}if(null!==(o=this.tsv.maintenance[r])&&void 0!==o?o:this.tsv.maintenance._)return this.setError(e,"/",503,"Service Temporarily Unavailable");if(2===this.isUnprotected(t,a))return this.lastSessionId=null,this.lastSessionData=null,this.lastSessionTime=0,this.hideCookie(t),s();Promise.resolve(this.fetchId(t)).then(o=>{if(""===o)return this.goToPortal(e,this.selfUri(r,n,i));this.retrieveSession(o,t).then(o=>{const i=o[this.tsv.whatToTrace];this.userLogger.debug(`User ${i} identified`),this.grant(t,a,o).then(n=>{n?(this.sendHeaders(t,o),this.hideCookie(t),s(),this.userLogger.info(`${$(r)}: user ${i} was granted access to ${$(a)}`)):(this.forbidden(t,e,o),this.userLogger.notice(`${$(r)}: user ${i} was denied access to ${$(a)}`))}).catch(t=>{this.userLogger.error(`Authorization check failed: ${t}`),this.setError(e,"/",503,"Service Unavailable")})}).catch(t=>{this.goToPortal(e,this.selfUri(r,n,i))})}).catch(t=>{this.userLogger.error(`Unable to fetch session id: ${t}`),this.goToPortal(e,this.selfUri(r,n,i))})}selfUri(t,e,s=t){return(this.tsv.https&&this.tsv.https[t]?"https":"http")+"://"+s+e}nginxServer(t){t.mode||(t.mode="fcgi"),t.port||(t.port=9090),t.ip||(t.ip="localhost");("fcgi"===t.mode?require("node-fastcgi"):a).createServer((t,e)=>{this.run(t,e,()=>{e.writeHead(200,t.headers)})}).listen(t.port,t.ip)}setError(t,e,s,o){if(this.tsv.useRedirectOnError){const e=this.tsv.portal()+`?lmError=${s.toString()}&url=`;t.redirect?t.redirect(e):t.writeHead(401,{Location:e})}else t.redirect?t.status(s).send(o):t.writeHead(s,o)}isUnprotected(t,e){const s=this.resolveAlias(t);if(!this.tsv.defaultCondition[s])return!1;for(let t=0;t<this.tsv.locationRegexp[s].length;t++)if(A(this.tsv.locationRegexp[s][t],e))return this.tsv.locationProtection[s][t];return this.tsv.defaultProtection[s]}resolveAlias(t){const e=t.headers.host;if(!e)return"undef";const s=e.replace(/:\d+$/,"").replace(/^\[|\]$/g,"").replace(/\.$/,"").toLowerCase();return this.tsv.vhostAlias[s]||s}fetchId(t){if(t.headers.cookie){const e=this.tsv.cookieDetect.exec(t.headers.cookie);if(e&&"0"!=e[1])return e[1]}return""}retrieveSession(t,e){return new Promise((e,s)=>{if(void 0===this.sessionAcc)return s("Server not ready, please wait");const o=Date.now()/1e3|0,i=this.tsv.handlerInternalCache||15;if(this.lastSessionId===t&&this.lastSessionData&&o-this.lastSessionTime<i)return this.userLogger.debug(`Get session ${t} from internal cache`),e(this.lastSessionData);this.lastSessionId=null,this.lastSessionData=null,this.sessionAcc.get(t).then(i=>{o-i._utime>this.tsv.timeout||this.tsv.timeoutActivity&&i._lastSeen&&o-i._lastSeen>this.tsv.timeoutActivity?s(`Session ${t} expired`):(this.tsv.timeoutActivity&&o-i._lastSeen>60&&(i._lastSeen=o,this.sessionAcc.update(i)),this.lastSessionId=t,this.lastSessionData=i,this.lastSessionTime=o,e(i))}).catch(e=>{s(`Session ${t} can't be found in store: ${e}`)})})}localUnlog(t){return c(this,void 0,void 0,function*(){this.userLogger.debug("Local handler logout");const e=t||this.lastSessionId;this.lastSessionId=null,this.lastSessionData=null,this.lastSessionTime=0,e&&this.sessionAcc&&(this.sessionAcc.clearMemoryCache(e),yield this.sessionAcc.clearLocalCache(e))})}grant(t,e,s){return new Promise((o,i)=>{const r=this.resolveAlias(t),n=`No configuration found for ${r} (or not listed in Node.js virtualHosts)`;if(!Object.prototype.hasOwnProperty.call(this.tsv.defaultCondition,r))return i(n);const a=this.tsv.defaultCondition[r];if("function"!=typeof a)return i(n);if(this.tsv.locationRegexp[r])for(let i=0;i<this.tsv.locationRegexp[r].length;i++){if(A(this.tsv.locationRegexp[r][i],e))return o(this.tsv.locationCondition[r][i](t,s))}o(!!a(t,s))})}sendHeaders(t,e){const s=this.resolveAlias(t);try{let o=0;t.headers["Lm-Remote-User"]=e[this.tsv.whatToTrace];const i=this.tsv.forgeHeaders[s](e);Object.keys(i).forEach(e=>{o++,t.headers[e]=i[e],t.rawHeaders.push(e,i[e]),t.redirect||(t.headers[`Headername${o}`]=e,t.headers[`Headervalue${o}`]=i[e])})}catch(t){return void this.userLogger.error(`Headers maybe not sent: ${t}`)}}hideCookie(t){t.headers.cookie&&(t.headers.cookie=t.headers.cookie.replace(this.tsv.cookieDetect,""))}forbidden(t,e,s){this.localUnlog(s._session_id).catch(t=>{this.userLogger.error(`Failed to clear local cache: ${t}`)}),s._logout?this.goToPortal(e,s._logout,"logout=1"):this.setError(e,"/",403,"Forbidden")}goToPortal(t,e,s=""){if("function"!=typeof this.tsv.portal)return void this.setError(t,e,503,"Waiting for configuration");const o=this.tsv.portal()+(e?"?url="+encodeURIComponent(Buffer.from(e).toString("base64")):"")+(s?(e?"&":"?")+s:"");t.redirect?t.redirect(o):t.writeHead(401,{Location:o})}}class y extends C{constructor(t){super(t),this.tsv.lastVhostUpdate={}}grant(t,e,s){const o=this.resolveAlias(t);if(this.tsv.defaultCondition[o]&&Date.now()/1e3-this.tsv.lastVhostUpdate[o]<600)return super.grant(t,e,s);const i=t.cgiParams&&t.cgiParams.RULES_URL?t.cgiParams.RULES_URL:(this.tsv.loopBackUrl||"http://127.0.0.1")+"/rules.json";if(!/^(https?):\/\/([^/:]+)(?::(\d+))?(.*)$/.test(i))return new Promise((t,e)=>e(`Bad loopBackUrl ${i}`));const r={prot:RegExp.$1,host:RegExp.$2,path:RegExp.$4,port:RegExp.$3||("https"==RegExp.$1?"443":"80"),lb:!(t.cgiParams&&t.cgiParams.RULES_URL)};return new Promise((i,n)=>{this.loadVhostConfig(t,o,r).then(()=>{this.grant(t,e,s).then(t=>{i(t)}).catch(t=>n(t))}).catch(o=>{this.userLogger.error(`Session retrieval error: ${o}`),this.grant(t,e,s).then(t=>{i(t)}).catch(t=>n(t))})})}loadVhostConfig(t,e,o){return new Promise((t,r)=>{o.lb||(e=o.host),e=e.toLowerCase(),delete o.lb,o.headers={Host:e};const a=require(o.prot);delete o.prot;const c=a.request(o,o=>{let a="";o.on("data",t=>{a+=t}),o.on("end",()=>{if(this.tsv.locationCondition[e]=[],this.tsv.locationProtection[e]=[],this.tsv.locationRegexp[e]=[],this.tsv.locationCount[e]=0,this.tsv.headerList[e]=[],""===a)return this.tsv.defaultCondition[e]=()=>!0,this.tsv.defaultProtection[e]=0,this.tsv.lastVhostUpdate[e]=Date.now()/1e3,t(!0);try{const o=JSON.parse(a);if(this.safe[e]=new s({cipher:this.tsv.cipher}),o.rules&&"object"==typeof o.rules&&(Object.keys(o.rules).forEach(t=>{const s=new String(o.rules[t]).valueOf(),[i,r]=this.conditionSub(s,this.safe[e]);"default"===t?(this.tsv.defaultCondition[e]=i,this.tsv.defaultProtection[e]=r):(this.tsv.locationCondition[e].push(i),this.tsv.locationProtection[e].push(r),this.tsv.locationRegexp[e].push(new n(t.replace(/\(\?#.*?\)/g,""),"i")),this.tsv.locationCount[e]++)}),this.tsv.defaultCondition[e]||(this.tsv.defaultCondition[e]=()=>!0,this.tsv.defaultProtection[e]=0)),o.headers&&"object"==typeof o.headers){const t=Object.keys(o.headers).map(t=>(this.tsv.headerList[e].push(t),`'${t}': ${this.substitute(o.headers[t])}`)).join(",");i.runInContext(`fg = function(session) {return {${t}}}`,this.safe[e]),this.tsv.forgeHeaders[e]=this.safe[e].fg}this.tsv.lastVhostUpdate[e]=Date.now()/1e3,t(!0)}catch(t){r("Unable to getremote config: "+t)}}),c.on("error",t=>{r(t)}),c.end()})})}}class O extends C{fetchId(t){const e=t.cgiParams?t.cgiParams.HTTP_X_LLNG_TOKEN:t.headers["x-llng-token"];if(e){let s;try{s=this.tsv.cipher.decrypt(e).split(":")}catch(t){return this.userLogger.error("Invalid token"),""}if(!s[2])return this.userLogger.error("Bad service token"),"";const o=Date.now()/1e3,i=parseInt(s[0]);if(i<o-30||i>o)return this.userLogger.warn("Expired service token"),"";const r=this.resolveAlias(t);return s.indexOf(r)<2?(this.userLogger.warn(`${r} not authorizated in token`),""):s[1]}return super.fetchId(t)}}function I(t,e){const s=t.split(".");if(s.length<2)return null;if(e>=s.length)return null;try{const t=function(t){let e=t.replace(/-/g,"+").replace(/_/g,"/");for(;e.length%4;)e+="=";return Buffer.from(e,"base64").toString("utf8")}(s[e]);return JSON.parse(t)}catch(t){return null}}function x(t){if(t.indexOf(".")>0){const e=I(t,1);return e&&"string"==typeof e.jti&&""!==e.jti?e.jti:null}return t}const _="O-",E=/^[A-Za-z0-9_-]+$/;function P(t,e,s=120){try{const o=t.decrypt(e).split(":");if(o.length<2)return null;const i=o[0],r=parseInt(o[1],10);if(!i||isNaN(r))return null;const n=Math.floor(Date.now()/1e3);return n-r>s||r>n+10?null:{sessionId:i,timestamp:r,domain:o[2]}}catch(t){return null}}let T;exports.class=void 0;const D={Main:C,DevOps:y,ServiceToken:O,ServiceTokenST:class extends y{fetchId(t){return O.prototype.fetchId.call(this,t)}},OAuth2:class extends C{constructor(){super(...arguments),this.ownOidcSessionAcc=!1,this.state=new WeakMap}reload(){const t=Object.create(null,{reload:{get:()=>super.reload}});return c(this,void 0,void 0,function*(){const e=yield t.reload.call(this);return yield this.initOidcSessionStorage(),e})}initOidcSessionStorage(){return c(this,void 0,void 0,function*(){const t=this.tsv.oidcStorageModule;if(!t)throw new Error("OAuth2 handler requires a session storage");let s,o;if(t===this.tsv.sessionStorageModule&&JSON.stringify(this.tsv.oidcStorageOptions||{})===JSON.stringify(this.tsv.sessionStorageOptions||{}))this.userLogger.debug("OAuth2 handler shares the main session storage"),s=this.sessionAcc,o=!1;else{try{s=new e({storageModule:t,storageModuleOptions:this.tsv.oidcStorageOptions||{}}),yield s.ready}catch(t){throw new Error(`Unable to load OIDC session module: ${t}`,{cause:t})}o=!0,this.userLogger.debug("OAuth2 OIDC session storage initialized")}const i=this.ownOidcSessionAcc?this.oidcSessionAcc:void 0;this.oidcSessionAcc=s,this.ownOidcSessionAcc=o,i&&i!==s&&(yield i.close())})}localUnlog(t){const e=Object.create(null,{localUnlog:{get:()=>super.localUnlog}});return c(this,void 0,void 0,function*(){const s=t||this.lastSessionId;yield e.localUnlog.call(this,t),s&&this.ownOidcSessionAcc&&this.oidcSessionAcc&&(yield this.oidcSessionAcc.clearAllCaches(s))})}run(t,e,s){const o={};return this.state.set(t,o),this.state.set(e,o),super.run(t,e,s)}fetchId(t){const e=Object.create(null,{fetchId:{get:()=>super.fetchId}});return c(this,void 0,void 0,function*(){const s=t.headers.authorization;if(!s||!/^bearer\s/i.test(s))return e.fetchId.call(this,t);const o=s.replace(/^bearer\s+/i,"").trim();if(!o)return this.userLogger.info("OAuth2: empty Bearer token"),this.fallbackToCookie(t);const i=x(o);if(!i)return this.invalidToken(t,"No session id found in access token");if(!this.isSessionId(i))return this.invalidToken(t,"Malformed access token session id");const r=yield this.getOIDCInfos(i);if("invalid"===r.status)return this.invalidToken(t,"Access token session is not usable");if("notFound"===r.status)return this.userLogger.info(`Unknown access token session ${i}`),this.fallbackToCookie(t);const n=r.data,a=n.rp?this.tokenAttributes(o,n):void 0;if(n.user_session_id){if(!this.isSessionId(n.user_session_id))return this.invalidToken(t,`Malformed user_session_id in access token session ${i}`);const e=this.stateFor(t);return e.viaToken=!0,e.attrs=a,this.userLogger.debug(`OAuth2: get user session ${n.user_session_id}`),n.user_session_id}if(n.offline_session_id){if(!this.isSessionId(n.offline_session_id))return this.invalidToken(t,`Malformed offline_session_id in access token session ${i}`);const e=this.stateFor(t);return e.viaToken=!0,e.attrs=a,this.userLogger.debug(`OAuth2: get offline session ${n.offline_session_id}`),`${_}${n.offline_session_id}`}return this.userLogger.warn(`Access token session ${i} references no session`),this.fallbackToCookie(t)})}retrieveSession(t,e){var s;const o=e?null===(s=this.state.get(e))||void 0===s?void 0:s.attrs:void 0;if(!t.startsWith(_))return super.retrieveSession(t,e).then(t=>this.withTokenAttributes(t,o),t=>{var s;throw e&&(null===(s=this.state.get(e))||void 0===s?void 0:s.viaToken)&&(this.stateFor(e).error="invalid_token"),t});const i=t.substring(2);return this.getOIDCInfos(i).then(t=>{if("ok"!==t.status)throw e&&(this.stateFor(e).error="invalid_token"),`Offline session ${i} can not be retrieved`;return this.withTokenAttributes(t.data,o)},t=>{throw e&&(this.stateFor(e).error="invalid_token"),t})}hideCookie(t){t.headers.authorization&&(this.userLogger.debug("OAuth2: removing Authorization header"),delete t.headers.authorization),super.hideCookie(t)}goToPortal(t,e,s=""){var o;const i=null===(o=this.state.get(t))||void 0===o?void 0:o.error;t.setHeader("WWW-Authenticate","Bearer"+(i?` error="${i}"`:"")),t.status?t.status(401).send("Unauthorized"):t.writeHead(401,"Unauthorized")}stopEventLoop(){const t=Object.create(null,{stopEventLoop:{get:()=>super.stopEventLoop}});return c(this,void 0,void 0,function*(){yield t.stopEventLoop.call(this),this.ownOidcSessionAcc&&this.oidcSessionAcc&&(yield this.oidcSessionAcc.close(),this.userLogger.debug("OIDC session storage closed"))})}getOIDCInfos(t){return void 0===this.oidcSessionAcc?Promise.resolve({status:"invalid"}):this.oidcSessionAcc.get(t).then(e=>{const s=Number(e._utime);if(!e._utime||!Number.isFinite(s))return this.userLogger.error(`_utime missing from OIDC session ${t}`),{status:"invalid"};return(Date.now()/1e3|0)-s>this.tsv.timeout?(this.userLogger.info(`OIDC session ${t} expired`),{status:"invalid"}):(this.userLogger.debug(`Get OIDC session ${t}`),{status:"ok",data:e})},e=>(this.userLogger.info(`OIDC session ${t} can not be retrieved: ${e}`),{status:"notFound"}))}tokenAttributes(t,e){var s,o;const i={_accessToken:t,_clientConfKey:e.rp};void 0!==e.scope&&(i._scope=e.scope),void 0!==e.grant_type&&(i._oidc_grant_type=e.grant_type),void 0!==e.aud&&(i._audiences=e.aud);const r=null===(o=null===(s=this.tsv.oauth2Options)||void 0===s?void 0:s[e.rp])||void 0===o?void 0:o.clientId;return r&&(i._clientId=r),i}withTokenAttributes(t,e){return e?Object.assign(Object.assign({},t),e):t}isSessionId(t){return"string"==typeof t&&E.test(t)}stateFor(t){let e=this.state.get(t);return e||(e={},this.state.set(t,e)),e}invalidToken(t,e){return this.userLogger.warn(`OAuth2: ${e}`),this.stateFor(t).error="invalid_token",""}fallbackToCookie(t){const e=Object.create(null,{fetchId:{get:()=>super.fetchId}});return c(this,void 0,void 0,function*(){const s=yield e.fetchId.call(this,t);return""===s&&(this.stateFor(t).error="invalid_token"),s})}},AuthBasic:class extends C{constructor(){super(...arguments),this.pendingAuth=new Map}fetchId(t){var e;const s=t.headers.authorization;if(s&&s.toLowerCase().startsWith("basic ")){const o=s.substring(6).trim();if(o){const s=Math.floor(Date.now()/1e3/this.tsv.timeout)+(this.tsv.keyH||""),i=r.createHash("sha256").update(o+s).digest("hex");try{const s=Buffer.from(o,"base64").toString("utf-8"),r=s.indexOf(":");if(r>0){const o=s.substring(0,r),n=s.substring(r+1),a=t.headers["x-forwarded-for"],c=t.ip||(null===(e=t.socket)||void 0===e?void 0:e.remoteAddress)||"",h=a?`${a}, ${c}`:c;this.pendingAuth.set(i,{username:o,password:n,xff:h})}}catch(t){}return this.userLogger.debug("AuthBasic: computed session ID for credentials"),i}}return super.fetchId(t)}retrieveSession(t){const e=Object.create(null,{retrieveSession:{get:()=>super.retrieveSession}});return new Promise((s,o)=>{e.retrieveSession.call(this,t).then(e=>{this.pendingAuth.delete(t),s(e)}).catch(()=>c(this,void 0,void 0,function*(){const i=this.pendingAuth.get(t);if(!i)return void o("No session and no pending authentication");this.pendingAuth.delete(t);(yield this.createSession(t,i.username,i.password,i.xff))?e.retrieveSession.call(this,t).then(s).catch(o):o("Authentication failed")}))})}createSession(t,e,s,o){return c(this,void 0,void 0,function*(){var i;if(!/^[a-fA-F0-9]{1,64}$/.test(t))return this.userLogger.error(`AuthBasic: Invalid session ID format: ${t}`),!1;const r=this.tsv.portal();if(!r)return this.userLogger.error("AuthBasic: portal URL not configured"),!1;let n=`${r}/sessions/global/${t}?auth`;n=n.replace(/\/\/sessions\//,"/sessions/");const a={user:e,password:s,secret:(null===(i=this.tsv.cipher)||void 0===i?void 0:i.encrypt(Date.now().toString()))||""};if(this.tsv.authChoiceAuthBasic){a[this.tsv.authChoiceParam||"lmAuth"]=this.tsv.authChoiceAuthBasic}const c=new URLSearchParams(a).toString();this.userLogger.debug(`AuthBasic: authenticating ${e} via portal`);try{const t=yield fetch(n,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json","X-Forwarded-For":o},body:c});return t.ok?(this.userLogger.info(`AuthBasic: authentication successful for ${e}`),!0):(this.userLogger.warn(`AuthBasic: authentication failed for ${e}: ${t.status} ${t.statusText}`),!1)}catch(t){return this.userLogger.error(`AuthBasic: portal request failed: ${t}`),!1}})}hideCookie(t){this.userLogger.debug("AuthBasic: removing Authorization header"),delete t.headers.authorization}goToPortal(t,e,s=""){s?super.goToPortal(t,e,s):(t.setHeader("WWW-Authenticate",'Basic realm="LemonLDAP::NG"'),this.setError(t,e,401,"Authentication required"))}},CDA:class extends C{fetchId(t){if(!this.tsv.cda)return super.fetchId(t);const e=function(t){try{return new URL(t,"http://localhost").searchParams.get("lemonldapcda")}catch(t){return null}}(t.url||"/");if(e){const s=P(this.tsv.cipher,e);if(s)return this.userLogger.debug("CDA: extracted session from URL parameter"),this.setCDACookie(t,s.sessionId),s.sessionId;this.userLogger.warn("CDA: invalid or expired URL parameter")}const s=`${this.tsv.cookieName}cda`,o=this.getCDACookie(t,s);if(o){const t=P(this.tsv.cipher,o);if(t)return this.userLogger.debug("CDA: extracted session from cookie"),t.sessionId;this.userLogger.warn("CDA: invalid or expired cookie")}return super.fetchId(t)}getCDACookie(t,e){const s=t.headers.cookie;if(!s)return null;const o=new RegExp(`${e}=([^;]+)`).exec(s);return o?o[1]:null}setCDACookie(t,e){}sendHeaders(t,e){if(super.sendHeaders(t,e),this.tsv.cda){const s=`${this.tsv.cookieName}cda`,o=this.getCDACookieDomain(t);o&&(t.llngCdaCookie=function(t,e,s,o=0,i=!1,r=!0){let n=`${t}=${e}`;s&&(n+=`; Domain=${s}`),n+="; Path=/",o>0&&(n+=`; Expires=${new Date(Date.now()+1e3*o).toUTCString()}`);return i&&(n+="; Secure"),r&&(n+="; HttpOnly"),n+="; SameSite=None",n}(s,e._session_id,o,this.tsv.cookieExpiration||0,this.tsv.securedCookie>0,this.tsv.httpOnly))}}getCDACookieDomain(t){const e=t.headers.host;if(!e)return"";const s=e.split(":")[0],o=s.split(".");return o.length>=2?"."+o.slice(-2).join("."):s}goToPortal(t,e,s=""){if(this.tsv.cda){const t="cda=1";s=s?`${s}&${t}`:t}super.goToPortal(t,e,s)}}};exports.init=t=>new Promise((e,s)=>{t.type||(t.type="Main"),D[t.type]?(exports.class=D[t.type],T=new D[t.type](t),T.init().then(()=>e(T)).catch(t=>s(t))):import("@lemonldap-ng/handler-"+t.type.toLowerCase()).then(s=>{exports.class=s.default,T=new exports.class(t),T.init().then(()=>e(T))}).catch(t=>s(t))}),exports.nginxServer=t=>{T.nginxServer(t)},exports.portal=()=>T.portal(),exports.run=(t,e,s)=>T.run(t,e,s),exports.shutdown=()=>c(void 0,void 0,void 0,function*(){T&&(yield T.stopEventLoop())});
|
|
2
2
|
//# sourceMappingURL=index.js.map
|