lemonldap-ng-handler 0.7.1 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -209,7 +209,7 @@ backends:
209
209
  - Redis _(install `redis` to use them)_:
210
210
  - [Apache::Session::Redis](https://metacpan.org/pod/Apache::Session::Redis)
211
211
  - [Apache::Session::Browseable::Redis](https://metacpan.org/pod/Apache::Session::Browseable::Redis)
212
- - LDAP backends _(install `ldapjs` to use them)_:
212
+ - LDAP backends _(install `ldapts` to use them)_:
213
213
  - [Apache::Session::LDAP](https://metacpan.org/pod/Apache::Session::LDAP)
214
214
  - [Apache::Session::Browseable::LDAP](https://metacpan.org/pod/Apache::Session::Browseable::LDAP)
215
215
  - SQL backends _(install `nodedbi` to use them)_:
package/lib/cda.d.ts ADDED
@@ -0,0 +1,64 @@
1
+ /**
2
+ * CDA (Cross-Domain Authentication) utilities for LemonLDAP::NG
3
+ * Port of Lemonldap::NG::Handler::Main::CDA
4
+ *
5
+ * CDA allows authentication to be shared across different domains
6
+ * by using encrypted cookies or URL parameters.
7
+ */
8
+ import Crypto from "@lemonldap-ng/crypto";
9
+ /**
10
+ * CDA cookie value structure
11
+ */
12
+ export interface CDAValue {
13
+ sessionId: string;
14
+ timestamp: number;
15
+ domain?: string;
16
+ }
17
+ /**
18
+ * Create a CDA cookie value
19
+ * @param cipher - Crypto instance for encryption
20
+ * @param sessionId - Session ID to encode
21
+ * @param timestamp - Optional timestamp (defaults to now)
22
+ * @returns Encrypted CDA cookie value
23
+ */
24
+ export declare function createCDACookie(cipher: Crypto, sessionId: string, timestamp?: number): string;
25
+ /**
26
+ * Parse and validate a CDA cookie value
27
+ * @param cipher - Crypto instance for decryption
28
+ * @param cookieValue - Encrypted cookie value
29
+ * @param maxAge - Maximum age in seconds (default: 120)
30
+ * @returns Parsed CDA value or null if invalid
31
+ */
32
+ export declare function parseCDACookie(cipher: Crypto, cookieValue: string, maxAge?: number): CDAValue | null;
33
+ /**
34
+ * Generate CDA URL parameter
35
+ * @param cipher - Crypto instance
36
+ * @param sessionId - Session ID
37
+ * @param url - Target URL
38
+ * @returns URL with CDA parameter
39
+ */
40
+ export declare function appendCDAParam(cipher: Crypto, sessionId: string, url: string): string;
41
+ /**
42
+ * Extract CDA value from URL
43
+ * @param url - URL potentially containing CDA parameter
44
+ * @returns CDA parameter value or null
45
+ */
46
+ export declare function extractCDAFromUrl(url: string): string | null;
47
+ /**
48
+ * Build Set-Cookie header for CDA
49
+ * @param cookieName - Cookie name
50
+ * @param value - Cookie value
51
+ * @param domain - Cookie domain
52
+ * @param expiration - Expiration in seconds (0 for session cookie)
53
+ * @param secure - Whether to set Secure flag
54
+ * @param httpOnly - Whether to set HttpOnly flag
55
+ * @returns Cookie header string
56
+ */
57
+ export declare function buildCDACookieHeader(cookieName: string, value: string, domain: string, expiration?: number, secure?: boolean, httpOnly?: boolean): string;
58
+ /**
59
+ * Delete CDA cookie header
60
+ * @param cookieName - Cookie name
61
+ * @param domain - Cookie domain
62
+ * @returns Cookie header string that expires the cookie
63
+ */
64
+ export declare function deleteCDACookieHeader(cookieName: string, domain: string): string;
@@ -0,0 +1,53 @@
1
+ /**
2
+ * AuthBasic Handler for LemonLDAP::NG
3
+ * Port of Lemonldap::NG::Handler::Lib::AuthBasic
4
+ *
5
+ * This handler supports HTTP Basic Authentication by:
6
+ * 1. Computing a deterministic session ID from credentials
7
+ * 2. Checking if session exists
8
+ * 3. If not, asking the portal to create it via REST API
9
+ * 4. Sending WWW-Authenticate challenge when needed
10
+ */
11
+ import express from "express";
12
+ import http from "http";
13
+ import { LLNG_Session } from "@lemonldap-ng/types";
14
+ import LemonldapNGHandler from "./handlerMain";
15
+ declare class LemonldapNGHandlerAuthBasic extends LemonldapNGHandler {
16
+ private pendingAuth;
17
+ /**
18
+ * Override fetchId to compute session ID from Basic Auth credentials
19
+ * Session ID = sha256(base64_creds + pepper)
20
+ * pepper = int(time / timeout) + keyH (changes daily)
21
+ * @param req - HTTP request
22
+ */
23
+ fetchId(req: express.Request | http.IncomingMessage): string;
24
+ /**
25
+ * Override retrieveSession to create session via portal if needed
26
+ * @param id - Session ID
27
+ */
28
+ retrieveSession(id: string): Promise<LLNG_Session>;
29
+ /**
30
+ * Create session via portal REST API
31
+ * POST to portal/sessions/global/{id}?auth
32
+ * @param id - Session ID to create
33
+ * @param username - Username from Basic auth
34
+ * @param password - Password from Basic auth
35
+ * @param xff - X-Forwarded-For header value
36
+ * @returns true if session created successfully
37
+ */
38
+ private createSession;
39
+ /**
40
+ * Hide Authorization header from protected application
41
+ * Called after successful authentication
42
+ * @param req - HTTP request
43
+ */
44
+ hideCookie(req: express.Request | http.IncomingMessage): void;
45
+ /**
46
+ * Override goToPortal to send Basic challenge instead of redirect
47
+ * @param res - HTTP response
48
+ * @param uri - Original URI
49
+ * @param args - Additional arguments
50
+ */
51
+ goToPortal(res: http.ServerResponse, uri: string, args?: string): void;
52
+ }
53
+ export default LemonldapNGHandlerAuthBasic;
@@ -0,0 +1,58 @@
1
+ /**
2
+ * CDA (Cross-Domain Authentication) Handler for LemonLDAP::NG
3
+ * Port of Lemonldap::NG::Handler::Main with CDA support
4
+ *
5
+ * This handler enables cross-domain authentication by:
6
+ * 1. Checking for CDA cookies/parameters on incoming requests
7
+ * 2. Setting CDA cookies when users authenticate
8
+ * 3. Propagating authentication across configured domains
9
+ */
10
+ import express from "express";
11
+ import http from "http";
12
+ import LemonldapNGHandler from "./handlerMain";
13
+ declare class LemonldapNGHandlerCDA extends LemonldapNGHandler {
14
+ /**
15
+ * Override fetchId to check for CDA cookie/parameter first
16
+ * @param req - HTTP request
17
+ */
18
+ fetchId(req: express.Request | http.IncomingMessage): string;
19
+ /**
20
+ * Get CDA cookie value from request
21
+ * @param req - HTTP request
22
+ * @param cookieName - Cookie name to look for
23
+ */
24
+ private getCDACookie;
25
+ /**
26
+ * Set CDA cookie on response (placeholder for middleware integration)
27
+ *
28
+ * TODO: Implement full CDA cookie setting mechanism. Options include:
29
+ * 1. Store the value in req.llngCdaInfo and set in sendHeaders via response
30
+ * 2. Use express middleware to intercept and set the cookie
31
+ * 3. Pass response object through the call chain
32
+ *
33
+ * Currently a no-op as we don't have access to the response object here.
34
+ *
35
+ * @param _req - HTTP request (unused)
36
+ * @param _sessionId - Session ID to set (unused)
37
+ */
38
+ private setCDACookie;
39
+ /**
40
+ * Override sendHeaders to also set CDA cookie
41
+ * @param req - HTTP request
42
+ * @param session - User session
43
+ */
44
+ sendHeaders(req: express.Request | http.IncomingMessage, session: import("@lemonldap-ng/types").LLNG_Session): void;
45
+ /**
46
+ * Get domain for CDA cookie
47
+ * @param req - HTTP request
48
+ */
49
+ private getCDACookieDomain;
50
+ /**
51
+ * Override goToPortal to include CDA parameter
52
+ * @param res - HTTP response
53
+ * @param uri - Original URI
54
+ * @param args - Additional arguments
55
+ */
56
+ goToPortal(res: http.ServerResponse, uri: string, args?: string): void;
57
+ }
58
+ export default LemonldapNGHandlerCDA;
@@ -8,6 +8,9 @@ export type FastCGI_Opts = {
8
8
  ip: string | undefined;
9
9
  };
10
10
  declare class LemonldapNGHandler extends HandlerInit {
11
+ private lastSessionId;
12
+ private lastSessionData;
13
+ private lastSessionTime;
11
14
  init(): Promise<boolean>;
12
15
  /**
13
16
  * run(), the access control function
@@ -20,6 +23,11 @@ declare class LemonldapNGHandler extends HandlerInit {
20
23
  resolveAlias(req: express.Request | http.IncomingMessage): string;
21
24
  fetchId(req: express.Request | http.IncomingMessage): string;
22
25
  retrieveSession(id: string): Promise<LLNG_Session>;
26
+ /**
27
+ * Local unlog - clear session from all local caches
28
+ * @param sessionId - Optional session ID to clear (uses last cached if not provided)
29
+ */
30
+ localUnlog(sessionId?: string): Promise<void>;
23
31
  grant(req: express.Request | http.IncomingMessage, uri: string, session: LLNG_Session): Promise<boolean>;
24
32
  sendHeaders(req: express.Request | http.IncomingMessage, session: LLNG_Session): void;
25
33
  hideCookie(req: express.Request | http.IncomingMessage): void;
@@ -0,0 +1,29 @@
1
+ /**
2
+ * OAuth2/OIDC Handler for LemonLDAP::NG
3
+ * Port of Lemonldap::NG::Handler::OAuth2
4
+ *
5
+ * This handler validates OAuth2/OIDC access tokens and retrieves
6
+ * the associated session from the OIDC session storage.
7
+ */
8
+ import express from "express";
9
+ import http from "http";
10
+ import LemonldapNGHandler from "./handlerMain";
11
+ import { LLNG_Session } from "@lemonldap-ng/types";
12
+ declare class LemonldapNGHandlerOAuth2 extends LemonldapNGHandler {
13
+ private oidcSessionAcc;
14
+ /**
15
+ * Override init to also initialize OIDC session storage
16
+ */
17
+ init(): Promise<boolean>;
18
+ /**
19
+ * Override fetchId to check for OAuth2 Bearer token
20
+ * @param req - HTTP request
21
+ */
22
+ fetchId(req: express.Request | http.IncomingMessage): string;
23
+ /**
24
+ * Override retrieveSession to use OIDC session storage if token-based
25
+ * @param id - Session ID
26
+ */
27
+ retrieveSession(id: string): Promise<LLNG_Session>;
28
+ }
29
+ export default LemonldapNGHandlerOAuth2;
@@ -0,0 +1,2 @@
1
+ "use strict";function e(e,t,r,i){return new(r||(r=Promise))(function(t,o){function s(e){try{u(i.next(e))}catch(e){o(e)}}function n(e){try{u(i.throw(e))}catch(e){o(e)}}function u(e){var i;e.done?t(e.value):(i=e.value,i instanceof r?i:new r(function(e){e(i)})).then(s,n)}u((i=i.apply(e,[])).next())})}"function"==typeof SuppressedError&&SuppressedError;exports.default=class{constructor(e,t){this.logger=t,this.subscriptions=new Set,this.logger.debug("NoBroker initialized (single instance mode)")}publish(t,r){return e(this,0,void 0,function*(){this.logger.debug(`NoBroker: publish to ${t} ignored (action: ${r.action})`)})}subscribe(t){return e(this,0,void 0,function*(){this.subscriptions.add(t),this.logger.debug(`NoBroker: subscribed to ${t} (no-op)`)})}getNextMessage(t,r){return e(this,0,void 0,function*(){})}waitForNextMessage(e){return this.logger.warn(`NoBroker: waitForNextMessage called for ${e} - this will never resolve`),new Promise(()=>{})}isSubscribed(e){return this.subscriptions.has(e)}};
2
+ //# sourceMappingURL=index-DXlSn3sb.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index-DXlSn3sb.js","sources":["../../message-broker-nobroker/lib/index.mjs"],"sourcesContent":["/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise, SuppressedError, Symbol, Iterator */\r\n\r\n\r\nfunction __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\ntypeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\r\n var e = new Error(message);\r\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\r\n};\n\n/**\n * NoBroker - No-op message broker for single instance mode\n * Port of Lemonldap::NG::Common::MessageBroker::NoBroker\n *\n * This implementation doesn't actually broker messages.\n * It's used when running in single-instance mode where\n * no distributed configuration reload is needed.\n */\nclass NoBroker {\n constructor(_conf, logger) {\n this.logger = logger;\n this.subscriptions = new Set();\n this.logger.debug(\"NoBroker initialized (single instance mode)\");\n }\n /**\n * Publish a message (no-op in single instance mode)\n * @param channel - Channel name\n * @param msg - Message to publish\n */\n publish(channel, msg) {\n return __awaiter(this, void 0, void 0, function* () {\n this.logger.debug(`NoBroker: publish to ${channel} ignored (action: ${msg.action})`);\n });\n }\n /**\n * Subscribe to a channel (tracked but no-op)\n * @param channel - Channel name\n */\n subscribe(channel) {\n return __awaiter(this, void 0, void 0, function* () {\n this.subscriptions.add(channel);\n this.logger.debug(`NoBroker: subscribed to ${channel} (no-op)`);\n });\n }\n /**\n * Get next message (always returns undefined)\n * @param _channel - Channel name\n * @param _delay - Optional delay (ignored)\n */\n getNextMessage(_channel, _delay) {\n return __awaiter(this, void 0, void 0, function* () {\n return undefined;\n });\n }\n /**\n * Wait for next message (never resolves in single instance mode)\n * This method should not be called in practice with NoBroker\n * @param channel - Channel name\n */\n waitForNextMessage(channel) {\n this.logger.warn(`NoBroker: waitForNextMessage called for ${channel} - this will never resolve`);\n return new Promise(() => {\n // Never resolves - NoBroker doesn't receive messages\n });\n }\n /**\n * Check if subscribed to a channel\n * @param channel - Channel name\n */\n isSubscribed(channel) {\n return this.subscriptions.has(channel);\n }\n}\n\nexport { NoBroker as default };\n//# sourceMappingURL=index.mjs.map\n"],"names":["__awaiter","thisArg","_arguments","P","generator","Promise","resolve","reject","fulfilled","value","step","next","e","rejected","result","done","then","apply","SuppressedError","constructor","_conf","logger","this","subscriptions","Set","debug","publish","channel","msg","action","subscribe","add","getNextMessage","_channel","_delay","waitForNextMessage","warn","isSubscribed","has"],"mappings":"aAiBA,SAASA,EAAUC,EAASC,EAAYC,EAAGC,GAEvC,OAAO,IAAKD,IAAMA,EAAIE,UAAU,SAAUC,EAASC,GAC/C,SAASC,EAAUC,GAAS,IAAMC,EAAKN,EAAUO,KAAKF,GAAS,CAAE,MAAOG,GAAKL,EAAOK,EAAI,CAAE,CAC1F,SAASC,EAASJ,GAAS,IAAMC,EAAKN,EAAiB,MAAEK,GAAS,CAAE,MAAOG,GAAKL,EAAOK,EAAI,CAAE,CAC7F,SAASF,EAAKI,GAJlB,IAAeL,EAIaK,EAAOC,KAAOT,EAAQQ,EAAOL,QAJ1CA,EAIyDK,EAAOL,MAJhDA,aAAiBN,EAAIM,EAAQ,IAAIN,EAAE,SAAUG,GAAWA,EAAQG,EAAQ,IAIjBO,KAAKR,EAAWK,EAAW,CAC7GH,GAAMN,EAAYA,EAAUa,MAAMhB,EAAuB,KAAKU,OAClE,EACJ,CAE2B,mBAApBO,iBAAiCA,gCAaxC,MACI,WAAAC,CAAYC,EAAOC,GACfC,KAAKD,OAASA,EACdC,KAAKC,cAAgB,IAAIC,IACzBF,KAAKD,OAAOI,MAAM,8CACtB,CAMA,OAAAC,CAAQC,EAASC,GACb,OAAO5B,EAAUsB,KAAM,OAAQ,EAAQ,YACnCA,KAAKD,OAAOI,MAAM,wBAAwBE,sBAA4BC,EAAIC,UAC9E,EACJ,CAKA,SAAAC,CAAUH,GACN,OAAO3B,EAAUsB,KAAM,OAAQ,EAAQ,YACnCA,KAAKC,cAAcQ,IAAIJ,GACvBL,KAAKD,OAAOI,MAAM,2BAA2BE,YACjD,EACJ,CAMA,cAAAK,CAAeC,EAAUC,GACrB,OAAOlC,EAAUsB,KAAM,OAAQ,EAAQ,YAEvC,EACJ,CAMA,kBAAAa,CAAmBR,GAEf,OADAL,KAAKD,OAAOe,KAAK,2CAA2CT,+BACrD,IAAItB,QAAQ,OAGvB,CAKA,YAAAgC,CAAaV,GACT,OAAOL,KAAKC,cAAce,IAAIX,EAClC"}
package/lib/index.d.ts CHANGED
@@ -7,4 +7,9 @@ declare let currentClass: typeof LemonldapNGHandler | typeof LemonldapNGHandlerD
7
7
  export declare const init: (args: Handler_Args) => Promise<LemonldapNGHandler>;
8
8
  export declare const run: (req: express.Request | http.IncomingMessage, res: http.ServerResponse, next: Function) => any;
9
9
  export declare const nginxServer: (args: FastCGI_Opts) => void;
10
+ /**
11
+ * Shutdown the handler (stops event loop and cleanup)
12
+ * Call this in tests' afterAll to prevent Jest from hanging
13
+ */
14
+ export declare const shutdown: () => Promise<void>;
10
15
  export { currentClass as class };
package/lib/index.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var t=require("@lemonldap-ng/conf"),e=require("@lemonldap-ng/session"),s=require("@lemonldap-ng/safelib"),o=require("@lemonldap-ng/logger"),r=require("vm"),i=require("re2"),n=require("http");const a=new i("^logout(?:_sso|_app|_app_sso|)(?:s+(.*))?$","i");let c=0;const h=["cda","cookieExpiration","cipher","cookieName","customFunctions","httpOnly","securedCookie","timeout","timeoutActivity","useRedirectOnError","useRedirectOnForbidden","whatToTrace","loopBackUrl"];class l{constructor(e){this.safe={},this.tsv={defaultCondition:{},defaultProtection:{},forgeHeaders:{},headerList:{},https:{},locationCondition:{},locationCount:{},locationProtection:{},locationRegexp:{},maintenance:{},port:{},portal:()=>"",vhostAlias:{}},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]+/)}reload(){return new Promise(((t,n)=>{this.confAcc.ready.then((()=>{this.confAcc.getConf({}).then((n=>{if(h.forEach((t=>{this.tsv[t]=n[t]})),Object.keys(this.localConf).forEach((t=>{n[t]=this.localConf[t]})),["https","port","maintenance"].forEach((t=>{if(void 0!==n[t]&&(this.tsv[t]={_:n[t]},n.vhostOptions)){const s=`vhost${e=t,e.charAt(0).toUpperCase()+e.slice(1)}`;Object.keys(n.vhostOptions).forEach((e=>{const o=n.vhostOptions[e][s];o>0&&(this.tsv[t][e]=o)}))}var e})),!n.portal)throw new Error("portal should be defined");if(this.tsv.portal=()=>n.portal,!n.globalStorage||!n.globalStorageOptions)throw new Error("Missing session storage configuration");try{this.sessionAcc=new e({storageModule:n.globalStorage,storageModuleOptions:n.globalStorageOptions})}catch(t){throw new Error(`Unable to load session module: ${t}`)}Object.keys(n.locationRules).forEach((t=>{if(-1==this.vhostList.indexOf(t))return;this.tsv.locationCount[t]=0,["locationRegexp","locationProtection","locationCondition"].forEach((e=>{void 0===this.tsv[e][t]&&(this.tsv[e][t]=[])})),this.safe[t]||(this.safe[t]=new s(n));const e=n.locationRules[t];Object.keys(e).forEach((s=>{const[o,r]=this.conditionSub(e[s],this.safe[t]);"default"===s?(this.tsv.defaultCondition[t]=o,this.tsv.defaultProtection[t]=r):(this.tsv.locationCondition[t].push(o),this.tsv.locationProtection[t].push(r),this.tsv.locationRegexp[t].push(new i(s.replace(/\(\?#.*?\)/,""))),this.tsv.locationCount[t]++)})),this.tsv.defaultCondition[t]||(this.tsv.defaultCondition[t]=()=>!0,this.tsv.defaultProtection[t]=0)})),void 0!==n.exportedHeaders&&Object.keys(n.exportedHeaders).forEach((t=>{const e=n.exportedHeaders[t];if(-1==this.vhostList.indexOf(t))return;this.tsv.headerList[t]||(this.tsv.headerList[t]=[]);let s="";Object.keys(e).forEach((o=>{this.tsv.headerList[t].push(o),s+=`'${o}': ${this.substitute(e[o])},`})),s=s.replace(/,$/,""),r.runInContext(`fg = function(session) {return {${s}};}`,this.safe[t]),this.tsv.forgeHeaders[t]=this.safe[t].fg})),void 0!==n.vhostOptions&&Object.keys(n.vhostOptions).forEach((t=>{n.vhostOptions[t].aliases&&n.vhostOptions[t].aliases.forEach((e=>{this.tsv.vhostAlias[e]=t}))})),this.tsv.cookieDetect=new i(`\\b${this.tsv.cookieName}=([^;]+)`),this.sessionAcc.ready.then((()=>{t(!0),o(n,!0).then((e=>{this.userLogger=e,t(!0)})).catch((t=>{throw console.error("Logger error",t),new Error(t)}))}))})).catch((t=>{n(`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=a.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 c++,r.runInContext(`sub${c.toString()} = function(req,session) {return (${t});}`,e),[e[`sub${c.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")}}const d=(t,e)=>e.some((e=>e instanceof RegExp?e.test(t):e===t));function p(t,e){if(e={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,...e},t=t.trim(),/^data:/i.test(t))return((t,{stripHash:e})=>{const s=/^data:(?<type>[^,]*?),(?<data>[^#]*?)(?:#(?<hash>.*))?$/.exec(t);if(!s)throw new Error(`Invalid URL: ${t}`);let{type:o,data:r,hash:i}=s.groups;const n=o.split(";");i=e?"":i;let a=!1;"base64"===n[n.length-1]&&(n.pop(),a=!0);const c=(n.shift()||"").toLowerCase(),h=[...n.map((t=>{let[e,s=""]=t.split("=").map((t=>t.trim()));return"charset"===e&&(s=s.toLowerCase(),"us-ascii"===s)?"":`${e}${s?`=${s}`:""}`})).filter(Boolean)];return a&&h.push("base64"),(h.length>0||c&&"text/plain"!==c)&&h.unshift(c),`data:${h.join(";")},${a?r.trim():r}${i?`#${i}`:""}`})(t,e);if(/^view-source:/i.test(t))throw new Error("`view-source:` is not supported as it is a non-standard protocol");const s=t.startsWith("//");!s&&/^\.*\//.test(t)||(t=t.replace(/^(?!(?:\w+:)?\/\/)|^\/\//,e.defaultProtocol));const o=new URL(t);if(e.forceHttp&&e.forceHttps)throw new Error("The `forceHttp` and `forceHttps` options cannot be used together");if(e.forceHttp&&"https:"===o.protocol&&(o.protocol="http:"),e.forceHttps&&"http:"===o.protocol&&(o.protocol="https:"),e.stripAuthentication&&(o.username="",o.password=""),e.stripHash?o.hash="":e.stripTextFragment&&(o.hash=o.hash.replace(/#?:~:text.*?$/i,"")),o.pathname){const t=/\b[a-z][a-z\d+\-.]{1,50}:\/\//g;let e=0,s="";for(;;){const r=t.exec(o.pathname);if(!r)break;const i=r[0],n=r.index;s+=o.pathname.slice(e,n).replace(/\/{2,}/g,"/"),s+=i,e=n+i.length}s+=o.pathname.slice(e,o.pathname.length).replace(/\/{2,}/g,"/"),o.pathname=s}if(o.pathname)try{o.pathname=decodeURI(o.pathname)}catch{}if(!0===e.removeDirectoryIndex&&(e.removeDirectoryIndex=[/^index\.[a-z]+$/]),Array.isArray(e.removeDirectoryIndex)&&e.removeDirectoryIndex.length>0){let t=o.pathname.split("/");const s=t[t.length-1];d(s,e.removeDirectoryIndex)&&(t=t.slice(0,-1),o.pathname=t.slice(1).join("/")+"/")}if(o.hostname&&(o.hostname=o.hostname.replace(/\.$/,""),e.stripWWW&&/^www\.(?!www\.)[a-z\-\d]{1,63}\.[a-z.\-\d]{2,63}$/.test(o.hostname)&&(o.hostname=o.hostname.replace(/^www\./,""))),Array.isArray(e.removeQueryParameters))for(const t of[...o.searchParams.keys()])d(t,e.removeQueryParameters)&&o.searchParams.delete(t);if(Array.isArray(e.keepQueryParameters)||!0!==e.removeQueryParameters||(o.search=""),Array.isArray(e.keepQueryParameters)&&e.keepQueryParameters.length>0)for(const t of[...o.searchParams.keys()])d(t,e.keepQueryParameters)||o.searchParams.delete(t);if(e.sortQueryParameters){o.searchParams.sort();try{o.search=decodeURIComponent(o.search)}catch{}}e.removeTrailingSlash&&(o.pathname=o.pathname.replace(/\/$/,"")),e.removeExplicitPort&&o.port&&(o.port="");const r=t;return t=o.toString(),e.removeSingleSlash||"/"!==o.pathname||r.endsWith("/")||""!==o.hash||(t=t.replace(/\/$/,"")),(e.removeTrailingSlash||"/"===o.pathname)&&""===o.hash&&e.removeSingleSlash&&(t=t.replace(/\/$/,"")),s&&!e.normalizeProtocol&&(t=t.replace(/^http:\/\//,"//")),e.stripProtocol&&(t=t.replace(/^(?:https?:)?\/\//,"")),t}class u extends l{init(){return this.reload()}run(t,e,s){const o=t.headers.host;if(void 0===o)return this.userLogger.error("Request without Host header"),void this.setError(e,"/",400,"Bad request");const r=new URL(p(o+t.url)).pathname||"/";if(this.tsv.maintenance[o])return this.setError(e,"/",503,"Service Temporarily Unavailable");if(2===this.isUnprotected(t,r))return s();const i=this.fetchId(t);""!==i?this.retrieveSession(i).then((i=>{const n=i[this.tsv.whatToTrace];this.userLogger.debug(`User ${n} identified`),this.grant(t,r,i).then((a=>{a?(this.sendHeaders(t,i),this.hideCookie(t),s(),this.userLogger.info(`${o}: user ${n} was granted access to ${r}`)):(this.forbidden(t,e,i),this.userLogger.notice(`${o}: user ${n} was denied access to ${r}`))})).catch((t=>{console.error(t),this.setError(e,"/",503,"Service Unavailable")}))})).catch((t=>{this.goToPortal(e,this.selfUri(o,r))})):this.goToPortal(e,this.selfUri(o,r))}selfUri(t,e){return(this.tsv.https&&this.tsv.https[t]?"https":"http")+"://"+t+e}nginxServer(t){t.mode||(t.mode="fcgi"),t.port||(t.port=9090),t.ip||(t.ip="localhost");("fcgi"===t.mode?require("node-fastcgi"):n).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(this.tsv.locationRegexp[s][t].test(e))return this.tsv.locationProtection[s][t];return this.tsv.defaultProtection[s]}resolveAlias(t){var e;const s=null===(e=t.headers.host)||void 0===e?void 0:e.split(":")[0];return s?this.tsv.vhostAlias[s]||s:"undef"}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){return new Promise(((e,s)=>{if(void 0===this.sessionAcc)return s("Server not ready, please wait");this.sessionAcc.get(t).then((o=>{const r=Date.now()/1e3|0;r-o._utime>this.tsv.timeout||this.tsv.timeoutActivity&&o._lastSeen&&r-o._lastSeen>this.tsv.timeoutActivity?s(`Session ${t} expired`):(this.tsv.timeoutActivity&&r-o._lastSeen>60&&(o._lastSeen=r,this.sessionAcc.update(o)),e(o))})).catch((e=>{s(`Session ${t} can't be found in store: ${e}`)}))}))}grant(t,e,s){return new Promise(((o,r)=>{const i=this.resolveAlias(t);if(!this.tsv.defaultCondition[i])return r(`No configuration found for ${i} (or not listed in Node.js virtualHosts)`);if(this.tsv.locationRegexp[i]){let r=0;this.tsv.locationRegexp[i].forEach((n=>{if(n.test(e))return o(this.tsv.locationCondition[i][r](t,s));r++}))}this.tsv.defaultCondition[i](t,s)?o(!0):r("Unauthorized")}))}sendHeaders(t,e){const s=this.resolveAlias(t);try{let o=0;t.headers["Lm-Remote-User"]=e[this.tsv.whatToTrace];const r=this.tsv.forgeHeaders[s](e);Object.keys(r).forEach((e=>{o++,t.headers[e]=r[e],t.rawHeaders.push(e,r[e]),t.redirect||(t.headers[`Headername${o}`]=e,t.headers[`Headervalue${o}`]=r[e])}))}catch(t){return void console.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){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="+new Buffer.from(encodeURI(e)).toString("base64"):"")+(s?(e?"&":"?")+s:"");t.redirect?t.redirect(o):t.writeHead(401,{Location:o})}}class f extends u{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 r=t.cgiParams&&t.cgiParams.RULES_URL?t.cgiParams.RULES_URL:(this.tsv.loopBackUrl||"http://127.0.0.1")+"/rules.json";if(!/^(https?):\/\/([^/:]+)(?::(\d+))?(.*)$/.test(r))return new Promise(((t,e)=>e(`Bad loopBackUrl ${r}`)));const i={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(((r,n)=>{this.loadVhostConfig(t,o,i).then((()=>{this.grant(t,e,s).then((t=>{r(t)})).catch((t=>n(t)))})).catch((o=>{console.error(o),this.grant(t,e,s).then((t=>{r(t)})).catch((t=>n(t)))}))}))}loadVhostConfig(t,e,o){return new Promise(((t,n)=>{o.lb||(e=o.host),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(),[r,n]=this.conditionSub(s,this.safe[e]);"default"===t?(this.tsv.defaultCondition[e]=r,this.tsv.defaultProtection[e]=n):(this.tsv.locationCondition[e].push(r),this.tsv.locationProtection[e].push(n),this.tsv.locationRegexp[e].push(new i(t.replace(/\(\?#.*?\)/,""))),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(",");r.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){n("Unable to getremote config: "+t)}})),c.on("error",(t=>{n(t)})),c.end()}))}))}}class v extends u{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,r=parseInt(s[0]);if(r<o-30||r>o)return this.userLogger.warn("Expired service token"),"";const i=this.resolveAlias(t);return s.indexOf(i)<2?(console.warn(`${i} not authorizated in token`),""):s[1]}return super.fetchId(t)}}let g;exports.class=void 0;const m={Main:u,DevOps:f,ServiceToken:v,ServiceTokenST:class extends f{fetchId(t){return v.prototype.fetchId.call(this,t)}}};exports.init=t=>new Promise(((e,s)=>{t.type||(t.type="Main"),m[t.type]?(exports.class=m[t.type],g=new m[t.type](t),g.init().then((()=>e(g))).catch((t=>s(t)))):import("@lemonldap-ng/handler-"+t.type.toLowerCase()).then((s=>{exports.class=s.default,g=new exports.class(t),g.init().then((()=>e(g)))})).catch((t=>s(t)))})),exports.nginxServer=t=>{g.nginxServer(t)},exports.run=(t,e,s)=>g.run(t,e,s);
1
+ "use strict";var e=require("@lemonldap-ng/conf"),t=require("@lemonldap-ng/session"),s=require("@lemonldap-ng/safelib"),o=require("@lemonldap-ng/logger"),r=require("vm"),i=require("crypto"),n=require("re2"),a=require("http");function h(e,t,s,o){return new(s||(s=Promise))(function(r,i){function n(e){try{h(o.next(e))}catch(e){i(e)}}function a(e){try{h(o.throw(e))}catch(e){i(e)}}function h(e){var t;e.done?r(e.value):(t=e.value,t instanceof s?t:new s(function(e){e(t)})).then(n,a)}h((o=o.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 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");try{this.sessionAcc=new t({storageModule:a.globalStorage,storageModuleOptions:a.globalStorageOptions})}catch(e){throw new Error(`Unable to load session module: ${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[o,r]=this.conditionSub(t[s],this.safe[e]);"default"===s?(this.tsv.defaultCondition[e]=o,this.tsv.defaultProtection[e]=r):(this.tsv.locationCondition[e].push(o),this.tsv.locationProtection[e].push(r),this.tsv.locationRegexp[e].push(new n(s.replace(/\(\?#.*?\)/,""))),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(/,$/,""),r.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=>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 o=c.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++,r.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 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(()=>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}`)}})}}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:r,hash:i}=s.groups;const n=o.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?r.trim():r}${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 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 r=e.exec(o.pathname);if(!r)break;const i=r[0],n=r.index;s+=o.pathname.slice(t,n).replace(/\/{2,}/g,"/"),s+=i,t=n+i.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 r=e;return e=o.toString(),t.removeSingleSlash||"/"!==o.pathname||r.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 r=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,r))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,r,i).then(a=>{a?(this.sendHeaders(e,i),this.hideCookie(e),s(),this.userLogger.info(`${o}: user ${n} was granted access to ${r}`)):(this.forbidden(e,t,i),this.userLogger.notice(`${o}: user ${n} was denied access to ${r}`))}).catch(e=>{this.userLogger.error(`Authorization check failed: ${e}`),this.setError(t,"/",503,"Service Unavailable")})}).catch(e=>{this.goToPortal(t,this.selfUri(o,r))}):this.goToPortal(t,this.selfUri(o,r))}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){return new Promise((t,s)=>{if(void 0===this.sessionAcc)return s("Server not ready, please wait");const o=Date.now()/1e3|0,r=this.tsv.handlerInternalCache||15;if(this.lastSessionId===e&&this.lastSessionData&&o-this.lastSessionTime<r)return this.userLogger.debug(`Get session ${e} from internal cache`),t(this.lastSessionData);this.lastSessionId=null,this.lastSessionData=null,this.sessionAcc.get(e).then(r=>{o-r._utime>this.tsv.timeout||this.tsv.timeoutActivity&&r._lastSeen&&o-r._lastSeen>this.tsv.timeoutActivity?s(`Session ${e} expired`):(this.tsv.timeoutActivity&&o-r._lastSeen>60&&(r._lastSeen=o,this.sessionAcc.update(r)),this.lastSessionId=e,this.lastSessionData=r,this.lastSessionTime=o,t(r))}).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((o,r)=>{const i=this.resolveAlias(e);if(!this.tsv.defaultCondition[i])return r(`No configuration found for ${i} (or not listed in Node.js virtualHosts)`);if(this.tsv.locationRegexp[i])for(let r=0;r<this.tsv.locationRegexp[i].length;r++){if(this.tsv.locationRegexp[i][r].test(t))return o(this.tsv.locationCondition[i][r](e,s))}this.tsv.defaultCondition[i](e,s)?o(!0):r("Unauthorized")})}sendHeaders(e,t){const s=this.resolveAlias(e);try{let o=0;e.headers["Lm-Remote-User"]=t[this.tsv.whatToTrace];const r=this.tsv.forgeHeaders[s](t);Object.keys(r).forEach(t=>{o++,e.headers[t]=r[t],e.rawHeaders.push(t,r[t]),e.redirect||(e.headers[`Headername${o}`]=t,e.headers[`Headervalue${o}`]=r[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 w 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 r=e.cgiParams&&e.cgiParams.RULES_URL?e.cgiParams.RULES_URL:(this.tsv.loopBackUrl||"http://127.0.0.1")+"/rules.json";if(!/^(https?):\/\/([^/:]+)(?::(\d+))?(.*)$/.test(r))return new Promise((e,t)=>t(`Bad loopBackUrl ${r}`));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((r,n)=>{this.loadVhostConfig(e,o,i).then(()=>{this.grant(e,t,s).then(e=>{r(e)}).catch(e=>n(e))}).catch(o=>{this.userLogger.error(`Session retrieval error: ${o}`),this.grant(e,t,s).then(e=>{r(e)}).catch(e=>n(e))})})}loadVhostConfig(e,t,o){return new Promise((e,i)=>{o.lb||(t=o.host),delete o.lb,o.headers={Host:t};const a=require(o.prot);delete o.prot;const h=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(),[r,i]=this.conditionSub(s,this.safe[t]);"default"===e?(this.tsv.defaultCondition[t]=r,this.tsv.defaultProtection[t]=i):(this.tsv.locationCondition[t].push(r),this.tsv.locationProtection[t].push(i),this.tsv.locationRegexp[t].push(new n(e.replace(/\(\?#.*?\)/,""))),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(",");r.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 o=Date.now()/1e3,r=parseInt(s[0]);if(r<o-30||r>o)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 o=e.decrypt(t).split(":");if(o.length<2)return null;const r=o[0],i=parseInt(o[1],10);if(!r||isNaN(i))return null;const n=Math.floor(Date.now()/1e3);return n-i>s||i>n+10?null:{sessionId:r,timestamp:i,domain:o[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(o=>{const r=Date.now()/1e3|0;r-o._utime>this.tsv.timeout||this.tsv.timeoutActivity&&o._lastSeen&&r-o._lastSeen>this.tsv.timeoutActivity?s(`OAuth2 session ${e} expired`):t(o)}).catch(o=>{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 o=s.substring(6).trim();if(o){const s=Math.floor(Date.now()/1e3/this.tsv.timeout)+(this.tsv.keyH||""),r=i.createHash("sha256").update(o+s).digest("hex");try{const s=Buffer.from(o,"base64").toString("utf-8"),i=s.indexOf(":");if(i>0){const o=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(r,{username:o,password:n,xff:c})}}catch(e){}return this.userLogger.debug("AuthBasic: computed session ID for credentials"),r}}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(()=>h(this,void 0,void 0,function*(){const r=this.pendingAuth.get(e);if(!r)return void o("No session and no pending authentication");this.pendingAuth.delete(e);(yield this.createSession(e,r.username,r.password,r.xff))?t.retrieveSession.call(this,e).then(s).catch(o):o("Authentication failed")}))})}createSession(e,t,s,o){return h(this,void 0,void 0,function*(){var r;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===(r=this.tsv.cipher)||void 0===r?void 0:r.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":o},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`,o=this.getCDACookie(e,s);if(o){const e=S(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,r=!1,i=!0){let n=`${e}=${t}`;s&&(n+=`; Domain=${s}`),n+="; Path=/",o>0&&(n+=`; Expires=${new Date(Date.now()+1e3*o).toUTCString()}`);return r&&(n+="; Secure"),i&&(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"),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.run=(e,t,s)=>$.run(e,t,s),exports.shutdown=()=>h(void 0,void 0,void 0,function*(){$&&(yield $.stopEventLoop())});
2
2
  //# sourceMappingURL=index.js.map