@interopio/gateway-server 0.20.0 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/changelog.md CHANGED
@@ -2,6 +2,21 @@
2
2
 
3
3
  # Change Log
4
4
 
5
+ ## 0.21.0 (2026-01-27)
6
+
7
+ ### Added
8
+ - feat: support for static resources (+ welcome page detection)
9
+ - feat: support for config from JSON
10
+ - feat: disable auth/ssl via --no-auth/--no-ssl/--no-tls options
11
+ - feat: middleware support for test clients
12
+ - feat: support for disabling metrics and mesh via config
13
+
14
+ ### Changed
15
+ - `gateway-server` cli no longer exposes gateway by default (--gateway option is needed)
16
+
17
+ ### Fixed
18
+ - fix: headers mapping in test client
19
+
5
20
  ## 0.20.0 (2026-01-20)
6
21
 
7
22
  ### Added
package/dist/index.cjs CHANGED
@@ -1,8 +1,8 @@
1
- "use strict";var Xr=Object.create;var xe=Object.defineProperty;var Jr=Object.getOwnPropertyDescriptor;var Kr=Object.getOwnPropertyNames;var Yr=Object.getPrototypeOf,Qr=Object.prototype.hasOwnProperty;var Dt=(t,e)=>{for(var r in e)xe(t,r,{get:e[r],enumerable:!0})},$t=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Kr(e))!Qr.call(t,o)&&o!==r&&xe(t,o,{get:()=>e[o],enumerable:!(n=Jr(e,o))||n.enumerable});return t};var ue=(t,e,r)=>(r=t!=null?Xr(Yr(t)):{},$t(e||!t||!t.__esModule?xe(r,"default",{value:t,enumerable:!0}):r,t)),Zr=t=>$t(xe({},"__esModule",{value:!0}),t);var Ao={};Dt(Ao,{GatewayServer:()=>It,default:()=>Eo});module.exports=Zr(Ao);var It={};Dt(It,{Factory:()=>Mt,VERSION:()=>Vr});var qr=ue(require("node:http"),1),zr=ue(require("node:https"),1),jr=require("node:async_hooks");var Wt=require("node:os"),en=/^(\d+|(0x[\da-f]+))(-(\d+|(0x[\da-f]+)))?$/i;function ct(t){if(t>65535)throw new Error(`bad port ${t}`);return t}function*Ut(t){if(typeof t=="string")for(let e of t.split(",")){let r=e.trim(),n=en.exec(r);if(n){let o=parseInt(n[1]),i=parseInt(n[4]??n[1]);for(let s=ct(o);s<ct(i)+1;s++)yield s}else throw new Error(`'${e}' is not a valid port or range.`)}else yield ct(t)}var Nt=(()=>{function t(r){return r.length>0?r[0]:void 0}let e=Object.values((0,Wt.networkInterfaces)()).flatMap(r=>(r??[]).filter(n=>n.family==="IPv4")).reduce((r,n)=>(r[n.internal?"internal":"external"].push(n),r),{internal:[],external:[]});return(t(e.internal)??t(e.external))?.address})();function B(t){if(t)return t.family==="IPv6"?`[${t.address}]:${t.port}`:`${t.address}:${t.port}`}var Ft=ue(require("@interopio/gateway/logging/core"),1);function w(t){return Ft.getLogger(`gateway.server.${t}`)}function Gt(t,e){return e instanceof RegExp?e.toString():e}var Bt=require("@interopio/gateway"),_t=require("node:async_hooks"),N=w("ws"),tn=Bt.IOGateway.Encoding.json();function rn(t){let e;if(t.authenticated&&(e=t.name,e===void 0&&t.principal!==void 0)){let r=t.principal;typeof r=="object"&&r!==null&&("username"in r||"name"in r)&&(e=r.username??r.name),e===void 0&&(r==null?e="":e=String(r))}return e}function nn(t,e,r,n){let o=B(n),i=n?.address??"<unknown>",s={key:o,host:i,codec:tn,onAuthenticate:async()=>{let a=await r();if(a?.authenticated)return{type:"success",user:rn(a)};throw new Error(`no valid client authentication ${o}`)},onPing:()=>{e.ping(a=>{a?N.warn(`failed to ping ${o}`,a):N.info(`ping sent to ${o}`)})},onDisconnect:a=>{switch(a){case"inactive":{N.warn(`no heartbeat (ping) received from ${o}, closing socket`),e.close(4001,"ping expected");break}case"shutdown":{e.close(1001,"shutdown");break}}}};try{return t.client(a=>e.send(a),s)}catch(a){N.warn(`${o} failed to create client`,a)}}async function on(t){return N.info(`starting gateway on ${t.endpoint}`),await this.start(t),async({socket:e,handshake:r})=>{let{logPrefix:n,remoteAddress:o,principal:i}=r,s=(await i())?.name;N.info(`${n}connected on gw as ${s??"<anonymous>"}`);let a=await this.getGateway(s),c=nn(a,e,i,o);if(!c){N.error(`${n}gw client init failed`),e.terminate();return}e.on("error",u=>{N.error(`${n}websocket error: ${u}`,u)});let d=t.storage!==void 0?_t.AsyncLocalStorage.snapshot():void 0;e.on("message",(u,l)=>{Array.isArray(u)&&(u=Buffer.concat(u)),d!==void 0?d(()=>c.send(u)):c.send(u)}),e.on("close",u=>{N.info(`${n}disconnected from gw. code: ${u}`),c.close()})}}var qt=on;var dt=require("@interopio/gateway");var A=w("gateway-manager");function zt(){return globalThis.crypto.randomUUID().replaceAll("-","")}var Ee=class{#e;#r;#t=new Map;#n=new Map;#i;#s=!1;#o;constructor(e){this.#i={baseConfig:e.baseConfig,scope:e.scope??"principal"},this.#e=e.baseConfig.node??zt(),A.enabledFor("debug")&&A.debug(`creating default gateway with gateway id: ${this.#e}`),this.#r=dt.IOGateway.Factory({...e.baseConfig,node:this.#e})}async start(e){return this.#s?this:(this.#o=e,A.debug("starting default gateway"),await this.#r.start(e),this.#s=!0,this)}async getGateway(e){if(this.#i.scope==="singleton"||!e)return this.#r;let r=this.#n.get(e),n=r?this.#t.get(r):void 0;return n?A.enabledFor("debug")&&A.debug(`reusing existing gateway for principal '${e}'`):(A.enabledFor("debug")&&A.debug(`no existing gateway for principal '${e}', creating new one`),n=await this.createPrincipalGateway(e)),n}async createPrincipalGateway(e){let r=zt(),n={...this.#i.baseConfig,node:r};A.enabledFor("debug")&&A.debug(`creating gateway for principal '${e}' with gateway id: ${n.node}`);let o=dt.IOGateway.Factory(n);return this.#n.set(e,r),this.#t.set(r,o),await o.start(this.#o),o}getGateways(){let e=new Map(this.#t);return e.set(this.#e,this.#r),e}info(e){if(e&&this.#e!==e){let r=this.#t.get(e);if(r)return r.info();throw new Error(`no gateway found with ID: ${e}`)}return e===this.#e?this.#r.info():{...this.#r.info(),managedGateways:this.#t.size,scope:this.#i.scope}}async stop(e){if(e&&this.#e!==e){let r=this.#t.get(e);if(r){A.info(`stopping gateway with ID: ${e}`),await r.stop(),this.#t.delete(e);for(let[n,o]of this.#n.entries())if(o===e){this.#n.delete(n);break}return r}else throw new Error(`no gateway found with ID: ${e}`)}if(e===this.#e)return A.debug("stopping default gateway (managed gateways will continue running)"),await this.#r.stop(),this.#s=!1,this.#r;A.info(`stopping all gateways (1 default + ${this.#t.size} managed)`);for(let[r,n]of this.#t.entries())A.enabledFor("debug")&&A.debug(`stopping gateway with ID: ${r}`),await n.stop();return this.#t.clear(),this.#n.clear(),A.debug("stopping default gateway"),await this.#r.stop(),this.#s=!1,this.#r}getPrincipalGatewayId(e){return this.#n.get(e)}getPrincipalGatewayIds(){return new Map(this.#n)}getDefaultGateway(){return this.#r}client(e,r){return this.#r.client(e,r)}async connect(e){return this.#r.connect(e)}getPrincipalCount(){return this.#t.size}};function jt(...t){if(!Array.isArray(t))throw new Error("middleware must be array!");let e=t.flat();for(let r of e)if(typeof r!="function")throw new Error("middleware must be compose of functions!");return async function(r,n){let o=async(i,s)=>{let a=i===e.length?n:e[i];if(a===void 0)return;let c=!1,d=!1,l=await a(s,async m=>{if(c)throw new Error("next() called multiple times");c=!0;try{return await o(i+1,m??s)}finally{d=!0}});if(c&&!d)throw new Error(`middleware resolved before downstream.
2
- You are probably missing an await or return statement in your middleware function.`);return l};return o(0,r)}}var Vt=require("node:net"),He=require("tough-cookie");function sn(t,e){let r=t.get("x-forwarded-host");if(Array.isArray(r)&&(r=r[0]),r){let n=t.one("x-forwarded-port");n&&(r=`${r}:${n}`)}return r??=t.one("host"),Array.isArray(r)&&(r=r[0]),r?r.split(",",1)[0].trim():e}function an(t){let e=t.one("x-forwarded-ssl");return typeof e=="string"&&e.toLowerCase()==="on"}function cn(t,e){let r=t.get("x-forwarded-proto");return Array.isArray(r)&&(r=r[0]),r!==void 0?r.split(",",1)[0].trim():an(t)?"https":e}function dn(t,e,r){let n=r?r.port:t.protocol==="https:"?443:80,o=e.one("x-forwarded-for");if(Array.isArray(o)&&(o=o[0]),o!==void 0)return o=o.split(",",1)[0].trim(),{address:o,port:Number(n),family:(0,Vt.isIP)(o)===6?"IPv6":"IPv4"}}var Ae=class{#e;constructor(e){this.#e=e}get headers(){return this.#e}},Ce=class t extends Ae{static logIdCounter=0;#e;get id(){return this.#e===void 0&&(this.#e=`${this.initId()}-${++t.logIdCounter}`),this.#e}initId(){return"request"}get cookies(){return ln(this.headers)}parseHost(e){return sn(this.headers,e)}parseProtocol(e){return cn(this.headers,e)}parseRemoteAddress(e){return dn(this.URL,this.headers,e)}},Pe=class extends Ae{get cookies(){return pn(this.headers)}setCookieValue(e){return new He.Cookie({key:e.name,value:e.value,maxAge:e.maxAge,domain:e.domain,path:e.path,secure:e.secure,httpOnly:e.httpOnly,sameSite:e.sameSite}).toString()}};function un(t){let e=[];{let r=0,n=0;for(let o=0;o<t.length;o++)switch(t.charCodeAt(o)){case 32:r===n&&(r=n=o+1);break;case 44:e.push(t.slice(r,n)),r=n=o+1;break;default:n=n+1;break}e.push(t.slice(r,n))}return e}function Xt(t){typeof t=="string"&&(t=[t]),typeof t=="number"&&(t=[String(t)]);let e=[];if(t)for(let r of t)r&&e.push(...un(r));return e}function ln(t){return t.list("cookie").map(e=>e.split(";").map(r=>He.Cookie.parse(r))).flat(1).filter(e=>e!==void 0).map(e=>Object.freeze({name:e.key,value:e.value}))}function pn(t){return t.list("set-cookie").map(e=>{let r=He.Cookie.parse(e);if(r){let n={name:r.key,value:r.value,maxAge:Number(r.maxAge??-1)};return r.httpOnly&&(n.httpOnly=!0),r.domain&&(n.domain=r.domain),r.path&&(n.path=r.path),r.secure&&(n.secure=!0),r.httpOnly&&(n.httpOnly=!0),r.sameSite&&(n.sameSite=r.sameSite),Object.freeze(n)}}).filter(e=>e!==void 0)}var le=class{constructor(){}toList(e){let r=this.get(e);return Xt(r)}},E=class extends Map{get(e){return super.get(e.toLowerCase())}one(e){return this.get(e)?.[0]}list(e){let r=super.get(e.toLowerCase());return Xt(r)}set(e,r){return typeof r=="number"&&(r=String(r)),typeof r=="string"&&(r=[r]),r?super.set(e.toLowerCase(),r):(super.delete(e.toLowerCase()),this)}add(e,r){let n=super.get(e.toLowerCase());return typeof r=="string"&&(r=[r]),n&&(r=n.concat(r)),this.set(e,r),this}};var ut=class{#e;constructor(e){this.#e=e}get value(){return this.#e}toString(){return this.#e.toString()}},S=class t{static CONTINUE=new t(100,"Continue");static SWITCHING_PROTOCOLS=new t(101,"Switching Protocols");static OK=new t(200,"OK");static CREATED=new t(201,"Created");static ACCEPTED=new t(202,"Accepted");static NON_AUTHORITATIVE_INFORMATION=new t(203,"Non-Authoritative Information");static NO_CONTENT=new t(204,"No Content");static RESET_CONTENT=new t(205,"Reset Content");static PARTIAL_CONTENT=new t(206,"Partial Content");static MULTI_STATUS=new t(207,"Multi-Status");static IM_USED=new t(226,"IM Used");static MULTIPLE_CHOICES=new t(300,"Multiple Choices");static MOVED_PERMANENTLY=new t(301,"Moved Permanently");static BAD_REQUEST=new t(400,"Bad Request");static UNAUTHORIZED=new t(401,"Unauthorized");static FORBIDDEN=new t(403,"Forbidden");static NOT_FOUND=new t(404,"Not Found");static METHOD_NOT_ALLOWED=new t(405,"Method Not Allowed");static NOT_ACCEPTABLE=new t(406,"Not Acceptable");static PROXY_AUTHENTICATION_REQUIRED=new t(407,"Proxy Authentication Required");static REQUEST_TIMEOUT=new t(408,"Request Timeout");static CONFLICT=new t(409,"Conflict");static GONE=new t(410,"Gone");static LENGTH_REQUIRED=new t(411,"Length Required");static PRECONDITION_FAILED=new t(412,"Precondition Failed");static PAYLOAD_TOO_LARGE=new t(413,"Payload Too Large");static URI_TOO_LONG=new t(414,"URI Too Long");static UNSUPPORTED_MEDIA_TYPE=new t(415,"Unsupported Media Type");static EXPECTATION_FAILED=new t(417,"Expectation Failed");static IM_A_TEAPOT=new t(418,"I'm a teapot");static TOO_EARLY=new t(425,"Too Early");static UPGRADE_REQUIRED=new t(426,"Upgrade Required");static PRECONDITION_REQUIRED=new t(428,"Precondition Required");static TOO_MANY_REQUESTS=new t(429,"Too Many Requests");static REQUEST_HEADER_FIELDS_TOO_LARGE=new t(431,"Request Header Fields Too Large");static UNAVAILABLE_FOR_LEGAL_REASONS=new t(451,"Unavailable For Legal Reasons");static INTERNAL_SERVER_ERROR=new t(500,"Internal Server Error");static NOT_IMPLEMENTED=new t(501,"Not Implemented");static BAD_GATEWAY=new t(502,"Bad Gateway");static SERVICE_UNAVAILABLE=new t(503,"Service Unavailable");static GATEWAY_TIMEOUT=new t(504,"Gateway Timeout");static HTTP_VERSION_NOT_SUPPORTED=new t(505,"HTTP Version Not Supported");static VARIANT_ALSO_NEGOTIATES=new t(506,"Variant Also Negotiates");static INSUFFICIENT_STORAGE=new t(507,"Insufficient Storage");static LOOP_DETECTED=new t(508,"Loop Detected");static NOT_EXTENDED=new t(510,"Not Extended");static NETWORK_AUTHENTICATION_REQUIRED=new t(511,"Network Authentication Required");static#e=[];static{Object.keys(t).filter(e=>e!=="VALUES"&&e!=="resolve").forEach(e=>{let r=t[e];r instanceof t&&(Object.defineProperty(r,"name",{enumerable:!0,value:e,writable:!1}),t.#e.push(r))})}static resolve(e){for(let r of t.#e)if(r.value===e)return r}#r;#t;constructor(e,r){this.#r=e,this.#t=r}get value(){return this.#r}get phrase(){return this.#t}toString(){return`${this.#r} ${this.name}`}};function Jt(t){if(typeof t=="number"){if(t<100||t>999)throw new Error(`status code ${t} should be in range 100-999`);let e=S.resolve(t);return e!==void 0?e:new ut(t)}return t}var De=ue(require("node:http"),1),ke=class extends De.default.IncomingMessage{exchange;upgradeHead;get urlBang(){return this.url}get socketEncrypted(){return this.socket.encrypted===!0}},Y=class extends De.default.ServerResponse{markHeadersSent(){this._header=!0}getRawHeaderNames(){return super.getRawHeaderNames()}},Re=class extends Ce{#e;get sslInfo(){return this.#e===void 0&&(this.#e=this.initSslInfo()),this.#e}},Te=class extends Pe{#e=[];#r;#t="new";#n=[];setStatusCode(e){return this.#t==="committed"?!1:(this.#r=e,!0)}setRawStatusCode(e){return this.setStatusCode(e===void 0?void 0:Jt(e))}get statusCode(){return this.#r}addCookie(e){if(this.#t==="committed")throw new Error(`Cannot add cookie ${JSON.stringify(e)} because HTTP response has already been committed`);return this.#e.push(e),this}beforeCommit(e){this.#n.push(e)}get commited(){let e=this.#t;return e!=="new"&&e!=="commit-action-failed"}async body(e){if(e instanceof ReadableStream)throw new Error("ReadableStream body not supported yet");let r=await e;try{return await this.doCommit(async()=>await this.bodyInternal(Promise.resolve(r))).catch(n=>{throw n})}catch(n){throw n}}async end(){return this.commited?Promise.resolve(!1):this.doCommit(async()=>await this.bodyInternal(Promise.resolve()))}doCommit(e){let r=this.#t,n=Promise.resolve();if(r==="new")this.#t="committing",this.#n.length>0&&(n=this.#n.reduce((o,i)=>o.then(()=>i()),Promise.resolve()).catch(o=>{this.#t==="committing"&&(this.#t="commit-action-failed")}));else if(r==="commit-action-failed")this.#t="committing";else return Promise.resolve(!1);return n=n.then(()=>{this.applyStatusCode(),this.applyHeaders(),this.applyCookies(),this.#t="committed"}),n.then(async()=>e!==void 0?await e():!0)}applyStatusCode(){}applyHeaders(){}applyCookies(){}},Q=class extends Re{#e;#r;#t;constructor(e){super(new pt(e)),this.#t=e}getNativeRequest(){return this.#t}get upgrade(){return this.#t.upgrade}get http2(){return this.#t.httpVersionMajor>=2}get path(){return this.URL?.pathname}get URL(){return this.#e??=new URL(this.#t.urlBang,`${this.protocol}://${this.host}`),this.#e}get query(){return this.URL?.search}get method(){return this.#t.method}get host(){let e;return this.#t.httpVersionMajor>=2&&(e=this.#t.headers[":authority"]),e??=this.#t.socket.remoteAddress,super.parseHost(e)}get protocol(){let e;return this.#t.httpVersionMajor>2&&(e=this.#t.headers[":scheme"]),e??=this.#t.socketEncrypted?"https":"http",super.parseProtocol(e)}get socket(){return this.#t.socket}get remoteAddress(){let e=this.#t.socket.remoteFamily,r=this.#t.socket.remoteAddress,n=this.#t.socket.remotePort,o=!e||!r||!n?void 0:{family:e,address:r,port:n};return super.parseRemoteAddress(o)??o}initSslInfo(){if(this.#t.socketEncrypted)return new lt(this.#t.socket)}get cookies(){return this.#r??=super.cookies,this.#r}get body(){return De.default.IncomingMessage.toWeb(this.#t)}async blob(){let e=[];if(this.body!==void 0)for await(let r of this.body)e.push(r);return new Blob(e,{type:this.headers.one("content-type")||"application/octet-stream"})}async text(){return await(await this.blob()).text()}async formData(){let r=await(await this.blob()).text();return new URLSearchParams(r)}async json(){let e=await this.blob();if(e.size===0)return;let r=await e.text();return JSON.parse(r)}initId(){let e=this.#t.socket.remoteAddress;if(!e)throw new Error("Socket has no remote address");return`${e}:${this.#t.socket.remotePort}`}},lt=class{peerCertificate;constructor(e){this.peerCertificate=e.getPeerX509Certificate()}},pt=class extends le{#e;constructor(e){super(),this.#e=e}has(e){return this.#e.headers[e]!==void 0}get(e){return this.#e.headers[e]}list(e){return super.toList(e)}one(e){let r=this.#e.headers[e];return Array.isArray(r)?r[0]:r}keys(){return Object.keys(this.#e.headers).values()}},ht=class extends le{#e;constructor(e){super(),this.#e=e}has(e){return this.#e.hasHeader(e)}keys(){return this.#e.getHeaderNames().values()}get(e){return this.#e.getHeader(e)}one(e){let r=this.#e.getHeader(e);return Array.isArray(r)?r[0]:r}set(e,r){return this.#e.headersSent||(Array.isArray(r)?r=r.map(n=>typeof n=="number"?String(n):n):typeof r=="number"&&(r=String(r)),r?this.#e.setHeader(e,r):this.#e.removeHeader(e)),this}add(e,r){return this.#e.headersSent||this.#e.appendHeader(e,r),this}list(e){return super.toList(e)}},Oe=class extends Te{#e;constructor(e){super(new ht(e)),this.#e=e}getNativeResponse(){return this.#e}get statusCode(){return super.statusCode??{value:this.#e.statusCode}}applyStatusCode(){let e=super.statusCode;e!==void 0&&(this.#e.statusCode=e.value)}addCookie(e){return this.headers.add("Set-Cookie",super.setCookieValue(e)),this}async bodyInternal(e){if(this.#e.headersSent)return!1;if(e instanceof ReadableStream)throw new Error("ReadableStream body not supported in response");{let r=await e;return await new Promise((n,o)=>{try{r===void 0?this.#e.end(()=>{n(!0)}):(this.headers.has("content-length")||(typeof r=="string"?this.headers.set("content-length",Buffer.byteLength(r)):r instanceof Blob?this.headers.set("content-length",r.size):this.headers.set("content-length",r.byteLength)),this.#e.end(r,()=>{n(!0)}))}catch(i){o(i instanceof Error?i:new Error(`end failed: ${i}`))}})}}},Me=class t{#e;constructor(e){this.#e=e}get delegate(){return this.#e}get id(){return this.#e.id}get method(){return this.#e.method}get path(){return this.#e.path}get protocol(){return this.#e.protocol}get host(){return this.#e.host}get URL(){return this.#e.URL}get headers(){return this.#e.headers}get cookies(){return this.#e.cookies}get remoteAddress(){return this.#e.remoteAddress}get upgrade(){return this.#e.upgrade}get sslInfo(){return this.#e.sslInfo}get body(){return this.#e.body}async blob(){return await this.#e.blob()}async text(){return await this.#e.text()}async formData(){return await this.#e.formData()}async json(){return await this.#e.json()}toString(){return`${t.name} [delegate: ${this.delegate.toString()}]`}static getNativeRequest(e){if(e instanceof Re)return e.getNativeRequest();if(e instanceof t)return t.getNativeRequest(e.delegate);throw new Error(`Cannot get native request from ${e.constructor.name}`)}},Z=class t{#e;constructor(e){this.#e=e}get delegate(){return this.#e}setStatusCode(e){return this.delegate.setStatusCode(e)}setRawStatusCode(e){return this.delegate.setRawStatusCode(e)}get statusCode(){return this.delegate.statusCode}get cookies(){return this.delegate.cookies}addCookie(e){return this.delegate.addCookie(e),this}async end(){return await this.delegate.end()}async body(e){return await this.#e.body(e)}get headers(){return this.#e.headers}toString(){return`${t.name} [delegate: ${this.delegate.toString()}]`}static getNativeResponse(e){if(e instanceof Te)return e.getNativeResponse();if(e instanceof t)return t.getNativeResponse(e.delegate);throw new Error(`Cannot get native response from ${e.constructor.name}`)}},Ie=class t{#e;constructor(e){this.#e=e}get delegate(){return this.#e}get request(){return this.#e.request}get response(){return this.#e.response}attribute(e){return this.#e.attribute(e)}principal(){return this.#e.principal()}get logPrefix(){return this.#e.logPrefix}toString(){return`${t.name} [delegate: ${this.delegate}]`}},Le=class{request;response;#e={};#r;#t="";constructor(e,r){this.#e[Kt]=e.id,this.request=e,this.response=r}get method(){return this.request.method}get path(){return this.request.path}get attributes(){return this.#e}attribute(e){return this.attributes[e]}principal(){return Promise.resolve(void 0)}get logPrefix(){let e=this.attribute(Kt);return this.#r!==e&&(this.#r=e,this.#t=e!==void 0?`[${e}] `:""),this.#t}},Kt="io.interop.gateway.server.log_id";var $e=require("node:v8"),F=require("node:fs/promises"),b=w("monitoring"),hn={memoryLimit:1024*1024*1024,reportInterval:600*1e3,dumpLocation:".",maxBackups:10,dumpPrefix:"Heap"};function fn(){return(0,$e.getHeapStatistics)()}async function Yt(t){let e=t.dumpPrefix??"Heap",r=`${t.dumpLocation}/${e}.heapsnapshot`;b.enabledFor("debug")&&b.debug(`starting heap dump in ${r}`),await ft(t.dumpLocation).catch(async o=>{b.enabledFor("debug")&&b.debug(`dump location ${t.dumpLocation} does not exists. Will try to create it`);try{await(0,F.mkdir)(t.dumpLocation,{recursive:!0}),b.info(`dump location dir ${t.dumpLocation} successfully created`)}catch{b.error(`failed to create dump location ${t.dumpLocation}`)}});let n=(0,$e.writeHeapSnapshot)(r);b.info("heap dumped");try{b.debug("rolling snapshot backups");let o=`${t.dumpLocation}/${e}.${t.maxBackups}.heapsnapshot`;await ft(o).then(async()=>{b.enabledFor("debug")&&b.debug(`deleting ${o}`);try{await(0,F.unlink)(o)}catch(s){b.warn(`failed to delete ${o}`,s)}}).catch(()=>{});for(let s=t.maxBackups-1;s>0;s--){let a=`${t.dumpLocation}/${e}.${s}.heapsnapshot`,c=`${t.dumpLocation}/${e}.${s+1}.heapsnapshot`;await ft(a).then(async()=>{try{await(0,F.rename)(a,c)}catch(d){b.warn(`failed to rename ${a} to ${c}`,d)}}).catch(()=>{})}let i=`${t.dumpLocation}/${e}.1.heapsnapshot`;try{await(0,F.rename)(n,i)}catch(s){b.warn(`failed to rename ${n} to ${i}`,s)}b.debug("snapshots rolled")}catch(o){throw b.error("error rolling backups",o),o}}async function ft(t){b.enabledFor("trace")&&b.debug(`checking file ${t}`),await(0,F.access)(t)}async function gn(t,e,r){b.enabledFor("debug")&&b.debug(`processing heap stats ${JSON.stringify(t)}`);let n=Math.min(r.memoryLimit,.95*t.heap_size_limit),o=t.used_heap_size;b.info(`heap stats ${JSON.stringify(t)}`),o>=n?(b.warn(`used heap ${o} bytes exceeds memory limit ${n} bytes`),e.memoryLimitExceeded?delete e.snapshot:(e.memoryLimitExceeded=!0,e.snapshot=!0),await Yt(r)):(e.memoryLimitExceeded=!1,delete e.snapshot)}function Qt(t){let e={...hn,...t},r=!1,n={memoryLimitExceeded:!1},o=async()=>{let a=fn();await gn(a,n,e)},i=setInterval(o,e.reportInterval);return{...e,channel:async a=>{if(!r)switch(a??="run",a){case"run":{await o();break}case"dump":{await Yt(e);break}case"stop":{r=!0,clearInterval(i),b.info("exit memory diagnostic");break}}return r}}}async function mn({channel:t},e){await t(e)||b.warn(`cannot execute command "${e}" already closed`)}async function Zt(t){return await mn(t,"stop")}var wn=(t,e)=>(e??=t,async({response:r},n)=>{e!==!1&&!r.headers.has("server")&&r.headers.set("Server",e),await n()}),er=(t,e)=>wn(t,e);var pe=require("@interopio/gateway");var gt=w("gateway.ws.client-verify");function Sn(t){switch(t.missing){case"allow":case"whitelist":return!0;case"block":case"blacklist":return!1;default:return!1}}function bn(t,e){let r=t.block??t.blacklist,n=t.allow??t.whitelist;if(r.length>0&&pe.IOGateway.Filtering.valuesMatch(r,e))return gt.warn(`origin ${e} matches block filter`),!1;if(n.length>0&&pe.IOGateway.Filtering.valuesMatch(n,e))return gt.enabledFor("debug")&&gt.debug(`origin ${e} matches allow filter`),!0}function vn(t){switch(t.non_matched){case"allow":case"whitelist":return!0;case"block":case"blacklist":return!1;default:return!1}}function tr(t,e){if(!e)return!0;if(t){let r=bn(e,t);return r||vn(e)}else return Sn(e)}function rr(t){if(t){let e=(t.block??t.blacklist??[]).map(pe.IOGateway.Filtering.regexify),r=(t.allow??t.whitelist??[]).map(pe.IOGateway.Filtering.regexify);return{non_matched:t.non_matched??"allow",missing:t.missing??"allow",allow:r,block:e}}}var nr=t=>async e=>{for(let r of t)if((await r(e)).match)return T();return H},ee=t=>{let e=async r=>{for(let n of t)if(!(await n(r)).match)return H;return T()};return e.toString=()=>`and(${t.map(r=>r.toString()).join(", ")})`,e},or=t=>async e=>(await t(e)).match?H:T(),he=async t=>T();he.toString=()=>"any-exchange";var ir=Object.freeze({}),H=Object.freeze({match:!1,variables:ir}),T=(t=ir)=>({match:!0,variables:t}),O=(t,e)=>{let r=e?.method,n=async o=>{let i=o.request,s=i.path;if(r!==void 0&&i.method!==r)return H;if(typeof t=="string")return s===t?T():H;{let a=t.exec(s);return a===null?H:{match:!0,variables:{...a.groups}}}};return n.toString=()=>`pattern(${t.toString()}, method=${r??"<any>"})`,n},mt=t=>{let e=r=>{if(t.ignoredMediaTypes!==void 0){for(let n of t.ignoredMediaTypes)if(r===n||n==="*/*")return!0}return!1};return async r=>{let n=r.request,o;try{o=n.headers.list("accept")}catch{return H}for(let i of o)if(!e(i)){for(let s of t.mediaTypes)if(i.startsWith(s))return T()}return H}},V=async({request:t})=>t.upgrade&&t.headers.one("upgrade")?.toLowerCase()==="websocket"?T():H;V.toString=()=>"websocket upgrade";var yt=require("@interopio/gateway");async function wt(t,e,r){let n=(i,s)=>{if(s?.cors){let a=s.cors===!0?{allowOrigins:s.origins?.allow?.map(yt.IOGateway.Filtering.regexify),allowMethods:i.method===void 0?["*"]:[i.method],allowCredentials:s.authorize?.access!=="permitted"?!0:void 0}:s.cors,c=i.path;r.cors.push([c,a])}},o=new class{handle(...i){i.forEach(({request:s,options:a,handler:c})=>{let d=O(yt.IOGateway.Filtering.regexify(s.path),{method:s.method});a?.authorize&&r.authorize.push([d,a.authorize]),n(s,a);let u=async(l,m)=>{let{match:x,variables:p}=await d(l);x?await c(l,p):await m()};r.middleware.push(u)})}socket(...i){for(let{path:s,factory:a,options:c}of i){let d=s??"/";r.sockets.set(d,{default:s===void 0,ping:c?.ping,factory:a,maxConnections:c?.maxConnections,authorize:c?.authorize,originFilters:rr(c?.origins)})}}};await t(o,e)}var Ne=require("@interopio/gateway");function En(t){let e=t.headers.one("origin");if(e===void 0)return!0;let r=t.URL,n=r.protocol,o=r.host,i=URL.parse(e),s=i?.host,a=i?.protocol;return n===a&&o===s}function An(t){return t.headers.has("origin")&&!En(t)}function ar(t){return t.method==="OPTIONS"&&t.headers.has("origin")&&t.headers.has("access-control-request-method")}var sr=["Origin","Access-Control-Request-Method","Access-Control-Request-Headers"],Cn=(t,e)=>{let{request:r,response:n}=t,o=n.headers;if(!o.has("Vary"))o.set("Vary",sr.join(", "));else{let s=o.list("Vary");for(let a of sr)s.find(c=>c===a)||s.push(a);o.set("Vary",s.join(", "))}try{if(!An(r))return!0}catch{return M.enabledFor("debug")&&M.debug("reject: origin is malformed"),fe(n),!1}if(o.has("access-control-allow-origin"))return M.enabledFor("trace")&&M.debug('skip: already contains "Access-Control-Allow-Origin"'),!0;let i=ar(r);return e?Hn(t,e,i):i?(fe(n),!1):!0},Ue=["*"],St=["GET","HEAD","POST"],cr={allowOrigins:Ue,allowMethods:St,allowHeaders:Ue,maxAge:1800};function Fe(t){if(t){let e=t.allowHeaders;e&&e!==v&&(t={...t,allowHeaders:e.map(n=>n.toLowerCase())});let r=t.allowOrigins;return r&&(r==="*"?(ur(t),lr(t)):t={...t,allowOrigins:r.map(n=>typeof n=="string"&&n!==v&&(n=Ne.IOGateway.Filtering.regexify(n),typeof n=="string")?pr(n).toLowerCase():n)}),t}}function We(t,e){if(e===void 0)return t!==void 0?t===v?[v]:t:[];if(t===void 0)return e===v?[v]:e;if(t==Ue||t===St)return e===v?[v]:e;if(e==Ue||e===St)return t===v?[v]:t;if(t===v||t.includes(v)||e===v||e.includes(v))return[v];let r=new Set;return t.forEach(n=>r.add(n)),e.forEach(n=>r.add(n)),Array.from(r)}var ge=(t,e)=>e===void 0?t:{allowOrigins:We(t.allowOrigins,e?.allowOrigins),allowMethods:We(t.allowMethods,e?.allowMethods),allowHeaders:We(t.allowHeaders,e?.allowHeaders),exposeHeaders:We(t.exposeHeaders,e?.exposeHeaders),allowCredentials:e?.allowCredentials??t.allowCredentials,allowPrivateNetwork:e?.allowPrivateNetwork??t.allowPrivateNetwork,maxAge:e?.maxAge??t.maxAge},Pn=t=>{let e=t.corsConfigSource,r=t.corsProcessor??Cn;if(e===void 0)throw new Error("corsConfigSource is required");if(r===void 0)throw new Error("corsProcessor is required");return async(n,o)=>{let i=await e(n);!r(n,i)||ar(n.request)||await o()}},dr=Pn,M=w("cors");function fe(t){t.setStatusCode(S.FORBIDDEN)}function Hn(t,e,r){let{request:n,response:o}=t,i=o.headers,s=n.headers.one("origin"),a=Rn(e,s);if(a===void 0)return M.enabledFor("debug")&&M.debug(`reject: '${s}' origin is not allowed`),fe(o),!1;let c=Mn(n,r),d=Tn(e,c);if(d===void 0)return M.enabledFor("debug")&&M.debug(`reject: HTTP '${c}' is not allowed`),fe(o),!1;let u=In(n,r),l=On(e,u);if(r&&l===void 0)return M.enabledFor("debug")&&M.debug(`reject: headers '${u}' are not allowed`),fe(o),!1;i.set("Access-Control-Allow-Origin",a),r&&i.set("Access-Control-Allow-Methods",d.join(",")),r&&l!==void 0&&l.length>0&&i.set("Access-Control-Allow-Headers",l.join(", "));let m=e.exposeHeaders;return m&&m.length>0&&i.set("Access-Control-Expose-Headers",m.join(", ")),e.allowCredentials&&i.set("Access-Control-Allow-Credentials","true"),e.allowPrivateNetwork&&n.headers.one("access-control-request-private-network")==="true"&&i.set("Access-Control-Allow-Private-Network","true"),r&&e.maxAge!==void 0&&i.set("Access-Control-Max-Age",e.maxAge.toString()),!0}var v="*",kn=["GET","HEAD"];function ur(t){if(t.allowCredentials===!0&&t.allowOrigins===v)throw new Error('when allowCredentials is true allowOrigins cannot be "*"')}function lr(t){if(t.allowPrivateNetwork===!0&&t.allowOrigins===v)throw new Error('when allowPrivateNetwork is true allowOrigins cannot be "*"')}function Rn(t,e){if(e){let r=t.allowOrigins;if(r){if(r===v)return ur(t),lr(t),v;let n=pr(e.toLowerCase());for(let o of r)if(o===v||Ne.IOGateway.Filtering.valueMatches(o,n))return e}}}function Tn(t,e){if(e){let r=t.allowMethods??kn;if(r===v)return[e];if(Ne.IOGateway.Filtering.valuesMatch(r,e))return r}}function On(t,e){if(e===void 0)return;if(e.length==0)return[];let r=t.allowHeaders;if(r===void 0)return;let n=r===v||r.includes(v),o=[];for(let i of e){let s=i?.trim();if(s){if(n)o.push(s);else for(let a of r)if(s.toLowerCase()===a){o.push(s);break}}}if(o.length>0)return o}function pr(t){return t.endsWith("/")?t.slice(0,-1):t}function Mn(t,e){return e?t.headers.one("access-control-request-method"):t.method}function In(t,e){let r=t.headers;return e?r.list("access-control-request-headers"):Array.from(r.keys())}var hr=t=>async e=>{for(let[r,n]of t.mappings)if((await r(e)).match)return M.debug(`resolved cors config on '${e.request.path}' using ${r}: ${JSON.stringify(n)}`),n};var fr=require("@interopio/gateway");function gr(t){let{sockets:e,cors:r}=t,n=t.corsConfig===!1?void 0:ge(cr,t.corsConfig),o=[];for(let[s,a]of e){let c=n;for(let[u,l]of r)fr.IOGateway.Filtering.valueMatches(u,s)&&(l===void 0?c=void 0:c=c===void 0?l:ge(c,l));let d=t.corsConfig===!1?void 0:{allowOrigins:a.originFilters?.allow,allowMethods:["GET","CONNECT","OPTIONS"],allowHeaders:["Upgrade","Connection","Origin","Sec-Websocket-Key","Sec-Websocket-Version","Sec-Websocket-Protocol","Sec-Websocket-Extensions"],exposeHeaders:["Sec-Websocket-Accept","Sec-Websocket-Protocol","Sec-Websocket-Extensions"],allowCredentials:a.authorize?.access!=="permitted"?!0:void 0};c=c===void 0?d:ge(c,d),o.push([ee([V,O(s)]),Fe(c)])}let i=[];for(let[s,a]of r){let[,c]=i.find(([u])=>String(u)===String(s))??[s,n];c=c===void 0?a:ge(c,a);let d=!1;for(let u of i)if(String(u[0])===String(s)){u[1]=c,d=!0;break}d||i.push([s,c])}for(let[s,a]of i)o.push([O(s),Fe(a)]);return o.push([O(/\/api\/.*/),Fe(n)]),hr({mappings:o})}function mr(t){return t!==void 0&&typeof t.type=="string"&&typeof t.authenticated=="boolean"}var C=class extends Error{_authentication;get authentication(){return this._authentication}set authentication(e){if(e===void 0)throw new TypeError("Authentication cannot be undefined");this._authentication=e}},Ge=class extends C{},te=class extends C{},re=class extends C{constructor(e){super(e)}},me=class extends re{constructor(e){super(e)}},ye=class extends re{constructor(e){super(e)}},we=class extends re{constructor(e){super(e)}},Se=class extends re{constructor(e){super(e)}};var X=class extends Error{},G=class{constructor(e){this.granted=e}granted},_=class{#e;constructor(e){this.#e=e}async verify(e,r){if(!(await this.#e(e,r))?.granted)throw new X("Access denied")}async authorize(e,r){return await this.#e(e,r)}},ne=class extends C{};var I=t=>async e=>{let r=!0,{response:n}=e;for(let o of t.keys())n.headers.has(o)&&(r=!1);if(r)for(let[o,i]of t)n.headers.set(o,i)},Ln=()=>I(new E().add("cache-control","no-cache, no-store, max-age=0, must-revalidate").add("pragma","no-cache").add("expires","0")),Dn=()=>I(new E().add("x-content-type-options","nosniff")),$n=(t,e,r)=>{let n=`max-age=${t}`;e&&(n+=" ; includeSubDomains"),r&&(n+=" ; preload");let o=I(new E().add("strict-transport-security",n)),i=s=>s.request.URL.protocol==="https:";return async s=>{i(s)&&await o(s)}},Wn=t=>I(new E().add("x-frame-options",t)),Un=t=>I(new E().add("x-xss-protection",t)),Nn=t=>{let e=t===void 0?void 0:I(new E().add("permissions-policy",t));return async r=>{e!==void 0&&await e(r)}},Fn=(t,e)=>{let r=e?"content-security-policy-report-only":"content-security-policy",n=t===void 0?void 0:I(new E().add(r,t));return async o=>{n!==void 0&&await n(o)}},Gn=(t="no-referrer")=>I(new E().add("referer-policy",t)),Bn=t=>{let e=t===void 0?void 0:I(new E().add("cross-origin-opener-policy",t));return async r=>{e!==void 0&&await e(r)}},_n=t=>{let e=t===void 0?void 0:I(new E().add("cross-origin-embedder-policy",t));return async r=>{e!==void 0&&await e(r)}},qn=t=>{let e=t===void 0?void 0:I(new E().add("cross-origin-resource-policy",t));return async r=>{e!==void 0&&await e(r)}},zn=(...t)=>async e=>{for(let r of t)await r(e)};function bt(t){let e=[];t?.cache?.disabled||e.push(Ln()),t?.contentType?.disabled||e.push(Dn()),t?.hsts?.disabled||e.push($n(t?.hsts?.maxAge??365*24*60*60,t?.hsts?.includeSubDomains??!0,t?.hsts?.preload??!1)),t?.frameOptions?.disabled||e.push(Wn(t?.frameOptions?.mode??"DENY")),t?.xss?.disabled||e.push(Un(t?.xss?.headerValue??"0")),t?.permissionsPolicy?.disabled||e.push(Nn(t?.permissionsPolicy?.policyDirectives)),t?.contentSecurityPolicy?.disabled||e.push(Fn(t?.contentSecurityPolicy?.policyDirectives??"default-src 'self'",t?.contentSecurityPolicy?.reportOnly)),t?.refererPolicy?.disabled||e.push(Gn(t?.refererPolicy?.policy??"no-referrer")),t?.crossOriginOpenerPolicy?.disabled||e.push(Bn(t?.crossOriginOpenerPolicy?.policy)),t?.crossOriginEmbedderPolicy?.disabled||e.push(_n(t?.crossOriginEmbedderPolicy?.policy)),t?.crossOriginResourcePolicy?.disabled||e.push(qn(t?.crossOriginResourcePolicy?.policy)),t?.writers&&e.push(...t.writers);let r=zn(...e);return async(n,o)=>{await r(n),await o()}}var oe=t=>{let e=t.entryPoint,r=t?.rethrowAuthenticationServiceError??!0;return async({exchange:n},o)=>{if(!r||!(o instanceof ne))return e(n,o);throw o}};var jn="Realm",Vn=t=>`Basic realm="${t}"`,ie=t=>{let e=Vn(t?.realm??jn);return async(r,n)=>{let{response:o}=r;o.setStatusCode(S.UNAUTHORIZED),o.headers.set("WWW-Authenticate",e)}};var yr="Basic ",Be=t=>{let e=t?.credentialsEncoding??"utf-8";return async r=>{let{request:n}=r,o=n.headers.one("authorization");if(!o||!/basic/i.test(o.substring(0)))return;let i=o.length<=yr.length?"":o.substring(yr.length),a=Buffer.from(i,"base64").toString(e).split(":",2);if(a.length!==2)return;let c=a[0],d=a[1];return{type:"UsernamePassword",authenticated:!1,principal:c,credentials:d,name:c,eraseCredentials:()=>{d=null}}}};var wr=require("node:async_hooks"),q=class t{static hasSecurityContext(e){return e.getStore()?.securityContext!==void 0}static async getSecurityContext(e){return await e.getStore()?.securityContext}static clearSecurityContext(e){delete e.getStore()?.securityContext}static withSecurityContext(e){return(r=new wr.AsyncLocalStorage)=>(r.getStore().securityContext=e,r)}static withAuthentication(e){return t.withSecurityContext(Promise.resolve({authentication:e}))}static async getContext(e){if(t.hasSecurityContext(e))return t.getSecurityContext(e)}};async function Xn(t,e,r,n,o,i){let a=await(await n(t))?.(r);if(a===void 0)throw new Error("No authentication manager found for the exchange");try{await Jn(a,{exchange:t,next:e},o,i)}catch(c){throw c instanceof C,c}}async function Jn(t,e,r,n){q.withAuthentication(t)(n),await r(e,t)}function z(t){let e={matcher:he,successHandler:async({next:n})=>{await n()},converter:Be({}),failureHandler:oe({entryPoint:ie({})}),...t},r=e.managerResolver;if(r===void 0&&e.manager!==void 0){let n=e.manager;r=async o=>n}if(r===void 0)throw new Error("Authentication filter requires a managerResolver or a manager");return async(n,o)=>{let s=(await e.matcher(n)).match?await e.converter(n):void 0;if(s===void 0){await o();return}try{await Xn(n,o,s,r,e.successHandler,e.storage)}catch(a){if(a instanceof C){await e.failureHandler({exchange:n,next:o},a);return}throw a}}}var Sr=t=>async(e,r)=>{e.response.setStatusCode(t.httpStatus)};var se=w("auth.entry-point"),_e=t=>{let e=t.defaultEntryPoint??(async({response:r},n)=>{r.setStatusCode(S.UNAUTHORIZED),await r.end()});return async(r,n)=>{for(let[o,i]of t.entryPoints)if(se.enabledFor("debug")&&se.debug(`trying to match using: ${o}`),(await o(r)).match)return se.enabledFor("debug")&&se.debug(`match found. using default entry point ${i}`),i(r,n);return se.enabledFor("debug")&&se.debug(`no match found. using default entry point ${e}`),e(r,n)}};var br=t=>async({exchange:e,next:r},n)=>{for(let o of t)await o({exchange:e,next:r},n)};function vt(t){let e=async m=>m.request.headers.list("X-Requested-With").includes("XMLHttpRequest")?T():H,r=_e({entryPoints:[[e,Sr({httpStatus:S.UNAUTHORIZED})]],defaultEntryPoint:ie({})}),n=t.entryPoint??r,o=t.manager,i=mt({mediaTypes:["application/atom+xml","application/x-www-form-urlencoded","application/json","application/octet-stream","application/xml","multipart/form-data","text/xml"],ignoredMediaTypes:["*/*"]}),s=or(mt({mediaTypes:["text/html"]})),a=ee([s,i]),c=nr([e,a]);t.defaultEntryPoints.push([c,n]);let d=t.failureHandler??oe({entryPoint:n}),u=br(t.successHandlers??t.defaultSuccessHandlers),l=Be({});return z({storage:t.storage,manager:o,failureHandler:d,successHandler:u,converter:l})}var vr={invalid_request:"invalid_request",invalid_token:"invalid_token",insufficient_scope:"insufficient_scope"},xr="https://tools.ietf.org/html/rfc6750#section-3.1";function qe(t){return{errorCode:vr.invalid_token,httpStatus:S.UNAUTHORIZED,description:t,uri:xr}}function xt(t){return{errorCode:vr.invalid_request,httpStatus:S.BAD_REQUEST,description:t,uri:xr}}var Kn="access_token",Yn=/^Bearer\s+(?<token>[a-zA-Z0-9-._~+/]+=*)$/i,D=class extends C{error;constructor(e,r,n){super(r??(typeof e=="string"?void 0:e.description),n),this.error=typeof e=="string"?{errorCode:e}:e}},Er=t=>t.type==="BearerToken",Qn=t=>async e=>{let{request:r}=e;return Promise.all([eo(r.headers,t?.headerName).then(n=>n!==void 0?[n]:void 0),to(r,t?.uriQueryParameter),ro(e,t?.formEncodedBodyParameter)]).then(n=>n.filter(o=>o!==void 0).flat(1)).then(Zn).then(n=>{if(n)return{authenticated:!1,type:"BearerToken",token:n}})};async function Zn(t){if(t.length===0)return;if(t.length>1){let r=xt("Found multiple access tokens in the request");throw new D(r)}let e=t[0];if(!e||e.length===0){let r=xt("The requested access token parameter is an empty string");throw new D(r)}return e}async function eo(t,e="authorization"){let r=t.one(e);if(!r||!/bearer/i.test(r.substring(0)))return;let n=Yn.exec(r);if(n===null){let o=qe("Bearer token is malformed");throw new D(o)}return n.groups?.token}async function Ar(t){let e=t.getAll(Kn);if(e.length!==0)return e}async function to(t,e=!1){if(!(!e||t.method!=="GET"))return Ar(t.URL.searchParams)}async function ro(t,e=!1){let{request:r}=t;if(!e||r.headers.one("content-type")!=="application/x-www-form-urlencoded"||r.method!=="POST")return;let n=await t.request.formData();if(n)return Ar(n)}var ze=Qn;function no(t){let e="Bearer";if(t.size!==0){e+=" ";let r=0;for(let[n,o]of t)e+=`${n}="${o}"`,r!==t.size-1&&(e+=", "),r++}return e}var Cr=t=>t.httpStatus!==void 0;function oo(t){if(t instanceof D){let{error:e}=t;if(Cr(e))return e.httpStatus}return S.UNAUTHORIZED}function io(t,e){let r=new Map;if(e&&r.set("realm",e),t instanceof D){let{error:n}=t;r.set("error",n.errorCode),n.description&&r.set("error_description",n.description),n.uri&&r.set("error_uri",n.uri),Cr(n)&&n.scope&&r.set("scope",n.scope)}return r}var so=t=>async(e,r)=>{let n=oo(r),o=io(r,t?.realmName),i=no(o),{response:s}=e;s.headers.set("WWW-Authenticate",i),s.setStatusCode(n),await s.end()},je=so;var ao=t=>{let e=t?.principalClaimName??"sub";return r=>({type:"JwtToken",authenticated:!0,name:r.getClaimAsString(e)})},co=t=>async e=>t(e),ae=class extends Error{},be=class extends ae{};function uo(t){if(t instanceof be)return new D(qe(t.message),t.message,{cause:t});throw new ne(t.message,{cause:t})}function Et(t){let e=t.decoder,r=t.authConverter??co(ao({}));return async n=>{if(Er(n)){let o=n.token;try{let i=await e(o);return await r(i)}catch(i){throw i instanceof ae?uo(i):i}}}}function At(t){let e=t.entryPoint??je({}),r=t?.converter??ze({}),n=t.failureHandler??oe({entryPoint:e});if(t.managerResolver!==void 0)return z({storage:t.storage,converter:r,failureHandler:n,managerResolver:t.managerResolver});if(t.jwt!==void 0){let o=t.jwt.manager??Et(t.jwt);return z({storage:t.storage,converter:r,failureHandler:n,managerResolver:async i=>o})}throw new Error("Invalid resource server configuration: either managerResolver or jwt must be provided")}var Ze=require("@interopio/gateway/jose/jwt");async function Pr(t,e,r){let n=new Ge("Full authentication is required to access this resource."),o=new C("Access Denied",{cause:n});e&&(o.authentication=e),await r(t,o)}function lo(t){return async(e,r)=>{e.response.setStatusCode(t),e.response.headers.set("Content-Type","text/plain; charset=utf-8");let n=Buffer.from("Access Denied","utf-8");e.response.headers.set("Content-Length",n.length),await e.response.body(n)}}var Hr=t=>{let e=lo(S.FORBIDDEN),r=t.authenticationEntryPoint??ie();return async(n,o)=>{try{await o()}catch(i){if(i instanceof X){let s=await n.principal();mr(s)?(s.authenticated||await e(n,i),await Pr(n,s,r)):await Pr(n,void 0,r);return}throw i}}};var po=w("security.auth");function Ct(t){let e=async(r,n)=>{let o;for(let[i,s]of t.mappings)if((await i(n))?.match){po.debug(`checking authorization on '${n.request.path}' using [${i}, ${s}]`);let a=await s.authorize(r,{exchange:n});if(a!==void 0){o=a;break}}return o??=new G(!1),o};return new _(e)}var Ve=w("security.auth");function Pt(t){let{manager:e,storage:r}=t;return async(n,o)=>{let i=q.getContext(r).then(s=>s?.authentication);try{await e.verify(i,n),Ve.enabledFor("debug")&&Ve.debug("authorization successful")}catch(s){throw s instanceof X&&Ve.enabledFor("debug")&&Ve.debug(`authorization failed: ${s.message}`),s}await o()}}var Ht=class extends Ie{#e;constructor(e,r){super(e),this.#e=r}async principal(){return(await this.#e())?.authentication}},kr=t=>{let e=t.storage;return async(r,n)=>{await n(new Ht(r,async()=>await q.getContext(e)))}};var Rr=t=>{let{principalExtractor:e}=t;return async r=>{let n=r.request.sslInfo;if(n===void 0||n.peerCertificate===void 0)return;let o=n.peerCertificate,i=e(o);return{type:"PreAuthenticated",authenticated:!1,principal:i,name:i??"",credentials:o}}};var Xe=t=>{let e=t?.principalAltName==="email",r=/CN=(.*?)(?:,|$)/mi;return n=>{if(e){let s=n.subjectAltName?.split(", ").find(a=>a.startsWith("email:"));if(s)return s.replace("email:","")}let o=r.exec(n.subject);if(o===null)throw new te(`Cannot extract principal from subject DN: ${n.subject}`);return o[1]}};var J=class{async encode(e){if(e!=null)return await this.encodeDefinedPassword(e.toString())}async matches(e,r){return!e||!r?!1:await this.matchesDefined(e.toString(),r)}upgradeEncoding(e){return e?this.upgradeEncodingDefined(e):!1}upgradeEncodingDefined(e){return!1}},ce=class t extends J{static DEFAULT_ID_PREFIX="{";static DEFAULT_ID_SUFFIX="}";#e;#r;#t;#n;#i;#s=new class extends J{#c;constructor(e){super(),this.#c=e}async encodeDefinedPassword(e){throw new Error("encode is not supported")}async matchesDefined(e,r){let n=this.#c.#o(r);if(!n)throw new Error(`No password encoder mapped for id ${n}`);if(r){let o=r.indexOf(this.#c.#e),i=r.indexOf(this.#c.#r,o+this.#c.#e.length);if(o===-1&&i===-1)throw new Error("No prefix found in encoded password")}throw new Error("malformed password encoder prefix")}}(this);constructor(e,r,n=t.DEFAULT_ID_PREFIX,o=t.DEFAULT_ID_SUFFIX){if(e==null)throw new Error("idForEncode cannot be null or undefined");if(n==null)throw new Error("idPrefix cannot be null or undefined");if(!o)throw new Error("idSuffix cannot be empty");if(n.indexOf(o)!==-1)throw new Error(`idPrefix "${n}" cannot contain idSuffix "${o}"`);if(!r.has(e))throw new Error(`No PasswordEncoder mapped for id "${e}"`);for(let i of r.keys())if(i!==null){if(n&&i.includes(n))throw new Error(`id "${i}" cannot include ${n}`);if(o&&i.includes(o))throw new Error(`id "${i}" cannot include ${o}`)}super(),this.#t=e,this.#n=r.get(e),this.#i=new Map(r),this.#e=n,this.#r=o}set defaultPasswordEncoderForMatches(e){if(e==null)throw new Error("defaultPasswordEncoderForMatches cannot be null or undefined");this.#s=e}async encodeDefinedPassword(e){let r=await this.#n.encode(e);return`${this.#e}${this.#t}${this.#r}${r}`}async matchesDefined(e,r){let n=this.#o(r),o=n?this.#i.get(n):void 0;if(o===void 0)return await this.#s.matches(e,r);{let i=this.#a(r);return await o.matches(e,i)}}#o(e){if(e===void 0)return;let r=e.indexOf(this.#e);if(r!==0)return;let n=e.indexOf(this.#r,r+this.#e.length);if(n!==-1)return e.substring(r+this.#e.length,n)}upgradeEncodingDefined(e){let r=this.#o(e);if(this.#t!==r)return!0;{let n=this.#a(e);return this.#n.upgradeEncoding?.(n)??!1}}#a(e){let r=e.indexOf(this.#r);return e.substring(r+this.#r.length)}},Je=class t extends J{static#e=new t;static get instance(){return t.#e}constructor(){super()}async encodeDefinedPassword(e){return e.toString()}async matchesDefined(e,r){return e.toString()===r}};var P=require("@interopio/gateway-server/tools");function ho(t,e){if(t.length!==e.length)return!1;let r=0;for(let n=0;n<t.length;n++)r|=t[n]^e[n];return r===0}var Ke=class extends J{#e;#r;#t;#n;#i;constructor(e=P.argon2.DEFAULT_SALT_LENGTH,r=P.argon2.DEFAULT_HASH_LENGTH,n=P.argon2.DEFAULT_PARALLELISM,o=P.argon2.DEFAULT_MEMORY,i=P.argon2.DEFAULT_PASSES){super(),this.#e=e,this.#r=r,this.#t=n,this.#n=o,this.#i=i}async matchesDefined(e,r){try{let n=P.argon2.decode(r),o=await P.argon2.createHash(n.algorithm,e,n.hash.length,n.parameters);return ho(n.hash,o)}catch{return!1}}async encodeDefinedPassword(e){let r=P.keygen.createSalt(this.#e),n={memory:this.#n,passes:this.#i,parallelism:this.#t,nonce:r},o=await P.argon2.createHash("argon2id",e,this.#r,n);return P.argon2.encode({algorithm:"argon2id",version:P.argon2.ARGON2_VERSION,parameters:n,hash:o})}upgradeEncodingDefined(e){let r=P.argon2.decode(e);return r.version<P.argon2.ARGON2_VERSION||r.parameters.memory<this.#n||r.parameters.passes<this.#i}};var kt=4096;function Tr(){let t="argon2id",e=new Map([[t,new Ke],["noop",Je.instance]]);return new ce(t,e,ce.DEFAULT_ID_PREFIX,ce.DEFAULT_ID_SUFFIX)}var Or={async updatePassword(t,e){return t}},Ye=class extends C{username;constructor(e,r,n){super(e,n),this.username=r}},Qe=class t{#e;#r;#t=[];#n;#i;#s;#o;#a=e=>e;constructor(){}static ofUsername(e){return new t().username(e)}static ofUserDetails(e){let r=t.ofUsername(e.username).accountExpired(e.accountExpired??!1).accountLocked(e.accountLocked??!1).authorities(e.authorities).credentialsExpired(e.credentialsExpired??!1).disabled(e.disabled??!1);return e.password!==void 0&&r.password(e.password),r}username(e){if(!e)throw new TypeError("username cannot be empty");return this.#e=e,this}password(e){return this.#r=e,this}passwordEncoder(e){if(!e)throw new TypeError("password encoder cannot be null or undefined");return this.#a=e,this}roles(...e){return this.authorities(e.map(r=>{if(r.startsWith("role:"))throw new Error(`${r} must not start with 'role:' (it is automatically added)`);return{authority:`role:${r}`}}))}authorities(e){return this.#t=[...e],this}accountExpired(e){return this.#n=e,this}accountLocked(e){return this.#i=e,this}credentialsExpired(e){return this.#s=e,this}disabled(e){return this.#o=e,this}build(){if(!this.#e)throw new TypeError("username is required");let e=this.#r!==void 0?this.#a(this.#r):void 0;return{username:this.#e,password:e,authorities:this.#t,accountExpired:this.#n,accountLocked:this.#i,credentialsExpired:this.#s,disabled:this.#o,eraseCredentials(){e=null},toString(){return`User(username=${this.username}, password=[PROTECTED], authorities=${JSON.stringify(this.authorities)}, accountExpired=${this.accountExpired}, accountLocked=${this.accountLocked}, credentialsExpired=${this.credentialsExpired}, disabled=${this.disabled})`}}}};var j=w("security.users");function Mr(t,e){let r=e?.preAuthenticationChecks??(a=>{if(a.accountLocked)throw j.debug("user account is locked"),new me("User account is locked");if(a.disabled)throw j.debug("user account is disabled"),new ye("User is disabled");if(a.accountExpired)throw j.debug("user account is expired"),new we("User account has expired")}),n=e?.postAuthenticationChecks??(a=>{if(a.credentialsExpired)throw j.debug("user credentials have expired"),new Se("User credentials have expired")}),o=e?.passwordEncoder??Tr(),i=e?.userDetailsPasswordService??Or,s=async(a,c)=>{let d=a.password;if(d!==void 0&&o.upgradeEncoding?.(d)){let l=await o.encode(c);return await i.updatePassword(a,l)}return a};return async a=>{let c=a.name,d=a.credentials!==void 0&&a.credentials!==null?a.credentials.toString():void 0,u=await t.findByUsername(c);if(!u)throw new Error(`User not found: ${c}`);if(r(u),!await o.matches(d,u.password))throw new te("Invalid Credentials");let l=await s(u,d);n(l);let m=l.password;return{type:"UsernamePassword",principal:l,credentials:m,authorities:l.authorities,authenticated:!0,name:l.username,eraseCredentials(){m=null}}}}function fo(){return t=>{if(t.accountLocked)throw j.debug("failed to authenticate since user account is locked"),new me("User account is locked");if(t.disabled)throw j.debug("failed to authenticate user account is disabled"),new ye("User is disabled");if(t.accountExpired)throw j.debug("failed to authenticate since user account is expired"),new we("User account has expired");if(t.credentialsExpired)throw j.debug("failed to authenticate since user credentials have expired"),new Se("User credentials have expired")}}function Ir(t){let e=t.userDetailsService,r=t.userDetailsChecker??fo(),n=o=>o.type==="PreAuthenticated"&&o.name!==void 0;return async o=>{let i=n(o)&&await e.findByUsername(o.name);if(!i)throw new Ye("user not found",o.name);r(i);let s=o.credentials;return{type:"PreAuthenticated",principal:i,credentials:s,authorities:i.authorities,authenticated:!0,details:i,name:i.username,eraseCredentials(){s=null}}}}function Rt(t){let e=t.manager??Ir({userDetailsService:t.getService("UserDetailsService")}),r=t.extractor??Xe(),n=t.converter??Rr({principalExtractor:r});return z({storage:t.storage,manager:e,converter:n})}var $={first:Number.MAX_SAFE_INTEGER,http_headers:100,https_redirect:200,cors:300,http_basic:600,authentication:800,security_context_server_web_exchange:1500,error_translation:1800,authorization:1900,last:Number.MAX_SAFE_INTEGER},W=Symbol.for("filterOrder"),Lr=(t,e)=>{let r=(a,c)=>{if(e===void 0)return c;if(a==="UserDetailsService"&&e.userDetailsService!==void 0)return e.userDetailsService;if(a==="AuthenticationManager"&&e.authenticationManager!==void 0)return e.authenticationManager;if(c!==void 0)return c;throw new Error(`No service registered with name: ${a}`)},n=()=>{if(e.authenticationManager!==void 0)return e.authenticationManager;if(e.userDetailsService!==void 0)return Mr(e.userDetailsService,{userDetailsPasswordService:e.userDetailsPasswordService})},o=[];class i{#e;#r=[];#t;set authenticationManager(c){this.#t=c}get authenticationEntryPoint(){return this.#e!==void 0||this.#r.length===0?this.#e:this.#r.length===1?this.#r[0][1]:_e({entryPoints:this.#r,defaultEntryPoint:this.#r[this.#r.length-1][1]})}build(){if(t.headers!==void 0&&t.headers.disabled!==!0){let d=bt(t.headers);d[W]=$.http_headers,o.push(d)}if(t.x509!==void 0&&t.x509.disabled!==!0){let d=Rt({storage:e.storage,getService:r,extractor:Xe({principalAltName:t.x509.principalAltName})});d[W]=$.authentication,o.push(d)}if(t.cors?.disabled!==!0&&e.corsConfigSource!==void 0){let d=dr({corsConfigSource:e.corsConfigSource});d[W]=$.cors,o.push(d)}if(t.basic!==void 0&&t.basic?.disabled!==!0){let d=[async({exchange:l,next:m},x)=>m()],u=vt({storage:e.storage,manager:this.#t,defaultEntryPoints:this.#r,defaultSuccessHandlers:d});u[W]=$.http_basic,o.push(u)}if(t.jwt!==void 0&&t.jwt.disabled!==!0){let d=(0,Ze.jwtVerifier)({issuerBaseUri:t.jwt.issuerUri,issuer:t.jwt.issuer,audience:t.jwt.audience}),u=async f=>{try{let{payload:h}=await d(f);return{tokenValue:f,subject:h.sub,getClaimAsString(y){return h[y]}}}catch(h){throw h instanceof Ze.JwtVerifyError?new be(h.message,{cause:h}):new ae("error occurred while attempting to decoding jwt",{cause:h})}},l=ze({uriQueryParameter:!0}),m=async f=>{try{return await l(f)===void 0?H:T()}catch{return H}},x=je({});this.#r.push([m,x]);let p=At({storage:e.storage,entryPoint:x,converter:l,jwt:{decoder:u}});p[W]=$.authentication,o.push(p)}let c=kr({storage:e.storage});if(o.push(c),c[W]=$.security_context_server_web_exchange,t.authorize!==void 0){let d=Hr({authenticationEntryPoint:this.authenticationEntryPoint});d[W]=$.error_translation,o.push(d);let l=(x=>{let p=[],f=!1;for(let[h,y]of x??[]){let k;if(h==="any-exchange")f=!0,k=he;else{if(f)throw new Error("Cannot register other matchers after 'any-exchange' matcher");k=h}let R;if(y.access==="permitted")R=new _(async()=>new G(!0)),R.toString=()=>"AuthorizationManager[permitted]";else if(y.access==="denied")R=new _(async()=>new G(!1)),R.toString=()=>"AuthorizationManager[denied]";else if(y.access==="authenticated")R=new _(async K=>{let Lt=await K;return Lt!==void 0?new G(Lt.authenticated):new G(!1)}),R.toString=()=>"AuthorizationManager[authenticated]";else throw new Error(`Unknown access type: ${JSON.stringify(y)}`);p.push([k,R])}return Ct({mappings:p})})(t.authorize),m=Pt({manager:l,storage:e.storage});m[W]=$.authorization,o.push(m)}o.sort((d,u)=>{let l=d[W]??$.last,m=u[W]??$.last;return l-m})}}let s=new i;return s.authenticationManager=n(),s.build(),o};var et=class{#e=new Map;constructor(...e){for(let r of e)this.#e.set(this.#r(r.username),r)}async findByUsername(e){let r=this.#r(e),n=this.#e.get(r);return n!==void 0?{...n}:void 0}async updatePassword(e,r){let n={...e,password:r};if(n){let o=this.#r(e.username);this.#e.set(o,n)}return n}#r(e){return e.toLowerCase()}};var Dr=require("node:crypto");var tt=w("auth");function go(t){let e=[],r=t.authConfig?.type,n={access:r!=="none"?"authenticated":"permitted"};tt.enabledFor("info")&&tt.info(`using auth type: ${r??"none"}, default access: ${n.access}`);for(let[o,i]of t.sockets){let s=i.authorize??n,a=O(o,{method:"GET"});a=ee([V,a]),e.push([a,s])}return e.push([O("/",{method:"GET"}),{access:"permitted"}]),e.push([O("/favicon.ico",{method:"GET"}),{access:"permitted"}]),e.push([O("/health",{method:"GET"}),{access:"permitted"}]),t.authorize.length>0&&e.push(...t.authorize),e.push(["any-exchange",n]),{authorize:e,cors:{disabled:t.corsConfig===!1},x509:{disabled:r!=="x509",...t.authConfig?.x509},basic:{disabled:r!=="basic",...t.authConfig?.basic},jwt:{disabled:r!=="oauth2",...t.authConfig?.oauth2?.jwt}}}function mo(t){function e(s,a){let c=s.password;if(c===void 0){let d=(0,Dr.randomUUID)().replaceAll("-","");tt.enabledFor("info")&&tt.info(`
1
+ "use strict";var nn=Object.create;var Ae=Object.defineProperty;var on=Object.getOwnPropertyDescriptor;var sn=Object.getOwnPropertyNames;var an=Object.getPrototypeOf,cn=Object.prototype.hasOwnProperty;var Nt=(t,e)=>{for(var r in e)Ae(t,r,{get:e[r],enumerable:!0})},Gt=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of sn(e))!cn.call(t,o)&&o!==r&&Ae(t,o,{get:()=>e[o],enumerable:!(n=on(e,o))||n.enumerable});return t};var le=(t,e,r)=>(r=t!=null?nn(an(t)):{},Gt(e||!t||!t.__esModule?Ae(r,"default",{value:t,enumerable:!0}):r,t)),dn=t=>Gt(Ae({},"__esModule",{value:!0}),t);var Wo={};Nt(Wo,{GatewayServer:()=>Ut,default:()=>$o});module.exports=dn(Wo);var Ut={};Nt(Ut,{Factory:()=>Wt,VERSION:()=>rn});var Zr=le(require("node:http"),1),en=le(require("node:https"),1),tn=require("node:async_hooks");var Bt=require("node:os"),un=/^(\d+|(0x[\da-f]+))(-(\d+|(0x[\da-f]+)))?$/i;function lt(t){if(t>65535)throw new Error(`bad port ${t}`);return t}function*_t(t){if(typeof t=="string")for(let e of t.split(",")){let r=e.trim(),n=un.exec(r);if(n){let o=parseInt(n[1]),i=parseInt(n[4]??n[1]);for(let s=lt(o);s<lt(i)+1;s++)yield s}else throw new Error(`'${e}' is not a valid port or range.`)}else yield lt(t)}var qt=(()=>{function t(r){return r.length>0?r[0]:void 0}let e=Object.values((0,Bt.networkInterfaces)()).flatMap(r=>(r??[]).filter(n=>n.family==="IPv4")).reduce((r,n)=>(r[n.internal?"internal":"external"].push(n),r),{internal:[],external:[]});return(t(e.internal)??t(e.external))?.address})();function B(t){if(t)return t.family==="IPv6"?`[${t.address}]:${t.port}`:`${t.address}:${t.port}`}var zt=le(require("@interopio/gateway/logging/core"),1);function w(t){return zt.getLogger(`gateway.server.${t}`)}function jt(t,e){return e instanceof RegExp?e.toString():e}var Vt=require("@interopio/gateway"),Xt=require("node:async_hooks"),F=w("ws"),ln=Vt.IOGateway.Encoding.json();function pn(t){let e;if(t.authenticated&&(e=t.name,e===void 0&&t.principal!==void 0)){let r=t.principal;typeof r=="object"&&r!==null&&("username"in r||"name"in r)&&(e=r.username??r.name),e===void 0&&(r==null?e="":e=String(r))}return e}function hn(t,e,r,n){let o=B(n),i=n?.address??"<unknown>",s={key:o,host:i,codec:ln,onAuthenticate:async()=>{let a=await r();if(a?.authenticated)return{type:"success",user:pn(a)};throw new Error(`no valid client authentication ${o}`)},onPing:()=>{e.ping(a=>{a?F.warn(`failed to ping ${o}`,a):F.info(`ping sent to ${o}`)})},onDisconnect:a=>{switch(a){case"inactive":{F.warn(`no heartbeat (ping) received from ${o}, closing socket`),e.close(4001,"ping expected");break}case"shutdown":{e.close(1001,"shutdown");break}}}};try{return t.client(a=>e.send(a),s)}catch(a){F.warn(`${o} failed to create client`,a)}}async function fn(t){return F.info(`starting gateway on ${t.endpoint}`),await this.start(t),async({socket:e,handshake:r})=>{let{logPrefix:n,remoteAddress:o,principal:i}=r,s=(await i())?.name;F.info(`${n}connected on gw as ${s??"<anonymous>"}`);let a=await this.getGateway(s),c=hn(a,e,i,o);if(!c){F.error(`${n}gw client init failed`),e.terminate();return}e.on("error",u=>{F.error(`${n}websocket error: ${u}`,u)});let d=t.storage!==void 0?Xt.AsyncLocalStorage.snapshot():void 0;e.on("message",(u,l)=>{Array.isArray(u)&&(u=Buffer.concat(u)),d!==void 0?d(()=>c.send(u)):c.send(u)}),e.on("close",u=>{F.info(`${n}disconnected from gw. code: ${u}`),c.close()})}}var Jt=fn;var ft=require("@interopio/gateway");var Y=require("@interopio/gateway");function pt(t){if(t!==void 0)return t.map(e=>{let r={...e};for(let[n,o]of Object.entries(e))n!=="identity"&&n!=="restrictions"&&o!==void 0&&(r[n]=Y.IOGateway.Filtering.regexify(o));if(e.identity!==void 0){r.identity={};for(let[n,o]of Object.entries(e.identity))r.identity[n]=Y.IOGateway.Filtering.regexify(o)}return r})}function Kt(t){if(!t)return;let e={...t};return t.publishers&&(e.publishers=t.publishers.map(r=>{let{metrics:n,identity:o,...i}=r,s={...i};if(s.identity={},o)for(let[a,c]of Object.entries(o))s.identity[a]=Y.IOGateway.Filtering.regexify(c);if(s.metrics={},n){let a=(n.allow??n.whitelist??[]).map(d=>Y.IOGateway.Filtering.regexify(d)),c=(n.block??n.blacklist??[]).map(d=>Y.IOGateway.Filtering.regexify(d));a.length>0&&(s.metrics.allow=a),c.length>0&&(s.metrics.block=c)}return s})),e}function ht(t){if(!t)return;let e={...t};return t.filters&&(e.filters=Kt(t.filters)),e}function gn(t){if(t?.enabled!==!1)return t}function mn(t){if(t===void 0||t?.enabled===!1)return;let e={...t};return t.filters&&(e.filters=Kt(t.filters)),t.file&&(e.file=ht(t.file)),t.rest&&(e.rest=ht(t.rest)),t.publishers&&(e.publishers=t.publishers.map(r=>{if(typeof r=="string")return[r];let n=ht(r);return n!==void 0?[n]:[]}).flat()),e}function Yt(t){let e={...t};return t.contexts&&(e.contexts={...t.contexts,visibility:pt(t.contexts.visibility)}),t.methods&&(e.methods={...t.methods,visibility:pt(t.methods.visibility)}),t.peers&&(e.peers={...t.peers,visibility:pt(t.peers.visibility)}),t.metrics&&(e.metrics=mn(t.metrics)),t.mesh&&(e.mesh=gn(t.mesh)),e}var A=w("gateway-manager");function Qt(){return globalThis.crypto.randomUUID().replaceAll("-","")}var Ce=class{#e;#r;#t=new Map;#n=new Map;#i;#s=!1;#o;constructor(e){this.#i={baseConfig:Yt(e.baseConfig),scope:e.scope??"principal"},this.#e=e.baseConfig.node??Qt(),A.enabledFor("debug")&&A.debug(`creating default gateway with gateway id: ${this.#e}`),this.#r=ft.IOGateway.Factory({...this.#i.baseConfig,node:this.#e})}async start(e){return this.#s?this:(this.#o=e,A.debug("starting default gateway"),await this.#r.start(e),this.#s=!0,this)}async getGateway(e){if(this.#i.scope==="singleton"||!e)return this.#r;let r=this.#n.get(e),n=r?this.#t.get(r):void 0;return n?A.enabledFor("debug")&&A.debug(`reusing existing gateway for principal '${e}'`):(A.enabledFor("debug")&&A.debug(`no existing gateway for principal '${e}', creating new one`),n=await this.#a(e)),n}async#a(e){let r=Qt(),n={...this.#i.baseConfig,node:r};A.enabledFor("debug")&&A.debug(`creating gateway for principal '${e}' with gateway id: ${n.node}`);let o=ft.IOGateway.Factory(n);return this.#n.set(e,r),this.#t.set(r,o),await o.start(this.#o),o}getGateways(){let e=new Map(this.#t);return e.set(this.#e,this.#r),e}info(e){if(e&&this.#e!==e){let r=this.#t.get(e);if(r)return r.info();throw new Error(`no gateway found with ID: ${e}`)}return e===this.#e?this.#r.info():{...this.#r.info(),managedGateways:this.#t.size,scope:this.#i.scope}}async stop(e){if(e&&this.#e!==e){let r=this.#t.get(e);if(r){A.info(`stopping gateway with ID: ${e}`),await r.stop(),this.#t.delete(e);for(let[n,o]of this.#n.entries())if(o===e){this.#n.delete(n);break}return r}else throw new Error(`no gateway found with ID: ${e}`)}if(e===this.#e)return A.debug("stopping default gateway (managed gateways will continue running)"),await this.#r.stop(),this.#s=!1,this.#r;A.info(`stopping all gateways (1 default + ${this.#t.size} managed)`);for(let[r,n]of this.#t.entries())A.enabledFor("debug")&&A.debug(`stopping gateway with ID: ${r}`),await n.stop();return this.#t.clear(),this.#n.clear(),A.debug("stopping default gateway"),await this.#r.stop(),this.#s=!1,this.#r}getPrincipalGatewayId(e){return this.#n.get(e)}getPrincipalGatewayIds(){return new Map(this.#n)}getDefaultGateway(){return this.#r}client(e,r){return this.#r.client(e,r)}async connect(e){return this.#r.connect(e)}getPrincipalCount(){return this.#t.size}};function Zt(...t){if(!Array.isArray(t))throw new Error("middleware must be array!");let e=t.flat();for(let r of e)if(typeof r!="function")throw new Error("middleware must be compose of functions!");return async function(r,n){let o=async(i,s)=>{let a=i===e.length?n:e[i];if(a===void 0)return;let c=!1,d=!1,l=await a(s,async m=>{if(c)throw new Error("next() called multiple times");c=!0;try{return await o(i+1,m??s)}finally{d=!0}});if(c&&!d)throw new Error(`middleware resolved before downstream.
2
+ You are probably missing an await or return statement in your middleware function.`);return l};return o(0,r)}}var er=require("node:net"),Re=require("tough-cookie");function yn(t,e){let r=t.get("x-forwarded-host");if(Array.isArray(r)&&(r=r[0]),r){let n=t.one("x-forwarded-port");n&&(r=`${r}:${n}`)}return r??=t.one("host"),Array.isArray(r)&&(r=r[0]),r?r.split(",",1)[0].trim():e}function wn(t){let e=t.one("x-forwarded-ssl");return typeof e=="string"&&e.toLowerCase()==="on"}function bn(t,e){let r=t.get("x-forwarded-proto");return Array.isArray(r)&&(r=r[0]),r!==void 0?r.split(",",1)[0].trim():wn(t)?"https":e}function Sn(t,e,r){let n=r?r.port:t.protocol==="https:"?443:80,o=e.one("x-forwarded-for");if(Array.isArray(o)&&(o=o[0]),o!==void 0)return o=o.split(",",1)[0].trim(),{address:o,port:Number(n),family:(0,er.isIP)(o)===6?"IPv6":"IPv4"}}var Pe=class{#e;constructor(e){this.#e=e}get headers(){return this.#e}},He=class t extends Pe{static logIdCounter=0;#e;get id(){return this.#e===void 0&&(this.#e=`${this.initId()}-${++t.logIdCounter}`),this.#e}initId(){return"request"}get cookies(){return xn(this.headers)}parseHost(e){return yn(this.headers,e)}parseProtocol(e){return bn(this.headers,e)}parseRemoteAddress(e){return Sn(this.URL,this.headers,e)}},ke=class extends Pe{get cookies(){return En(this.headers)}setCookieValue(e){return new Re.Cookie({key:e.name,value:e.value,maxAge:e.maxAge,domain:e.domain,path:e.path,secure:e.secure,httpOnly:e.httpOnly,sameSite:e.sameSite}).toString()}};function vn(t){let e=[];{let r=0,n=0;for(let o=0;o<t.length;o++)switch(t.charCodeAt(o)){case 32:r===n&&(r=n=o+1);break;case 44:e.push(t.slice(r,n)),r=n=o+1;break;default:n=n+1;break}e.push(t.slice(r,n))}return e}function tr(t){typeof t=="string"&&(t=[t]),typeof t=="number"&&(t=[String(t)]);let e=[];if(t)for(let r of t)r&&e.push(...vn(r));return e}function xn(t){return t.list("cookie").map(e=>e.split(";").map(r=>Re.Cookie.parse(r))).flat(1).filter(e=>e!==void 0).map(e=>Object.freeze({name:e.key,value:e.value}))}function En(t){return t.list("set-cookie").map(e=>{let r=Re.Cookie.parse(e);if(r){let n={name:r.key,value:r.value,maxAge:Number(r.maxAge??-1)};return r.httpOnly&&(n.httpOnly=!0),r.domain&&(n.domain=r.domain),r.path&&(n.path=r.path),r.secure&&(n.secure=!0),r.httpOnly&&(n.httpOnly=!0),r.sameSite&&(n.sameSite=r.sameSite),Object.freeze(n)}}).filter(e=>e!==void 0)}var pe=class{constructor(){}toList(e){let r=this.get(e);return tr(r)}},E=class extends Map{get(e){return super.get(e.toLowerCase())}one(e){return this.get(e)?.[0]}list(e){let r=super.get(e.toLowerCase());return tr(r)}set(e,r){return typeof r=="number"&&(r=String(r)),typeof r=="string"&&(r=[r]),r?super.set(e.toLowerCase(),r):(super.delete(e.toLowerCase()),this)}add(e,r){let n=super.get(e.toLowerCase());return typeof r=="string"&&(r=[r]),n&&(r=n.concat(r)),this.set(e,r),this}};var gt=class{#e;constructor(e){this.#e=e}get value(){return this.#e}toString(){return this.#e.toString()}},b=class t{static CONTINUE=new t(100,"Continue");static SWITCHING_PROTOCOLS=new t(101,"Switching Protocols");static OK=new t(200,"OK");static CREATED=new t(201,"Created");static ACCEPTED=new t(202,"Accepted");static NON_AUTHORITATIVE_INFORMATION=new t(203,"Non-Authoritative Information");static NO_CONTENT=new t(204,"No Content");static RESET_CONTENT=new t(205,"Reset Content");static PARTIAL_CONTENT=new t(206,"Partial Content");static MULTI_STATUS=new t(207,"Multi-Status");static IM_USED=new t(226,"IM Used");static MULTIPLE_CHOICES=new t(300,"Multiple Choices");static MOVED_PERMANENTLY=new t(301,"Moved Permanently");static BAD_REQUEST=new t(400,"Bad Request");static UNAUTHORIZED=new t(401,"Unauthorized");static FORBIDDEN=new t(403,"Forbidden");static NOT_FOUND=new t(404,"Not Found");static METHOD_NOT_ALLOWED=new t(405,"Method Not Allowed");static NOT_ACCEPTABLE=new t(406,"Not Acceptable");static PROXY_AUTHENTICATION_REQUIRED=new t(407,"Proxy Authentication Required");static REQUEST_TIMEOUT=new t(408,"Request Timeout");static CONFLICT=new t(409,"Conflict");static GONE=new t(410,"Gone");static LENGTH_REQUIRED=new t(411,"Length Required");static PRECONDITION_FAILED=new t(412,"Precondition Failed");static PAYLOAD_TOO_LARGE=new t(413,"Payload Too Large");static URI_TOO_LONG=new t(414,"URI Too Long");static UNSUPPORTED_MEDIA_TYPE=new t(415,"Unsupported Media Type");static EXPECTATION_FAILED=new t(417,"Expectation Failed");static IM_A_TEAPOT=new t(418,"I'm a teapot");static TOO_EARLY=new t(425,"Too Early");static UPGRADE_REQUIRED=new t(426,"Upgrade Required");static PRECONDITION_REQUIRED=new t(428,"Precondition Required");static TOO_MANY_REQUESTS=new t(429,"Too Many Requests");static REQUEST_HEADER_FIELDS_TOO_LARGE=new t(431,"Request Header Fields Too Large");static UNAVAILABLE_FOR_LEGAL_REASONS=new t(451,"Unavailable For Legal Reasons");static INTERNAL_SERVER_ERROR=new t(500,"Internal Server Error");static NOT_IMPLEMENTED=new t(501,"Not Implemented");static BAD_GATEWAY=new t(502,"Bad Gateway");static SERVICE_UNAVAILABLE=new t(503,"Service Unavailable");static GATEWAY_TIMEOUT=new t(504,"Gateway Timeout");static HTTP_VERSION_NOT_SUPPORTED=new t(505,"HTTP Version Not Supported");static VARIANT_ALSO_NEGOTIATES=new t(506,"Variant Also Negotiates");static INSUFFICIENT_STORAGE=new t(507,"Insufficient Storage");static LOOP_DETECTED=new t(508,"Loop Detected");static NOT_EXTENDED=new t(510,"Not Extended");static NETWORK_AUTHENTICATION_REQUIRED=new t(511,"Network Authentication Required");static#e=[];static{Object.keys(t).filter(e=>e!=="VALUES"&&e!=="resolve").forEach(e=>{let r=t[e];r instanceof t&&(Object.defineProperty(r,"name",{enumerable:!0,value:e,writable:!1}),t.#e.push(r))})}static resolve(e){for(let r of t.#e)if(r.value===e)return r}#r;#t;constructor(e,r){this.#r=e,this.#t=r}get value(){return this.#r}get phrase(){return this.#t}toString(){return`${this.#r} ${this.name}`}};function rr(t){if(typeof t=="number"){if(t<100||t>999)throw new Error(`status code ${t} should be in range 100-999`);let e=b.resolve(t);return e!==void 0?e:new gt(t)}return t}var We=le(require("node:http"),1),Te=class extends We.default.IncomingMessage{exchange;upgradeHead;get urlBang(){return this.url}get socketEncrypted(){return this.socket.encrypted===!0}},Q=class extends We.default.ServerResponse{markHeadersSent(){this._header=!0}getRawHeaderNames(){return super.getRawHeaderNames()}},Oe=class extends He{#e;get sslInfo(){return this.#e===void 0&&(this.#e=this.initSslInfo()),this.#e}},Me=class extends ke{#e=[];#r;#t="new";#n=[];setStatusCode(e){return this.#t==="committed"?!1:(this.#r=e,!0)}setRawStatusCode(e){return this.setStatusCode(e===void 0?void 0:rr(e))}get statusCode(){return this.#r}addCookie(e){if(this.#t==="committed")throw new Error(`Cannot add cookie ${JSON.stringify(e)} because HTTP response has already been committed`);return this.#e.push(e),this}beforeCommit(e){this.#n.push(e)}get commited(){let e=this.#t;return e!=="new"&&e!=="commit-action-failed"}async body(e){if(e instanceof ReadableStream)throw new Error("ReadableStream body not supported yet");let r=await e;try{return await this.doCommit(async()=>await this.bodyInternal(Promise.resolve(r))).catch(n=>{throw n})}catch(n){throw n}}async end(){return this.commited?Promise.resolve(!1):this.doCommit(async()=>await this.bodyInternal(Promise.resolve()))}doCommit(e){let r=this.#t,n=Promise.resolve();if(r==="new")this.#t="committing",this.#n.length>0&&(n=this.#n.reduce((o,i)=>o.then(()=>i()),Promise.resolve()).catch(o=>{this.#t==="committing"&&(this.#t="commit-action-failed")}));else if(r==="commit-action-failed")this.#t="committing";else return Promise.resolve(!1);return n=n.then(()=>{this.applyStatusCode(),this.applyHeaders(),this.applyCookies(),this.#t="committed"}),n.then(async()=>e!==void 0?await e():!0)}applyStatusCode(){}applyHeaders(){}applyCookies(){}},Z=class extends Oe{#e;#r;#t;constructor(e){super(new yt(e)),this.#t=e}getNativeRequest(){return this.#t}get upgrade(){return this.#t.upgrade}get http2(){return this.#t.httpVersionMajor>=2}get path(){return this.URL?.pathname}get URL(){return this.#e??=new URL(this.#t.urlBang,`${this.protocol}://${this.host}`),this.#e}get query(){return this.URL?.search}get method(){return this.#t.method}get host(){let e;return this.#t.httpVersionMajor>=2&&(e=this.#t.headers[":authority"]),e??=this.#t.socket.remoteAddress,super.parseHost(e)}get protocol(){let e;return this.#t.httpVersionMajor>2&&(e=this.#t.headers[":scheme"]),e??=this.#t.socketEncrypted?"https":"http",super.parseProtocol(e)}get socket(){return this.#t.socket}get remoteAddress(){let e=this.#t.socket.remoteFamily,r=this.#t.socket.remoteAddress,n=this.#t.socket.remotePort,o=!e||!r||!n?void 0:{family:e,address:r,port:n};return super.parseRemoteAddress(o)??o}initSslInfo(){if(this.#t.socketEncrypted)return new mt(this.#t.socket)}get cookies(){return this.#r??=super.cookies,this.#r}get body(){return We.default.IncomingMessage.toWeb(this.#t)}async blob(){let e=[];if(this.body!==void 0)for await(let r of this.body)e.push(r);return new Blob(e,{type:this.headers.one("content-type")||"application/octet-stream"})}async text(){return await(await this.blob()).text()}async formData(){let r=await(await this.blob()).text();return new URLSearchParams(r)}async json(){let e=await this.blob();if(e.size===0)return;let r=await e.text();return JSON.parse(r)}initId(){let e=this.#t.socket.remoteAddress;if(!e)throw new Error("Socket has no remote address");return`${e}:${this.#t.socket.remotePort}`}},mt=class{peerCertificate;constructor(e){this.peerCertificate=e.getPeerX509Certificate()}},yt=class extends pe{#e;constructor(e){super(),this.#e=e}has(e){return this.#e.headers[e]!==void 0}get(e){return this.#e.headers[e]}list(e){return super.toList(e)}one(e){let r=this.#e.headers[e];return Array.isArray(r)?r[0]:r}keys(){return Object.keys(this.#e.headers).values()}},wt=class extends pe{#e;constructor(e){super(),this.#e=e}has(e){return this.#e.hasHeader(e)}keys(){return this.#e.getHeaderNames().values()}get(e){return this.#e.getHeader(e)}one(e){let r=this.#e.getHeader(e);return Array.isArray(r)?r[0]:r}set(e,r){return this.#e.headersSent||(Array.isArray(r)?r=r.map(n=>typeof n=="number"?String(n):n):typeof r=="number"&&(r=String(r)),r?this.#e.setHeader(e,r):this.#e.removeHeader(e)),this}add(e,r){return this.#e.headersSent||this.#e.appendHeader(e,r),this}list(e){return super.toList(e)}},Ie=class extends Me{#e;constructor(e){super(new wt(e)),this.#e=e}getNativeResponse(){return this.#e}get statusCode(){return super.statusCode??{value:this.#e.statusCode}}applyStatusCode(){let e=super.statusCode;e!==void 0&&(this.#e.statusCode=e.value)}addCookie(e){return this.headers.add("Set-Cookie",super.setCookieValue(e)),this}async bodyInternal(e){if(this.#e.headersSent)return!1;if(e instanceof ReadableStream)throw new Error("ReadableStream body not supported in response");{let r=await e;return await new Promise((n,o)=>{try{r===void 0?this.#e.end(()=>{n(!0)}):(this.headers.has("content-length")||(typeof r=="string"?this.headers.set("Content-Length",Buffer.byteLength(r)):r instanceof Blob?this.headers.set("Content-Length",r.size):this.headers.set("Content-Length",r.byteLength)),this.#e.end(r,()=>{n(!0)}))}catch(i){o(i instanceof Error?i:new Error(`end failed: ${i}`))}})}}},Le=class t{#e;constructor(e){this.#e=e}get delegate(){return this.#e}get id(){return this.#e.id}get method(){return this.#e.method}get path(){return this.#e.path}get protocol(){return this.#e.protocol}get host(){return this.#e.host}get URL(){return this.#e.URL}get headers(){return this.#e.headers}get cookies(){return this.#e.cookies}get remoteAddress(){return this.#e.remoteAddress}get upgrade(){return this.#e.upgrade}get sslInfo(){return this.#e.sslInfo}get body(){return this.#e.body}async blob(){return await this.#e.blob()}async text(){return await this.#e.text()}async formData(){return await this.#e.formData()}async json(){return await this.#e.json()}toString(){return`${t.name} [delegate: ${this.delegate.toString()}]`}static getNativeRequest(e){if(e instanceof Oe)return e.getNativeRequest();if(e instanceof t)return t.getNativeRequest(e.delegate);throw new Error(`Cannot get native request from ${e.constructor.name}`)}},ee=class t{#e;constructor(e){this.#e=e}get delegate(){return this.#e}setStatusCode(e){return this.delegate.setStatusCode(e)}setRawStatusCode(e){return this.delegate.setRawStatusCode(e)}get statusCode(){return this.delegate.statusCode}get cookies(){return this.delegate.cookies}addCookie(e){return this.delegate.addCookie(e),this}async end(){return await this.delegate.end()}async body(e){return await this.#e.body(e)}get headers(){return this.#e.headers}toString(){return`${t.name} [delegate: ${this.delegate.toString()}]`}static getNativeResponse(e){if(e instanceof Me)return e.getNativeResponse();if(e instanceof t)return t.getNativeResponse(e.delegate);throw new Error(`Cannot get native response from ${e.constructor.name}`)}},De=class t{#e;constructor(e){this.#e=e}get delegate(){return this.#e}get request(){return this.#e.request}get response(){return this.#e.response}attribute(e){return this.#e.attribute(e)}principal(){return this.#e.principal()}get logPrefix(){return this.#e.logPrefix}toString(){return`${t.name} [delegate: ${this.delegate}]`}},$e=class{request;response;#e={};#r;#t="";constructor(e,r){this.#e[nr]=e.id,this.request=e,this.response=r}get method(){return this.request.method}get path(){return this.request.path}get attributes(){return this.#e}attribute(e){return this.attributes[e]}principal(){return Promise.resolve(void 0)}get logPrefix(){let e=this.attribute(nr);return this.#r!==e&&(this.#r=e,this.#t=e!==void 0?`[${e}] `:""),this.#t}},nr="io.interop.gateway.server.log_id";var Ue=require("node:v8"),N=require("node:fs/promises"),S=w("monitoring"),An={memoryLimit:1024*1024*1024,reportInterval:600*1e3,dumpLocation:".",maxBackups:10,dumpPrefix:"Heap"};function Cn(){return(0,Ue.getHeapStatistics)()}async function or(t){let e=t.dumpPrefix??"Heap",r=`${t.dumpLocation}/${e}.heapsnapshot`;S.enabledFor("debug")&&S.debug(`starting heap dump in ${r}`),await bt(t.dumpLocation).catch(async o=>{S.enabledFor("debug")&&S.debug(`dump location ${t.dumpLocation} does not exists. Will try to create it`);try{await(0,N.mkdir)(t.dumpLocation,{recursive:!0}),S.info(`dump location dir ${t.dumpLocation} successfully created`)}catch{S.error(`failed to create dump location ${t.dumpLocation}`)}});let n=(0,Ue.writeHeapSnapshot)(r);S.info("heap dumped");try{S.debug("rolling snapshot backups");let o=`${t.dumpLocation}/${e}.${t.maxBackups}.heapsnapshot`;await bt(o).then(async()=>{S.enabledFor("debug")&&S.debug(`deleting ${o}`);try{await(0,N.unlink)(o)}catch(s){S.warn(`failed to delete ${o}`,s)}}).catch(()=>{});for(let s=t.maxBackups-1;s>0;s--){let a=`${t.dumpLocation}/${e}.${s}.heapsnapshot`,c=`${t.dumpLocation}/${e}.${s+1}.heapsnapshot`;await bt(a).then(async()=>{try{await(0,N.rename)(a,c)}catch(d){S.warn(`failed to rename ${a} to ${c}`,d)}}).catch(()=>{})}let i=`${t.dumpLocation}/${e}.1.heapsnapshot`;try{await(0,N.rename)(n,i)}catch(s){S.warn(`failed to rename ${n} to ${i}`,s)}S.debug("snapshots rolled")}catch(o){throw S.error("error rolling backups",o),o}}async function bt(t){S.enabledFor("trace")&&S.debug(`checking file ${t}`),await(0,N.access)(t)}async function Pn(t,e,r){S.enabledFor("debug")&&S.debug(`processing heap stats ${JSON.stringify(t)}`);let n=Math.min(r.memoryLimit,.95*t.heap_size_limit),o=t.used_heap_size;S.info(`heap stats ${JSON.stringify(t)}`),o>=n?(S.warn(`used heap ${o} bytes exceeds memory limit ${n} bytes`),e.memoryLimitExceeded?delete e.snapshot:(e.memoryLimitExceeded=!0,e.snapshot=!0),await or(r)):(e.memoryLimitExceeded=!1,delete e.snapshot)}function ir(t){let e={...An,...t},r=!1,n={memoryLimitExceeded:!1},o=async()=>{let a=Cn();await Pn(a,n,e)},i=setInterval(o,e.reportInterval);return{...e,channel:async a=>{if(!r)switch(a??="run",a){case"run":{await o();break}case"dump":{await or(e);break}case"stop":{r=!0,clearInterval(i),S.info("exit memory diagnostic");break}}return r}}}async function Hn({channel:t},e){await t(e)||S.warn(`cannot execute command "${e}" already closed`)}async function sr(t){return await Hn(t,"stop")}var Rn=(t,e)=>(e??=t,async({response:r},n)=>{e!==!1&&!r.headers.has("server")&&r.headers.set("Server",e),await n()}),ar=(t,e)=>Rn(t,e);var he=require("@interopio/gateway");var St=w("gateway.ws.client-verify");function Tn(t){switch(t.missing){case"allow":case"whitelist":return!0;case"block":case"blacklist":return!1;default:return!1}}function On(t,e){let r=t.block??t.blacklist,n=t.allow??t.whitelist;if(r.length>0&&he.IOGateway.Filtering.valuesMatch(r,e))return St.warn(`origin ${e} matches block filter`),!1;if(n.length>0&&he.IOGateway.Filtering.valuesMatch(n,e))return St.enabledFor("debug")&&St.debug(`origin ${e} matches allow filter`),!0}function Mn(t){switch(t.non_matched){case"allow":case"whitelist":return!0;case"block":case"blacklist":return!1;default:return!1}}function cr(t,e){if(!e)return!0;if(t){let r=On(e,t);return r||Mn(e)}else return Tn(e)}function dr(t){if(t){let e=(t.block??t.blacklist??[]).map(he.IOGateway.Filtering.regexify),r=(t.allow??t.whitelist??[]).map(he.IOGateway.Filtering.regexify);return{non_matched:t.non_matched??"allow",missing:t.missing??"allow",allow:r,block:e}}}var ur=t=>async e=>{for(let r of t)if((await r(e)).match)return T();return H},te=t=>{let e=async r=>{for(let n of t)if(!(await n(r)).match)return H;return T()};return e.toString=()=>`and(${t.map(r=>r.toString()).join(", ")})`,e},lr=t=>async e=>(await t(e)).match?H:T(),fe=async t=>T();fe.toString=()=>"any-exchange";var pr=Object.freeze({}),H=Object.freeze({match:!1,variables:pr}),T=(t=pr)=>({match:!0,variables:t}),O=(t,e)=>{let r=e?.method,n=async o=>{let i=o.request,s=i.path;if(r!==void 0&&i.method!==r)return H;if(typeof t=="string")return s===t?T():H;{let a=t.exec(s);return a===null?H:{match:!0,variables:{...a.groups}}}};return n.toString=()=>`pattern(${t.toString()}, method=${r??"<any>"})`,n},ge=t=>{let e=r=>{if(t.ignoredMediaTypes!==void 0){for(let n of t.ignoredMediaTypes)if(r===n||n==="*/*")return!0}return!1};return async r=>{let n=r.request,o;try{o=n.headers.list("accept")}catch{return H}for(let i of o)if(!e(i)){for(let s of t.mediaTypes)if(i.startsWith(s))return T()}return H}},V=async({request:t})=>t.upgrade&&t.headers.one("upgrade")?.toLowerCase()==="websocket"?T():H;V.toString=()=>"websocket upgrade";var vt=require("@interopio/gateway");async function xt(t,e,r){let n=(i,s)=>{if(s?.cors){let a=s.cors===!0?{allowOrigins:s.origins?.allow?.map(vt.IOGateway.Filtering.regexify),allowMethods:i.method===void 0?["*"]:[i.method],allowCredentials:s.authorize?.access!=="permitted"?!0:void 0}:s.cors,c=i.path;r.cors.push([c,a])}},o=new class{handle(...i){i.forEach(({request:s,options:a,handler:c})=>{let d=O(vt.IOGateway.Filtering.regexify(s.path),{method:s.method});a?.authorize&&r.authorize.push([d,a.authorize]),n(s,a);let u=async(l,m)=>{let{match:x,variables:p}=await d(l);x?await c(l,p):await m()};r.middleware.push(u)})}socket(...i){for(let{path:s,factory:a,options:c}of i){let d=s??"/";r.sockets.set(d,{default:s===void 0||s==="/",ping:c?.ping,factory:a,maxConnections:c?.maxConnections,authorize:c?.authorize,originFilters:dr(c?.origins)})}}};await t(o,e)}var Ge=require("@interopio/gateway");function Ln(t){let e=t.headers.one("origin");if(e===void 0)return!0;let r=t.URL,n=r.protocol,o=r.host,i=URL.parse(e),s=i?.host,a=i?.protocol;return n===a&&o===s}function Dn(t){return t.headers.has("origin")&&!Ln(t)}function fr(t){return t.method==="OPTIONS"&&t.headers.has("origin")&&t.headers.has("access-control-request-method")}var hr=["Origin","Access-Control-Request-Method","Access-Control-Request-Headers"],$n=(t,e)=>{let{request:r,response:n}=t,o=n.headers;if(!o.has("Vary"))o.set("Vary",hr.join(", "));else{let s=o.list("Vary");for(let a of hr)s.find(c=>c===a)||s.push(a);o.set("Vary",s.join(", "))}try{if(!Dn(r))return!0}catch{return M.enabledFor("debug")&&M.debug("reject: origin is malformed"),me(n),!1}if(o.has("access-control-allow-origin"))return M.enabledFor("trace")&&M.debug('skip: already contains "Access-Control-Allow-Origin"'),!0;let i=fr(r);return e?Un(t,e,i):i?(me(n),!1):!0},Ne=["*"],Et=["GET","HEAD","POST"],gr={allowOrigins:Ne,allowMethods:Et,allowHeaders:Ne,maxAge:1800};function Be(t){if(t){let e=t.allowHeaders;e&&e!==v&&(t={...t,allowHeaders:e.map(n=>n.toLowerCase())});let r=t.allowOrigins;return r&&(r==="*"?(yr(t),wr(t)):t={...t,allowOrigins:r.map(n=>typeof n=="string"&&n!==v&&(n=Ge.IOGateway.Filtering.regexify(n),typeof n=="string")?br(n).toLowerCase():n)}),t}}function Fe(t,e){if(e===void 0)return t!==void 0?t===v?[v]:t:[];if(t===void 0)return e===v?[v]:e;if(t==Ne||t===Et)return e===v?[v]:e;if(e==Ne||e===Et)return t===v?[v]:t;if(t===v||t.includes(v)||e===v||e.includes(v))return[v];let r=new Set;return t.forEach(n=>r.add(n)),e.forEach(n=>r.add(n)),Array.from(r)}var ye=(t,e)=>e===void 0?t:{allowOrigins:Fe(t.allowOrigins,e?.allowOrigins),allowMethods:Fe(t.allowMethods,e?.allowMethods),allowHeaders:Fe(t.allowHeaders,e?.allowHeaders),exposeHeaders:Fe(t.exposeHeaders,e?.exposeHeaders),allowCredentials:e?.allowCredentials??t.allowCredentials,allowPrivateNetwork:e?.allowPrivateNetwork??t.allowPrivateNetwork,maxAge:e?.maxAge??t.maxAge},Wn=t=>{let e=t.corsConfigSource,r=t.corsProcessor??$n;if(e===void 0)throw new Error("corsConfigSource is required");if(r===void 0)throw new Error("corsProcessor is required");return async(n,o)=>{let i=await e(n);!r(n,i)||fr(n.request)||await o()}},mr=Wn,M=w("cors");function me(t){t.setStatusCode(b.FORBIDDEN)}function Un(t,e,r){let{request:n,response:o}=t,i=o.headers,s=n.headers.one("origin"),a=Nn(e,s);if(a===void 0)return M.enabledFor("debug")&&M.debug(`reject: '${s}' origin is not allowed`),me(o),!1;let c=_n(n,r),d=Gn(e,c);if(d===void 0)return M.enabledFor("debug")&&M.debug(`reject: HTTP '${c}' is not allowed`),me(o),!1;let u=qn(n,r),l=Bn(e,u);if(r&&l===void 0)return M.enabledFor("debug")&&M.debug(`reject: headers '${u}' are not allowed`),me(o),!1;i.set("Access-Control-Allow-Origin",a),r&&i.set("Access-Control-Allow-Methods",d.join(",")),r&&l!==void 0&&l.length>0&&i.set("Access-Control-Allow-Headers",l.join(", "));let m=e.exposeHeaders;return m&&m.length>0&&i.set("Access-Control-Expose-Headers",m.join(", ")),e.allowCredentials&&i.set("Access-Control-Allow-Credentials","true"),e.allowPrivateNetwork&&n.headers.one("access-control-request-private-network")==="true"&&i.set("Access-Control-Allow-Private-Network","true"),r&&e.maxAge!==void 0&&i.set("Access-Control-Max-Age",e.maxAge.toString()),!0}var v="*",Fn=["GET","HEAD"];function yr(t){if(t.allowCredentials===!0&&t.allowOrigins===v)throw new Error('when allowCredentials is true allowOrigins cannot be "*"')}function wr(t){if(t.allowPrivateNetwork===!0&&t.allowOrigins===v)throw new Error('when allowPrivateNetwork is true allowOrigins cannot be "*"')}function Nn(t,e){if(e){let r=t.allowOrigins;if(r){if(r===v)return yr(t),wr(t),v;let n=br(e.toLowerCase());for(let o of r)if(o===v||Ge.IOGateway.Filtering.valueMatches(o,n))return e}}}function Gn(t,e){if(e){let r=t.allowMethods??Fn;if(r===v)return[e];if(Ge.IOGateway.Filtering.valuesMatch(r,e))return r}}function Bn(t,e){if(e===void 0)return;if(e.length==0)return[];let r=t.allowHeaders;if(r===void 0)return;let n=r===v||r.includes(v),o=[];for(let i of e){let s=i?.trim();if(s){if(n)o.push(s);else for(let a of r)if(s.toLowerCase()===a){o.push(s);break}}}if(o.length>0)return o}function br(t){return t.endsWith("/")?t.slice(0,-1):t}function _n(t,e){return e?t.headers.one("access-control-request-method"):t.method}function qn(t,e){let r=t.headers;return e?r.list("access-control-request-headers"):Array.from(r.keys())}var Sr=t=>async e=>{for(let[r,n]of t.mappings)if((await r(e)).match)return M.debug(`resolved cors config on '${e.request.path}' using ${r}: ${JSON.stringify(n)}`),n};var vr=require("@interopio/gateway");function xr(t){let{sockets:e,cors:r}=t,n=t.corsConfig===!1?void 0:ye(gr,t.corsConfig),o=[];for(let[s,a]of e){let c=n;for(let[u,l]of r)vr.IOGateway.Filtering.valueMatches(u,s)&&(l===void 0?c=void 0:c=c===void 0?l:ye(c,l));let d=t.corsConfig===!1?void 0:{allowOrigins:a.originFilters?.allow,allowMethods:["GET","CONNECT","OPTIONS"],allowHeaders:["Upgrade","Connection","Origin","Sec-Websocket-Key","Sec-Websocket-Version","Sec-Websocket-Protocol","Sec-Websocket-Extensions"],exposeHeaders:["Sec-Websocket-Accept","Sec-Websocket-Protocol","Sec-Websocket-Extensions"],allowCredentials:a.authorize?.access!=="permitted"?!0:void 0};c=c===void 0?d:ye(c,d),o.push([te([V,O(s)]),Be(c)])}let i=[];for(let[s,a]of r){let[,c]=i.find(([u])=>String(u)===String(s))??[s,n];c=c===void 0?a:ye(c,a);let d=!1;for(let u of i)if(String(u[0])===String(s)){u[1]=c,d=!0;break}d||i.push([s,c])}for(let[s,a]of i)o.push([O(s),Be(a)]);return o.push([O(/\/api\/.*/),Be(n)]),Sr({mappings:o})}function Er(t){return t!==void 0&&typeof t.type=="string"&&typeof t.authenticated=="boolean"}var C=class extends Error{_authentication;get authentication(){return this._authentication}set authentication(e){if(e===void 0)throw new TypeError("Authentication cannot be undefined");this._authentication=e}},_e=class extends C{},re=class extends C{},ne=class extends C{constructor(e){super(e)}},we=class extends ne{constructor(e){super(e)}},be=class extends ne{constructor(e){super(e)}},Se=class extends ne{constructor(e){super(e)}},ve=class extends ne{constructor(e){super(e)}};var X=class extends Error{},G=class{constructor(e){this.granted=e}granted},_=class{#e;constructor(e){this.#e=e}async verify(e,r){if(!(await this.#e(e,r))?.granted)throw new X("Access denied")}async authorize(e,r){return await this.#e(e,r)}},oe=class extends C{};var I=t=>async e=>{let r=!0,{response:n}=e;for(let o of t.keys())n.headers.has(o)&&(r=!1);if(r)for(let[o,i]of t)n.headers.set(o,i)},zn=()=>I(new E().add("cache-control","no-cache, no-store, max-age=0, must-revalidate").add("pragma","no-cache").add("expires","0")),jn=()=>I(new E().add("x-content-type-options","nosniff")),Vn=(t,e,r)=>{let n=`max-age=${t}`;e&&(n+=" ; includeSubDomains"),r&&(n+=" ; preload");let o=I(new E().add("strict-transport-security",n)),i=s=>s.request.URL.protocol==="https:";return async s=>{i(s)&&await o(s)}},Xn=t=>I(new E().add("x-frame-options",t)),Jn=t=>I(new E().add("x-xss-protection",t)),Kn=t=>{let e=t===void 0?void 0:I(new E().add("permissions-policy",t));return async r=>{e!==void 0&&await e(r)}},Yn=(t,e)=>{let r=e?"content-security-policy-report-only":"content-security-policy",n=t===void 0?void 0:I(new E().add(r,t));return async o=>{n!==void 0&&await n(o)}},Qn=(t="no-referrer")=>I(new E().add("referer-policy",t)),Zn=t=>{let e=t===void 0?void 0:I(new E().add("cross-origin-opener-policy",t));return async r=>{e!==void 0&&await e(r)}},eo=t=>{let e=t===void 0?void 0:I(new E().add("cross-origin-embedder-policy",t));return async r=>{e!==void 0&&await e(r)}},to=t=>{let e=t===void 0?void 0:I(new E().add("cross-origin-resource-policy",t));return async r=>{e!==void 0&&await e(r)}},ro=(...t)=>async e=>{for(let r of t)await r(e)};function At(t){let e=[];t?.cache?.disabled||e.push(zn()),t?.contentType?.disabled||e.push(jn()),t?.hsts?.disabled||e.push(Vn(t?.hsts?.maxAge??365*24*60*60,t?.hsts?.includeSubDomains??!0,t?.hsts?.preload??!1)),t?.frameOptions?.disabled||e.push(Xn(t?.frameOptions?.mode??"DENY")),t?.xss?.disabled||e.push(Jn(t?.xss?.headerValue??"0")),t?.permissionsPolicy?.disabled||e.push(Kn(t?.permissionsPolicy?.policyDirectives)),t?.contentSecurityPolicy?.disabled||e.push(Yn(t?.contentSecurityPolicy?.policyDirectives??"default-src 'self'",t?.contentSecurityPolicy?.reportOnly)),t?.refererPolicy?.disabled||e.push(Qn(t?.refererPolicy?.policy??"no-referrer")),t?.crossOriginOpenerPolicy?.disabled||e.push(Zn(t?.crossOriginOpenerPolicy?.policy)),t?.crossOriginEmbedderPolicy?.disabled||e.push(eo(t?.crossOriginEmbedderPolicy?.policy)),t?.crossOriginResourcePolicy?.disabled||e.push(to(t?.crossOriginResourcePolicy?.policy)),t?.writers&&e.push(...t.writers);let r=ro(...e);return async(n,o)=>{await r(n),await o()}}var ie=t=>{let e=t.entryPoint,r=t?.rethrowAuthenticationServiceError??!0;return async({exchange:n},o)=>{if(!r||!(o instanceof oe))return e(n,o);throw o}};var no="Realm",oo=t=>`Basic realm="${t}"`,se=t=>{let e=oo(t?.realm??no);return async(r,n)=>{let{response:o}=r;o.setStatusCode(b.UNAUTHORIZED),o.headers.set("WWW-Authenticate",e)}};var Ar="Basic ",qe=t=>{let e=t?.credentialsEncoding??"utf-8";return async r=>{let{request:n}=r,o=n.headers.one("authorization");if(!o||!/basic/i.test(o.substring(0)))return;let i=o.length<=Ar.length?"":o.substring(Ar.length),a=Buffer.from(i,"base64").toString(e).split(":",2);if(a.length!==2)return;let c=a[0],d=a[1];return{type:"UsernamePassword",authenticated:!1,principal:c,credentials:d,name:c,eraseCredentials:()=>{d=null}}}};var Cr=require("node:async_hooks"),q=class t{static hasSecurityContext(e){return e.getStore()?.securityContext!==void 0}static async getSecurityContext(e){return await e.getStore()?.securityContext}static clearSecurityContext(e){delete e.getStore()?.securityContext}static withSecurityContext(e){return(r=new Cr.AsyncLocalStorage)=>(r.getStore().securityContext=e,r)}static withAuthentication(e){return t.withSecurityContext(Promise.resolve({authentication:e}))}static async getContext(e){if(t.hasSecurityContext(e))return t.getSecurityContext(e)}};async function io(t,e,r,n,o,i){let a=await(await n(t))?.(r);if(a===void 0)throw new Error("No authentication manager found for the exchange");try{await so(a,{exchange:t,next:e},o,i)}catch(c){throw c instanceof C,c}}async function so(t,e,r,n){q.withAuthentication(t)(n),await r(e,t)}function z(t){let e={matcher:fe,successHandler:async({next:n})=>{await n()},converter:qe({}),failureHandler:ie({entryPoint:se({})}),...t},r=e.managerResolver;if(r===void 0&&e.manager!==void 0){let n=e.manager;r=async o=>n}if(r===void 0)throw new Error("Authentication filter requires a managerResolver or a manager");return async(n,o)=>{let s=(await e.matcher(n)).match?await e.converter(n):void 0;if(s===void 0){await o();return}try{await io(n,o,s,r,e.successHandler,e.storage)}catch(a){if(a instanceof C){await e.failureHandler({exchange:n,next:o},a);return}throw a}}}var Pr=t=>async(e,r)=>{e.response.setStatusCode(t.httpStatus)};var ae=w("auth.entry-point"),ze=t=>{let e=t.defaultEntryPoint??(async({response:r},n)=>{r.setStatusCode(b.UNAUTHORIZED),await r.end()});return async(r,n)=>{for(let[o,i]of t.entryPoints)if(ae.enabledFor("debug")&&ae.debug(`trying to match using: ${o}`),(await o(r)).match)return ae.enabledFor("debug")&&ae.debug(`match found. using default entry point ${i}`),i(r,n);return ae.enabledFor("debug")&&ae.debug(`no match found. using default entry point ${e}`),e(r,n)}};var Hr=t=>async({exchange:e,next:r},n)=>{for(let o of t)await o({exchange:e,next:r},n)};function Ct(t){let e=async m=>m.request.headers.list("X-Requested-With").includes("XMLHttpRequest")?T():H,r=ze({entryPoints:[[e,Pr({httpStatus:b.UNAUTHORIZED})]],defaultEntryPoint:se({})}),n=t.entryPoint??r,o=t.manager,i=ge({mediaTypes:["application/atom+xml","application/x-www-form-urlencoded","application/json","application/octet-stream","application/xml","multipart/form-data","text/xml"],ignoredMediaTypes:["*/*"]}),s=lr(ge({mediaTypes:["text/html"]})),a=te([s,i]),c=ur([e,a]);t.defaultEntryPoints.push([c,n]);let d=t.failureHandler??ie({entryPoint:n}),u=Hr(t.successHandlers??t.defaultSuccessHandlers),l=qe({});return z({storage:t.storage,manager:o,failureHandler:d,successHandler:u,converter:l})}var kr={invalid_request:"invalid_request",invalid_token:"invalid_token",insufficient_scope:"insufficient_scope"},Rr="https://tools.ietf.org/html/rfc6750#section-3.1";function je(t){return{errorCode:kr.invalid_token,httpStatus:b.UNAUTHORIZED,description:t,uri:Rr}}function Pt(t){return{errorCode:kr.invalid_request,httpStatus:b.BAD_REQUEST,description:t,uri:Rr}}var ao="access_token",co=/^Bearer\s+(?<token>[a-zA-Z0-9-._~+/]+=*)$/i,D=class extends C{error;constructor(e,r,n){super(r??(typeof e=="string"?void 0:e.description),n),this.error=typeof e=="string"?{errorCode:e}:e}},Tr=t=>t.type==="BearerToken",uo=t=>async e=>{let{request:r}=e;return Promise.all([po(r.headers,t?.headerName).then(n=>n!==void 0?[n]:void 0),ho(r,t?.uriQueryParameter),fo(e,t?.formEncodedBodyParameter)]).then(n=>n.filter(o=>o!==void 0).flat(1)).then(lo).then(n=>{if(n)return{authenticated:!1,type:"BearerToken",token:n}})};async function lo(t){if(t.length===0)return;if(t.length>1){let r=Pt("Found multiple access tokens in the request");throw new D(r)}let e=t[0];if(!e||e.length===0){let r=Pt("The requested access token parameter is an empty string");throw new D(r)}return e}async function po(t,e="authorization"){let r=t.one(e);if(!r||!/bearer/i.test(r.substring(0)))return;let n=co.exec(r);if(n===null){let o=je("Bearer token is malformed");throw new D(o)}return n.groups?.token}async function Or(t){let e=t.getAll(ao);if(e.length!==0)return e}async function ho(t,e=!1){if(!(!e||t.method!=="GET"))return Or(t.URL.searchParams)}async function fo(t,e=!1){let{request:r}=t;if(!e||r.headers.one("content-type")!=="application/x-www-form-urlencoded"||r.method!=="POST")return;let n=await t.request.formData();if(n)return Or(n)}var Ve=uo;function go(t){let e="Bearer";if(t.size!==0){e+=" ";let r=0;for(let[n,o]of t)e+=`${n}="${o}"`,r!==t.size-1&&(e+=", "),r++}return e}var Mr=t=>t.httpStatus!==void 0;function mo(t){if(t instanceof D){let{error:e}=t;if(Mr(e))return e.httpStatus}return b.UNAUTHORIZED}function yo(t,e){let r=new Map;if(e&&r.set("realm",e),t instanceof D){let{error:n}=t;r.set("error",n.errorCode),n.description&&r.set("error_description",n.description),n.uri&&r.set("error_uri",n.uri),Mr(n)&&n.scope&&r.set("scope",n.scope)}return r}var wo=t=>async(e,r)=>{let n=mo(r),o=yo(r,t?.realmName),i=go(o),{response:s}=e;s.headers.set("WWW-Authenticate",i),s.setStatusCode(n),await s.end()},Xe=wo;var bo=t=>{let e=t?.principalClaimName??"sub";return r=>({type:"JwtToken",authenticated:!0,name:r.getClaimAsString(e)})},So=t=>async e=>t(e),ce=class extends Error{},xe=class extends ce{};function vo(t){if(t instanceof xe)return new D(je(t.message),t.message,{cause:t});throw new oe(t.message,{cause:t})}function Ht(t){let e=t.decoder,r=t.authConverter??So(bo({}));return async n=>{if(Tr(n)){let o=n.token;try{let i=await e(o);return await r(i)}catch(i){throw i instanceof ce?vo(i):i}}}}function kt(t){let e=t.entryPoint??Xe({}),r=t?.converter??Ve({}),n=t.failureHandler??ie({entryPoint:e});if(t.managerResolver!==void 0)return z({storage:t.storage,converter:r,failureHandler:n,managerResolver:t.managerResolver});if(t.jwt!==void 0){let o=t.jwt.manager??Ht(t.jwt);return z({storage:t.storage,converter:r,failureHandler:n,managerResolver:async i=>o})}throw new Error("Invalid resource server configuration: either managerResolver or jwt must be provided")}var tt=require("@interopio/gateway/jose/jwt");async function Ir(t,e,r){let n=new _e("Full authentication is required to access this resource."),o=new C("Access Denied",{cause:n});e&&(o.authentication=e),await r(t,o)}function xo(t){return async(e,r)=>{e.response.setStatusCode(t),e.response.headers.set("Content-Type","text/plain; charset=utf-8");let n=Buffer.from("Access Denied","utf-8");e.response.headers.set("Content-Length",n.length),await e.response.body(n)}}var Lr=t=>{let e=xo(b.FORBIDDEN),r=t.authenticationEntryPoint??se();return async(n,o)=>{try{await o()}catch(i){if(i instanceof X){let s=await n.principal();Er(s)?(s.authenticated||await e(n,i),await Ir(n,s,r)):await Ir(n,void 0,r);return}throw i}}};var Eo=w("security.auth");function Rt(t){let e=async(r,n)=>{let o;for(let[i,s]of t.mappings)if((await i(n))?.match){Eo.debug(`checking authorization on '${n.request.path}' using [${i}, ${s}]`);let a=await s.authorize(r,{exchange:n});if(a!==void 0){o=a;break}}return o??=new G(!1),o};return new _(e)}var Je=w("security.auth");function Tt(t){let{manager:e,storage:r}=t;return async(n,o)=>{let i=q.getContext(r).then(s=>s?.authentication);try{await e.verify(i,n),Je.enabledFor("debug")&&Je.debug("authorization successful")}catch(s){throw s instanceof X&&Je.enabledFor("debug")&&Je.debug(`authorization failed: ${s.message}`),s}await o()}}var Ot=class extends De{#e;constructor(e,r){super(e),this.#e=r}async principal(){return(await this.#e())?.authentication}},Dr=t=>{let e=t.storage;return async(r,n)=>{await n(new Ot(r,async()=>await q.getContext(e)))}};var $r=t=>{let{principalExtractor:e}=t;return async r=>{let n=r.request.sslInfo;if(n===void 0||n.peerCertificate===void 0)return;let o=n.peerCertificate,i=e(o);return{type:"PreAuthenticated",authenticated:!1,principal:i,name:i??"",credentials:o}}};var Ke=t=>{let e=t?.principalAltName==="email",r=/CN=(.*?)(?:,|$)/mi;return n=>{if(e){let s=n.subjectAltName?.split(", ").find(a=>a.startsWith("email:"));if(s)return s.replace("email:","")}let o=r.exec(n.subject);if(o===null)throw new re(`Cannot extract principal from subject DN: ${n.subject}`);return o[1]}};var J=class{async encode(e){if(e!=null)return await this.encodeDefinedPassword(e.toString())}async matches(e,r){return!e||!r?!1:await this.matchesDefined(e.toString(),r)}upgradeEncoding(e){return e?this.upgradeEncodingDefined(e):!1}upgradeEncodingDefined(e){return!1}},de=class t extends J{static DEFAULT_ID_PREFIX="{";static DEFAULT_ID_SUFFIX="}";#e;#r;#t;#n;#i;#s=new class extends J{#c;constructor(e){super(),this.#c=e}async encodeDefinedPassword(e){throw new Error("encode is not supported")}async matchesDefined(e,r){let n=this.#c.#o(r);if(!n)throw new Error(`No password encoder mapped for id ${n}`);if(r){let o=r.indexOf(this.#c.#e),i=r.indexOf(this.#c.#r,o+this.#c.#e.length);if(o===-1&&i===-1)throw new Error("No prefix found in encoded password")}throw new Error("malformed password encoder prefix")}}(this);constructor(e,r,n=t.DEFAULT_ID_PREFIX,o=t.DEFAULT_ID_SUFFIX){if(e==null)throw new Error("idForEncode cannot be null or undefined");if(n==null)throw new Error("idPrefix cannot be null or undefined");if(!o)throw new Error("idSuffix cannot be empty");if(n.indexOf(o)!==-1)throw new Error(`idPrefix "${n}" cannot contain idSuffix "${o}"`);if(!r.has(e))throw new Error(`No PasswordEncoder mapped for id "${e}"`);for(let i of r.keys())if(i!==null){if(n&&i.includes(n))throw new Error(`id "${i}" cannot include ${n}`);if(o&&i.includes(o))throw new Error(`id "${i}" cannot include ${o}`)}super(),this.#t=e,this.#n=r.get(e),this.#i=new Map(r),this.#e=n,this.#r=o}set defaultPasswordEncoderForMatches(e){if(e==null)throw new Error("defaultPasswordEncoderForMatches cannot be null or undefined");this.#s=e}async encodeDefinedPassword(e){let r=await this.#n.encode(e);return`${this.#e}${this.#t}${this.#r}${r}`}async matchesDefined(e,r){let n=this.#o(r),o=n?this.#i.get(n):void 0;if(o===void 0)return await this.#s.matches(e,r);{let i=this.#a(r);return await o.matches(e,i)}}#o(e){if(e===void 0)return;let r=e.indexOf(this.#e);if(r!==0)return;let n=e.indexOf(this.#r,r+this.#e.length);if(n!==-1)return e.substring(r+this.#e.length,n)}upgradeEncodingDefined(e){let r=this.#o(e);if(this.#t!==r)return!0;{let n=this.#a(e);return this.#n.upgradeEncoding?.(n)??!1}}#a(e){let r=e.indexOf(this.#r);return e.substring(r+this.#r.length)}},Ye=class t extends J{static#e=new t;static get instance(){return t.#e}constructor(){super()}async encodeDefinedPassword(e){return e.toString()}async matchesDefined(e,r){return e.toString()===r}};var P=require("@interopio/gateway-server/tools");function Ao(t,e){if(t.length!==e.length)return!1;let r=0;for(let n=0;n<t.length;n++)r|=t[n]^e[n];return r===0}var Qe=class extends J{#e;#r;#t;#n;#i;constructor(e=P.argon2.DEFAULT_SALT_LENGTH,r=P.argon2.DEFAULT_HASH_LENGTH,n=P.argon2.DEFAULT_PARALLELISM,o=P.argon2.DEFAULT_MEMORY,i=P.argon2.DEFAULT_PASSES){super(),this.#e=e,this.#r=r,this.#t=n,this.#n=o,this.#i=i}async matchesDefined(e,r){try{let n=P.argon2.decode(r),o=await P.argon2.createHash(n.algorithm,e,n.hash.length,n.parameters);return Ao(n.hash,o)}catch{return!1}}async encodeDefinedPassword(e){let r=P.keygen.createSalt(this.#e),n={memory:this.#n,passes:this.#i,parallelism:this.#t,nonce:r},o=await P.argon2.createHash("argon2id",e,this.#r,n);return P.argon2.encode({algorithm:"argon2id",version:P.argon2.ARGON2_VERSION,parameters:n,hash:o})}upgradeEncodingDefined(e){let r=P.argon2.decode(e);return r.version<P.argon2.ARGON2_VERSION||r.parameters.memory<this.#n||r.parameters.passes<this.#i}};var Mt=4096;function Wr(){let t="argon2id",e=new Map([[t,new Qe],["noop",Ye.instance]]);return new de(t,e,de.DEFAULT_ID_PREFIX,de.DEFAULT_ID_SUFFIX)}var Ur={async updatePassword(t,e){return t}},Ze=class extends C{username;constructor(e,r,n){super(e,n),this.username=r}},et=class t{#e;#r;#t=[];#n;#i;#s;#o;#a=e=>e;constructor(){}static ofUsername(e){return new t().username(e)}static ofUserDetails(e){let r=t.ofUsername(e.username).accountExpired(e.accountExpired??!1).accountLocked(e.accountLocked??!1).authorities(e.authorities).credentialsExpired(e.credentialsExpired??!1).disabled(e.disabled??!1);return e.password!==void 0&&r.password(e.password),r}username(e){if(!e)throw new TypeError("username cannot be empty");return this.#e=e,this}password(e){return this.#r=e,this}passwordEncoder(e){if(!e)throw new TypeError("password encoder cannot be null or undefined");return this.#a=e,this}roles(...e){return this.authorities(e.map(r=>{if(r.startsWith("role:"))throw new Error(`${r} must not start with 'role:' (it is automatically added)`);return{authority:`role:${r}`}}))}authorities(e){return this.#t=[...e],this}accountExpired(e){return this.#n=e,this}accountLocked(e){return this.#i=e,this}credentialsExpired(e){return this.#s=e,this}disabled(e){return this.#o=e,this}build(){if(!this.#e)throw new TypeError("username is required");let e=this.#r!==void 0?this.#a(this.#r):void 0;return{username:this.#e,password:e,authorities:this.#t,accountExpired:this.#n,accountLocked:this.#i,credentialsExpired:this.#s,disabled:this.#o,eraseCredentials(){e=null},toString(){return`User(username=${this.username}, password=[PROTECTED], authorities=${JSON.stringify(this.authorities)}, accountExpired=${this.accountExpired}, accountLocked=${this.accountLocked}, credentialsExpired=${this.credentialsExpired}, disabled=${this.disabled})`}}}};var j=w("security.users");function Fr(t,e){let r=e?.preAuthenticationChecks??(a=>{if(a.accountLocked)throw j.debug("user account is locked"),new we("User account is locked");if(a.disabled)throw j.debug("user account is disabled"),new be("User is disabled");if(a.accountExpired)throw j.debug("user account is expired"),new Se("User account has expired")}),n=e?.postAuthenticationChecks??(a=>{if(a.credentialsExpired)throw j.debug("user credentials have expired"),new ve("User credentials have expired")}),o=e?.passwordEncoder??Wr(),i=e?.userDetailsPasswordService??Ur,s=async(a,c)=>{let d=a.password;if(d!==void 0&&o.upgradeEncoding?.(d)){let l=await o.encode(c);return await i.updatePassword(a,l)}return a};return async a=>{let c=a.name,d=a.credentials!==void 0&&a.credentials!==null?a.credentials.toString():void 0,u=await t.findByUsername(c);if(!u)throw new Error(`User not found: ${c}`);if(r(u),!await o.matches(d,u.password))throw new re("Invalid Credentials");let l=await s(u,d);n(l);let m=l.password;return{type:"UsernamePassword",principal:l,credentials:m,authorities:l.authorities,authenticated:!0,name:l.username,eraseCredentials(){m=null}}}}function Co(){return t=>{if(t.accountLocked)throw j.debug("failed to authenticate since user account is locked"),new we("User account is locked");if(t.disabled)throw j.debug("failed to authenticate user account is disabled"),new be("User is disabled");if(t.accountExpired)throw j.debug("failed to authenticate since user account is expired"),new Se("User account has expired");if(t.credentialsExpired)throw j.debug("failed to authenticate since user credentials have expired"),new ve("User credentials have expired")}}function Nr(t){let e=t.userDetailsService,r=t.userDetailsChecker??Co(),n=o=>o.type==="PreAuthenticated"&&o.name!==void 0;return async o=>{let i=n(o)&&await e.findByUsername(o.name);if(!i)throw new Ze("user not found",o.name);r(i);let s=o.credentials;return{type:"PreAuthenticated",principal:i,credentials:s,authorities:i.authorities,authenticated:!0,details:i,name:i.username,eraseCredentials(){s=null}}}}function It(t){let e=t.manager??Nr({userDetailsService:t.getService("UserDetailsService")}),r=t.extractor??Ke(),n=t.converter??$r({principalExtractor:r});return z({storage:t.storage,manager:e,converter:n})}var $={first:Number.MAX_SAFE_INTEGER,http_headers:100,https_redirect:200,cors:300,http_basic:600,authentication:800,security_context_server_web_exchange:1500,error_translation:1800,authorization:1900,last:Number.MAX_SAFE_INTEGER},W=Symbol.for("filterOrder"),Gr=(t,e)=>{let r=(a,c)=>{if(e===void 0)return c;if(a==="UserDetailsService"&&e.userDetailsService!==void 0)return e.userDetailsService;if(a==="AuthenticationManager"&&e.authenticationManager!==void 0)return e.authenticationManager;if(c!==void 0)return c;throw new Error(`No service registered with name: ${a}`)},n=()=>{if(e.authenticationManager!==void 0)return e.authenticationManager;if(e.userDetailsService!==void 0)return Fr(e.userDetailsService,{userDetailsPasswordService:e.userDetailsPasswordService})},o=[];class i{#e;#r=[];#t;set authenticationManager(c){this.#t=c}get authenticationEntryPoint(){return this.#e!==void 0||this.#r.length===0?this.#e:this.#r.length===1?this.#r[0][1]:ze({entryPoints:this.#r,defaultEntryPoint:this.#r[this.#r.length-1][1]})}build(){if(t.headers!==void 0&&t.headers.disabled!==!0){let d=At(t.headers);d[W]=$.http_headers,o.push(d)}if(t.x509!==void 0&&t.x509.disabled!==!0){let d=It({storage:e.storage,getService:r,extractor:Ke({principalAltName:t.x509.principalAltName})});d[W]=$.authentication,o.push(d)}if(t.cors?.disabled!==!0&&e.corsConfigSource!==void 0){let d=mr({corsConfigSource:e.corsConfigSource});d[W]=$.cors,o.push(d)}if(t.basic!==void 0&&t.basic?.disabled!==!0){let d=[async({exchange:l,next:m},x)=>m()],u=Ct({storage:e.storage,manager:this.#t,defaultEntryPoints:this.#r,defaultSuccessHandlers:d});u[W]=$.http_basic,o.push(u)}if(t.jwt!==void 0&&t.jwt.disabled!==!0){let d=(0,tt.jwtVerifier)({issuerBaseUri:t.jwt.issuerUri,issuer:t.jwt.issuer,audience:t.jwt.audience}),u=async f=>{try{let{payload:h}=await d(f);return{tokenValue:f,subject:h.sub,getClaimAsString(y){return h[y]}}}catch(h){throw h instanceof tt.JwtVerifyError?new xe(h.message,{cause:h}):new ce("error occurred while attempting to decoding jwt",{cause:h})}},l=Ve({uriQueryParameter:!0}),m=async f=>{try{return await l(f)===void 0?H:T()}catch{return H}},x=Xe({});this.#r.push([m,x]);let p=kt({storage:e.storage,entryPoint:x,converter:l,jwt:{decoder:u}});p[W]=$.authentication,o.push(p)}let c=Dr({storage:e.storage});if(o.push(c),c[W]=$.security_context_server_web_exchange,t.authorize!==void 0){let d=Lr({authenticationEntryPoint:this.authenticationEntryPoint});d[W]=$.error_translation,o.push(d);let l=(x=>{let p=[],f=!1;for(let[h,y]of x??[]){let k;if(h==="any-exchange")f=!0,k=fe;else{if(f)throw new Error("Cannot register other matchers after 'any-exchange' matcher");k=h}let R;if(y.access==="permitted")R=new _(async()=>new G(!0)),R.toString=()=>"AuthorizationManager[permitted]";else if(y.access==="denied")R=new _(async()=>new G(!1)),R.toString=()=>"AuthorizationManager[denied]";else if(y.access==="authenticated")R=new _(async K=>{let Ft=await K;return Ft!==void 0?new G(Ft.authenticated):new G(!1)}),R.toString=()=>"AuthorizationManager[authenticated]";else throw new Error(`Unknown access type: ${JSON.stringify(y)}`);p.push([k,R])}return Rt({mappings:p})})(t.authorize),m=Tt({manager:l,storage:e.storage});m[W]=$.authorization,o.push(m)}o.sort((d,u)=>{let l=d[W]??$.last,m=u[W]??$.last;return l-m})}}let s=new i;return s.authenticationManager=n(),s.build(),o};var rt=class{#e=new Map;constructor(...e){for(let r of e)this.#e.set(this.#r(r.username),r)}async findByUsername(e){let r=this.#r(e),n=this.#e.get(r);return n!==void 0?{...n}:void 0}async updatePassword(e,r){let n={...e,password:r};if(n){let o=this.#r(e.username);this.#e.set(o,n)}return n}#r(e){return e.toLowerCase()}};var Br=require("node:crypto");var nt=w("auth");function Po(t){let e=[],r=t.authConfig?.type,n={access:r!=="none"?"authenticated":"permitted"};nt.enabledFor("info")&&nt.info(`using auth type: ${r??"none"}, default access: ${n.access}`);for(let[o,i]of t.sockets){let s=i.authorize??n,a=O(o,{method:"GET"});a=te([V,a]),e.push([a,s])}return e.push([O("/",{method:"GET"}),{access:"permitted"}]),e.push([O("/favicon.ico",{method:"GET"}),{access:"permitted"}]),e.push([O("/health",{method:"GET"}),{access:"permitted"}]),t.authorize.length>0&&e.push(...t.authorize),e.push(["any-exchange",n]),{authorize:e,cors:{disabled:t.corsConfig===!1},x509:{disabled:r!=="x509",...t.authConfig?.x509},basic:{disabled:r!=="basic",...t.authConfig?.basic},jwt:{disabled:r!=="oauth2",...t.authConfig?.oauth2?.jwt}}}function Ho(t){if(t.authConfig?.type==="none")return;function e(s,a){if(t.authConfig?.type==="x509")return null;let c=s.password;if(c===void 0){let d=(0,Br.randomUUID)().replaceAll("-","");nt.enabledFor("info")&&nt.info(`
3
3
 
4
4
  using generated password: ${d}
5
5
 
6
6
  This generated password is for development only. Your authentication configuration should be updated before running in production.
7
- `),c=d}if(c.length>kt)throw new Error(`Password length exceeds maximum length of ${kt} characters`);return a!=null||/^\{.+}.*$/.test(c)?c:`{noop}${c}`}let r={name:"dev-user",roles:[],...t.authConfig?.user},n=e(r),o=r.roles,i=Qe.ofUsername(r.name).password(n).roles(...o).build();return new et(i)}async function $r(t){let e=gr(t),r=mo(t),n=go(t),{storage:o}=t;return Lr(n,{storage:o,corsConfigSource:e,userDetailsService:r,userDetailsPasswordService:r})}var Wr=require("node:async_hooks");var rt=class extends Z{},Tt=class{#e;#r=!1;#t;#n;constructor(e,r){this.#e=e,this.#t=r}createExchange(e,r){return new Le(e,r)}set storage(e){this.#n=e}set enableLoggingRequestDetails(e){this.#r=e}formatHeaders(e){let r="{";for(let n of e.keys())if(this.#r){let o=e.get(n);r+=`"${n}": "${o}", `}else{r+="masked, ";break}return r.endsWith(", ")&&(r=r.slice(0,-2)),r+="}",r}formatRequest(e){let r=e.URL.search;return`HTTP ${e.method} "${e.path}${r}`}logRequest(e){if(this.#e.enabledFor("debug")){let r=this.#e.enabledFor("trace");this.#e.debug(`${e.logPrefix}${this.formatRequest(e.request)}${r?`, headers: ${this.formatHeaders(e.request.headers)}`:""}"`)}}logResponse(e){if(this.#e.enabledFor("debug")){let r=this.#e.enabledFor("trace"),n=e.response.statusCode;this.#e.debug(`${e.logPrefix}Completed ${n??"200 OK"}${r?`, headers: ${this.formatHeaders(e.response.headers)}`:""}"`)}}handleUnresolvedError(e,r){let{request:n,response:o,logPrefix:i}=e;if(o.setStatusCode(S.INTERNAL_SERVER_ERROR)){this.#e.error(`${i}500 Server Error for ${this.formatRequest(n)}`,r);return}throw this.#e.error(`${i}Error [${r.message} for ${this.formatRequest(n)}, but already ended (${o.statusCode})`,r),r}async web(e){return await this.#t(e)}async http(e,r){let n=this.createExchange(e,r),o=()=>(this.logRequest(n),this.web(n).then(()=>{this.logResponse(n)}).catch(i=>{this.handleUnresolvedError(n,i)}).then(async()=>{await n.response.end()}));await new Promise((i,s)=>{this.#n!==void 0?this.#n.run({exchange:n},()=>{o().then(()=>i()).catch(a=>s(a))}):o().then(()=>i()).catch(a=>s(a))})}},nt=class{#e;#r=new Wr.AsyncLocalStorage;#t;storage(e){return this.#r=e,this}httpHandlerDecorator(e){if(this.#t===void 0)this.#t=e;else{let r=this.#t;this.#t=n=>(n=r(n),e(n))}return this}constructor(e){this.#e=e}build(){let e=w("http"),r=new Tt(e,this.#e);this.#r!==void 0&&(r.storage=this.#r),r.enableLoggingRequestDetails=!1;let n=async(o,i)=>r.http(o,i);return this.#t?this.#t(n):n}};var Gr=require("ws");function Ur(t,e){let r=t?.exchange,n=r?.request??new Q(t),o=r?.principal,i=o?o.bind(r):async function(){},s=n.URL,a=new E;for(let m of n.headers.keys())a.set(m,n.headers.list(m));let c=n.cookies,d=r?.logPrefix??`[${n.id}] `,u=n.remoteAddress;return{url:s,headers:a,cookies:c,principal:i,protocol:e,remoteAddress:u,logPrefix:d}}function Nr(t){return[async(r,n)=>{let i=r.request.path??"/",s=t.sockets,a=s.get(i)??Array.from(s.values()).find(c=>{if(i==="/"&&c.default===!0)return!0});if(a!==void 0){let{request:c,response:d}=r,u=await V(r);if((c.method==="GET"||c.method==="CONNECT")&&u.match)if(a.upgradeStrategy!==void 0){a.upgradeStrategy(r);return}else throw new Error(`No upgrade strategy defined for route on ${i}`);else{if(a.default){await n();return}d.setStatusCode(S.UPGRADE_REQUIRED),d.headers.set("Upgrade","websocket").set("Connection","Upgrade").set("Content-Type","text/plain");let l=Buffer.from(`This service [${c.path}] requires use of the websocket protocol.`,"utf-8");await d.body(l)}}else await n()}]}var Fr=require("ws"),ot=class extends Fr.WebSocket{constructor(e,r,n){super(null,void 0,n)}connected},it=class t{static#e=Buffer.alloc(0);static#r=[0,Buffer.alloc(8)];#t;#n;#i;#s=!1;#o;constructor(e,r,n){this.#o=e,this.#n=typeof n=="number"?n:n?.interval,this.#t=typeof n=="number"||n?.data==="timestamp"?()=>t.#d(Date.now()):()=>t.#e,this.#n&&(this.#i=setInterval(()=>{let[o,i]=r();for(let s of i)this.#a(s,o)||this.#c(s,o)},this.#n))}#a(e,r){return e.connected===!1?(this.#o.enabledFor("debug")&&this.#o.debug(`terminating unresponsive ws client on [${r}]`),e.terminate(),!0):!1}#c(e,r){e.connected=!1;let n=this.#t();this.#o.enabledFor("trace")&&this.#o.debug(`pinging ws client on [${r}]`),e.ping(n,this.#s,o=>{o&&this.#o.enabledFor("warn")&&this.#o.warn(`failed to ping ws client on [${r}]`,o)})}static#d(e=Date.now()){if(e-t.#r[0]>0){let r=Buffer.allocUnsafe(8);r.writeBigInt64BE(BigInt(e),0),t.#r=[e,r]}return t.#r[1]}static#u(e){return e.length===8?Number(e.readBigInt64BE(0)):0}close(){clearInterval(this.#i)}handlePing(e,r,n){r.connected=!0,r.pong(n,!1,o=>{o&&this.#o.enabledFor("warn")&&this.#o.warn(`${e.logPrefix}failed to pong ws client ${B(e.remoteAddress)}`,o)})}handlePong(e,r,n){if(r.connected=!0,this.#o.enabledFor("warn")){let o=t.#u(n);if(o>0){let i=Date.now()-o;this.#o.enabledFor("debug")&&this.#o.debug(`${e.logPrefix}ws client ${B(e.remoteAddress)} ping-pong latency: ${i}ms`),this.#n&&i>this.#n/2&&this.#o.enabledFor("warn")&&this.#o.warn(`${e.logPrefix}ws client ${B(e.remoteAddress)} high ping-pong latency: ${i}ms`)}}}};var L=w("ws");function yo(t,e,r,n){return o=>{let{logPrefix:i,request:s}=o,a=Me.getNativeRequest(s);a.exchange=o;let{socket:c,upgradeHead:d}=a,u=s.host;if(c.removeListener("error",n),e.maxConnections!==void 0&&r.clients?.size>=e.maxConnections){L.warn(`${i}dropping ws connection request on ${u}${t}. max connections exceeded.`),c.destroy();return}let l=s.headers.one("origin");if(!tr(l,e.originFilters)){L.enabledFor("info")&&L.info(`${i}dropping ws connection request on ${u}${t}. origin ${l??"<missing>"}`),c.destroy();return}L.enabledFor("debug")&&L.debug(`${i}accepted new ws connection request on ${u}${t}`),r.handleUpgrade(a,c,d,(m,x)=>{r.emit("connection",m,x)})}}function wo(t,e){let r=new Set;t.forEach((o,i)=>{if(i===0&&o.startsWith("HTTP/1.1 101 ")){e.setStatusCode(S.SWITCHING_PROTOCOLS);return}let[s,a]=o.split(": ");e.headers.has(s)?t[i]=`${s}: ${e.headers.one(s)}`:e.headers.set(s,a),r.add(s.toLowerCase())});let n=Z.getNativeResponse(e);for(let o of n.getRawHeaderNames()){let i=o.toLowerCase();if(!r.has(i)){let s=e.headers.get(i);s!==void 0&&t.push(`${o}: ${s}`)}}n.markHeadersSent()}async function Br(t,e,r,n,o){try{L.info(`creating ws server for [${t}]. max connections: ${e.maxConnections??"<unlimited>"}, origin filters: ${e.originFilters?JSON.stringify(e.originFilters,Gt):"<none>"}, ping: ${typeof e.ping=="number"?e.ping+"ms":e.ping?JSON.stringify(e.ping):"<none>"}`);let i=new Gr.WebSocketServer({noServer:!0,WebSocket:ot,autoPong:!1}),s=new it(L.child("pings"),()=>[t,i.clients],e.ping),a=await e.factory({endpoint:r,storage:n});i.on("error",c=>{L.error(`error starting the ws server for [${t}]`,c)}).on("listening",()=>{L.info(`ws server for [${t}] is listening`)}).on("headers",(c,d)=>{if(d.exchange!==void 0){let{response:u}=d.exchange;wo(c,u)}}).on("connection",(c,d)=>{let u=Ur(d,c.protocol);c.on("pong",l=>{s.handlePong(u,c,l)}),c.on("ping",l=>{s.handlePing(u,c,l)}),a({socket:c,handshake:u})}),i.on("close",()=>{s.close()}),e.upgradeStrategy=yo(t,e,i,o),e.close=async()=>{await a.close?.call(a),L.info(`stopping ws server for [${t}]. clients: ${i.clients?.size??0}`),i.clients?.forEach(c=>{c.terminate()}),i.close()}}catch(i){L.warn(`failed to init route ${t}`,i)}}var g=require("node:fs"),ve=require("node:path"),at=require("jsrsasign"),st=require("@interopio/gateway-server/tools");var de=w("ssl");function _r(t,e){let r={};if(t.requestCert!==void 0&&(r.requestCert=t.requestCert),t.rejectUnauthorized!==void 0&&(r.rejectUnauthorized=t.rejectUnauthorized),t.key&&t.cert&&(0,g.existsSync)(t.key)&&(0,g.existsSync)(t.cert)){de.info(`using SSL/TLS certificate ${t.cert} with private key in ${t.key}${t.passphrase?" (password-protected)":""}`);let p={key:(0,g.readFileSync)(t.key),cert:(0,g.readFileSync)(t.cert),...r};return t.passphrase&&(p.passphrase=t.passphrase),t.requestCert&&t.ca&&(0,g.existsSync)(t.ca)&&(p.ca=(0,g.readFileSync)(t.ca)),p}if(!t.key&&!t.cert){let p="./gateway-server.key",f="./gateway-server.crt";if((0,g.existsSync)(p)&&(0,g.existsSync)(f)){de.info(`using SSL/TLS certificate ${f} with private key in ${p}${t.passphrase?" (password-protected)":""}`);let h={key:(0,g.readFileSync)(p),cert:(0,g.readFileSync)(f),...r};return t.passphrase&&(h.passphrase=t.passphrase),t.requestCert&&t.ca&&(0,g.existsSync)(t.ca)&&(h.ca=(0,g.readFileSync)(t.ca)),h}}if(!e)throw new Error("SSL/TLS enabled but no server certificate provided. Either provide ssl.key and ssl.cert, or configure auth.x509.key for auto-generation.");let n=e.key??"gateway-ca.key",o=t.ca??`${n.replace(/\.key$/,".crt")}`,i=e.passphrase??t.passphrase;if(!(0,g.existsSync)(n)){if((0,g.existsSync)(o))throw new Error(`CA key file not found: ${n} (CA certificate exists: ${o})`);let p=st.mkcert.generateRootCA({name:st.mkcert.DEFAULT_CA_NAME,passphrase:i}),f=(0,ve.dirname)(n);f&&f!=="."&&!(0,g.existsSync)(f)&&(0,g.mkdirSync)(f,{recursive:!0});let h=(0,ve.dirname)(o);h&&h!=="."&&h!==f&&!(0,g.existsSync)(h)&&(0,g.mkdirSync)(h,{recursive:!0}),(0,g.writeFileSync)(n,p.key,{mode:256}),(0,g.writeFileSync)(o,p.cert,{mode:420}),de.info(`created new local Root CA in ${o}, ${n}${i?" (password-protected)":""}`)}let s=(0,g.readFileSync)(n,"utf8"),a=at.KEYUTIL.getKey(s,i),c=(0,g.readFileSync)(o,"utf8"),d=new at.X509;d.readCertPEM(c);let u=d.getSubjectString(),l=e.host;de.debug(`generating server certificate signed by: ${u} for host: ${l}`);let m=st.mkcert.generateCert(a,u,[l],!1);if(t.key||t.cert){let p=t.key||"./gateway-server.key",f=t.cert||"./gateway-server.crt",h=(0,ve.dirname)(p);h&&h!=="."&&!(0,g.existsSync)(h)&&(0,g.mkdirSync)(h,{recursive:!0});let y=(0,ve.dirname)(f);y&&y!=="."&&y!==h&&!(0,g.existsSync)(y)&&(0,g.mkdirSync)(y,{recursive:!0}),(0,g.writeFileSync)(p,m.key,{mode:384}),(0,g.writeFileSync)(f,m.cert,{mode:420}),de.info(`generated server certificate saved to ${f} with private key in ${p}${i?" (password-protected)":""}`)}else de.info(`using in-memory server certificate for host: ${l}`);let x={key:m.key,cert:m.cert,...r};return t.requestCert&&t.ca&&(0,g.existsSync)(o)&&(x.ca=(0,g.readFileSync)(o)),x}var Ot=ue(require("@interopio/gateway-server/package.json"),1),U=w("app");async function So(t,e){let r=t.build();return async(n,o)=>{n.socket.addListener("error",e);let i;o instanceof Y?i=o:(n.upgradeHead=o,i=new Y(n),i.assignSocket(n.socket));let s=new Q(n),a=new Oe(i),c=s.method==="HEAD"?new rt(a):a;await r(s,c)}}function bo(t){return new Promise((e,r)=>{let n=t(o=>{o?r(o):e(n)})})}function vo(t){if(t)return Qt({memoryLimit:t.memory_limit,dumpLocation:t.dump_location,dumpPrefix:t.dump_prefix,reportInterval:t.report_interval,maxBackups:t.max_backups})}var Vr=`${Ot.default.name} - v${Ot.default.version}`;async function xo(t){let e=t.storage,r=await $r(t),n=Nr(t),o=jt(er(Vr,t.serverHeader),...r,...n,...t.middleware,async({request:i,response:s},a)=>{if(i.method==="GET"&&i.path==="/health"){s.setStatusCode(S.OK);let c=Buffer.from("UP","utf-8");s.headers.set("Content-Type","text/plain; charset=utf-8"),await s.body(c)}else await a()},async({request:i,response:s},a)=>{if(i.method==="GET"&&i.path==="/"){s.setStatusCode(S.OK);let c=Buffer.from("io.Gateway Server","utf-8");s.headers.set("Content-Type","text/plain; charset=utf-8"),await s.body(c)}else await a()},async({response:i},s)=>{i.setStatusCode(S.NOT_FOUND),await i.end()});return new nt(o).storage(e)}var Mt=async t=>{let e=t.ssl,r=t.host,n=t.auth?.x509?.key?{host:r??"localhost",key:t.auth.x509.key,passphrase:t.auth.x509.passphrase}:void 0,o=e?(p,f)=>zr.default.createServer({...p,..._r(e,n)},f):(p,f)=>qr.default.createServer(p,f),i=vo(t.memory),s={middleware:[],corsConfig:t.cors,cors:[],authConfig:t.auth,authorize:[],storage:new jr.AsyncLocalStorage,sockets:new Map},a=new Ee({baseConfig:{...t.gateway},scope:t.gateway?.scope??"principal"});if(t.gateway){let p=t.gateway;await wt(async f=>{f.socket({path:p.route,factory:qt.bind(a),options:p})},t,s)}t.app&&await wt(t.app,t,s);let c=Ut(t.port??0),d=p=>U.error(`socket error: ${p}`,p),u=await xo(s),l=await So(u,d),x=await new Promise((p,f)=>{let h=o({IncomingMessage:ke,ServerResponse:Y,...t.http},l);h.on("error",y=>{if(y.code==="EADDRINUSE"){U.debug(`port ${y.port} already in use on address ${y.address}`);let{value:k}=c.next();k?(U.info(`retry starting server on port ${k} and host ${r??"<unspecified>"}`),h.close(),h.listen(k,r)):(U.warn(`all configured port(s) ${t.port} are in use. closing...`),h.close(),f(y))}else U.error(`server error: ${y.message}`,y),f(y)}),h.on("listening",async()=>{let y=h.address();for(let[k,R]of s.sockets){let K=`${e?"wss":"ws"}://${Nt}:${y.port}${k}`;await Br(k,R,K,s.storage,d)}U.info(`http server listening on ${e?"https":"http"}://${B(y)}`),p(h)}),h.on("upgrade",(y,k,R)=>{try{l(y,R)}catch(K){U.error(`upgrade error: ${K}`,K)}}).on("close",async()=>{U.info("http server closed.")});try{let{value:y}=c.next();h.listen(y,r)}catch(y){U.error("error starting web socket server",y),f(y instanceof Error?y:new Error(`listen failed: ${y}`))}});return new class{gateway=a;get address(){let p=x.address();return typeof p=="object"?p:null}async close(){for(let[p,f]of s.sockets)try{f.close!==void 0&&await f.close()}catch(h){U.warn(`error closing route ${p}`,h)}await bo(p=>{x.closeAllConnections(),x.close(p)}),i&&await Zt(i),await a.stop()}}};var Eo=Mt;0&&(module.exports={GatewayServer});
7
+ `),c=d}if(c.length>Mt)throw new Error(`Password length exceeds maximum length of ${Mt} characters`);return a!=null||/^\{.+}.*$/.test(c)?c:`{noop}${c}`}let r={name:"dev-user",roles:[],...t.authConfig?.user},n=e(r),o=r.roles,i=et.ofUsername(r.name).password(n).roles(...o).build();return new rt(i)}async function _r(t){let e=xr(t),r=Po(t),n=Ho(t),{storage:o}=t;return Gr(r,{storage:o,corsConfigSource:e,userDetailsService:n,userDetailsPasswordService:n})}var qr=require("node:async_hooks");var ot=class extends ee{};function ko(t,e){if(t==null)return!1;let{code:r,message:n}=t;return r==="ECONNRESET"||r==="EPIPE"||r==="ERR_STREAM_PREMATURE_CLOSE"||n?.toLowerCase().includes("client aborted")||n?.toLowerCase().includes("socket hang up")||n?.toLowerCase().includes("aborted")?(e.enabledFor("trace")?e.trace("looks like the client has gone away:",t):e.enabledFor("debug")&&e.debug(`looks like the client has gone away: ${t.message} (For full stack trace enable trace logging level.)`),!0):!1}var Lt=class{#e;#r=!1;#t;#n;constructor(e,r){this.#e=e,this.#t=r}createExchange(e,r){return new $e(e,r)}set storage(e){this.#n=e}set enableLoggingRequestDetails(e){this.#r=e}formatHeaders(e){let r="{";for(let n of e.keys())if(this.#r){let o=e.get(n);r+=`"${n}": "${o}", `}else{r+="masked, ";break}return r.endsWith(", ")&&(r=r.slice(0,-2)),r+="}",r}formatRequest(e){let r=e.URL.search;return`HTTP ${e.method} "${e.path}${r}`}logRequest(e){if(this.#e.enabledFor("debug")){let r=this.#e.enabledFor("trace");this.#e.debug(`${e.logPrefix}${this.formatRequest(e.request)}${r?`, headers: ${this.formatHeaders(e.request.headers)}`:""}"`)}}logResponse(e){if(this.#e.enabledFor("debug")){let r=this.#e.enabledFor("trace"),n=e.response.statusCode;this.#e.debug(`${e.logPrefix}Completed ${n??"200 OK"}${r?`, headers: ${this.formatHeaders(e.response.headers)}`:""}"`)}}handleUnresolvedError(e,r){let{request:n,response:o,logPrefix:i}=e;if(o.setStatusCode(b.INTERNAL_SERVER_ERROR)){this.#e.error(`${i}500 Server Error for ${this.formatRequest(n)}`,r);return}if(!ko(r,this.#e))throw this.#e.error(`${i}Error [${r.message} for ${this.formatRequest(n)}, but already ended (${o.statusCode})`,r),r}async web(e){return await this.#t(e)}async http(e,r){let n=this.createExchange(e,r),o=()=>(this.logRequest(n),this.web(n).then(()=>{this.logResponse(n)}).catch(i=>{this.handleUnresolvedError(n,i)}).then(async()=>{await n.response.end()}));await new Promise((i,s)=>{this.#n!==void 0?this.#n.run({exchange:n},()=>{o().then(()=>i()).catch(a=>s(a))}):o().then(()=>i()).catch(a=>s(a))})}},it=class{#e;#r=[];#t=new qr.AsyncLocalStorage;#n;constructor(e){this.#e=e}middleware(e){return e(this.#r),this}storage(e){return this.#t=e,this}httpHandlerDecorator(e){if(this.#n===void 0)this.#n=e;else{let r=this.#n;this.#n=n=>(n=e(n),n=r(n),n)}return this}hasHttpHandlerDecorator(){return this.#n!==void 0}build(){let e=w("http"),r=new Lt(e,this.#e);this.#t!==void 0&&(r.storage=this.#t),r.enableLoggingRequestDetails=!1;let n=async(o,i)=>r.http(o,i);return this.#n?this.#n(n):n}};var Xr=require("ws");function zr(t,e){let r=t?.exchange,n=r?.request??new Z(t),o=r?.principal,i=o?o.bind(r):async function(){},s=n.URL,a=new E;for(let m of n.headers.keys())a.set(m,n.headers.list(m));let c=n.cookies,d=r?.logPrefix??`[${n.id}] `,u=n.remoteAddress;return{url:s,headers:a,cookies:c,principal:i,protocol:e,remoteAddress:u,logPrefix:d}}function jr(t){return[async(r,n)=>{let i=r.request.path??"/",s=t.sockets,a=s.get(i)??Array.from(s.values()).find(c=>{if(i==="/"&&c.default===!0)return!0});if(a!==void 0){let{request:c,response:d}=r,u=await V(r);if((c.method==="GET"||c.method==="CONNECT")&&u.match)if(a.upgradeStrategy!==void 0){a.upgradeStrategy(r);return}else throw new Error(`No upgrade strategy defined for route on ${i}`);else{if(a.default){await n();return}d.setStatusCode(b.UPGRADE_REQUIRED),d.headers.set("Upgrade","websocket").set("Connection","Upgrade").set("Content-Type","text/plain");let l=Buffer.from(`This service [${c.path}] requires use of the websocket protocol.`,"utf-8");await d.body(l)}}else await n()}]}var Vr=require("ws"),st=class extends Vr.WebSocket{constructor(e,r,n){super(null,void 0,n)}connected},at=class t{static#e=Buffer.alloc(0);static#r=[0,Buffer.alloc(8)];#t;#n;#i;#s=!1;#o;constructor(e,r,n){this.#o=e,this.#n=typeof n=="number"?n:n?.interval,this.#t=typeof n=="number"||n?.data==="timestamp"?()=>t.#d(Date.now()):()=>t.#e,this.#n&&(this.#i=setInterval(()=>{let[o,i]=r();for(let s of i)this.#a(s,o)||this.#c(s,o)},this.#n))}#a(e,r){return e.connected===!1?(this.#o.enabledFor("debug")&&this.#o.debug(`terminating unresponsive ws client on [${r}]`),e.terminate(),!0):!1}#c(e,r){e.connected=!1;let n=this.#t();this.#o.enabledFor("trace")&&this.#o.debug(`pinging ws client on [${r}]`),e.ping(n,this.#s,o=>{o&&this.#o.enabledFor("warn")&&this.#o.warn(`failed to ping ws client on [${r}]`,o)})}static#d(e=Date.now()){if(e-t.#r[0]>0){let r=Buffer.allocUnsafe(8);r.writeBigInt64BE(BigInt(e),0),t.#r=[e,r]}return t.#r[1]}static#u(e){return e.length===8?Number(e.readBigInt64BE(0)):0}close(){clearInterval(this.#i)}handlePing(e,r,n){r.connected=!0,r.pong(n,!1,o=>{o&&this.#o.enabledFor("warn")&&this.#o.warn(`${e.logPrefix}failed to pong ws client ${B(e.remoteAddress)}`,o)})}handlePong(e,r,n){if(r.connected=!0,this.#o.enabledFor("warn")){let o=t.#u(n);if(o>0){let i=Date.now()-o;this.#o.enabledFor("debug")&&this.#o.debug(`${e.logPrefix}ws client ${B(e.remoteAddress)} ping-pong latency: ${i}ms`),this.#n&&i>this.#n/2&&this.#o.enabledFor("warn")&&this.#o.warn(`${e.logPrefix}ws client ${B(e.remoteAddress)} high ping-pong latency: ${i}ms`)}}}};var L=w("ws");function Ro(t,e,r,n){return o=>{let{logPrefix:i,request:s}=o,a=Le.getNativeRequest(s);a.exchange=o;let{socket:c,upgradeHead:d}=a,u=s.host;if(c.removeListener("error",n),e.maxConnections!==void 0&&r.clients?.size>=e.maxConnections){L.warn(`${i}dropping ws connection request on ${u}${t}. max connections exceeded.`),c.destroy();return}let l=s.headers.one("origin");if(!cr(l,e.originFilters)){L.enabledFor("info")&&L.info(`${i}dropping ws connection request on ${u}${t}. origin ${l??"<missing>"}`),c.destroy();return}L.enabledFor("debug")&&L.debug(`${i}accepted new ws connection request on ${u}${t}`),r.handleUpgrade(a,c,d,(m,x)=>{r.emit("connection",m,x)})}}function To(t,e){let r=new Set;t.forEach((o,i)=>{if(i===0&&o.startsWith("HTTP/1.1 101 ")){e.setStatusCode(b.SWITCHING_PROTOCOLS);return}let[s,a]=o.split(": ");e.headers.has(s)?t[i]=`${s}: ${e.headers.one(s)}`:e.headers.set(s,a),r.add(s.toLowerCase())});let n=ee.getNativeResponse(e);for(let o of n.getRawHeaderNames()){let i=o.toLowerCase();if(!r.has(i)){let s=e.headers.get(i);s!==void 0&&t.push(`${o}: ${s}`)}}n.markHeadersSent()}async function Jr(t,e,r,n,o){try{L.info(`creating ws server for [${t}]. max connections: ${e.maxConnections??"<unlimited>"}, origin filters: ${e.originFilters?JSON.stringify(e.originFilters,jt):"<none>"}, ping: ${typeof e.ping=="number"?e.ping+"ms":e.ping?JSON.stringify(e.ping):"<none>"}`);let i=new Xr.WebSocketServer({noServer:!0,WebSocket:st,autoPong:!1}),s=new at(L.child("pings"),()=>[t,i.clients],e.ping),a=await e.factory({endpoint:r,storage:n});i.on("error",c=>{L.error(`error starting the ws server for [${t}]`,c)}).on("listening",()=>{L.info(`ws server for [${t}] is listening`)}).on("headers",(c,d)=>{if(d.exchange!==void 0){let{response:u}=d.exchange;To(c,u)}}).on("connection",(c,d)=>{let u=zr(d,c.protocol);c.on("pong",l=>{s.handlePong(u,c,l)}),c.on("ping",l=>{s.handlePing(u,c,l)}),a({socket:c,handshake:u})}),i.on("close",()=>{s.close()}),e.upgradeStrategy=Ro(t,e,i,o),e.close=async()=>{await a.close?.call(a),L.info(`stopping ws server for [${t}]. clients: ${i.clients?.size??0}`),i.clients?.forEach(c=>{c.terminate()}),i.close()}}catch(i){L.warn(`failed to init route ${t}`,i)}}var g=require("node:fs"),Ee=require("node:path"),dt=require("jsrsasign"),ct=require("@interopio/gateway-server/tools");var ue=w("ssl");function Kr(t,e){let r={};if(t.requestCert!==void 0&&(r.requestCert=t.requestCert),t.rejectUnauthorized!==void 0&&(r.rejectUnauthorized=t.rejectUnauthorized),t.key&&t.cert&&(0,g.existsSync)(t.key)&&(0,g.existsSync)(t.cert)){ue.info(`using SSL/TLS certificate ${t.cert} with private key in ${t.key}${t.passphrase?" (password-protected)":""}`);let p={key:(0,g.readFileSync)(t.key),cert:(0,g.readFileSync)(t.cert),...r};return t.passphrase&&(p.passphrase=t.passphrase),t.requestCert&&t.ca&&(0,g.existsSync)(t.ca)&&(p.ca=(0,g.readFileSync)(t.ca)),p}if(!t.key&&!t.cert){let p="./gateway-server.key",f="./gateway-server.crt";if((0,g.existsSync)(p)&&(0,g.existsSync)(f)){ue.info(`using SSL/TLS certificate ${f} with private key in ${p}${t.passphrase?" (password-protected)":""}`);let h={key:(0,g.readFileSync)(p),cert:(0,g.readFileSync)(f),...r};return t.passphrase&&(h.passphrase=t.passphrase),t.requestCert&&t.ca&&(0,g.existsSync)(t.ca)&&(h.ca=(0,g.readFileSync)(t.ca)),h}}if(!e)throw new Error("SSL/TLS enabled but no server certificate provided. Either provide ssl.key and ssl.cert, or configure auth.x509.key for auto-generation.");let n=e.key??"gateway-ca.key",o=t.ca??`${n.replace(/\.key$/,".crt")}`,i=e.passphrase??t.passphrase;if(!(0,g.existsSync)(n)){if((0,g.existsSync)(o))throw new Error(`CA key file not found: ${n} (CA certificate exists: ${o})`);let p=ct.mkcert.generateRootCA({name:ct.mkcert.DEFAULT_CA_NAME,passphrase:i}),f=(0,Ee.dirname)(n);f&&f!=="."&&!(0,g.existsSync)(f)&&(0,g.mkdirSync)(f,{recursive:!0});let h=(0,Ee.dirname)(o);h&&h!=="."&&h!==f&&!(0,g.existsSync)(h)&&(0,g.mkdirSync)(h,{recursive:!0}),(0,g.writeFileSync)(n,p.key,{mode:256}),(0,g.writeFileSync)(o,p.cert,{mode:420}),ue.info(`created new local Root CA in ${o}, ${n}${i?" (password-protected)":""}`)}let s=(0,g.readFileSync)(n,"utf8"),a=dt.KEYUTIL.getKey(s,i),c=(0,g.readFileSync)(o,"utf8"),d=new dt.X509;d.readCertPEM(c);let u=d.getSubjectString(),l=e.host;ue.debug(`generating server certificate signed by: ${u} for host: ${l}`);let m=ct.mkcert.generateCert(a,u,[l],!1);if(t.key||t.cert){let p=t.key||"./gateway-server.key",f=t.cert||"./gateway-server.crt",h=(0,Ee.dirname)(p);h&&h!=="."&&!(0,g.existsSync)(h)&&(0,g.mkdirSync)(h,{recursive:!0});let y=(0,Ee.dirname)(f);y&&y!=="."&&y!==h&&!(0,g.existsSync)(y)&&(0,g.mkdirSync)(y,{recursive:!0}),(0,g.writeFileSync)(p,m.key,{mode:384}),(0,g.writeFileSync)(f,m.cert,{mode:420}),ue.info(`generated server certificate saved to ${f} with private key in ${p}${i?" (password-protected)":""}`)}else ue.info(`using in-memory server certificate for host: ${l}`);let x={key:m.key,cert:m.cert,...r};return t.requestCert&&t.ca&&(0,g.existsSync)(o)&&(x.ca=(0,g.readFileSync)(o)),x}var $t=le(require("@interopio/gateway-server/package.json"),1);var Yr=require("node:path"),ut=require("node:fs/promises"),Qr=require("node:fs");async function Oo(t){if(t)for(let e of t){let r=(0,Yr.resolve)(e,"index.html");try{return await(0,ut.access)(r,Qr.constants.R_OK),r}catch{}}}async function Dt(t){let e=await Oo(t),r=ge({mediaTypes:["text/html"]});return async(n,o)=>{let{request:i,response:s}=n;if(i.method==="GET"&&i.path==="/")if(s.setStatusCode(b.OK),e!==void 0&&(await r(n)).match)s.headers.set("Content-Type","text/html; charset=utf-8"),await s.body((0,ut.readFile)(e));else{s.headers.set("Content-Type","text/plain; charset=utf-8");let a=Buffer.from("io.Gateway Server","utf-8");await s.body(a)}else await o()}}var U=w("app");async function Mo(t,e){let r=t.build();return async(n,o)=>{n.socket.addListener("error",e);let i;o instanceof Q?i=o:(n.upgradeHead=o,i=new Q(n),i.assignSocket(n.socket));let s=new Z(n),a=new Ie(i),c=s.method==="HEAD"?new ot(a):a;await r(s,c)}}function Io(t){return new Promise((e,r)=>{let n=t(o=>{o?r(o):e(n)})})}function Lo(t){if(t)return ir({memoryLimit:t.memory_limit,dumpLocation:t.dump_location,dumpPrefix:t.dump_prefix,reportInterval:t.report_interval,maxBackups:t.max_backups})}var rn=`${$t.default.name} - v${$t.default.version}`;async function Do(t){let e=t.storage,r=await _r(t),n=jr(t),o=Zt(ar(rn,t.serverHeader),...r,...n,...t.middleware,async({request:i,response:s},a)=>{if(i.method==="GET"&&i.path==="/health"){s.setStatusCode(b.OK);let c=Buffer.from("UP","utf-8");s.headers.set("Content-Type","text/plain; charset=utf-8"),await s.body(c)}else await a()},await Dt(t.resourcesConfig?.locations),async({response:i},s)=>{i.setStatusCode(b.NOT_FOUND),await i.end()});return new it(o).storage(e)}var Wt=async t=>{let e=t.ssl,r=t.host,n=t.auth?.x509?.key?{host:r??"localhost",key:t.auth.x509.key,passphrase:t.auth.x509.passphrase}:void 0,o=e?(p,f)=>en.default.createServer({...p,...Kr(e,n)},f):(p,f)=>Zr.default.createServer(p,f),i=Lo(t.memory),s={middleware:[],corsConfig:t.cors,cors:[],authConfig:t.auth,authorize:[],storage:new tn.AsyncLocalStorage,sockets:new Map,resourcesConfig:t.resources},a=new Ce({baseConfig:{...t.gateway},scope:t.gateway?.scope??"principal"});if(t.gateway){let p=t.gateway.route?t.gateway.route==="/"?void 0:t.gateway.route:void 0;await xt(async f=>{f.socket({path:p,factory:Jt.bind(a),options:t.gateway})},t,s)}t.app&&await xt(t.app,t,s);let c=_t(t.port??0),d=p=>U.error(`socket error: ${p}`,p),u=await Do(s),l=await Mo(u,d),x=await new Promise((p,f)=>{let h=o({IncomingMessage:Te,ServerResponse:Q,...t.http},l);h.on("error",y=>{if(y.code==="EADDRINUSE"){U.debug(`port ${y.port} already in use on address ${y.address}`);let{value:k}=c.next();k?(U.info(`retry starting server on port ${k} and host ${r??"<unspecified>"}`),h.close(),h.listen(k,r)):(U.warn(`all configured port(s) ${t.port} are in use. closing...`),h.close(),f(y))}else U.error(`server error: ${y.message}`,y),f(y)}),h.on("listening",async()=>{let y=h.address();for(let[k,R]of s.sockets){let K=`${e?"wss":"ws"}://${qt}:${y.port}${k}`;await Jr(k,R,K,s.storage,d)}U.info(`http server listening on ${e?"https":"http"}://${B(y)}`),p(h)}),h.on("upgrade",(y,k,R)=>{try{l(y,R)}catch(K){U.error(`upgrade error: ${K}`,K)}}).on("close",async()=>{U.info("http server closed.")});try{let{value:y}=c.next();h.listen(y,r)}catch(y){U.error("error starting web socket server",y),f(y instanceof Error?y:new Error(`listen failed: ${y}`))}});return new class{gateway=a;get address(){let p=x.address();return typeof p=="object"?p:null}async close(){for(let[p,f]of s.sockets)try{f.close!==void 0&&await f.close()}catch(h){U.warn(`error closing route ${p}`,h)}await Io(p=>{x.closeAllConnections(),x.close(p)}),i&&await sr(i),await a.stop()}}};var $o=Wt;0&&(module.exports={GatewayServer});
8
8
  //# sourceMappingURL=index.cjs.map