lemonldap-ng-handler 0.9.6 → 0.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,9 +1,18 @@
1
1
  /**
2
2
  * OAuth2/OIDC Handler for LemonLDAP::NG
3
- * Port of Lemonldap::NG::Handler::OAuth2
3
+ * Port of Lemonldap::NG::Handler::Lib::OAuth2
4
4
  *
5
- * This handler validates OAuth2/OIDC access tokens and retrieves
6
- * the associated session from the OIDC session storage.
5
+ * A Bearer access token is an *opaque credential*: the token itself (or the
6
+ * `jti` claim of its JWT serialization) is the identifier of an access token
7
+ * session created by the Portal. This handler therefore:
8
+ *
9
+ * 1. resolves the access token session in the OIDC session storage,
10
+ * 2. follows it to the user session (or offline session) it was issued for,
11
+ * 3. exposes the token attributes (scope, client, audiences, grant type) as
12
+ * session attributes so that rules and headers can use them.
13
+ *
14
+ * Nothing but the session identifier is ever read from the token: the trust
15
+ * anchor is the session store, not the token payload.
7
16
  */
8
17
  import express from "express";
9
18
  import http from "http";
@@ -11,19 +20,121 @@ import LemonldapNGHandler from "./handlerMain";
11
20
  import { LLNG_Session } from "@lemonldap-ng/types";
12
21
  declare class LemonldapNGHandlerOAuth2 extends LemonldapNGHandler {
13
22
  private oidcSessionAcc;
23
+ private ownOidcSessionAcc;
24
+ private state;
25
+ /**
26
+ * Override reload() - and not init() - to set up the OIDC session storage.
27
+ *
28
+ * init() runs once, while reload() runs again on every configuration change
29
+ * announced by the message broker, and it rebuilds the main session
30
+ * accessor. The OIDC accessor must follow: else the handler would keep
31
+ * querying the previous storage (with its own cache), localUnlog() would
32
+ * only purge the new one, and a modified oidcStorage would never be applied.
33
+ */
34
+ reload(): Promise<boolean>;
35
+ /**
36
+ * (Re)build the accessor used for access token and offline sessions
37
+ *
38
+ * The new accessor is only installed once it is known to be usable: a
39
+ * reload announcing a broken oidcStorage must leave the handler running on
40
+ * its previous storage rather than answering 401 to every token, and must
41
+ * not leak the accessor it failed to replace (its node-persist timers would
42
+ * keep the process alive).
43
+ */
44
+ private initOidcSessionStorage;
45
+ /**
46
+ * Override localUnlog to purge the OIDC caches too
47
+ *
48
+ * When the Portal revokes an access token, it broadcasts an unlog/delSession
49
+ * message holding the id of the deleted session. With a dedicated
50
+ * oidcStorage, that session lives in the OIDC accessor, whose caches
51
+ * Main::localUnlog() does not know about: the revoked token would keep
52
+ * authenticating until the cache entry expires.
53
+ * @param sessionId - Session ID to clear (uses last cached if not provided)
54
+ */
55
+ localUnlog(sessionId?: string): Promise<void>;
14
56
  /**
15
- * Override init to also initialize OIDC session storage
57
+ * Override run to bind the per-request state to both req and res: fetchId()
58
+ * and retrieveSession() only see the request, goToPortal() only sees the
59
+ * response.
16
60
  */
17
- init(): Promise<boolean>;
61
+ run(req: express.Request | http.IncomingMessage, res: http.ServerResponse, next: Function): any;
18
62
  /**
19
- * Override fetchId to check for OAuth2 Bearer token
63
+ * Override fetchId to resolve an OAuth2 Bearer token into a session id
64
+ *
65
+ * Contrary to the cookie case, the value carried by the request is *not* the
66
+ * user session id: it identifies an access token session, which in turn
67
+ * references the user session (or an offline session).
20
68
  * @param req - HTTP request
21
69
  */
22
- fetchId(req: express.Request | http.IncomingMessage): string;
70
+ fetchId(req: express.Request | http.IncomingMessage): Promise<string>;
71
+ /**
72
+ * Override retrieveSession to handle offline sessions and to expose the
73
+ * access token attributes to rules and headers
74
+ * @param id - Session ID, prefixed by "O-" for offline sessions
75
+ * @param req - HTTP request, when available
76
+ */
77
+ retrieveSession(id: string, req?: express.Request | http.IncomingMessage): Promise<LLNG_Session>;
78
+ /**
79
+ * Hide the access token from the protected application
80
+ * @param req - HTTP request
81
+ */
82
+ hideCookie(req: express.Request | http.IncomingMessage): void;
83
+ /**
84
+ * A resource server never redirects: answer with a 401 and the challenge
85
+ * described in RFC 6750 section 3
86
+ * @param res - HTTP response
87
+ * @param _uri - Original URI (unused)
88
+ * @param _args - Additional arguments (unused)
89
+ */
90
+ goToPortal(res: http.ServerResponse, _uri: string, _args?: string): void;
91
+ /**
92
+ * Close the dedicated OIDC session storage, if any
93
+ */
94
+ stopEventLoop(): Promise<void>;
95
+ /**
96
+ * Get a session from the OIDC storage and check that it is not expired
97
+ *
98
+ * Note: the session backends do not tell an unknown session apart from an
99
+ * unreachable storage, so both end up as "notFound" here, exactly as in the
100
+ * Perl handler and as in the cookie path of Handler::Main. A storage outage
101
+ * is therefore reported to the client as an invalid token. Fixing this
102
+ * requires a "not found" signal in every @lemonldap-ng/session-* backend.
103
+ * @param id - Access token, offline or OIDC session id
104
+ */
105
+ private getOIDCInfos;
106
+ /**
107
+ * Collect the access token session fields exposed to rules and headers
108
+ * @param accessToken - Bearer token, as received
109
+ * @param infos - Access token session
110
+ */
111
+ private tokenAttributes;
112
+ /**
113
+ * Build a copy of the session enriched with the access token attributes.
114
+ * A copy is mandatory: the session object may be shared with the session
115
+ * caches.
116
+ */
117
+ private withTokenAttributes;
118
+ /**
119
+ * Check that a value may be handed over to the session storage
120
+ *
121
+ * Applied both to the id carried by the token and to the ids read from the
122
+ * access token session: the latter are written by the Portal, but they end
123
+ * up in a LDAP DN or in an URL just the same.
124
+ * @param id - Candidate session id
125
+ */
126
+ private isSessionId;
127
+ /**
128
+ * Get (or create) the state attached to a request or a response
129
+ */
130
+ private stateFor;
131
+ /**
132
+ * Reject the request with an "invalid_token" OAuth2 error
133
+ */
134
+ private invalidToken;
23
135
  /**
24
- * Override retrieveSession to use OIDC session storage if token-based
25
- * @param id - Session ID
136
+ * Use the LLNG cookie when the Bearer token can not be resolved
26
137
  */
27
- retrieveSession(id: string): Promise<LLNG_Session>;
138
+ private fallbackToCookie;
28
139
  }
29
140
  export default LemonldapNGHandlerOAuth2;
@@ -0,0 +1,7 @@
1
+ import express from "express";
2
+ import http from "http";
3
+ import LemonldapNGHandler from "./handlerMain.mjs";
4
+ declare class LemonldapNGHandlerServiceToken extends LemonldapNGHandler {
5
+ fetchId(req: express.Request | http.IncomingMessage): string;
6
+ }
7
+ export default LemonldapNGHandlerServiceToken;
@@ -0,0 +1,20 @@
1
+ import express from "express";
2
+ import http from "http";
3
+ import { Handler_Args } from "./init.mjs";
4
+ import LemonldapNGHandler, { FastCGI_Opts } from "./handlerMain.mjs";
5
+ import LemonldapNGHandlerDevOps from "./handlerDevOps.mjs";
6
+ declare let currentClass: typeof LemonldapNGHandler | typeof LemonldapNGHandlerDevOps;
7
+ export declare const init: (args: Handler_Args) => Promise<LemonldapNGHandler>;
8
+ export declare const run: (req: express.Request | http.IncomingMessage, res: http.ServerResponse, next: Function) => any;
9
+ export declare const nginxServer: (args: FastCGI_Opts) => void;
10
+ /**
11
+ * Returns the portal URL from LemonLDAP::NG configuration
12
+ * @returns Portal URL string
13
+ */
14
+ export declare const portal: () => string;
15
+ /**
16
+ * Shutdown the handler (stops event loop and cleanup)
17
+ * Call this in tests' afterAll to prevent Jest from hanging
18
+ */
19
+ export declare const shutdown: () => Promise<void>;
20
+ export { currentClass as class };
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"),r=require("@lemonldap-ng/logger"),o=require("vm"),i=require("crypto"),n=require("re2"),a=require("http");function h(e,t,s,r){return new(s||(s=Promise))(function(o,i){function n(e){try{h(r.next(e))}catch(e){i(e)}}function a(e){try{h(r.throw(e))}catch(e){i(e)}}function h(e){var t;e.done?o(e.value):(t=e.value,t instanceof s?t:new s(function(e){e(t)})).then(n,a)}h((r=r.apply(e,t||[])).next())})}"function"==typeof SuppressedError&&SuppressedError;const c=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=i.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 r=a.vhostOptions[t][s];r>0&&(this.tsv[e][t]=r)})}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");try{this.sessionAcc=new t({storageModule:a.globalStorage,storageModuleOptions:a.globalStorageOptions})}catch(e){throw new Error(`Unable to load session module: ${e}`,{cause:e})}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[r,o]=this.conditionSub(t[s],this.safe[e]);"default"===s?(this.tsv.defaultCondition[e]=r,this.tsv.defaultProtection[e]=o):(this.tsv.locationCondition[e].push(r),this.tsv.locationProtection[e].push(o),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(r=>{this.tsv.headerList[e].push(r),s+=`'${r}': ${this.substitute(t[r])},`}),s=s.replace(/,$/,""),o.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(()=>{r(a,!0).then(t=>h(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 r=c.exec(e);if(r&&r[1]){const e=r[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++,o.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 h(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 r=`@lemonldap-ng/message-broker-${t.toLowerCase()}`;try{const e=(yield import(r)).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 ${r}: ${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(()=>h(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 h(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 h(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 h(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 h(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:r,data:o,hash:i}=s.groups;const n=r.split(";");i=t?"":i;let a=!1;"base64"===n[n.length-1]&&(n.pop(),a=!0);const h=(n.shift()||"").toLowerCase(),c=[...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&&c.push("base64"),(c.length>0||h&&"text/plain"!==h)&&c.unshift(h),`data:${c.join(";")},${a?o.trim():o}${i?`#${i}`:""}`})(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 r=new URL(e);if(t.forceHttp&&t.forceHttps)throw new Error("The `forceHttp` and `forceHttps` options cannot be used together");if(t.forceHttp&&"https:"===r.protocol&&(r.protocol="http:"),t.forceHttps&&"http:"===r.protocol&&(r.protocol="https:"),t.stripAuthentication&&(r.username="",r.password=""),t.stripHash?r.hash="":t.stripTextFragment&&(r.hash=r.hash.replace(/#?:~:text.*?$/i,"")),r.pathname){const e=/\b[a-z][a-z\d+\-.]{1,50}:\/\//g;let t=0,s="";for(;;){const o=e.exec(r.pathname);if(!o)break;const i=o[0],n=o.index;s+=r.pathname.slice(t,n).replace(/\/{2,}/g,"/"),s+=i,t=n+i.length}s+=r.pathname.slice(t,r.pathname.length).replace(/\/{2,}/g,"/"),r.pathname=s}if(r.pathname)try{r.pathname=decodeURI(r.pathname)}catch{}if(!0===t.removeDirectoryIndex&&(t.removeDirectoryIndex=[/^index\.[a-z]+$/]),Array.isArray(t.removeDirectoryIndex)&&t.removeDirectoryIndex.length>0){let e=r.pathname.split("/");const s=e[e.length-1];f(s,t.removeDirectoryIndex)&&(e=e.slice(0,-1),r.pathname=e.slice(1).join("/")+"/")}if(r.hostname&&(r.hostname=r.hostname.replace(/\.$/,""),t.stripWWW&&/^www\.(?!www\.)[a-z\-\d]{1,63}\.[a-z.\-\d]{2,63}$/.test(r.hostname)&&(r.hostname=r.hostname.replace(/^www\./,""))),Array.isArray(t.removeQueryParameters))for(const e of[...r.searchParams.keys()])f(e,t.removeQueryParameters)&&r.searchParams.delete(e);if(Array.isArray(t.keepQueryParameters)||!0!==t.removeQueryParameters||(r.search=""),Array.isArray(t.keepQueryParameters)&&t.keepQueryParameters.length>0)for(const e of[...r.searchParams.keys()])f(e,t.keepQueryParameters)||r.searchParams.delete(e);if(t.sortQueryParameters){r.searchParams.sort();try{r.search=decodeURIComponent(r.search)}catch{}}t.removeTrailingSlash&&(r.pathname=r.pathname.replace(/\/$/,"")),t.removeExplicitPort&&r.port&&(r.port="");const o=e;return e=r.toString(),t.removeSingleSlash||"/"!==r.pathname||o.endsWith("/")||""!==r.hash||(e=e.replace(/\/$/,"")),(t.removeTrailingSlash||"/"===r.pathname)&&""===r.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 r=e.headers.host;if(void 0===r)return this.userLogger.error("Request without Host header"),void this.setError(t,"/",400,"Bad request");const o=new URL(v(r+e.url)).pathname||"/";if(this.tsv.maintenance[r])return this.setError(t,"/",503,"Service Temporarily Unavailable");if(2===this.isUnprotected(e,o))return this.lastSessionId=null,this.lastSessionData=null,this.lastSessionTime=0,this.hideCookie(e),s();const i=this.fetchId(e);""!==i?this.retrieveSession(i).then(i=>{const n=i[this.tsv.whatToTrace];this.userLogger.debug(`User ${n} identified`),this.grant(e,o,i).then(a=>{a?(this.sendHeaders(e,i),this.hideCookie(e),s(),this.userLogger.info(`${r}: user ${n} was granted access to ${o}`)):(this.forbidden(e,t,i),this.userLogger.notice(`${r}: user ${n} was denied access to ${o}`))}).catch(e=>{this.userLogger.error(`Authorization check failed: ${e}`),this.setError(t,"/",503,"Service Unavailable")})}).catch(e=>{this.goToPortal(t,this.selfUri(r,o))}):this.goToPortal(t,this.selfUri(r,o))}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,r){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(r):e.writeHead(s,r)}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){return new Promise((t,s)=>{if(void 0===this.sessionAcc)return s("Server not ready, please wait");const r=Date.now()/1e3|0,o=this.tsv.handlerInternalCache||15;if(this.lastSessionId===e&&this.lastSessionData&&r-this.lastSessionTime<o)return this.userLogger.debug(`Get session ${e} from internal cache`),t(this.lastSessionData);this.lastSessionId=null,this.lastSessionData=null,this.sessionAcc.get(e).then(o=>{r-o._utime>this.tsv.timeout||this.tsv.timeoutActivity&&o._lastSeen&&r-o._lastSeen>this.tsv.timeoutActivity?s(`Session ${e} expired`):(this.tsv.timeoutActivity&&r-o._lastSeen>60&&(o._lastSeen=r,this.sessionAcc.update(o)),this.lastSessionId=e,this.lastSessionData=o,this.lastSessionTime=r,t(o))}).catch(t=>{s(`Session ${e} can't be found in store: ${t}`)})})}localUnlog(e){return h(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((r,o)=>{const i=this.resolveAlias(e);if(!Object.prototype.hasOwnProperty.call(this.tsv.defaultCondition,i))return o(`No configuration found for ${i} (or not listed in Node.js virtualHosts)`);if(this.tsv.locationRegexp[i])for(let o=0;o<this.tsv.locationRegexp[i].length;o++){if(this.tsv.locationRegexp[i][o].test(t))return r(this.tsv.locationCondition[i][o](e,s))}this.tsv.defaultCondition[i](e,s)?r(!0):o("Unauthorized")})}sendHeaders(e,t){const s=this.resolveAlias(e);try{let r=0;e.headers["Lm-Remote-User"]=t[this.tsv.whatToTrace];const o=this.tsv.forgeHeaders[s](t);Object.keys(o).forEach(t=>{r++,e.headers[t]=o[t],e.rawHeaders.push(t,o[t]),e.redirect||(e.headers[`Headername${r}`]=t,e.headers[`Headervalue${r}`]=o[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 r=this.tsv.portal()+(t?"?url="+new Buffer.from(encodeURI(t)).toString("base64"):"")+(s?(t?"&":"?")+s:"");e.redirect?e.redirect(r):e.writeHead(401,{Location:r})}}class w extends m{constructor(e){super(e),this.tsv.lastVhostUpdate={}}grant(e,t,s){const r=this.resolveAlias(e);if(this.tsv.defaultCondition[r]&&Date.now()/1e3-this.tsv.lastVhostUpdate[r]<600)return super.grant(e,t,s);const o=e.cgiParams&&e.cgiParams.RULES_URL?e.cgiParams.RULES_URL:(this.tsv.loopBackUrl||"http://127.0.0.1")+"/rules.json";if(!/^(https?):\/\/([^/:]+)(?::(\d+))?(.*)$/.test(o))return new Promise((e,t)=>t(`Bad loopBackUrl ${o}`));const i={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((o,n)=>{this.loadVhostConfig(e,r,i).then(()=>{this.grant(e,t,s).then(e=>{o(e)}).catch(e=>n(e))}).catch(r=>{this.userLogger.error(`Session retrieval error: ${r}`),this.grant(e,t,s).then(e=>{o(e)}).catch(e=>n(e))})})}loadVhostConfig(e,t,r){return new Promise((e,i)=>{r.lb||(t=r.host),delete r.lb,r.headers={Host:t};const a=require(r.prot);delete r.prot;const h=a.request(r,r=>{let a="";r.on("data",e=>{a+=e}),r.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 r=JSON.parse(a);if(this.safe[t]=new s({cipher:this.tsv.cipher}),r.rules&&"object"==typeof r.rules&&(Object.keys(r.rules).forEach(e=>{const s=new String(r.rules[e]).valueOf(),[o,i]=this.conditionSub(s,this.safe[t]);"default"===e?(this.tsv.defaultCondition[t]=o,this.tsv.defaultProtection[t]=i):(this.tsv.locationCondition[t].push(o),this.tsv.locationProtection[t].push(i),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)),r.headers&&"object"==typeof r.headers){const e=Object.keys(r.headers).map(e=>(this.tsv.headerList[t].push(e),`'${e}': ${this.substitute(r.headers[e])}`)).join(",");o.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){i("Unable to getremote config: "+e)}}),h.on("error",e=>{i(e)}),h.end()})})}}class y 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 r=Date.now()/1e3,o=parseInt(s[0]);if(o<r-30||o>r)return this.userLogger.warn("Expired service token"),"";const i=this.resolveAlias(e);return s.indexOf(i)<2?(this.userLogger.warn(`${i} not authorizated in token`),""):s[1]}return super.fetchId(e)}}function b(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 k(e){if(e.indexOf(".")>0){const t=b(e,1);return t&&t.jti?t.jti:null}return e}function S(e,t,s=120){try{const r=e.decrypt(t).split(":");if(r.length<2)return null;const o=r[0],i=parseInt(r[1],10);if(!o||isNaN(i))return null;const n=Math.floor(Date.now()/1e3);return n-i>s||i>n+10?null:{sessionId:o,timestamp:i,domain:r[2]}}catch(e){return null}}let $;exports.class=void 0;const L={Main:m,DevOps:w,ServiceToken:y,ServiceTokenST:class extends w{fetchId(e){return y.prototype.fetchId.call(this,e)}},OAuth2:class extends m{init(){return new Promise((e,s)=>{super.init().then(()=>{if(this.tsv.oidcStorageModule)try{this.oidcSessionAcc=new t({storageModule:this.tsv.oidcStorageModule,storageModuleOptions:this.tsv.oidcStorageOptions||{}}),this.oidcSessionAcc.ready.then(()=>{this.userLogger.debug("OAuth2 OIDC session storage initialized"),e(!0)}).catch(e=>{this.userLogger.error(`Failed to initialize OIDC session storage: ${e}`),s(e)})}catch(e){this.userLogger.error(`Failed to create OIDC session accessor: ${e}`),s(e)}else this.userLogger.debug("OAuth2 handler using default session storage for OIDC"),e(!0)}).catch(s)})}fetchId(e){const t=e.headers.authorization;if(t&&t.toLowerCase().startsWith("bearer ")){const e=t.substring(7).trim();if(e){const t=k(e);return t?(this.userLogger.debug("OAuth2: extracted session ID from token"),t):(this.userLogger.warn("OAuth2: could not extract session ID from token"),"")}}return super.fetchId(e)}retrieveSession(e){return this.oidcSessionAcc?new Promise((t,s)=>{this.oidcSessionAcc.get(e).then(r=>{const o=Date.now()/1e3|0;o-r._utime>this.tsv.timeout||this.tsv.timeoutActivity&&r._lastSeen&&o-r._lastSeen>this.tsv.timeoutActivity?s(`OAuth2 session ${e} expired`):t(r)}).catch(r=>{super.retrieveSession(e).then(t).catch(s)})}):super.retrieveSession(e)}},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 r=s.substring(6).trim();if(r){const s=Math.floor(Date.now()/1e3/this.tsv.timeout)+(this.tsv.keyH||""),o=i.createHash("sha256").update(r+s).digest("hex");try{const s=Buffer.from(r,"base64").toString("utf-8"),i=s.indexOf(":");if(i>0){const r=s.substring(0,i),n=s.substring(i+1),a=e.headers["x-forwarded-for"],h=e.ip||(null===(t=e.socket)||void 0===t?void 0:t.remoteAddress)||"",c=a?`${a}, ${h}`:h;this.pendingAuth.set(o,{username:r,password:n,xff:c})}}catch(e){}return this.userLogger.debug("AuthBasic: computed session ID for credentials"),o}}return super.fetchId(e)}retrieveSession(e){const t=Object.create(null,{retrieveSession:{get:()=>super.retrieveSession}});return new Promise((s,r)=>{t.retrieveSession.call(this,e).then(t=>{this.pendingAuth.delete(e),s(t)}).catch(()=>h(this,void 0,void 0,function*(){const o=this.pendingAuth.get(e);if(!o)return void r("No session and no pending authentication");this.pendingAuth.delete(e);(yield this.createSession(e,o.username,o.password,o.xff))?t.retrieveSession.call(this,e).then(s).catch(r):r("Authentication failed")}))})}createSession(e,t,s,r){return h(this,void 0,void 0,function*(){var o;if(!/^[a-fA-F0-9]{1,64}$/.test(e))return this.userLogger.error(`AuthBasic: Invalid session ID format: ${e}`),!1;const i=this.tsv.portal();if(!i)return this.userLogger.error("AuthBasic: portal URL not configured"),!1;let n=`${i}/sessions/global/${e}?auth`;n=n.replace(/\/\/sessions\//,"/sessions/");const a={user:t,password:s,secret:(null===(o=this.tsv.cipher)||void 0===o?void 0:o.encrypt(Date.now().toString()))||""};if(this.tsv.authChoiceAuthBasic){a[this.tsv.authChoiceParam||"lmAuth"]=this.tsv.authChoiceAuthBasic}const h=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":r},body:h});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=S(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`,r=this.getCDACookie(e,s);if(r){const e=S(this.tsv.cipher,r);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 r=new RegExp(`${t}=([^;]+)`).exec(s);return r?r[1]:null}setCDACookie(e,t){}sendHeaders(e,t){if(super.sendHeaders(e,t),this.tsv.cda){const s=`${this.tsv.cookieName}cda`,r=this.getCDACookieDomain(e);r&&(e.llngCdaCookie=function(e,t,s,r=0,o=!1,i=!0){let n=`${e}=${t}`;s&&(n+=`; Domain=${s}`),n+="; Path=/",r>0&&(n+=`; Expires=${new Date(Date.now()+1e3*r).toUTCString()}`);return o&&(n+="; Secure"),i&&(n+="; HttpOnly"),n+="; SameSite=None",n}(s,t._session_id,r,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],r=s.split(".");return r.length>=2?"."+r.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"),L[e.type]?(exports.class=L[e.type],$=new L[e.type](e),$.init().then(()=>t($)).catch(e=>s(e))):import("@lemonldap-ng/handler-"+e.type.toLowerCase()).then(s=>{exports.class=s.default,$=new exports.class(e),$.init().then(()=>t($))}).catch(e=>s(e))}),exports.nginxServer=e=>{$.nginxServer(e)},exports.portal=()=>$.portal(),exports.run=(e,t,s)=>$.run(e,t,s),exports.shutdown=()=>h(void 0,void 0,void 0,function*(){$&&(yield $.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);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(A(this.tsv.locationRegexp[r][i],e))return o(this.tsv.locationCondition[r][i](t,s))}this.tsv.defaultCondition[r](t,s)?o(!0):i("Unauthorized")})}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 U={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"),U[t.type]?(exports.class=U[t.type],T=new U[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