@openfin/cloud-interop-core-api 0.0.1-alpha.fff06d4 → 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/README.md CHANGED
@@ -10,5 +10,6 @@ It is callable via browser or node applications.
10
10
  The library supports authentication with the HERE Cloud Interop Service using the following methods:
11
11
  - Basic Authentication
12
12
  - JWT Token Authentication
13
+ - OAuth client credentials, for a server-side application. The service URL must be absolute and use `https:`, such as `https://host/interop`. `http:` is only accepted for `localhost` and `127.0.0.1` during local development, and a path such as `/interop` is not enough. A client secret is rejected in the browser.
13
14
  - Default Authentication i.e. Interactive session based authentication using cookies
14
15
 
package/bundle.d.ts CHANGED
@@ -250,6 +250,7 @@ export declare class CloudInteropAPI {
250
250
  * @memberof CloudInteropAPI
251
251
  * @throws CloudInteropAPIError - If an error occurs during connection
252
252
  * @throws AuthorizationError - If the connection is unauthorized
253
+ * @throws OAuthAuthenticationError - If OAuth parameters are invalid, the client credentials are rejected, or an access token cannot be obtained
253
254
  */
254
255
  connect(parameters: ConnectParameters): Promise<void>;
255
256
  /**
@@ -341,9 +342,10 @@ export declare type ConnectParameters = {
341
342
  *
342
343
  * 'jwt' - Use JWT authentication, in this case jwtAuthenticationParameters must also be provided
343
344
  * 'basic' - Use basic authentication, in this case basicAuthenticationParameters must also be provided
345
+ * 'oauth' - Use OAuth client credentials, in this case oauthAuthenticationParameters must also be provided
344
346
  * 'default' - Authentication will be inherited from the current session
345
347
  */
346
- authenticationType?: 'jwt' | 'basic' | 'default';
348
+ authenticationType?: 'jwt' | 'basic' | 'oauth' | 'default';
347
349
  /**
348
350
  * Optional parameters for basic authentication
349
351
  */
@@ -364,7 +366,7 @@ export declare type ConnectParameters = {
364
366
  /**
365
367
  * When JWT authentication is being used, this will be invoked just whenever a JWT token is required for a request
366
368
  */
367
- jwtRequestCallback: () => string | object;
369
+ jwtRequestCallback: () => string | object | Promise<string | object>;
368
370
  /**
369
371
  * The id of the service gateway JWT authentication definition to use
370
372
  *
@@ -372,6 +374,11 @@ export declare type ConnectParameters = {
372
374
  */
373
375
  authenticationId: string;
374
376
  };
377
+ /**
378
+ * Optional parameters for OAuth client-credentials authentication.
379
+ * Server-side only. A client secret is rejected in the browser.
380
+ */
381
+ oauthAuthenticationParameters?: OAuthAuthenticationParameters;
375
382
  };
376
383
 
377
384
  /**
@@ -714,6 +721,40 @@ declare const intentResultSchema: z.ZodUnion<[z.ZodObject<{
714
721
 
715
722
  export declare type LogLevel = 'log' | 'debug' | 'info' | 'warn' | 'error';
716
723
 
724
+ export declare class OAuthAuthenticationError extends CloudInteropAPIError {
725
+ constructor(message: string, cause?: unknown);
726
+ }
727
+
728
+ /**
729
+ * Parameters for OAuth client-credentials authentication.
730
+ *
731
+ * Use these from a server-side application only. A client secret is rejected when the library runs in a browser.
732
+ * Load the secret from the environment or a secret store rather than hard-coding it.
733
+ *
734
+ * @example
735
+ * ```typescript
736
+ * const oauthAuthenticationParameters: OAuthAuthenticationParameters = {
737
+ * grantType: 'client_credentials',
738
+ * clientId: 'your-client-id',
739
+ * clientSecret,
740
+ * };
741
+ * ```
742
+ */
743
+ export declare type OAuthAuthenticationParameters = {
744
+ /**
745
+ * Only `client_credentials` is supported.
746
+ */
747
+ grantType: 'client_credentials';
748
+ /**
749
+ * The client id of an OAuth application an admin already registered.
750
+ */
751
+ clientId: string;
752
+ /**
753
+ * The client secret for that application. Not accepted from a browser page.
754
+ */
755
+ clientSecret: string;
756
+ };
757
+
717
758
  /**
718
759
  * Options used to raise an Intent
719
760
  * @public
package/index.cjs CHANGED
@@ -5,7 +5,9 @@ require('fs');
5
5
  require('path');
6
6
  var mqtt = require('mqtt');
7
7
 
8
- var u=n=>{let e=n.replaceAll("-","+").replaceAll("_","/");return e.padEnd(e.length+(4-e.length%4)%4,"=")};
8
+ 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())};
9
+
10
+ var y=e=>{let n=e.replaceAll("-","+").replaceAll("_","/");return n.padEnd(n.length+(4-n.length%4)%4,"=")};
9
11
 
10
12
  class CloudInteropAPIError extends Error {
11
13
  code;
@@ -20,6 +22,21 @@ class AuthorizationError extends CloudInteropAPIError {
20
22
  super(message, code, undefined);
21
23
  }
22
24
  }
25
+ class OAuthAuthenticationError extends CloudInteropAPIError {
26
+ constructor(message, cause) {
27
+ super(message, 'ERR_OAUTH', cause);
28
+ }
29
+ }
30
+
31
+ const rethrowAsOAuthAuthenticationError = (error) => {
32
+ if (error instanceof w) {
33
+ throw new OAuthAuthenticationError(error.message, error);
34
+ }
35
+ if (error instanceof TypeError) {
36
+ throw new OAuthAuthenticationError('OAuth access token could not be obtained', error);
37
+ }
38
+ throw error;
39
+ };
23
40
 
24
41
  class EventController {
25
42
  #eventListeners = new Map();
@@ -53,11 +70,20 @@ class EventController {
53
70
  const isErrorIntentResult = (result) => 'error' in result;
54
71
 
55
72
  const APP_ID_DELIM = '::';
56
- const getRequestHeaders = (connectionParameters) => {
73
+ const getRequestHeaders = async (connectionParameters, tokenClient) => {
57
74
  const headers = {};
58
75
  headers['Content-Type'] = 'application/json';
76
+ if (connectionParameters.authenticationType === 'oauth' && tokenClient) {
77
+ try {
78
+ const accessToken = await tokenClient.getAccessToken();
79
+ headers['Authorization'] = `Bearer ${accessToken}`;
80
+ }
81
+ catch (error) {
82
+ rethrowAsOAuthAuthenticationError(error);
83
+ }
84
+ }
59
85
  if (connectionParameters.authenticationType === 'jwt' && connectionParameters.jwtAuthenticationParameters) {
60
- const tokenResult = connectionParameters.jwtAuthenticationParameters.jwtRequestCallback();
86
+ const tokenResult = await connectionParameters.jwtAuthenticationParameters.jwtRequestCallback();
61
87
  if (!tokenResult) {
62
88
  throw new Error('jwtRequestCallback must return a token');
63
89
  }
@@ -139,16 +165,16 @@ class IntentController {
139
165
  #url;
140
166
  #mqttClient;
141
167
  #sessionDetails;
142
- #connectionParams;
168
+ #authenticatedFetch;
143
169
  #events;
144
170
  #logger;
145
171
  #discovery = newDiscovery();
146
172
  #discoveryTimeout;
147
- constructor(url, mqttClient, sessionDetails, connectionParameters, events, logger) {
173
+ constructor(url, mqttClient, sessionDetails, authenticatedFetch, events, logger) {
148
174
  this.#url = url;
149
175
  this.#mqttClient = mqttClient;
150
176
  this.#sessionDetails = sessionDetails;
151
- this.#connectionParams = connectionParameters;
177
+ this.#authenticatedFetch = authenticatedFetch;
152
178
  this.#events = events;
153
179
  this.#logger = logger;
154
180
  }
@@ -160,9 +186,8 @@ class IntentController {
160
186
  // clamp min value to 500ms
161
187
  const clampedTimeout = Math.max(timeout, MIN_TIMEOUT);
162
188
  try {
163
- const startResponse = await fetch(`${this.#url}/api/intents/${this.#sessionDetails.sessionId}`, {
189
+ const startResponse = await this.#authenticatedFetch(`${this.#url}/api/intents/${this.#sessionDetails.sessionId}`, {
164
190
  method: 'POST',
165
- headers: getRequestHeaders(this.#connectionParams),
166
191
  body: JSON.stringify({ findOptions }),
167
192
  });
168
193
  if (!startResponse.ok) {
@@ -205,9 +230,8 @@ class IntentController {
205
230
  this.#logger('warn', `Error ending intent discovery: could not unsubscribe from discovery id ${this.#discovery.id}`);
206
231
  });
207
232
  }
208
- await fetch(`${this.#url}/api/intents/${this.#sessionDetails.sessionId}/${this.#discovery.id}`, {
233
+ await this.#authenticatedFetch(`${this.#url}/api/intents/${this.#sessionDetails.sessionId}/${this.#discovery.id}`, {
209
234
  method: 'DELETE',
210
- headers: getRequestHeaders(this.#connectionParams),
211
235
  })
212
236
  .then((deleteResponse) => {
213
237
  if (!deleteResponse.ok) {
@@ -226,9 +250,8 @@ class IntentController {
226
250
  // TODO: should we add more info here about the format?
227
251
  throw new CloudInteropAPIError(`Invalid AppId specified, must be encoded as a cloud-session app id`, 'ERR_INVALID_TARGET_SESSION_ID');
228
252
  }
229
- const postResponse = await fetch(`${this.#url}/api/intents/${this.#sessionDetails.sessionId}/sessions/${targetSessionId}`, {
253
+ const postResponse = await this.#authenticatedFetch(`${this.#url}/api/intents/${this.#sessionDetails.sessionId}/sessions/${targetSessionId}`, {
230
254
  method: 'POST',
231
- headers: getRequestHeaders(this.#connectionParams),
232
255
  body: JSON.stringify({ raiseOptions }),
233
256
  });
234
257
  if (!postResponse.ok) {
@@ -240,9 +263,8 @@ class IntentController {
240
263
  async reportAppIntents(discoveryId, intents) {
241
264
  intents = encodeAppIntents(intents, getSourceFromSession(this.#sessionDetails));
242
265
  try {
243
- const reportResponse = await fetch(`${this.#url}/api/intents/${this.#sessionDetails.sessionId}/${discoveryId}`, {
266
+ const reportResponse = await this.#authenticatedFetch(`${this.#url}/api/intents/${this.#sessionDetails.sessionId}/${discoveryId}`, {
244
267
  method: 'POST',
245
- headers: getRequestHeaders(this.#connectionParams),
246
268
  body: JSON.stringify({ intents }),
247
269
  });
248
270
  if (reportResponse.ok) {
@@ -264,9 +286,8 @@ class IntentController {
264
286
  result.source = typeof result.source === 'string' ? encoded : { ...result.source, appId: encoded };
265
287
  }
266
288
  const { sessionId } = getSourceFromSession(this.#sessionDetails);
267
- const resultResponse = await fetch(`${this.#url}/api/intents/${initiatingSessionId}/result/${sessionId}`, {
289
+ const resultResponse = await this.#authenticatedFetch(`${this.#url}/api/intents/${initiatingSessionId}/result/${sessionId}`, {
268
290
  method: 'POST',
269
- headers: getRequestHeaders(this.#connectionParams),
270
291
  body: JSON.stringify({ result }),
271
292
  });
272
293
  if (!resultResponse.ok) {
@@ -350,10 +371,12 @@ class CloudInteropAPI {
350
371
  #reconnectRetryLimit = 30;
351
372
  #keepAliveIntervalSeconds = 30;
352
373
  #logger = (level, message) => {
374
+ // eslint-disable-next-line security/detect-object-injection -- level is restricted to the LogLevel union
353
375
  console[level](message);
354
376
  };
355
377
  #reconnectRetries = 0;
356
378
  #connectionParams;
379
+ #tokenClient;
357
380
  #attemptingToReconnect = false;
358
381
  #events = new EventController();
359
382
  #intents;
@@ -375,17 +398,29 @@ class CloudInteropAPI {
375
398
  * @memberof CloudInteropAPI
376
399
  * @throws CloudInteropAPIError - If an error occurs during connection
377
400
  * @throws AuthorizationError - If the connection is unauthorized
401
+ * @throws OAuthAuthenticationError - If OAuth parameters are invalid, the client credentials are rejected, or an access token cannot be obtained
378
402
  */
379
403
  async connect(parameters) {
380
404
  this.#validateConnectParams(parameters);
405
+ const oauthParameters = parameters.oauthAuthenticationParameters;
406
+ if (parameters.authenticationType === 'oauth' && oauthParameters) {
407
+ try {
408
+ this.#tokenClient = Je.fromServiceUrl(this.#cloudInteropSettings.url, oauthParameters.clientId, oauthParameters.clientSecret);
409
+ }
410
+ catch (error) {
411
+ rethrowAsOAuthAuthenticationError(error);
412
+ }
413
+ }
414
+ else {
415
+ this.#tokenClient = undefined;
416
+ }
381
417
  this.#connectionParams = parameters;
382
418
  this.#reconnectRetryLimit = parameters.reconnectRetryLimit || this.#reconnectRetryLimit;
383
419
  this.#keepAliveIntervalSeconds = parameters.keepAliveIntervalSeconds || this.#keepAliveIntervalSeconds;
384
420
  this.#logger = parameters.logger || this.#logger;
385
421
  const { sourceId, platformId } = this.#connectionParams;
386
- const createSessionResponse = await fetch(`${this.#cloudInteropSettings.url}/api/sessions`, {
422
+ const createSessionResponse = await this.#authenticatedFetch(`${this.#cloudInteropSettings.url}/api/sessions`, {
387
423
  method: 'POST',
388
- headers: getRequestHeaders(this.#connectionParams),
389
424
  body: JSON.stringify({ sourceId: sourceId.trim(), platformId }),
390
425
  });
391
426
  if (!createSessionResponse.ok) {
@@ -423,11 +458,12 @@ class CloudInteropAPI {
423
458
  // TODO: Dynamic intent discovery
424
459
  // search for any ongoing discoveries in DB and fire report-intents on self
425
460
  this.#logger('log', `Cloud Interop successfully connected to ${this.#cloudInteropSettings.url}`);
461
+ // eslint-disable-next-line security-node/detect-unhandled-event-errors -- this callback handles MQTT error events
426
462
  this.#mqttClient.on('error', async (error) => {
427
463
  // We will receive errors for each failed reconnection attempt
428
464
  // We don't want to disconnect on these else we will never reconnect
429
465
  if (!this.#attemptingToReconnect) {
430
- await this.#disconnect(false);
466
+ await this.#disconnectAndLogFailure();
431
467
  }
432
468
  if (error instanceof mqtt.ErrorWithReasonCode) {
433
469
  switch (error.code) {
@@ -453,15 +489,15 @@ class CloudInteropAPI {
453
489
  }
454
490
  }
455
491
  });
456
- this.#mqttClient.on('reconnect', () => {
492
+ this.#mqttClient.on('reconnect', async () => {
457
493
  this.#attemptingToReconnect = true;
458
494
  this.#reconnectRetries += 1;
459
495
  this.#logger('debug', `Cloud Interop attempting reconnection - ${this.#reconnectRetries}...`);
496
+ this.#events.emitEvent('reconnecting', this.#reconnectRetries);
460
497
  if (this.#reconnectRetries === this.#reconnectRetryLimit) {
461
498
  this.#logger('warn', `Cloud Interop reached max reconnection attempts - ${this.#reconnectRetryLimit}...`);
462
- this.#disconnect(true);
499
+ await this.#disconnectAndLogFailure(true);
463
500
  }
464
- this.#events.emitEvent('reconnecting', this.#reconnectRetries);
465
501
  });
466
502
  // Does not fire on initial connection, only successful reconnection attempts
467
503
  this.#mqttClient.on('connect', () => {
@@ -481,7 +517,7 @@ class CloudInteropAPI {
481
517
  this.#mqttClient.subscribe(`${sessionRootTopic}/context-groups/#`);
482
518
  // Listen out for global commands
483
519
  this.#mqttClient.subscribe(`${sessionRootTopic}/commands`);
484
- this.#initControllers(this.#mqttClient, this.#sessionDetails, this.#connectionParams);
520
+ this.#initControllers(this.#mqttClient, this.#sessionDetails);
485
521
  }
486
522
  /**
487
523
  * Disconnects from the Cloud Interop service
@@ -513,9 +549,8 @@ class CloudInteropAPI {
513
549
  context,
514
550
  timestamp: Date.now(),
515
551
  };
516
- const postResponse = await fetch(`${this.#cloudInteropSettings.url}/api/context-groups/${this.#sessionDetails.sessionId}/${contextGroup}`, {
552
+ const postResponse = await this.#authenticatedFetch(`${this.#cloudInteropSettings.url}/api/context-groups/${this.#sessionDetails.sessionId}/${contextGroup}`, {
517
553
  method: 'POST',
518
- headers: getRequestHeaders(this.#connectionParams),
519
554
  body: JSON.stringify(payload),
520
555
  });
521
556
  if (!postResponse.ok) {
@@ -573,9 +608,8 @@ class CloudInteropAPI {
573
608
  clearTimeout(this.#sessionTimer);
574
609
  this.#sessionTimer = undefined;
575
610
  }
576
- const disconnectResponse = await fetch(`${this.#cloudInteropSettings.url}/api/sessions/${this.#sessionDetails.sessionId}`, {
611
+ const disconnectResponse = await this.#authenticatedFetch(`${this.#cloudInteropSettings.url}/api/sessions/${this.#sessionDetails.sessionId}`, {
577
612
  method: 'DELETE',
578
- headers: getRequestHeaders(this.#connectionParams),
579
613
  });
580
614
  if (disconnectResponse.status !== 200) {
581
615
  throw new CloudInteropAPIError('Error during session tear down - unexpected status', 'ERR_DISCONNECT', new Error(disconnectResponse.statusText));
@@ -598,6 +632,7 @@ class CloudInteropAPI {
598
632
  }
599
633
  }
600
634
  #handleMessage(topic, message, sessionDetails) {
635
+ this.#logger('debug', `Received message on topic: ${topic}`);
601
636
  if (message.length === 0 || !sessionDetails) {
602
637
  // Ignore clean up messages
603
638
  return;
@@ -656,10 +691,35 @@ class CloudInteropAPI {
656
691
  (!parameters.basicAuthenticationParameters?.username || !parameters.basicAuthenticationParameters?.password)) {
657
692
  throw new Error('basicAuthenticationParameters must be provided when using basic authentication');
658
693
  }
694
+ if (parameters.authenticationType === 'oauth') {
695
+ if (!parameters.oauthAuthenticationParameters?.clientId?.trim() || !parameters.oauthAuthenticationParameters?.clientSecret?.trim()) {
696
+ throw new OAuthAuthenticationError('oauthAuthenticationParameters must be provided when using oauth authentication');
697
+ }
698
+ try {
699
+ $n(parameters.oauthAuthenticationParameters);
700
+ }
701
+ catch (error) {
702
+ rethrowAsOAuthAuthenticationError(error);
703
+ }
704
+ }
659
705
  };
660
- #initControllers(mqttClient, sessionDetails, connectionParameters) {
661
- this.#intents = new IntentController(this.#cloudInteropSettings.url, mqttClient, sessionDetails, connectionParameters, this.#events, this.#logger);
706
+ #initControllers(mqttClient, sessionDetails) {
707
+ this.#intents = new IntentController(this.#cloudInteropSettings.url, mqttClient, sessionDetails, this.#authenticatedFetch, this.#events, this.#logger);
662
708
  }
709
+ #authenticatedFetch = async (url, { method, body }) => {
710
+ const connectionParameters = this.#connectionParams;
711
+ if (!connectionParameters) {
712
+ throw new Error('Connect parameters must be provided');
713
+ }
714
+ const attempt = async () => {
715
+ const headers = await getRequestHeaders(connectionParameters, this.#tokenClient);
716
+ return fetch(url, { method, headers, body });
717
+ };
718
+ if (connectionParameters.authenticationType === 'oauth' && this.#tokenClient) {
719
+ return Fn(this.#tokenClient, attempt);
720
+ }
721
+ return attempt();
722
+ };
663
723
  #destroyControllers() {
664
724
  this.#intents = undefined;
665
725
  }
@@ -688,7 +748,7 @@ class CloudInteropAPI {
688
748
  }
689
749
  const payload = parts[1];
690
750
  // Decode base64url encoded payload
691
- const decodedBytes = buffer.Buffer.from(u(payload), 'base64');
751
+ const decodedBytes = buffer.Buffer.from(y(payload), 'base64');
692
752
  const payloadJson = decodedBytes.toString('utf8');
693
753
  // Parse JSON to get the exp claim
694
754
  const claims = JSON.parse(payloadJson);
@@ -749,12 +809,21 @@ class CloudInteropAPI {
749
809
  * Handles session expiry by executing the same actions as the BadUserNamePasswordError case.
750
810
  */
751
811
  async #handleSessionExpiry() {
752
- await this.#disconnect(false);
812
+ await this.#disconnectAndLogFailure();
753
813
  this.#logger('warn', 'Session expired');
754
814
  this.#events.emitEvent('session-expired');
755
815
  }
816
+ async #disconnectAndLogFailure(fireDisconnectedEvent = false) {
817
+ try {
818
+ await this.#disconnect(fireDisconnectedEvent);
819
+ }
820
+ catch (error) {
821
+ this.#logger('error', `Session teardown failed: ${error instanceof Error ? error.message : String(error)}`);
822
+ }
823
+ }
756
824
  }
757
825
 
758
826
  exports.AuthorizationError = AuthorizationError;
759
827
  exports.CloudInteropAPI = CloudInteropAPI;
760
828
  exports.CloudInteropAPIError = CloudInteropAPIError;
829
+ exports.OAuthAuthenticationError = OAuthAuthenticationError;
package/index.mjs CHANGED
@@ -3,7 +3,9 @@ import 'fs';
3
3
  import 'path';
4
4
  import mqtt from 'mqtt';
5
5
 
6
- var u=n=>{let e=n.replaceAll("-","+").replaceAll("_","/");return e.padEnd(e.length+(4-e.length%4)%4,"=")};
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,"=")};
7
9
 
8
10
  class CloudInteropAPIError extends Error {
9
11
  code;
@@ -18,6 +20,21 @@ class AuthorizationError extends CloudInteropAPIError {
18
20
  super(message, code, undefined);
19
21
  }
20
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
+ };
21
38
 
22
39
  class EventController {
23
40
  #eventListeners = new Map();
@@ -51,11 +68,20 @@ class EventController {
51
68
  const isErrorIntentResult = (result) => 'error' in result;
52
69
 
53
70
  const APP_ID_DELIM = '::';
54
- const getRequestHeaders = (connectionParameters) => {
71
+ const getRequestHeaders = async (connectionParameters, tokenClient) => {
55
72
  const headers = {};
56
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
+ }
57
83
  if (connectionParameters.authenticationType === 'jwt' && connectionParameters.jwtAuthenticationParameters) {
58
- const tokenResult = connectionParameters.jwtAuthenticationParameters.jwtRequestCallback();
84
+ const tokenResult = await connectionParameters.jwtAuthenticationParameters.jwtRequestCallback();
59
85
  if (!tokenResult) {
60
86
  throw new Error('jwtRequestCallback must return a token');
61
87
  }
@@ -137,16 +163,16 @@ class IntentController {
137
163
  #url;
138
164
  #mqttClient;
139
165
  #sessionDetails;
140
- #connectionParams;
166
+ #authenticatedFetch;
141
167
  #events;
142
168
  #logger;
143
169
  #discovery = newDiscovery();
144
170
  #discoveryTimeout;
145
- constructor(url, mqttClient, sessionDetails, connectionParameters, events, logger) {
171
+ constructor(url, mqttClient, sessionDetails, authenticatedFetch, events, logger) {
146
172
  this.#url = url;
147
173
  this.#mqttClient = mqttClient;
148
174
  this.#sessionDetails = sessionDetails;
149
- this.#connectionParams = connectionParameters;
175
+ this.#authenticatedFetch = authenticatedFetch;
150
176
  this.#events = events;
151
177
  this.#logger = logger;
152
178
  }
@@ -158,9 +184,8 @@ class IntentController {
158
184
  // clamp min value to 500ms
159
185
  const clampedTimeout = Math.max(timeout, MIN_TIMEOUT);
160
186
  try {
161
- const startResponse = await fetch(`${this.#url}/api/intents/${this.#sessionDetails.sessionId}`, {
187
+ const startResponse = await this.#authenticatedFetch(`${this.#url}/api/intents/${this.#sessionDetails.sessionId}`, {
162
188
  method: 'POST',
163
- headers: getRequestHeaders(this.#connectionParams),
164
189
  body: JSON.stringify({ findOptions }),
165
190
  });
166
191
  if (!startResponse.ok) {
@@ -203,9 +228,8 @@ class IntentController {
203
228
  this.#logger('warn', `Error ending intent discovery: could not unsubscribe from discovery id ${this.#discovery.id}`);
204
229
  });
205
230
  }
206
- await fetch(`${this.#url}/api/intents/${this.#sessionDetails.sessionId}/${this.#discovery.id}`, {
231
+ await this.#authenticatedFetch(`${this.#url}/api/intents/${this.#sessionDetails.sessionId}/${this.#discovery.id}`, {
207
232
  method: 'DELETE',
208
- headers: getRequestHeaders(this.#connectionParams),
209
233
  })
210
234
  .then((deleteResponse) => {
211
235
  if (!deleteResponse.ok) {
@@ -224,9 +248,8 @@ class IntentController {
224
248
  // TODO: should we add more info here about the format?
225
249
  throw new CloudInteropAPIError(`Invalid AppId specified, must be encoded as a cloud-session app id`, 'ERR_INVALID_TARGET_SESSION_ID');
226
250
  }
227
- const postResponse = await fetch(`${this.#url}/api/intents/${this.#sessionDetails.sessionId}/sessions/${targetSessionId}`, {
251
+ const postResponse = await this.#authenticatedFetch(`${this.#url}/api/intents/${this.#sessionDetails.sessionId}/sessions/${targetSessionId}`, {
228
252
  method: 'POST',
229
- headers: getRequestHeaders(this.#connectionParams),
230
253
  body: JSON.stringify({ raiseOptions }),
231
254
  });
232
255
  if (!postResponse.ok) {
@@ -238,9 +261,8 @@ class IntentController {
238
261
  async reportAppIntents(discoveryId, intents) {
239
262
  intents = encodeAppIntents(intents, getSourceFromSession(this.#sessionDetails));
240
263
  try {
241
- const reportResponse = await fetch(`${this.#url}/api/intents/${this.#sessionDetails.sessionId}/${discoveryId}`, {
264
+ const reportResponse = await this.#authenticatedFetch(`${this.#url}/api/intents/${this.#sessionDetails.sessionId}/${discoveryId}`, {
242
265
  method: 'POST',
243
- headers: getRequestHeaders(this.#connectionParams),
244
266
  body: JSON.stringify({ intents }),
245
267
  });
246
268
  if (reportResponse.ok) {
@@ -262,9 +284,8 @@ class IntentController {
262
284
  result.source = typeof result.source === 'string' ? encoded : { ...result.source, appId: encoded };
263
285
  }
264
286
  const { sessionId } = getSourceFromSession(this.#sessionDetails);
265
- const resultResponse = await fetch(`${this.#url}/api/intents/${initiatingSessionId}/result/${sessionId}`, {
287
+ const resultResponse = await this.#authenticatedFetch(`${this.#url}/api/intents/${initiatingSessionId}/result/${sessionId}`, {
266
288
  method: 'POST',
267
- headers: getRequestHeaders(this.#connectionParams),
268
289
  body: JSON.stringify({ result }),
269
290
  });
270
291
  if (!resultResponse.ok) {
@@ -348,10 +369,12 @@ class CloudInteropAPI {
348
369
  #reconnectRetryLimit = 30;
349
370
  #keepAliveIntervalSeconds = 30;
350
371
  #logger = (level, message) => {
372
+ // eslint-disable-next-line security/detect-object-injection -- level is restricted to the LogLevel union
351
373
  console[level](message);
352
374
  };
353
375
  #reconnectRetries = 0;
354
376
  #connectionParams;
377
+ #tokenClient;
355
378
  #attemptingToReconnect = false;
356
379
  #events = new EventController();
357
380
  #intents;
@@ -373,17 +396,29 @@ class CloudInteropAPI {
373
396
  * @memberof CloudInteropAPI
374
397
  * @throws CloudInteropAPIError - If an error occurs during connection
375
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
376
400
  */
377
401
  async connect(parameters) {
378
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
+ }
379
415
  this.#connectionParams = parameters;
380
416
  this.#reconnectRetryLimit = parameters.reconnectRetryLimit || this.#reconnectRetryLimit;
381
417
  this.#keepAliveIntervalSeconds = parameters.keepAliveIntervalSeconds || this.#keepAliveIntervalSeconds;
382
418
  this.#logger = parameters.logger || this.#logger;
383
419
  const { sourceId, platformId } = this.#connectionParams;
384
- const createSessionResponse = await fetch(`${this.#cloudInteropSettings.url}/api/sessions`, {
420
+ const createSessionResponse = await this.#authenticatedFetch(`${this.#cloudInteropSettings.url}/api/sessions`, {
385
421
  method: 'POST',
386
- headers: getRequestHeaders(this.#connectionParams),
387
422
  body: JSON.stringify({ sourceId: sourceId.trim(), platformId }),
388
423
  });
389
424
  if (!createSessionResponse.ok) {
@@ -421,11 +456,12 @@ class CloudInteropAPI {
421
456
  // TODO: Dynamic intent discovery
422
457
  // search for any ongoing discoveries in DB and fire report-intents on self
423
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
424
460
  this.#mqttClient.on('error', async (error) => {
425
461
  // We will receive errors for each failed reconnection attempt
426
462
  // We don't want to disconnect on these else we will never reconnect
427
463
  if (!this.#attemptingToReconnect) {
428
- await this.#disconnect(false);
464
+ await this.#disconnectAndLogFailure();
429
465
  }
430
466
  if (error instanceof mqtt.ErrorWithReasonCode) {
431
467
  switch (error.code) {
@@ -451,15 +487,15 @@ class CloudInteropAPI {
451
487
  }
452
488
  }
453
489
  });
454
- this.#mqttClient.on('reconnect', () => {
490
+ this.#mqttClient.on('reconnect', async () => {
455
491
  this.#attemptingToReconnect = true;
456
492
  this.#reconnectRetries += 1;
457
493
  this.#logger('debug', `Cloud Interop attempting reconnection - ${this.#reconnectRetries}...`);
494
+ this.#events.emitEvent('reconnecting', this.#reconnectRetries);
458
495
  if (this.#reconnectRetries === this.#reconnectRetryLimit) {
459
496
  this.#logger('warn', `Cloud Interop reached max reconnection attempts - ${this.#reconnectRetryLimit}...`);
460
- this.#disconnect(true);
497
+ await this.#disconnectAndLogFailure(true);
461
498
  }
462
- this.#events.emitEvent('reconnecting', this.#reconnectRetries);
463
499
  });
464
500
  // Does not fire on initial connection, only successful reconnection attempts
465
501
  this.#mqttClient.on('connect', () => {
@@ -479,7 +515,7 @@ class CloudInteropAPI {
479
515
  this.#mqttClient.subscribe(`${sessionRootTopic}/context-groups/#`);
480
516
  // Listen out for global commands
481
517
  this.#mqttClient.subscribe(`${sessionRootTopic}/commands`);
482
- this.#initControllers(this.#mqttClient, this.#sessionDetails, this.#connectionParams);
518
+ this.#initControllers(this.#mqttClient, this.#sessionDetails);
483
519
  }
484
520
  /**
485
521
  * Disconnects from the Cloud Interop service
@@ -511,9 +547,8 @@ class CloudInteropAPI {
511
547
  context,
512
548
  timestamp: Date.now(),
513
549
  };
514
- const postResponse = await fetch(`${this.#cloudInteropSettings.url}/api/context-groups/${this.#sessionDetails.sessionId}/${contextGroup}`, {
550
+ const postResponse = await this.#authenticatedFetch(`${this.#cloudInteropSettings.url}/api/context-groups/${this.#sessionDetails.sessionId}/${contextGroup}`, {
515
551
  method: 'POST',
516
- headers: getRequestHeaders(this.#connectionParams),
517
552
  body: JSON.stringify(payload),
518
553
  });
519
554
  if (!postResponse.ok) {
@@ -571,9 +606,8 @@ class CloudInteropAPI {
571
606
  clearTimeout(this.#sessionTimer);
572
607
  this.#sessionTimer = undefined;
573
608
  }
574
- const disconnectResponse = await fetch(`${this.#cloudInteropSettings.url}/api/sessions/${this.#sessionDetails.sessionId}`, {
609
+ const disconnectResponse = await this.#authenticatedFetch(`${this.#cloudInteropSettings.url}/api/sessions/${this.#sessionDetails.sessionId}`, {
575
610
  method: 'DELETE',
576
- headers: getRequestHeaders(this.#connectionParams),
577
611
  });
578
612
  if (disconnectResponse.status !== 200) {
579
613
  throw new CloudInteropAPIError('Error during session tear down - unexpected status', 'ERR_DISCONNECT', new Error(disconnectResponse.statusText));
@@ -596,6 +630,7 @@ class CloudInteropAPI {
596
630
  }
597
631
  }
598
632
  #handleMessage(topic, message, sessionDetails) {
633
+ this.#logger('debug', `Received message on topic: ${topic}`);
599
634
  if (message.length === 0 || !sessionDetails) {
600
635
  // Ignore clean up messages
601
636
  return;
@@ -654,10 +689,35 @@ class CloudInteropAPI {
654
689
  (!parameters.basicAuthenticationParameters?.username || !parameters.basicAuthenticationParameters?.password)) {
655
690
  throw new Error('basicAuthenticationParameters must be provided when using basic authentication');
656
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
+ }
657
703
  };
658
- #initControllers(mqttClient, sessionDetails, connectionParameters) {
659
- this.#intents = new IntentController(this.#cloudInteropSettings.url, mqttClient, sessionDetails, connectionParameters, this.#events, this.#logger);
704
+ #initControllers(mqttClient, sessionDetails) {
705
+ this.#intents = new IntentController(this.#cloudInteropSettings.url, mqttClient, sessionDetails, this.#authenticatedFetch, this.#events, this.#logger);
660
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
+ };
661
721
  #destroyControllers() {
662
722
  this.#intents = undefined;
663
723
  }
@@ -686,7 +746,7 @@ class CloudInteropAPI {
686
746
  }
687
747
  const payload = parts[1];
688
748
  // Decode base64url encoded payload
689
- const decodedBytes = Buffer.from(u(payload), 'base64');
749
+ const decodedBytes = Buffer.from(y(payload), 'base64');
690
750
  const payloadJson = decodedBytes.toString('utf8');
691
751
  // Parse JSON to get the exp claim
692
752
  const claims = JSON.parse(payloadJson);
@@ -747,10 +807,18 @@ class CloudInteropAPI {
747
807
  * Handles session expiry by executing the same actions as the BadUserNamePasswordError case.
748
808
  */
749
809
  async #handleSessionExpiry() {
750
- await this.#disconnect(false);
810
+ await this.#disconnectAndLogFailure();
751
811
  this.#logger('warn', 'Session expired');
752
812
  this.#events.emitEvent('session-expired');
753
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
+ }
754
822
  }
755
823
 
756
- export { AuthorizationError, CloudInteropAPI, CloudInteropAPIError };
824
+ export { AuthorizationError, CloudInteropAPI, CloudInteropAPIError, OAuthAuthenticationError };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openfin/cloud-interop-core-api",
3
- "version": "0.0.1-alpha.fff06d4",
3
+ "version": "0.0.1",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "main": "./index.cjs",
@@ -12,4 +12,4 @@
12
12
  "mqtt": "catalog:",
13
13
  "zod": "catalog:"
14
14
  }
15
- }
15
+ }