@openfin/cloud-interop-core-api 0.0.1-alpha.fffeb9a → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.mjs ADDED
@@ -0,0 +1,824 @@
1
+ import { Buffer } from 'buffer';
2
+ import 'fs';
3
+ import 'path';
4
+ import mqtt from 'mqtt';
5
+
6
+ var Y;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(Y="oauth4webapi/v3.8.8");function q(e,t){if(e==null)return false;try{return e instanceof t||Object.getPrototypeOf(e)[Symbol.toStringTag]===t.prototype[Symbol.toStringTag]}catch{return false}}var y$1="ERR_INVALID_ARG_VALUE",_="ERR_INVALID_ARG_TYPE";function l(e,t,n){let r=new TypeError(e,{cause:n});return Object.assign(r,{code:t}),r}var L=Symbol(),W=Symbol(),M=Symbol(),O=Symbol();var qe=new TextEncoder,We=new TextDecoder;function le(e){return typeof e=="string"?qe.encode(e):We.decode(e)}var Q;Uint8Array.prototype.toBase64?Q=e=>(e instanceof ArrayBuffer&&(e=new Uint8Array(e)),e.toBase64({alphabet:"base64url",omitPadding:true})):Q=t=>{t instanceof ArrayBuffer&&(t=new Uint8Array(t));let n=[];for(let r=0;r<t.byteLength;r+=32768)n.push(String.fromCharCode.apply(null,t.subarray(r,r+32768)));return btoa(n.join("")).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")};var X;Uint8Array.fromBase64?X=e=>{try{return Uint8Array.fromBase64(e,{alphabet:"base64url"})}catch(t){throw l("The input to be decoded is not correctly encoded.",y$1,t)}}:X=e=>{try{let t=atob(e.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"")),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n}catch(t){throw l("The input to be decoded is not correctly encoded.",y$1,t)}};function fe(e){return typeof e=="string"?X(e):Q(e)}var T=class extends Error{code;constructor(t,n){super(t,n),this.name=this.constructor.name,this.code=K,Error.captureStackTrace?.(this,this.constructor);}},D=class extends Error{code;constructor(t,n){super(t,n),this.name=this.constructor.name,n?.code&&(this.code=n?.code),Error.captureStackTrace?.(this,this.constructor);}};function i(e,t,n){return new D(e,{code:t,cause:n})}function H(e){return !(e===null||typeof e!="object"||Array.isArray(e))}function me(e){q(e,Headers)&&(e=Object.fromEntries(e.entries()));let t=new Headers(e??{});if(Y&&!t.has("user-agent")&&t.set("user-agent",Y),t.has("authorization"))throw l('"options.headers" must not include the "authorization" header name',y$1);return t}function ye(e,t){if(t!==void 0){if(typeof t=="function"&&(t=t(e.href)),!(t instanceof AbortSignal))throw l('"options.signal" must return or be an instance of AbortSignal',_);return t}}function _e(e){return e.includes("//")?e.replace("//","/"):e}function Me(e,t,n=false){return e.pathname==="/"?e.pathname=t:e.pathname=_e(`${t}/${n?e.pathname:e.pathname.replace(/(\/)$/,"")}`),e}function ze(e,t){return e.pathname=_e(`${e.pathname}/${t}`),e}async function Ke(e,t,n,r){if(!(e instanceof URL))throw l(`"${t}" must be an instance of URL`,_);z(e,r?.[L]!==true);let o=n(new URL(e.href)),s=me(r?.headers);return s.set("accept","application/json"),(r?.[O]||fetch)(o.href,{body:void 0,headers:Object.fromEntries(s.entries()),method:"GET",redirect:"manual",signal:ye(o,r?.signal)})}async function ge(e,t){return Ke(e,"issuerIdentifier",n=>{switch(t?.algorithm){case void 0:case "oidc":ze(n,".well-known/openid-configuration");break;case "oauth2":Me(n,".well-known/oauth-authorization-server");break;default:throw l('"options.algorithm" must be "oidc" (default), or "oauth2"',y$1)}return n},t)}function Z(e,t,n,r,o){try{if(typeof e!="number"||!Number.isFinite(e))throw l(`${n} must be a number`,_,o);if(e>0)return;if(t){if(e!==0)throw l(`${n} must be a non-negative number`,y$1,o);return}throw l(`${n} must be a positive number`,y$1,o)}catch(s){throw r?i(s.message,r,o):s}}function b(e,t,n,r){try{if(typeof e!="string")throw l(`${t} must be a string`,_,r);if(e.length===0)throw l(`${t} must not be empty`,y$1,r)}catch(o){throw n?i(o.message,n,r):o}}async function Re(e,t){let n=e;if(!(n instanceof URL)&&n!==J)throw l('"expectedIssuerIdentifier" must be an instance of URL',_);if(!q(t,Response))throw l('"response" must be an instance of Response',_);if(t.status!==200)throw i('"response" is not a conform Authorization Server Metadata response (unexpected HTTP status code)',$,t);oe(t);let r=await Ie(t);if(b(r.issuer,'"response" body "issuer" property',d,{body:r}),n!==J&&new URL(r.issuer).href!==n.href)throw i('"response" body "issuer" property does not match the expected value',F,{expected:n.href,body:r,attribute:"issuer"});return r}function be(e){Fe(e,"application/json");}function $e(e,...t){let n='"response" content-type must be ';if(t.length>2){let r=t.pop();n+=`${t.join(", ")}, or ${r}`;}else t.length===2?n+=`${t[0]} or ${t[1]}`:n+=t[0];return i(n,te,e)}function Fe(e,t){if(Ee(e)!==t)throw $e(e,t)}function Be(e){let t=e?.[W];return typeof t=="number"&&Number.isFinite(t)?t:0}function Ge(e){let t=e?.[M];return typeof t=="number"&&Number.isFinite(t)&&Math.sign(t)!==-1?t:30}function Ve(){return Math.floor(Date.now()/1e3)}function Se(e){if(typeof e!="object"||e===null)throw l('"as" must be an object',_);b(e.issuer,'"as.issuer"');}function Pe(e){if(typeof e!="object"||e===null)throw l('"client" must be an object',_);b(e.client_id,'"client.client_id"');}function ee(e){return b(e,'"clientSecret"'),(t,n,r,o)=>{r.set("client_id",n.client_id),r.set("client_secret",e);}}function Ae(){return (e,t,n,r)=>{n.set("client_id",t.client_id);}}var Ye=URL.parse?(e,t)=>URL.parse(e,t):(e,t)=>{try{return new URL(e,t)}catch{return null}};function z(e,t){if(t&&e.protocol!=="https:")throw i("only requests to HTTPS are allowed",ne,e);if(e.protocol!=="https:"&&e.protocol!=="http:")throw i("only HTTP and HTTPS requests are allowed",re,e)}function pe(e,t,n,r){let o;if(typeof e!="string"||!(o=Ye(e)))throw i(`authorization server metadata does not contain a valid ${n?`"as.mtls_endpoint_aliases.${t}"`:`"as.${t}"`}`,e===void 0?Tt:kt,{attribute:n?`mtls_endpoint_aliases.${t}`:t});return z(o,r),o}function Te(e,t,n,r){return n&&e.mtls_endpoint_aliases&&t in e.mtls_endpoint_aliases?pe(e.mtls_endpoint_aliases[t],t,n,r):pe(e[t],t,n,r)}var g=class extends Error{cause;code;error;status;error_description;response;constructor(t,n){super(t,n),this.name=this.constructor.name,this.code=Pt,this.cause=n.cause,this.error=n.cause.error,this.status=n.response.status,this.error_description=n.cause.error_description,Object.defineProperty(this,"response",{enumerable:false,value:n.response}),Error.captureStackTrace?.(this,this.constructor);}},I=class extends Error{cause;code;error;error_description;constructor(t,n){super(t,n),this.name=this.constructor.name,this.code=At,this.cause=n.cause,this.error=n.cause.get("error"),this.error_description=n.cause.get("error_description")??void 0,Error.captureStackTrace?.(this,this.constructor);}},k=class extends Error{cause;code;response;status;constructor(t,n){super(t,n),this.name=this.constructor.name,this.code=St,this.cause=n.cause,this.status=n.response.status,this.response=n.response,Object.defineProperty(this,"response",{enumerable:false}),Error.captureStackTrace?.(this,this.constructor);}},N="[a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+",Qe="[a-zA-Z0-9\\-\\._\\~\\+\\/]+={0,2}",Xe='"((?:[^"\\\\]|\\\\[\\s\\S])*)"',Ze="("+N+")\\s*=\\s*"+Xe,et="("+N+")\\s*=\\s*("+N+")",tt=new RegExp("^[,\\s]*("+N+")"),nt=new RegExp("^[,\\s]*"+Ze+"[,\\s]*(.*)"),rt=new RegExp("^[,\\s]*"+et+"[,\\s]*(.*)"),ot=new RegExp("^("+Qe+")(?:$|[,\\s])(.*)");function at(e){if(!q(e,Response))throw l('"response" must be an instance of Response',_);let t=e.headers.get("www-authenticate");if(t===null)return;let n=[],r=t;for(;r;){let o=r.match(tt),s=o?.[1].toLowerCase();if(!s)return;let a=r.substring(o[0].length);if(a&&!a.match(/^[\s,]/))return;let u=a.match(/^\s+(.*)$/),h=!!u;r=u?u[1]:void 0;let c={},p;if(h)for(;r;){let P,A;if(o=r.match(nt)){[,P,A,r]=o,A.includes("\\")&&(A=A.replace(/\\([\s\S])/g,"$1")),c[P.toLowerCase()]=A;continue}if(o=r.match(rt)){[,P,A,r]=o,c[P.toLowerCase()]=A;continue}if(o=r.match(ot)){if(Object.keys(c).length)break;[,p,r]=o;break}return}else r=a||void 0;let m={scheme:s,parameters:c};p&&(m.token68=p),n.push(m);}if(n.length)return n}async function st(e){if(e.status>399&&e.status<500){oe(e),be(e);try{let t=await e.clone().json();if(H(t)&&typeof t.error=="string"&&t.error.length)return t}catch{}}}async function it(e,t,n){if(e.status!==t){ft(e);let r;throw (r=await st(e))?(await e.body?.cancel(),new g("server responded with an error in the response body",{cause:r,response:e})):i(`"response" is not a conform ${n} response (unexpected HTTP status code)`,$,e)}}function Ee(e){return e.headers.get("content-type")?.split(";")[0]}async function ut(e,t,n,r,o,s,a){return await n(e,t,o,s),s.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"),(a?.[O]||fetch)(r.href,{body:o,headers:Object.fromEntries(s.entries()),method:"POST",redirect:"manual",signal:ye(r,a?.signal)})}async function dt(e,t,n,r,o,s){let a=Te(e,"token_endpoint",t.use_mtls_endpoint_aliases,s?.[L]!==true);o.set("grant_type",r);let u=me(s?.headers);u.set("accept","application/json");let h=await ut(e,t,n,a,o,u,s);return h}var xe=new WeakMap,ht=new WeakMap;function Oe(e){if(!e.id_token)return;let t=xe.get(e);if(!t)throw l('"ref" was already garbage collected or did not resolve from the proper sources',y$1);return t}async function lt(e,t,n,r,o,s){if(Se(e),Pe(t),!q(n,Response))throw l('"response" must be an instance of Response',_);await it(n,200,"Token Endpoint"),oe(n);let a=await Ie(n);if(b(a.access_token,'"response" body "access_token" property',d,{body:a}),b(a.token_type,'"response" body "token_type" property',d,{body:a}),a.token_type=a.token_type.toLowerCase(),a.expires_in!==void 0){let u=typeof a.expires_in!="number"?parseFloat(a.expires_in):a.expires_in;Z(u,true,'"response" body "expires_in" property',d,{body:a}),a.expires_in=u;}if(a.refresh_token!==void 0&&b(a.refresh_token,'"response" body "refresh_token" property',d,{body:a}),a.scope!==void 0&&typeof a.scope!="string")throw i('"response" body "scope" property must be a string',d,{body:a});if(a.id_token!==void 0){b(a.id_token,'"response" body "id_token" property',d,{body:a});let u=[];t.require_auth_time===true&&u.push("auth_time"),t.default_max_age!==void 0&&(Z(t.default_max_age,true,'"client.default_max_age"'),u.push("auth_time"));let{claims:h,jwt:c}=await gt(e,t,a.id_token,u);bt(t,h),Rt(h),ht.set(n,c),xe.set(a,h);}if(a.token_type!=="dpop"&&a.token_type!=="bearer")throw new T("unsupported `token_type` value",{cause:{body:a}});return a}function ft(e){let t;if(t=at(e))throw new k("server responded with a challenge in the WWW-Authenticate HTTP Header",{cause:t,response:e})}function pt(e,t){if(Array.isArray(t.claims.aud)){if(!t.claims.aud.includes(e))throw i('unexpected JWT "aud" (audience) claim value',E,{expected:e,claims:t.claims,claim:"aud"})}else if(t.claims.aud!==e)throw i('unexpected JWT "aud" (audience) claim value',E,{expected:e,claims:t.claims,claim:"aud"});return t}function wt(e,t){let n=e[ae]?.(t)??e.issuer;if(t.claims.iss!==n)throw i('unexpected JWT "iss" (issuer) claim value',E,{expected:n,claims:t.claims,claim:"iss"});return t}var Ce={aud:"audience",c_hash:"code hash",client_id:"client id",exp:"expiration time",iat:"issued at",iss:"issuer",jti:"jwt id",nonce:"nonce",s_hash:"state hash",sub:"subject",ath:"access token hash",htm:"http method",htu:"http uri",cnf:"confirmation",auth_time:"authentication time"};function yt(e,t){for(let n of e)if(t.claims[n]===void 0)throw i(`JWT "${n}" (${Ce[n]}) claim missing`,d,{claims:t.claims});return t}function _t(e,t){if(typeof t.claims[e]!="string")throw i(`unexpected JWT "${e}" (${Ce[e]}) claim type`,d,{claims:t.claims});return t}function gt(e,t,n,r,o){return Et(n,xt.bind(void 0,t.id_token_signed_response_alg,e.id_token_signing_alg_values_supported,"RS256"),Be(t),Ge(t)).then(yt.bind(void 0,["aud","exp","iat","iss","sub",...r])).then(wt.bind(void 0,e)).then(pt.bind(void 0,t.client_id)).then(_t.bind(void 0,"sub"))}function Rt(e){e.auth_time!==void 0&&Z(e.auth_time,true,'ID Token "auth_time" (authentication time)',d,{claims:e});}function bt(e,t){if(Array.isArray(t.aud)&&t.aud.length!==1){if(t.azp===void 0)throw i('ID Token "aud" (audience) claim includes additional untrusted audiences',E,{claims:t,claim:"aud"});if(t.azp!==e.client_id)throw i('unexpected ID Token "azp" (authorized party) claim value',E,{expected:e.client_id,claims:t,claim:"azp"})}}var St="OAUTH_WWW_AUTHENTICATE_CHALLENGE",Pt="OAUTH_RESPONSE_BODY_ERROR",K="OAUTH_UNSUPPORTED_OPERATION",At="OAUTH_AUTHORIZATION_RESPONSE_ERROR";var U="OAUTH_PARSE_ERROR",d="OAUTH_INVALID_RESPONSE";var te="OAUTH_RESPONSE_IS_NOT_JSON",$="OAUTH_RESPONSE_IS_NOT_CONFORM",ne="OAUTH_HTTP_REQUEST_FORBIDDEN",re="OAUTH_REQUEST_PROTOCOL_FORBIDDEN",j="OAUTH_JWT_TIMESTAMP_CHECK_FAILED",E="OAUTH_JWT_CLAIM_COMPARISON_FAILED",F="OAUTH_JSON_ATTRIBUTE_COMPARISON_FAILED";var Tt="OAUTH_MISSING_SERVER_METADATA",kt="OAUTH_INVALID_SERVER_METADATA";async function ve(e,t,n,r,o){return Se(e),Pe(t),dt(e,t,n,"client_credentials",new URLSearchParams(r),o)}async function De(e,t,n,r){return lt(e,t,n)}function oe(e){if(e.bodyUsed)throw l('"response" body has been used already',y$1)}async function Et(e,t,n,r,o){let{0:s,1:a,length:u}=e.split(".");if(u===5)throw new T("JWE decryption is not configured",{cause:e});if(u!==3)throw i("Invalid JWT",d,e);let h;try{h=JSON.parse(le(fe(s)));}catch(m){throw i("failed to parse JWT Header body as base64url encoded JSON",U,m)}if(!H(h))throw i("JWT Header must be a top level object",d,e);if(t(h),h.crit!==void 0)throw new T('no JWT "crit" header parameter extensions are supported',{cause:{header:h}});let c;try{c=JSON.parse(le(fe(a)));}catch(m){throw i("failed to parse JWT Payload body as base64url encoded JSON",U,m)}if(!H(c))throw i("JWT Payload must be a top level object",d,e);let p=Ve()+n;if(c.exp!==void 0){if(typeof c.exp!="number")throw i('unexpected JWT "exp" (expiration time) claim type',d,{claims:c});if(c.exp<=p-r)throw i('unexpected JWT "exp" (expiration time) claim value, expiration is past current timestamp',j,{claims:c,now:p,tolerance:r,claim:"exp"})}if(c.iat!==void 0&&typeof c.iat!="number")throw i('unexpected JWT "iat" (issued at) claim type',d,{claims:c});if(c.iss!==void 0&&typeof c.iss!="string")throw i('unexpected JWT "iss" (issuer) claim type',d,{claims:c});if(c.nbf!==void 0){if(typeof c.nbf!="number")throw i('unexpected JWT "nbf" (not before) claim type',d,{claims:c});if(c.nbf>p+r)throw i('unexpected JWT "nbf" (not before) claim value',j,{claims:c,now:p,tolerance:r,claim:"nbf"})}if(c.aud!==void 0&&typeof c.aud!="string"&&!Array.isArray(c.aud))throw i('unexpected JWT "aud" (audience) claim type',d,{claims:c});return {header:h,claims:c,jwt:e}}function xt(e,t,n,r){if(e!==void 0){if(typeof e=="string"?r.alg!==e:!e.includes(r.alg))throw i('unexpected JWT "alg" header parameter',d,{header:r,expected:e,reason:"client configuration"});return}if(Array.isArray(t)){if(!t.includes(r.alg))throw i('unexpected JWT "alg" header parameter',d,{header:r,expected:t,reason:"authorization server metadata"});return}if(n!==void 0){if(typeof n=="string"?r.alg!==n:typeof n=="function"?!n(r.alg):!n.includes(r.alg))throw i('unexpected JWT "alg" header parameter',d,{header:r,expected:n,reason:"default value"});return}throw i('missing client or server configuration to verify used JWT "alg" header parameter',void 0,{client:e,issuer:t,fallback:n})}async function Ie(e,t=be){let n;try{n=await e.json();}catch(r){throw t(e),i('failed to parse "response" body as JSON',U,r)}if(!H(n))throw i('"response" body must be a top level object',d,{body:n});return n}var J=Symbol(),ae=Symbol();var B,Ue;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(Ue="openid-client/v6.8.8",B={"user-agent":Ue});var R=e=>se.get(e),se;function ce(e){if(e!==void 0)return ee(e);let t=new WeakMap;return (n,r,o,s)=>{let a;return (a=t.get(r))||(Ct(r.client_secret,'"metadata.client_secret"'),a=ee(r.client_secret),t.set(r,a)),a(n,r,o,s)}}function Ct(e,t){if(typeof e!="string")throw x(`${t} must be a string`,V);if(e.length===0)throw x(`${t} must not be empty`,ue)}function vt(){return Ae()}var S=O;var ue="ERR_INVALID_ARG_VALUE",V="ERR_INVALID_ARG_TYPE";function x(e,t,n){let r=new TypeError(e,{cause:n});return Object.assign(r,{code:t}),r}var C=class extends Error{code;constructor(t,n){super(t,n),this.name=this.constructor.name,this.code=n?.code,Error.captureStackTrace?.(this,this.constructor);}};new TextDecoder;function f(e,t,n){return new C(e,{cause:t,code:n})}function ie(e){if(e instanceof TypeError||e instanceof C||e instanceof g||e instanceof I||e instanceof k)throw e;if(e instanceof D)switch(e.code){case ne:throw f("only requests to HTTPS are allowed",e,e.code);case re:throw f("only requests to HTTP or HTTPS are allowed",e,e.code);case $:throw f("unexpected HTTP response status code",e.cause,e.code);case te:throw f("unexpected response content-type",e.cause,e.code);case U:throw f("parsing error occured",e,e.code);case d:throw f("invalid response encountered",e,e.code);case E:throw f("unexpected JWT claim value encountered",e,e.code);case F:throw f("unexpected JSON attribute value encountered",e,e.code);case j:throw f("JWT timestamp claim value failed validation",e,e.code);default:throw f(e.message,e,e.code)}if(e instanceof T)throw f("unsupported operation",e,e.code);if(e instanceof DOMException)switch(e.name){case "OperationError":throw f("runtime operation error",e,K);case "NotSupportedError":throw f("runtime unsupported operation",e,K);case "TimeoutError":throw f("operation timed out",e,"OAUTH_TIMEOUT");case "AbortError":throw f("operation aborted",e,"OAUTH_ABORT")}throw new C("something went wrong",{cause:e})}function Dt(e,t,n){return e.origin==="https://login.microsoftonline.com"&&(!n?.algorithm||n.algorithm==="oidc")?(t[He]=true,true):false}function It(e,t){return !!(e.hostname.endsWith(".b2clogin.com")&&(!t?.algorithm||t.algorithm==="oidc"))}async function Le(e,t,n,r,o){let s=await Ut(e,o),a=new v(s,t,n,r),u=R(a);if(o?.[S]&&(u.fetch=o[S]),o?.timeout!==void 0&&(u.timeout=o.timeout),o?.execute)for(let h of o.execute)h(a);return a}async function Ut(e,t){if(!(e instanceof URL))throw x('"server" must be an instance of URL',V);let n=!e.href.includes("/.well-known/"),r=t?.timeout??30,o=AbortSignal.timeout(r*1e3),s=await(n?ge(e,{algorithm:t?.algorithm,[O]:t?.[S],[L]:t?.execute?.includes(G),signal:o,headers:new Headers(B)}):(t?.[S]||fetch)((z(e,!t?.execute?.includes(G)),e.href),{headers:Object.fromEntries(new Headers({accept:"application/json",...B}).entries()),body:void 0,method:"GET",redirect:"manual",signal:o})).then(a=>Re(J,a)).catch(ie);return n&&new URL(s.issuer).href!==e.href&&(Dt(e,s,t)||It(e,t)||(()=>{throw new C("discovered metadata issuer does not match the expected issuer",{code:F,cause:{expected:e.href,body:s,attribute:"issuer"}})})()),s}function Lt(e){return {supportsPKCE:{__proto__:null,value(t="S256"){return e.code_challenge_methods_supported?.includes(t)===true}}}}function Ht(e){Object.defineProperties(e,Lt(e));}var He=Symbol(),v=class{constructor(t,n,r,o){if(typeof n!="string"||!n.length)throw x('"clientId" must be a non-empty string',V);if(typeof r=="string"&&(r={client_secret:r}),r?.client_id!==void 0&&n!==r.client_id)throw x('"clientId" and "metadata.client_id" must be the same',ue);let s={...structuredClone(r),client_id:n};s[W]=r?.[W]??0,s[M]=r?.[M]??30;let a;o?a=o:typeof s.client_secret=="string"&&s.client_secret.length?a=ce(s.client_secret):a=vt();let u=Object.freeze(s),h=structuredClone(t);He in t&&(h[ae]=({claims:{tid:p}})=>t.issuer.replace("{tenantid}",p));let c=Object.freeze(h);se||=new WeakMap,se.set(this,{__proto__:null,as:c,c:u,auth:a,tlsOnly:true,timeout:30,jwksCache:{}});}serverMetadata(){let t=structuredClone(R(this).as);return Ht(t),t}clientMetadata(){return structuredClone(R(this).c)}get timeout(){return R(this).timeout}set timeout(t){R(this).timeout=t;}get[S](){return R(this).fetch}set[S](t){R(this).fetch=t;}};Object.freeze(v.prototype);function Nt(e){let t;return e.expires_in!==void 0&&(t=Date.now()+e.expires_in*1e3),{expiresIn:{__proto__:null,value(){if(t){let n=Date.now();return t>n?Math.floor((t-n)/1e3):0}}},claims:{__proto__:null,value(){return Oe(e)}}}}function jt(e){Object.defineProperties(e,Nt(e));}function G(e){R(e).tlsOnly=false;}async function de(e,t,n){Jt(e),t=new URLSearchParams(t);let{as:r,c:o,auth:s,fetch:a,tlsOnly:u,timeout:h}=R(e),c=await ve(r,o,s,t,{[O]:a,[L]:!u,DPoP:n?.DPoP,headers:new Headers(B),signal:qt(h)}).catch(ie),p=De(r,o,c),m;try{m=await p;}catch(P){ie(P);}return jt(m),m}function Jt(e){if(!(e instanceof v))throw x('"config" must be an instance of Configuration',V);if(Object.getPrototypeOf(e)!==v.prototype)throw x("subclassing Configuration is not allowed",ue)}function qt(e){return e?AbortSignal.timeout(e*1e3):void 0}var w=class extends Error{code;constructor(t,n){super(t,{cause:n}),this.name="OAuthClientCredentialsError",this.code="ERR_OAUTH";}};var zt=6e4,Kt=new Set(["localhost","127.0.0.1"]),je=e=>e.protocol==="http:"&&Kt.has(e.hostname),$t=e=>typeof e=="number"&&Number.isFinite(e)&&e>0,Ft=e=>{try{return new URL(e)}catch{return}},he=e=>e?`OAuth token request failed: ${e}`:"OAuth token request failed",Je=class e{#e;constructor(t,n,r,o){if(t.protocol!=="https:"&&!je(t))throw new w("OAuth client credentials require an https service URL; http is only allowed for localhost and 127.0.0.1");this.#e={issuer:t,clientId:n,clientSecret:r,fetchImpl:o?.fetch,clock:o?.clock??(()=>Date.now()),cachedToken:void 0,configuration:void 0,flight:void 0,generation:0};}static fromServiceUrl(t,n,r){let o=Ft(t);if(!o||o.protocol!=="http:"&&o.protocol!=="https:")throw new w("OAuth client credentials require an absolute service URL");return new e(new URL(o.origin),n,r)}async getAccessToken(){let{cachedToken:t,clock:n}=this.#e;if(t!==void 0&&t.expiresAt-n()>zt)return t.accessToken;if(this.#e.flight)return this.#e.flight;let r=this.#e.generation,o=this.#t(r).finally(()=>{this.#e.flight===o&&(this.#e.flight=void 0);});return this.#e.flight=o,o}invalidate(){this.#e.cachedToken=void 0,this.#e.generation+=1,this.#e.flight=void 0;}async#t(t){let n=await this.#n(),r;try{r=await de(n);}catch(s){throw s instanceof TypeError||s instanceof w?s:s instanceof g?new w(he(s.error),s):new w(he(),s)}let o=r.access_token;if(typeof o!="string"||o.length===0)throw new w(he());if(this.#e.generation===t){let s=r.expires_in;this.#e.cachedToken=$t(s)?{accessToken:o,expiresAt:this.#e.clock()+s*1e3}:void 0;}return o}async#n(){if(this.#e.configuration)return this.#e.configuration;let t=this.#e.fetchImpl??globalThis.fetch;try{let n=await Le(this.#e.issuer,this.#e.clientId,this.#e.clientSecret,ce(this.#e.clientSecret),{algorithm:"oauth2",[S]:t,...je(this.#e.issuer)?{execute:[G]}:{}});return this.#e.configuration=n,n}catch(n){throw n instanceof TypeError?n:new w("OAuth authorization server discovery failed",n)}}},$n=({grantType:e,clientSecret:t})=>{if(e!=="client_credentials")throw new w("Only the client_credentials grant is supported");if(globalThis.window!==void 0&&t.length>0)throw new w("Client credentials authentication is not supported in the browser")},Fn=async(e,t)=>{let n=await t();return n.status!==401?n:(await n.body?.cancel().catch(()=>{}),e.invalidate(),t())};
7
+
8
+ var y=e=>{let n=e.replaceAll("-","+").replaceAll("_","/");return n.padEnd(n.length+(4-n.length%4)%4,"=")};
9
+
10
+ class CloudInteropAPIError extends Error {
11
+ code;
12
+ constructor(message = 'An unexpected error has occurred', code = 'UNEXPECTED_ERROR', cause) {
13
+ super(message, { cause: cause });
14
+ this.name = this.constructor.name;
15
+ this.code = code;
16
+ }
17
+ }
18
+ class AuthorizationError extends CloudInteropAPIError {
19
+ constructor(message = 'Not authorized', code = 'ERR_UNAUTHORIZED') {
20
+ super(message, code, undefined);
21
+ }
22
+ }
23
+ class OAuthAuthenticationError extends CloudInteropAPIError {
24
+ constructor(message, cause) {
25
+ super(message, 'ERR_OAUTH', cause);
26
+ }
27
+ }
28
+
29
+ const rethrowAsOAuthAuthenticationError = (error) => {
30
+ if (error instanceof w) {
31
+ throw new OAuthAuthenticationError(error.message, error);
32
+ }
33
+ if (error instanceof TypeError) {
34
+ throw new OAuthAuthenticationError('OAuth access token could not be obtained', error);
35
+ }
36
+ throw error;
37
+ };
38
+
39
+ class EventController {
40
+ #eventListeners = new Map();
41
+ addEventListener(type, callback) {
42
+ const listeners = this.#eventListeners.get(type) || [];
43
+ listeners.push(callback);
44
+ this.#eventListeners.set(type, listeners);
45
+ }
46
+ removeEventListener(type, callback) {
47
+ const listeners = this.#eventListeners.get(type) || [];
48
+ const index = listeners.indexOf(callback);
49
+ if (index !== -1) {
50
+ listeners.splice(index, 1);
51
+ }
52
+ this.#eventListeners.set(type, listeners);
53
+ }
54
+ once(type, callback) {
55
+ const listener = (...args) => {
56
+ this.removeEventListener(type, listener);
57
+ // @ts-expect-error - TS doesn't like the spread operator here
58
+ callback(...args);
59
+ };
60
+ this.addEventListener(type, listener);
61
+ }
62
+ emitEvent(type, ...args) {
63
+ const listeners = this.#eventListeners.get(type) || [];
64
+ listeners.forEach((listener) => listener(...args));
65
+ }
66
+ }
67
+
68
+ const isErrorIntentResult = (result) => 'error' in result;
69
+
70
+ const APP_ID_DELIM = '::';
71
+ const getRequestHeaders = async (connectionParameters, tokenClient) => {
72
+ const headers = {};
73
+ headers['Content-Type'] = 'application/json';
74
+ if (connectionParameters.authenticationType === 'oauth' && tokenClient) {
75
+ try {
76
+ const accessToken = await tokenClient.getAccessToken();
77
+ headers['Authorization'] = `Bearer ${accessToken}`;
78
+ }
79
+ catch (error) {
80
+ rethrowAsOAuthAuthenticationError(error);
81
+ }
82
+ }
83
+ if (connectionParameters.authenticationType === 'jwt' && connectionParameters.jwtAuthenticationParameters) {
84
+ const tokenResult = await connectionParameters.jwtAuthenticationParameters.jwtRequestCallback();
85
+ if (!tokenResult) {
86
+ throw new Error('jwtRequestCallback must return a token');
87
+ }
88
+ headers['x-of-auth-id'] = connectionParameters.jwtAuthenticationParameters.authenticationId;
89
+ headers['Authorization'] =
90
+ typeof tokenResult === 'string' ? `Bearer ${tokenResult}` : `Bearer ${Buffer.from(JSON.stringify(tokenResult)).toString('base64')}`;
91
+ }
92
+ if (connectionParameters.authenticationType === 'basic' && connectionParameters.basicAuthenticationParameters) {
93
+ const { username, password } = connectionParameters.basicAuthenticationParameters;
94
+ headers['Authorization'] = `Basic ${Buffer.from(`${username}:${password}`).toString('base64')}`;
95
+ }
96
+ return headers;
97
+ };
98
+ /**
99
+ * Encodes all app intents in the format: `appId::sourceId::sessionId`,
100
+ * where sourceId and sessionId are URI encoded
101
+ * @param appIntents
102
+ * @param source
103
+ * @returns
104
+ */
105
+ const encodeAppIntents = (appIntents, source) => appIntents.map((intent) => ({
106
+ ...intent,
107
+ apps: intent.apps.map((app) => ({ ...app, appId: encodeAppId(app.appId, source) })),
108
+ }));
109
+ /**
110
+ * Decodes all app intents by URI decoding the parts previously encoded by `encodeAppIntents`
111
+ * @param appIntents
112
+ * @returns
113
+ */
114
+ const decodeAppIntents = (appIntents) => appIntents.map((intent) => ({
115
+ ...intent,
116
+ apps: intent.apps.map((app) => ({ ...app, appId: decodeAppId(app.appId) })),
117
+ }));
118
+ const encodeAppId = (appIdString, { sessionId, sourceId }) => {
119
+ const id = encodeURIComponent(appIdString);
120
+ const sId = encodeURIComponent(sourceId);
121
+ return `${id}${APP_ID_DELIM}${sId}${APP_ID_DELIM}${sessionId}`;
122
+ };
123
+ const decodeAppId = (appId) => {
124
+ const [encodedAppId, encodedSourceId, sessionId] = appId.split(APP_ID_DELIM);
125
+ const id = decodeURIComponent(encodedAppId);
126
+ const sourceId = decodeURIComponent(encodedSourceId);
127
+ return `${id}${APP_ID_DELIM}${sourceId}${APP_ID_DELIM}${sessionId}`;
128
+ };
129
+ /**
130
+ * Decodes the AppIdentifier to extract the appId, sourceId, and sessionId.
131
+ * @returns an object with:
132
+ * - appId: The appId, or the original appId if unable to parse.
133
+ * - sourceId: The sourceId, or an '' if unable to parse.
134
+ * - sessionId: The sessionId, or an '' if unable to parse.
135
+ */
136
+ const parseCloudAppId = (appId = '') => {
137
+ const originalAppString = typeof appId === 'string' ? appId : (appId.appId ?? '');
138
+ const parts = originalAppString.split(APP_ID_DELIM);
139
+ return {
140
+ appId: parts[0]?.trim() ?? originalAppString,
141
+ sourceId: parts[1]?.trim() ?? '',
142
+ sessionId: parts[2]?.trim() ?? '',
143
+ };
144
+ };
145
+ const getSourceFromSession = (sessionDetails) => ({
146
+ sessionId: sessionDetails.sessionId,
147
+ sourceId: sessionDetails.sourceId,
148
+ userId: sessionDetails.sub,
149
+ orgId: sessionDetails.orgId,
150
+ platformId: sessionDetails.platformId,
151
+ });
152
+
153
+ const MIN_TIMEOUT = 500;
154
+ const DEFAULT_TIMEOUT = 3000;
155
+ const newDiscovery = () => ({
156
+ id: undefined,
157
+ pendingIntentDetailsEvents: [],
158
+ sessionCount: 0,
159
+ responseCount: 0,
160
+ state: 'not-started',
161
+ });
162
+ class IntentController {
163
+ #url;
164
+ #mqttClient;
165
+ #sessionDetails;
166
+ #authenticatedFetch;
167
+ #events;
168
+ #logger;
169
+ #discovery = newDiscovery();
170
+ #discoveryTimeout;
171
+ constructor(url, mqttClient, sessionDetails, authenticatedFetch, events, logger) {
172
+ this.#url = url;
173
+ this.#mqttClient = mqttClient;
174
+ this.#sessionDetails = sessionDetails;
175
+ this.#authenticatedFetch = authenticatedFetch;
176
+ this.#events = events;
177
+ this.#logger = logger;
178
+ }
179
+ async startIntentDiscovery(options) {
180
+ if (this.#discovery.state === 'in-progress') {
181
+ throw new Error('Intent discovery already in progress');
182
+ }
183
+ const { timeout = DEFAULT_TIMEOUT, findOptions } = options;
184
+ // clamp min value to 500ms
185
+ const clampedTimeout = Math.max(timeout, MIN_TIMEOUT);
186
+ try {
187
+ const startResponse = await this.#authenticatedFetch(`${this.#url}/api/intents/${this.#sessionDetails.sessionId}`, {
188
+ method: 'POST',
189
+ body: JSON.stringify({ findOptions }),
190
+ });
191
+ if (!startResponse.ok) {
192
+ throw new Error(`Error creating intent discovery record: ${startResponse.statusText}`);
193
+ }
194
+ // TODO: type this response?
195
+ const json = await startResponse.json();
196
+ this.#discovery.id = json.discoveryId;
197
+ this.#discovery.sessionCount = json.sessionCount;
198
+ this.#discovery.state = 'in-progress';
199
+ if (this.#discovery.sessionCount === 1) {
200
+ // since we have no other connected sessions, we can end discovery immediately
201
+ await this.#endIntentDiscovery(false);
202
+ return;
203
+ }
204
+ // Listen out for discovery results directly sent to us
205
+ await this.#mqttClient.subscribeAsync(`${this.#sessionDetails.sessionRootTopic}/commands/${this.#discovery.id}`);
206
+ this.#discoveryTimeout = setTimeout(() => this.#endIntentDiscovery(), clampedTimeout);
207
+ }
208
+ catch (error) {
209
+ // Clean up any ongoing discoveries
210
+ this.#endIntentDiscovery();
211
+ throw new CloudInteropAPIError('Error starting intent discovery', 'ERR_STARTING_INTENT_DISCOVERY', error);
212
+ }
213
+ }
214
+ async #endIntentDiscovery(mqttUnsubscribe = true) {
215
+ if (this.#discovery.state !== 'in-progress') {
216
+ return;
217
+ }
218
+ if (this.#discoveryTimeout) {
219
+ clearTimeout(this.#discoveryTimeout);
220
+ this.#discoveryTimeout = undefined;
221
+ }
222
+ this.#discovery.state = 'ended';
223
+ // emit our aggregated events
224
+ this.#events.emitEvent('aggregate-intent-details', { responses: this.#discovery.pendingIntentDetailsEvents });
225
+ if (mqttUnsubscribe) {
226
+ // gracefully end discovery
227
+ await this.#mqttClient.unsubscribeAsync(`${this.#sessionDetails.sessionRootTopic}/commands/${this.#discovery.id}`).catch(() => {
228
+ this.#logger('warn', `Error ending intent discovery: could not unsubscribe from discovery id ${this.#discovery.id}`);
229
+ });
230
+ }
231
+ await this.#authenticatedFetch(`${this.#url}/api/intents/${this.#sessionDetails.sessionId}/${this.#discovery.id}`, {
232
+ method: 'DELETE',
233
+ })
234
+ .then((deleteResponse) => {
235
+ if (!deleteResponse.ok) {
236
+ throw new Error(`Error ending intent discovery: ${deleteResponse.statusText}`);
237
+ }
238
+ })
239
+ .catch((error) => {
240
+ this.#logger('warn', `Error ending intent discovery: ${error}`);
241
+ });
242
+ // clean up
243
+ this.#discovery = newDiscovery();
244
+ }
245
+ async raiseIntent({ raiseOptions, appId }) {
246
+ const targetSessionId = parseCloudAppId(appId).sessionId;
247
+ if (!targetSessionId) {
248
+ // TODO: should we add more info here about the format?
249
+ throw new CloudInteropAPIError(`Invalid AppId specified, must be encoded as a cloud-session app id`, 'ERR_INVALID_TARGET_SESSION_ID');
250
+ }
251
+ const postResponse = await this.#authenticatedFetch(`${this.#url}/api/intents/${this.#sessionDetails.sessionId}/sessions/${targetSessionId}`, {
252
+ method: 'POST',
253
+ body: JSON.stringify({ raiseOptions }),
254
+ });
255
+ if (!postResponse.ok) {
256
+ // TODO: maybe add a debug flag to print these when dev'ing?
257
+ // console.log(`Error raising intent: ${await postResponse.text()}`);
258
+ throw new CloudInteropAPIError(`Error raising intent`, 'ERR_RAISING_INTENT', new Error(postResponse.statusText));
259
+ }
260
+ }
261
+ async reportAppIntents(discoveryId, intents) {
262
+ intents = encodeAppIntents(intents, getSourceFromSession(this.#sessionDetails));
263
+ try {
264
+ const reportResponse = await this.#authenticatedFetch(`${this.#url}/api/intents/${this.#sessionDetails.sessionId}/${discoveryId}`, {
265
+ method: 'POST',
266
+ body: JSON.stringify({ intents }),
267
+ });
268
+ if (reportResponse.ok) {
269
+ return true;
270
+ }
271
+ throw new CloudInteropAPIError('Error reporting intents', 'ERR_REPORTING_INTENTS', new Error(reportResponse.statusText));
272
+ }
273
+ catch (error) {
274
+ this.#logger('warn', `Error reporting intents for discovery ID ${discoveryId}: ${error}`);
275
+ }
276
+ return false;
277
+ }
278
+ async sendIntentResult(initiatingSessionId, result) {
279
+ if (!isErrorIntentResult(result)) {
280
+ // cloud-encode the source app id to support chained intent actions over cloud
281
+ // https://fdc3.finos.org/docs/2.0/api/spec#resolution-object -> "Use metadata about the resolving app instance to target a further intent"
282
+ const source = getSourceFromSession(this.#sessionDetails);
283
+ const encoded = encodeAppId(typeof result.source === 'string' ? result.source : result.source.appId, source);
284
+ result.source = typeof result.source === 'string' ? encoded : { ...result.source, appId: encoded };
285
+ }
286
+ const { sessionId } = getSourceFromSession(this.#sessionDetails);
287
+ const resultResponse = await this.#authenticatedFetch(`${this.#url}/api/intents/${initiatingSessionId}/result/${sessionId}`, {
288
+ method: 'POST',
289
+ body: JSON.stringify({ result }),
290
+ });
291
+ if (!resultResponse.ok) {
292
+ throw new CloudInteropAPIError('Error sending intent result', 'ERR_SENDING_INTENT_RESULT', new Error(resultResponse.statusText));
293
+ }
294
+ }
295
+ handleCommandMessage(message) {
296
+ switch (message.command) {
297
+ case 'report-intents': {
298
+ if (message.initiatingSessionId === this.#sessionDetails?.sessionId) {
299
+ // Ignore if this originated from us
300
+ return;
301
+ }
302
+ const { command: _, ...event } = message;
303
+ this.#events.emitEvent('report-intents', event);
304
+ break;
305
+ }
306
+ case 'intent-details': {
307
+ /**
308
+ * We aggregate intent details commands from all connected sessions on the server side
309
+ * to ensure upstream clients don't have to do this. Also given @openfin/cloud-interop
310
+ * exposes FDC3 compliant APIs, there is no concept of streaming available, hence we
311
+ * aggregate the responses here and send them in a synchronous manner.
312
+ */
313
+ const { command: _, ...event } = message;
314
+ // Decode intents before emitting to client
315
+ event.intents = decodeAppIntents(event.intents);
316
+ // always emit individual intent-details events in addition to aggregate-intent-details
317
+ // for flexibility after intent discovery has ended, this can be useful for late-joining
318
+ // clients nearing the timeout
319
+ this.#events.emitEvent('intent-details', event);
320
+ if (message.discoveryId !== this.#discovery.id || this.#discovery.state !== 'in-progress') {
321
+ // Ignore if its any other discovery id for some reason, or
322
+ // if we're not in the middle of a discovery
323
+ return;
324
+ }
325
+ this.#discovery.responseCount += 1;
326
+ this.#logger('debug', `Received intent details from ${message.source.sessionId}, received: ${this.#discovery.responseCount}, out of connected sessions: ${this.#discovery.sessionCount - 1}`);
327
+ this.#discovery.pendingIntentDetailsEvents.push(event);
328
+ const allResponded = this.#discovery.responseCount === this.#discovery.sessionCount - 1;
329
+ if (allResponded) {
330
+ this.#endIntentDiscovery();
331
+ }
332
+ break;
333
+ }
334
+ case 'raise-intent': {
335
+ if (message.targetSessionId === this.#sessionDetails?.sessionId) {
336
+ const { command: _, ...event } = message;
337
+ this.#events.emitEvent('raise-intent', event);
338
+ }
339
+ break;
340
+ }
341
+ case 'intent-result': {
342
+ if (message.initiatingSessionId === this.#sessionDetails?.sessionId) {
343
+ // Return result to originator and end discovery
344
+ const { command: _, ...resultEvent } = message;
345
+ this.#events.emitEvent('intent-result', resultEvent);
346
+ }
347
+ break;
348
+ }
349
+ default: {
350
+ this.#logger('warn', `Unknown command message received:\n${JSON.stringify(message, null, 2)}`);
351
+ break;
352
+ }
353
+ }
354
+ }
355
+ }
356
+
357
+ // Error codes as defined in https://docs.emqx.com/en/cloud/latest/connect_to_deployments/mqtt_client_error_codes.html
358
+ const BadUserNamePasswordError = 134;
359
+ /**
360
+ * Represents a single connection to a Cloud Interop service
361
+ *
362
+ * @public
363
+ * @class
364
+ */
365
+ class CloudInteropAPI {
366
+ #cloudInteropSettings;
367
+ #sessionDetails;
368
+ #mqttClient;
369
+ #reconnectRetryLimit = 30;
370
+ #keepAliveIntervalSeconds = 30;
371
+ #logger = (level, message) => {
372
+ // eslint-disable-next-line security/detect-object-injection -- level is restricted to the LogLevel union
373
+ console[level](message);
374
+ };
375
+ #reconnectRetries = 0;
376
+ #connectionParams;
377
+ #tokenClient;
378
+ #attemptingToReconnect = false;
379
+ #events = new EventController();
380
+ #intents;
381
+ #sessionTimer;
382
+ constructor(cloudInteropSettings) {
383
+ this.#cloudInteropSettings = cloudInteropSettings;
384
+ }
385
+ get sessionDetails() {
386
+ return this.#sessionDetails;
387
+ }
388
+ get mqttClient() {
389
+ return this.#mqttClient;
390
+ }
391
+ /**
392
+ * Connects and creates a session on the Cloud Interop service
393
+ *
394
+ * @param parameters - The parameters to use to connect
395
+ * @returns Promise that resolves when connection is established
396
+ * @memberof CloudInteropAPI
397
+ * @throws CloudInteropAPIError - If an error occurs during connection
398
+ * @throws AuthorizationError - If the connection is unauthorized
399
+ * @throws OAuthAuthenticationError - If OAuth parameters are invalid, the client credentials are rejected, or an access token cannot be obtained
400
+ */
401
+ async connect(parameters) {
402
+ this.#validateConnectParams(parameters);
403
+ const oauthParameters = parameters.oauthAuthenticationParameters;
404
+ if (parameters.authenticationType === 'oauth' && oauthParameters) {
405
+ try {
406
+ this.#tokenClient = Je.fromServiceUrl(this.#cloudInteropSettings.url, oauthParameters.clientId, oauthParameters.clientSecret);
407
+ }
408
+ catch (error) {
409
+ rethrowAsOAuthAuthenticationError(error);
410
+ }
411
+ }
412
+ else {
413
+ this.#tokenClient = undefined;
414
+ }
415
+ this.#connectionParams = parameters;
416
+ this.#reconnectRetryLimit = parameters.reconnectRetryLimit || this.#reconnectRetryLimit;
417
+ this.#keepAliveIntervalSeconds = parameters.keepAliveIntervalSeconds || this.#keepAliveIntervalSeconds;
418
+ this.#logger = parameters.logger || this.#logger;
419
+ const { sourceId, platformId } = this.#connectionParams;
420
+ const createSessionResponse = await this.#authenticatedFetch(`${this.#cloudInteropSettings.url}/api/sessions`, {
421
+ method: 'POST',
422
+ body: JSON.stringify({ sourceId: sourceId.trim(), platformId }),
423
+ });
424
+ if (!createSessionResponse.ok) {
425
+ if (createSessionResponse.status === 401 || createSessionResponse.status === 403) {
426
+ throw new AuthorizationError();
427
+ }
428
+ throw new CloudInteropAPIError();
429
+ }
430
+ if (createSessionResponse.status !== 201) {
431
+ throw new CloudInteropAPIError(`Failed to connect to the Cloud Interop service: ${this.#cloudInteropSettings.url}`, 'ERR_CONNECT', new Error(createSessionResponse.statusText));
432
+ }
433
+ this.#sessionDetails = (await createSessionResponse.json());
434
+ // If local session expiry handling is enabled, start the session timer
435
+ if (this.#sessionDetails.localSessionExpiryHandling) {
436
+ this.#logger('debug', `Local session expiry handling is enabled`);
437
+ this.#startSessionTimer();
438
+ }
439
+ const sessionRootTopic = this.#sessionDetails.sessionRootTopic;
440
+ const clientOptions = {
441
+ keepalive: this.#keepAliveIntervalSeconds,
442
+ clientId: this.#sessionDetails.sessionId,
443
+ clean: true,
444
+ protocolVersion: 5,
445
+ // The "will" message will be published on an unexpected disconnection
446
+ // The server can then tidy up. So it needs every for this client to do that, the session details is perfect
447
+ will: {
448
+ topic: 'interop/lastwill',
449
+ payload: Buffer.from(JSON.stringify(this.#sessionDetails)),
450
+ qos: 0,
451
+ retain: false,
452
+ },
453
+ username: this.#sessionDetails.token,
454
+ };
455
+ this.#mqttClient = await mqtt.connectAsync(this.#sessionDetails.url, clientOptions);
456
+ // TODO: Dynamic intent discovery
457
+ // search for any ongoing discoveries in DB and fire report-intents on self
458
+ this.#logger('log', `Cloud Interop successfully connected to ${this.#cloudInteropSettings.url}`);
459
+ // eslint-disable-next-line security-node/detect-unhandled-event-errors -- this callback handles MQTT error events
460
+ this.#mqttClient.on('error', async (error) => {
461
+ // We will receive errors for each failed reconnection attempt
462
+ // We don't want to disconnect on these else we will never reconnect
463
+ if (!this.#attemptingToReconnect) {
464
+ await this.#disconnectAndLogFailure();
465
+ }
466
+ if (error instanceof mqtt.ErrorWithReasonCode) {
467
+ switch (error.code) {
468
+ case BadUserNamePasswordError: {
469
+ this.#handleSessionExpiry();
470
+ return;
471
+ }
472
+ default: {
473
+ this.#logger('error', `Unknown Infrastructure Error Code ${error.code} : ${error.message}${this.#attemptingToReconnect ? ' during reconnection attempt' : ''}`);
474
+ // As we are in the middle of a reconnect, lets not emit an error to cut down on the event noise
475
+ if (!this.#attemptingToReconnect) {
476
+ this.#events.emitEvent('error', new CloudInteropAPIError(`Unknown Infrastructure Error Code ${error.code} : ${error.message}`, 'ERR_INFRASTRUCTURE', error));
477
+ break;
478
+ }
479
+ }
480
+ }
481
+ }
482
+ else {
483
+ this.#logger('error', `Unknown Error${this.#attemptingToReconnect ? ' during reconnection attempt' : ''}: ${error}`);
484
+ // As we are in the middle of a reconnect, lets not emit an error to cut down on the event noise
485
+ if (!this.#attemptingToReconnect) {
486
+ this.#events.emitEvent('error', new CloudInteropAPIError(`Unknown Error`, 'ERR_UNKNOWN', error));
487
+ }
488
+ }
489
+ });
490
+ this.#mqttClient.on('reconnect', async () => {
491
+ this.#attemptingToReconnect = true;
492
+ this.#reconnectRetries += 1;
493
+ this.#logger('debug', `Cloud Interop attempting reconnection - ${this.#reconnectRetries}...`);
494
+ this.#events.emitEvent('reconnecting', this.#reconnectRetries);
495
+ if (this.#reconnectRetries === this.#reconnectRetryLimit) {
496
+ this.#logger('warn', `Cloud Interop reached max reconnection attempts - ${this.#reconnectRetryLimit}...`);
497
+ await this.#disconnectAndLogFailure(true);
498
+ }
499
+ });
500
+ // Does not fire on initial connection, only successful reconnection attempts
501
+ this.#mqttClient.on('connect', () => {
502
+ this.#logger('debug', `Cloud Interop successfully reconnected after ${this.#reconnectRetries} attempts`);
503
+ this.#reconnectRetries = 0;
504
+ this.#attemptingToReconnect = false;
505
+ this.#events.emitEvent('reconnected');
506
+ });
507
+ this.#mqttClient.on('message', (topic, message) => {
508
+ if (!this.#sessionDetails) {
509
+ this.#logger('warn', 'Received message when session not connected');
510
+ return;
511
+ }
512
+ this.#handleMessage(topic, message, this.#sessionDetails);
513
+ });
514
+ // Subscribe to all context groups
515
+ this.#mqttClient.subscribe(`${sessionRootTopic}/context-groups/#`);
516
+ // Listen out for global commands
517
+ this.#mqttClient.subscribe(`${sessionRootTopic}/commands`);
518
+ this.#initControllers(this.#mqttClient, this.#sessionDetails);
519
+ }
520
+ /**
521
+ * Disconnects from the Cloud Interop service
522
+ *
523
+ * @returns Promise that resolves when disconnected
524
+ * @memberof CloudInteropAPI
525
+ * @throws CloudInteropAPIError - If an error occurs during disconnection
526
+ */
527
+ async disconnect() {
528
+ await this.#disconnect(true);
529
+ }
530
+ /**
531
+ * Publishes a new context for the given context group to the other connected sessions
532
+ *
533
+ * @param contextGroup - The context group to publish to
534
+ * @param context - The context to publish
535
+ * @returns Promise that resolves when context is published
536
+ * @memberof CloudInteropAPI
537
+ */
538
+ async setContext(contextGroup, context) {
539
+ // TODO: make context of type OpenFin.Context
540
+ if (!this.#sessionDetails || !this.#connectionParams) {
541
+ throw new Error('Session not connected');
542
+ }
543
+ if (!this.#mqttClient) {
544
+ throw new Error('MQTT client not connected');
545
+ }
546
+ const payload = {
547
+ context,
548
+ timestamp: Date.now(),
549
+ };
550
+ const postResponse = await this.#authenticatedFetch(`${this.#cloudInteropSettings.url}/api/context-groups/${this.#sessionDetails.sessionId}/${contextGroup}`, {
551
+ method: 'POST',
552
+ body: JSON.stringify(payload),
553
+ });
554
+ if (!postResponse.ok) {
555
+ throw new CloudInteropAPIError(`Error setting context for ${contextGroup}`, 'ERR_SETTING_CONTEXT', new Error(postResponse.statusText));
556
+ }
557
+ }
558
+ /**
559
+ * Starts an intent discovery operation
560
+ *
561
+ * @returns Promise that resolves when intent discovery is started
562
+ * @memberof CloudInteropAPI
563
+ * @throws CloudInteropAPIError - If an error occurs during intent discovery
564
+ */
565
+ async startIntentDiscovery(options) {
566
+ this.#throwIfNotConnected();
567
+ return this.#intents?.startIntentDiscovery(options);
568
+ }
569
+ async raiseIntent(options) {
570
+ this.#throwIfNotConnected();
571
+ return this.#intents?.raiseIntent(options);
572
+ }
573
+ async reportAppIntents(discoveryId, intents) {
574
+ this.#throwIfNotConnected();
575
+ return this.#intents?.reportAppIntents(discoveryId, intents) ?? false;
576
+ }
577
+ async sendIntentResult(initiatingSessionId, result) {
578
+ this.#throwIfNotConnected();
579
+ return this.#intents?.sendIntentResult(initiatingSessionId, result);
580
+ }
581
+ parseSessionId(appId) {
582
+ return parseCloudAppId(appId).sessionId;
583
+ }
584
+ parseAppId(appId) {
585
+ return parseCloudAppId(appId).appId;
586
+ }
587
+ addEventListener(type, callback) {
588
+ this.#events.addEventListener(type, callback);
589
+ }
590
+ removeEventListener(type, callback) {
591
+ this.#events.removeEventListener(type, callback);
592
+ }
593
+ once(type, callback) {
594
+ this.#events.once(type, callback);
595
+ }
596
+ async #disconnect(fireDisconnectedEvent) {
597
+ if (!this.#sessionDetails) {
598
+ return;
599
+ }
600
+ try {
601
+ if (!this.#connectionParams) {
602
+ throw new Error('Connect parameters must be provided');
603
+ }
604
+ // Cancel session timer if it's running
605
+ if (this.#sessionTimer) {
606
+ clearTimeout(this.#sessionTimer);
607
+ this.#sessionTimer = undefined;
608
+ }
609
+ const disconnectResponse = await this.#authenticatedFetch(`${this.#cloudInteropSettings.url}/api/sessions/${this.#sessionDetails.sessionId}`, {
610
+ method: 'DELETE',
611
+ });
612
+ if (disconnectResponse.status !== 200) {
613
+ throw new CloudInteropAPIError('Error during session tear down - unexpected status', 'ERR_DISCONNECT', new Error(disconnectResponse.statusText));
614
+ }
615
+ }
616
+ catch (error) {
617
+ throw new CloudInteropAPIError('Error during disconnection', 'ERR_DISCONNECT', error);
618
+ }
619
+ finally {
620
+ this.#destroyControllers();
621
+ this.#mqttClient?.removeAllListeners();
622
+ await this.#mqttClient?.endAsync(true);
623
+ this.#sessionDetails = undefined;
624
+ this.#mqttClient = undefined;
625
+ this.#reconnectRetries = 0;
626
+ this.#attemptingToReconnect = false;
627
+ if (fireDisconnectedEvent) {
628
+ this.#events.emitEvent('disconnected');
629
+ }
630
+ }
631
+ }
632
+ #handleMessage(topic, message, sessionDetails) {
633
+ this.#logger('debug', `Received message on topic: ${topic}`);
634
+ if (message.length === 0 || !sessionDetails) {
635
+ // Ignore clean up messages
636
+ return;
637
+ }
638
+ const messageEnvelope = JSON.parse(message.toString());
639
+ if (topic.startsWith(`${sessionDetails.sessionRootTopic}/context-groups/`)) {
640
+ const contextEvent = messageEnvelope;
641
+ if (contextEvent.source.sessionId === sessionDetails.sessionId) {
642
+ return;
643
+ }
644
+ const { context, payload, contextGroup, channelName, source, history } = contextEvent;
645
+ this.#events.emitEvent('context', {
646
+ contextGroup: channelName || contextGroup,
647
+ context: payload || context,
648
+ source,
649
+ history: { ...history, clientReceived: Date.now() },
650
+ });
651
+ }
652
+ else if (topic.startsWith(`${sessionDetails.sessionRootTopic}/commands`)) {
653
+ this.#handleCommandMessage(messageEnvelope);
654
+ }
655
+ }
656
+ #handleCommandMessage(message) {
657
+ switch (message.command) {
658
+ case 'report-intents':
659
+ case 'intent-details':
660
+ case 'raise-intent':
661
+ case 'intent-result': {
662
+ this.#intents?.handleCommandMessage(message);
663
+ break;
664
+ }
665
+ default: {
666
+ this.#logger('warn', `Unknown command message received:\n${JSON.stringify(message, null, 2)}`);
667
+ break;
668
+ }
669
+ }
670
+ }
671
+ #validateConnectParams = (parameters) => {
672
+ if (!parameters) {
673
+ throw new Error('Connect parameters must be provided');
674
+ }
675
+ if (!parameters.sourceId) {
676
+ throw new Error('sourceId must be provided');
677
+ }
678
+ if (parameters.sourceId.includes(APP_ID_DELIM)) {
679
+ throw new Error(`sourceId cannot contain "${APP_ID_DELIM}"`);
680
+ }
681
+ if (!parameters.platformId) {
682
+ throw new Error('platformId must be provided');
683
+ }
684
+ if (parameters.authenticationType === 'jwt' &&
685
+ (!parameters.jwtAuthenticationParameters?.jwtRequestCallback || !parameters.jwtAuthenticationParameters?.authenticationId)) {
686
+ throw new Error('jwtAuthenticationParameters must be provided when using jwt authentication');
687
+ }
688
+ if (parameters.authenticationType === 'basic' &&
689
+ (!parameters.basicAuthenticationParameters?.username || !parameters.basicAuthenticationParameters?.password)) {
690
+ throw new Error('basicAuthenticationParameters must be provided when using basic authentication');
691
+ }
692
+ if (parameters.authenticationType === 'oauth') {
693
+ if (!parameters.oauthAuthenticationParameters?.clientId?.trim() || !parameters.oauthAuthenticationParameters?.clientSecret?.trim()) {
694
+ throw new OAuthAuthenticationError('oauthAuthenticationParameters must be provided when using oauth authentication');
695
+ }
696
+ try {
697
+ $n(parameters.oauthAuthenticationParameters);
698
+ }
699
+ catch (error) {
700
+ rethrowAsOAuthAuthenticationError(error);
701
+ }
702
+ }
703
+ };
704
+ #initControllers(mqttClient, sessionDetails) {
705
+ this.#intents = new IntentController(this.#cloudInteropSettings.url, mqttClient, sessionDetails, this.#authenticatedFetch, this.#events, this.#logger);
706
+ }
707
+ #authenticatedFetch = async (url, { method, body }) => {
708
+ const connectionParameters = this.#connectionParams;
709
+ if (!connectionParameters) {
710
+ throw new Error('Connect parameters must be provided');
711
+ }
712
+ const attempt = async () => {
713
+ const headers = await getRequestHeaders(connectionParameters, this.#tokenClient);
714
+ return fetch(url, { method, headers, body });
715
+ };
716
+ if (connectionParameters.authenticationType === 'oauth' && this.#tokenClient) {
717
+ return Fn(this.#tokenClient, attempt);
718
+ }
719
+ return attempt();
720
+ };
721
+ #destroyControllers() {
722
+ this.#intents = undefined;
723
+ }
724
+ #throwIfNotConnected() {
725
+ if (!this.#sessionDetails || !this.#connectionParams) {
726
+ throw new Error('Session not connected');
727
+ }
728
+ if (!this.#mqttClient) {
729
+ throw new Error('MQTT client not connected');
730
+ }
731
+ }
732
+ /**
733
+ * Extracts the expiration timestamp from a JWT token.
734
+ *
735
+ * @param token - The JWT token string
736
+ * @returns The expiration timestamp in seconds, or null if extraction fails
737
+ */
738
+ #extractExpirationFromJwt(token) {
739
+ try {
740
+ // JWT tokens have three parts separated by dots: header.payload.signature
741
+ // The exp claim is in the payload
742
+ const parts = token.split('.');
743
+ if (parts.length < 2) {
744
+ this.#logger('warn', 'Invalid JWT token format: expected at least 2 parts');
745
+ return null;
746
+ }
747
+ const payload = parts[1];
748
+ // Decode base64url encoded payload
749
+ const decodedBytes = Buffer.from(y(payload), 'base64');
750
+ const payloadJson = decodedBytes.toString('utf8');
751
+ // Parse JSON to get the exp claim
752
+ const claims = JSON.parse(payloadJson);
753
+ const exp = claims.exp;
754
+ if (exp === undefined || exp === null) {
755
+ this.#logger('warn', "JWT token does not contain 'exp' claim");
756
+ return null;
757
+ }
758
+ if (typeof exp !== 'number') {
759
+ this.#logger('warn', `JWT token 'exp' claim is not a number: ${exp}`);
760
+ return null;
761
+ }
762
+ return exp;
763
+ }
764
+ catch (error) {
765
+ this.#logger('error', `Failed to extract expiration from JWT token: ${error instanceof Error ? error.message : error}`);
766
+ return null;
767
+ }
768
+ }
769
+ /**
770
+ * Start a session timer that will expire at the time specified in the JWT token's exp claim.
771
+ * When the timer fires, it executes the same actions as the BadUserNamePasswordError case.
772
+ */
773
+ #startSessionTimer() {
774
+ if (!this.#sessionDetails?.localSessionExpiryHandling) {
775
+ return;
776
+ }
777
+ const token = this.#sessionDetails.token;
778
+ if (!token) {
779
+ this.#logger('warn', 'Cannot start session timer: token not available');
780
+ return;
781
+ }
782
+ // Extract expiration time from JWT token
783
+ const expTimestamp = this.#extractExpirationFromJwt(token);
784
+ if (expTimestamp === null) {
785
+ this.#logger('warn', 'Cannot start session timer: could not extract expiration from JWT token');
786
+ return;
787
+ }
788
+ const currentTimeSeconds = Math.floor(Date.now() / 1000);
789
+ const delaySeconds = expTimestamp - currentTimeSeconds;
790
+ if (delaySeconds <= 0) {
791
+ this.#logger('warn', 'JWT token has already expired or expires immediately');
792
+ // Execute the same actions as BadUserNamePasswordError case
793
+ this.#handleSessionExpiry();
794
+ return;
795
+ }
796
+ // Clear any existing timer
797
+ if (this.#sessionTimer) {
798
+ clearTimeout(this.#sessionTimer);
799
+ }
800
+ const expirationTimeString = new Date(expTimestamp * 1000).toISOString();
801
+ this.#logger('debug', `Starting session timer to expire in ${delaySeconds} seconds (at ${expirationTimeString})`);
802
+ this.#sessionTimer = setTimeout(async () => {
803
+ this.#handleSessionExpiry();
804
+ }, delaySeconds * 1000);
805
+ }
806
+ /**
807
+ * Handles session expiry by executing the same actions as the BadUserNamePasswordError case.
808
+ */
809
+ async #handleSessionExpiry() {
810
+ await this.#disconnectAndLogFailure();
811
+ this.#logger('warn', 'Session expired');
812
+ this.#events.emitEvent('session-expired');
813
+ }
814
+ async #disconnectAndLogFailure(fireDisconnectedEvent = false) {
815
+ try {
816
+ await this.#disconnect(fireDisconnectedEvent);
817
+ }
818
+ catch (error) {
819
+ this.#logger('error', `Session teardown failed: ${error instanceof Error ? error.message : String(error)}`);
820
+ }
821
+ }
822
+ }
823
+
824
+ export { AuthorizationError, CloudInteropAPI, CloudInteropAPIError, OAuthAuthenticationError };