@openfin/cloud-interop-core-api 15.2.15 → 16.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -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
  */
@@ -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
@@ -1,11 +1,9 @@
1
1
  'use strict';
2
2
 
3
3
  var buffer = require('buffer');
4
- require('fs');
5
- require('path');
6
4
  var mqtt = require('mqtt');
7
5
 
8
- var d=n=>{let t=n.replaceAll("-","+").replaceAll("_","/");return t.padEnd(t.length+(4-t.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="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,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,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);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)}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,o);return}throw l(`${n} must be a positive number`,y,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,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);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)}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
7
 
10
8
  class CloudInteropAPIError extends Error {
11
9
  code;
@@ -20,6 +18,21 @@ class AuthorizationError extends CloudInteropAPIError {
20
18
  super(message, code, undefined);
21
19
  }
22
20
  }
21
+ class OAuthAuthenticationError extends CloudInteropAPIError {
22
+ constructor(message, cause) {
23
+ super(message, 'ERR_OAUTH', cause);
24
+ }
25
+ }
26
+
27
+ const rethrowAsOAuthAuthenticationError = (error) => {
28
+ if (error instanceof w) {
29
+ throw new OAuthAuthenticationError(error.message, error);
30
+ }
31
+ if (error instanceof TypeError) {
32
+ throw new OAuthAuthenticationError('OAuth access token could not be obtained', error);
33
+ }
34
+ throw error;
35
+ };
23
36
 
24
37
  class EventController {
25
38
  #eventListeners = new Map();
@@ -53,9 +66,18 @@ class EventController {
53
66
  const isErrorIntentResult = (result) => 'error' in result;
54
67
 
55
68
  const APP_ID_DELIM = '::';
56
- const getRequestHeaders = async (connectionParameters) => {
69
+ const getRequestHeaders = async (connectionParameters, tokenClient) => {
57
70
  const headers = {};
58
71
  headers['Content-Type'] = 'application/json';
72
+ if (connectionParameters.authenticationType === 'oauth' && tokenClient) {
73
+ try {
74
+ const accessToken = await tokenClient.getAccessToken();
75
+ headers['Authorization'] = `Bearer ${accessToken}`;
76
+ }
77
+ catch (error) {
78
+ rethrowAsOAuthAuthenticationError(error);
79
+ }
80
+ }
59
81
  if (connectionParameters.authenticationType === 'jwt' && connectionParameters.jwtAuthenticationParameters) {
60
82
  const tokenResult = await connectionParameters.jwtAuthenticationParameters.jwtRequestCallback();
61
83
  if (!tokenResult) {
@@ -139,16 +161,16 @@ class IntentController {
139
161
  #url;
140
162
  #mqttClient;
141
163
  #sessionDetails;
142
- #connectionParams;
164
+ #authenticatedFetch;
143
165
  #events;
144
166
  #logger;
145
167
  #discovery = newDiscovery();
146
168
  #discoveryTimeout;
147
- constructor(url, mqttClient, sessionDetails, connectionParameters, events, logger) {
169
+ constructor(url, mqttClient, sessionDetails, authenticatedFetch, events, logger) {
148
170
  this.#url = url;
149
171
  this.#mqttClient = mqttClient;
150
172
  this.#sessionDetails = sessionDetails;
151
- this.#connectionParams = connectionParameters;
173
+ this.#authenticatedFetch = authenticatedFetch;
152
174
  this.#events = events;
153
175
  this.#logger = logger;
154
176
  }
@@ -160,9 +182,8 @@ class IntentController {
160
182
  // clamp min value to 500ms
161
183
  const clampedTimeout = Math.max(timeout, MIN_TIMEOUT);
162
184
  try {
163
- const startResponse = await fetch(`${this.#url}/api/intents/${this.#sessionDetails.sessionId}`, {
185
+ const startResponse = await this.#authenticatedFetch(`${this.#url}/api/intents/${this.#sessionDetails.sessionId}`, {
164
186
  method: 'POST',
165
- headers: await getRequestHeaders(this.#connectionParams),
166
187
  body: JSON.stringify({ findOptions }),
167
188
  });
168
189
  if (!startResponse.ok) {
@@ -205,9 +226,8 @@ class IntentController {
205
226
  this.#logger('warn', `Error ending intent discovery: could not unsubscribe from discovery id ${this.#discovery.id}`);
206
227
  });
207
228
  }
208
- await fetch(`${this.#url}/api/intents/${this.#sessionDetails.sessionId}/${this.#discovery.id}`, {
229
+ await this.#authenticatedFetch(`${this.#url}/api/intents/${this.#sessionDetails.sessionId}/${this.#discovery.id}`, {
209
230
  method: 'DELETE',
210
- headers: await getRequestHeaders(this.#connectionParams),
211
231
  })
212
232
  .then((deleteResponse) => {
213
233
  if (!deleteResponse.ok) {
@@ -226,9 +246,8 @@ class IntentController {
226
246
  // TODO: should we add more info here about the format?
227
247
  throw new CloudInteropAPIError(`Invalid AppId specified, must be encoded as a cloud-session app id`, 'ERR_INVALID_TARGET_SESSION_ID');
228
248
  }
229
- const postResponse = await fetch(`${this.#url}/api/intents/${this.#sessionDetails.sessionId}/sessions/${targetSessionId}`, {
249
+ const postResponse = await this.#authenticatedFetch(`${this.#url}/api/intents/${this.#sessionDetails.sessionId}/sessions/${targetSessionId}`, {
230
250
  method: 'POST',
231
- headers: await getRequestHeaders(this.#connectionParams),
232
251
  body: JSON.stringify({ raiseOptions }),
233
252
  });
234
253
  if (!postResponse.ok) {
@@ -240,9 +259,8 @@ class IntentController {
240
259
  async reportAppIntents(discoveryId, intents) {
241
260
  intents = encodeAppIntents(intents, getSourceFromSession(this.#sessionDetails));
242
261
  try {
243
- const reportResponse = await fetch(`${this.#url}/api/intents/${this.#sessionDetails.sessionId}/${discoveryId}`, {
262
+ const reportResponse = await this.#authenticatedFetch(`${this.#url}/api/intents/${this.#sessionDetails.sessionId}/${discoveryId}`, {
244
263
  method: 'POST',
245
- headers: await getRequestHeaders(this.#connectionParams),
246
264
  body: JSON.stringify({ intents }),
247
265
  });
248
266
  if (reportResponse.ok) {
@@ -264,9 +282,8 @@ class IntentController {
264
282
  result.source = typeof result.source === 'string' ? encoded : { ...result.source, appId: encoded };
265
283
  }
266
284
  const { sessionId } = getSourceFromSession(this.#sessionDetails);
267
- const resultResponse = await fetch(`${this.#url}/api/intents/${initiatingSessionId}/result/${sessionId}`, {
285
+ const resultResponse = await this.#authenticatedFetch(`${this.#url}/api/intents/${initiatingSessionId}/result/${sessionId}`, {
268
286
  method: 'POST',
269
- headers: await getRequestHeaders(this.#connectionParams),
270
287
  body: JSON.stringify({ result }),
271
288
  });
272
289
  if (!resultResponse.ok) {
@@ -355,6 +372,7 @@ class CloudInteropAPI {
355
372
  };
356
373
  #reconnectRetries = 0;
357
374
  #connectionParams;
375
+ #tokenClient;
358
376
  #attemptingToReconnect = false;
359
377
  #events = new EventController();
360
378
  #intents;
@@ -376,17 +394,29 @@ class CloudInteropAPI {
376
394
  * @memberof CloudInteropAPI
377
395
  * @throws CloudInteropAPIError - If an error occurs during connection
378
396
  * @throws AuthorizationError - If the connection is unauthorized
397
+ * @throws OAuthAuthenticationError - If OAuth parameters are invalid, the client credentials are rejected, or an access token cannot be obtained
379
398
  */
380
399
  async connect(parameters) {
381
400
  this.#validateConnectParams(parameters);
401
+ const oauthParameters = parameters.oauthAuthenticationParameters;
402
+ if (parameters.authenticationType === 'oauth' && oauthParameters) {
403
+ try {
404
+ this.#tokenClient = Je.fromServiceUrl(this.#cloudInteropSettings.url, oauthParameters.clientId, oauthParameters.clientSecret);
405
+ }
406
+ catch (error) {
407
+ rethrowAsOAuthAuthenticationError(error);
408
+ }
409
+ }
410
+ else {
411
+ this.#tokenClient = undefined;
412
+ }
382
413
  this.#connectionParams = parameters;
383
414
  this.#reconnectRetryLimit = parameters.reconnectRetryLimit || this.#reconnectRetryLimit;
384
415
  this.#keepAliveIntervalSeconds = parameters.keepAliveIntervalSeconds || this.#keepAliveIntervalSeconds;
385
416
  this.#logger = parameters.logger || this.#logger;
386
417
  const { sourceId, platformId } = this.#connectionParams;
387
- const createSessionResponse = await fetch(`${this.#cloudInteropSettings.url}/api/sessions`, {
418
+ const createSessionResponse = await this.#authenticatedFetch(`${this.#cloudInteropSettings.url}/api/sessions`, {
388
419
  method: 'POST',
389
- headers: await getRequestHeaders(this.#connectionParams),
390
420
  body: JSON.stringify({ sourceId: sourceId.trim(), platformId }),
391
421
  });
392
422
  if (!createSessionResponse.ok) {
@@ -429,7 +459,7 @@ class CloudInteropAPI {
429
459
  // We will receive errors for each failed reconnection attempt
430
460
  // We don't want to disconnect on these else we will never reconnect
431
461
  if (!this.#attemptingToReconnect) {
432
- await this.#disconnect(false);
462
+ await this.#disconnectAndLogFailure();
433
463
  }
434
464
  if (error instanceof mqtt.ErrorWithReasonCode) {
435
465
  switch (error.code) {
@@ -455,15 +485,15 @@ class CloudInteropAPI {
455
485
  }
456
486
  }
457
487
  });
458
- this.#mqttClient.on('reconnect', () => {
488
+ this.#mqttClient.on('reconnect', async () => {
459
489
  this.#attemptingToReconnect = true;
460
490
  this.#reconnectRetries += 1;
461
491
  this.#logger('debug', `Cloud Interop attempting reconnection - ${this.#reconnectRetries}...`);
492
+ this.#events.emitEvent('reconnecting', this.#reconnectRetries);
462
493
  if (this.#reconnectRetries === this.#reconnectRetryLimit) {
463
494
  this.#logger('warn', `Cloud Interop reached max reconnection attempts - ${this.#reconnectRetryLimit}...`);
464
- this.#disconnect(true);
495
+ await this.#disconnectAndLogFailure(true);
465
496
  }
466
- this.#events.emitEvent('reconnecting', this.#reconnectRetries);
467
497
  });
468
498
  // Does not fire on initial connection, only successful reconnection attempts
469
499
  this.#mqttClient.on('connect', () => {
@@ -483,7 +513,7 @@ class CloudInteropAPI {
483
513
  this.#mqttClient.subscribe(`${sessionRootTopic}/context-groups/#`);
484
514
  // Listen out for global commands
485
515
  this.#mqttClient.subscribe(`${sessionRootTopic}/commands`);
486
- this.#initControllers(this.#mqttClient, this.#sessionDetails, this.#connectionParams);
516
+ this.#initControllers(this.#mqttClient, this.#sessionDetails);
487
517
  }
488
518
  /**
489
519
  * Disconnects from the Cloud Interop service
@@ -515,9 +545,8 @@ class CloudInteropAPI {
515
545
  context,
516
546
  timestamp: Date.now(),
517
547
  };
518
- const postResponse = await fetch(`${this.#cloudInteropSettings.url}/api/context-groups/${this.#sessionDetails.sessionId}/${contextGroup}`, {
548
+ const postResponse = await this.#authenticatedFetch(`${this.#cloudInteropSettings.url}/api/context-groups/${this.#sessionDetails.sessionId}/${contextGroup}`, {
519
549
  method: 'POST',
520
- headers: await getRequestHeaders(this.#connectionParams),
521
550
  body: JSON.stringify(payload),
522
551
  });
523
552
  if (!postResponse.ok) {
@@ -575,9 +604,8 @@ class CloudInteropAPI {
575
604
  clearTimeout(this.#sessionTimer);
576
605
  this.#sessionTimer = undefined;
577
606
  }
578
- const disconnectResponse = await fetch(`${this.#cloudInteropSettings.url}/api/sessions/${this.#sessionDetails.sessionId}`, {
607
+ const disconnectResponse = await this.#authenticatedFetch(`${this.#cloudInteropSettings.url}/api/sessions/${this.#sessionDetails.sessionId}`, {
579
608
  method: 'DELETE',
580
- headers: await getRequestHeaders(this.#connectionParams),
581
609
  });
582
610
  if (disconnectResponse.status !== 200) {
583
611
  throw new CloudInteropAPIError('Error during session tear down - unexpected status', 'ERR_DISCONNECT', new Error(disconnectResponse.statusText));
@@ -659,10 +687,35 @@ class CloudInteropAPI {
659
687
  (!parameters.basicAuthenticationParameters?.username || !parameters.basicAuthenticationParameters?.password)) {
660
688
  throw new Error('basicAuthenticationParameters must be provided when using basic authentication');
661
689
  }
690
+ if (parameters.authenticationType === 'oauth') {
691
+ if (!parameters.oauthAuthenticationParameters?.clientId?.trim() || !parameters.oauthAuthenticationParameters?.clientSecret?.trim()) {
692
+ throw new OAuthAuthenticationError('oauthAuthenticationParameters must be provided when using oauth authentication');
693
+ }
694
+ try {
695
+ $n(parameters.oauthAuthenticationParameters);
696
+ }
697
+ catch (error) {
698
+ rethrowAsOAuthAuthenticationError(error);
699
+ }
700
+ }
662
701
  };
663
- #initControllers(mqttClient, sessionDetails, connectionParameters) {
664
- this.#intents = new IntentController(this.#cloudInteropSettings.url, mqttClient, sessionDetails, connectionParameters, this.#events, this.#logger);
702
+ #initControllers(mqttClient, sessionDetails) {
703
+ this.#intents = new IntentController(this.#cloudInteropSettings.url, mqttClient, sessionDetails, this.#authenticatedFetch, this.#events, this.#logger);
665
704
  }
705
+ #authenticatedFetch = async (url, { method, body }) => {
706
+ const connectionParameters = this.#connectionParams;
707
+ if (!connectionParameters) {
708
+ throw new Error('Connect parameters must be provided');
709
+ }
710
+ const attempt = async () => {
711
+ const headers = await getRequestHeaders(connectionParameters, this.#tokenClient);
712
+ return fetch(url, { method, headers, body });
713
+ };
714
+ if (connectionParameters.authenticationType === 'oauth' && this.#tokenClient) {
715
+ return Fn(this.#tokenClient, attempt);
716
+ }
717
+ return attempt();
718
+ };
666
719
  #destroyControllers() {
667
720
  this.#intents = undefined;
668
721
  }
@@ -690,8 +743,8 @@ class CloudInteropAPI {
690
743
  return null;
691
744
  }
692
745
  const payload = parts[1];
693
- // Decode base64url encoded payload
694
- const decodedBytes = buffer.Buffer.from(d(payload), 'base64');
746
+ // 'base64' also decodes unpadded base64url. The browser `buffer` polyfill has no 'base64url' encoding.
747
+ const decodedBytes = buffer.Buffer.from(payload, 'base64');
695
748
  const payloadJson = decodedBytes.toString('utf8');
696
749
  // Parse JSON to get the exp claim
697
750
  const claims = JSON.parse(payloadJson);
@@ -752,12 +805,21 @@ class CloudInteropAPI {
752
805
  * Handles session expiry by executing the same actions as the BadUserNamePasswordError case.
753
806
  */
754
807
  async #handleSessionExpiry() {
755
- await this.#disconnect(false);
808
+ await this.#disconnectAndLogFailure();
756
809
  this.#logger('warn', 'Session expired');
757
810
  this.#events.emitEvent('session-expired');
758
811
  }
812
+ async #disconnectAndLogFailure(fireDisconnectedEvent = false) {
813
+ try {
814
+ await this.#disconnect(fireDisconnectedEvent);
815
+ }
816
+ catch (error) {
817
+ this.#logger('error', `Session teardown failed: ${error instanceof Error ? error.message : String(error)}`);
818
+ }
819
+ }
759
820
  }
760
821
 
761
822
  exports.AuthorizationError = AuthorizationError;
762
823
  exports.CloudInteropAPI = CloudInteropAPI;
763
824
  exports.CloudInteropAPIError = CloudInteropAPIError;
825
+ exports.OAuthAuthenticationError = OAuthAuthenticationError;
package/index.mjs CHANGED
@@ -1,9 +1,7 @@
1
1
  import { Buffer } from 'buffer';
2
- import 'fs';
3
- import 'path';
4
2
  import mqtt from 'mqtt';
5
3
 
6
- var d=n=>{let t=n.replaceAll("-","+").replaceAll("_","/");return t.padEnd(t.length+(4-t.length%4)%4,"=")};
4
+ 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="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,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,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);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)}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,o);return}throw l(`${n} must be a positive number`,y,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,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);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)}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
5
 
8
6
  class CloudInteropAPIError extends Error {
9
7
  code;
@@ -18,6 +16,21 @@ class AuthorizationError extends CloudInteropAPIError {
18
16
  super(message, code, undefined);
19
17
  }
20
18
  }
19
+ class OAuthAuthenticationError extends CloudInteropAPIError {
20
+ constructor(message, cause) {
21
+ super(message, 'ERR_OAUTH', cause);
22
+ }
23
+ }
24
+
25
+ const rethrowAsOAuthAuthenticationError = (error) => {
26
+ if (error instanceof w) {
27
+ throw new OAuthAuthenticationError(error.message, error);
28
+ }
29
+ if (error instanceof TypeError) {
30
+ throw new OAuthAuthenticationError('OAuth access token could not be obtained', error);
31
+ }
32
+ throw error;
33
+ };
21
34
 
22
35
  class EventController {
23
36
  #eventListeners = new Map();
@@ -51,9 +64,18 @@ class EventController {
51
64
  const isErrorIntentResult = (result) => 'error' in result;
52
65
 
53
66
  const APP_ID_DELIM = '::';
54
- const getRequestHeaders = async (connectionParameters) => {
67
+ const getRequestHeaders = async (connectionParameters, tokenClient) => {
55
68
  const headers = {};
56
69
  headers['Content-Type'] = 'application/json';
70
+ if (connectionParameters.authenticationType === 'oauth' && tokenClient) {
71
+ try {
72
+ const accessToken = await tokenClient.getAccessToken();
73
+ headers['Authorization'] = `Bearer ${accessToken}`;
74
+ }
75
+ catch (error) {
76
+ rethrowAsOAuthAuthenticationError(error);
77
+ }
78
+ }
57
79
  if (connectionParameters.authenticationType === 'jwt' && connectionParameters.jwtAuthenticationParameters) {
58
80
  const tokenResult = await connectionParameters.jwtAuthenticationParameters.jwtRequestCallback();
59
81
  if (!tokenResult) {
@@ -137,16 +159,16 @@ class IntentController {
137
159
  #url;
138
160
  #mqttClient;
139
161
  #sessionDetails;
140
- #connectionParams;
162
+ #authenticatedFetch;
141
163
  #events;
142
164
  #logger;
143
165
  #discovery = newDiscovery();
144
166
  #discoveryTimeout;
145
- constructor(url, mqttClient, sessionDetails, connectionParameters, events, logger) {
167
+ constructor(url, mqttClient, sessionDetails, authenticatedFetch, events, logger) {
146
168
  this.#url = url;
147
169
  this.#mqttClient = mqttClient;
148
170
  this.#sessionDetails = sessionDetails;
149
- this.#connectionParams = connectionParameters;
171
+ this.#authenticatedFetch = authenticatedFetch;
150
172
  this.#events = events;
151
173
  this.#logger = logger;
152
174
  }
@@ -158,9 +180,8 @@ class IntentController {
158
180
  // clamp min value to 500ms
159
181
  const clampedTimeout = Math.max(timeout, MIN_TIMEOUT);
160
182
  try {
161
- const startResponse = await fetch(`${this.#url}/api/intents/${this.#sessionDetails.sessionId}`, {
183
+ const startResponse = await this.#authenticatedFetch(`${this.#url}/api/intents/${this.#sessionDetails.sessionId}`, {
162
184
  method: 'POST',
163
- headers: await getRequestHeaders(this.#connectionParams),
164
185
  body: JSON.stringify({ findOptions }),
165
186
  });
166
187
  if (!startResponse.ok) {
@@ -203,9 +224,8 @@ class IntentController {
203
224
  this.#logger('warn', `Error ending intent discovery: could not unsubscribe from discovery id ${this.#discovery.id}`);
204
225
  });
205
226
  }
206
- await fetch(`${this.#url}/api/intents/${this.#sessionDetails.sessionId}/${this.#discovery.id}`, {
227
+ await this.#authenticatedFetch(`${this.#url}/api/intents/${this.#sessionDetails.sessionId}/${this.#discovery.id}`, {
207
228
  method: 'DELETE',
208
- headers: await getRequestHeaders(this.#connectionParams),
209
229
  })
210
230
  .then((deleteResponse) => {
211
231
  if (!deleteResponse.ok) {
@@ -224,9 +244,8 @@ class IntentController {
224
244
  // TODO: should we add more info here about the format?
225
245
  throw new CloudInteropAPIError(`Invalid AppId specified, must be encoded as a cloud-session app id`, 'ERR_INVALID_TARGET_SESSION_ID');
226
246
  }
227
- const postResponse = await fetch(`${this.#url}/api/intents/${this.#sessionDetails.sessionId}/sessions/${targetSessionId}`, {
247
+ const postResponse = await this.#authenticatedFetch(`${this.#url}/api/intents/${this.#sessionDetails.sessionId}/sessions/${targetSessionId}`, {
228
248
  method: 'POST',
229
- headers: await getRequestHeaders(this.#connectionParams),
230
249
  body: JSON.stringify({ raiseOptions }),
231
250
  });
232
251
  if (!postResponse.ok) {
@@ -238,9 +257,8 @@ class IntentController {
238
257
  async reportAppIntents(discoveryId, intents) {
239
258
  intents = encodeAppIntents(intents, getSourceFromSession(this.#sessionDetails));
240
259
  try {
241
- const reportResponse = await fetch(`${this.#url}/api/intents/${this.#sessionDetails.sessionId}/${discoveryId}`, {
260
+ const reportResponse = await this.#authenticatedFetch(`${this.#url}/api/intents/${this.#sessionDetails.sessionId}/${discoveryId}`, {
242
261
  method: 'POST',
243
- headers: await getRequestHeaders(this.#connectionParams),
244
262
  body: JSON.stringify({ intents }),
245
263
  });
246
264
  if (reportResponse.ok) {
@@ -262,9 +280,8 @@ class IntentController {
262
280
  result.source = typeof result.source === 'string' ? encoded : { ...result.source, appId: encoded };
263
281
  }
264
282
  const { sessionId } = getSourceFromSession(this.#sessionDetails);
265
- const resultResponse = await fetch(`${this.#url}/api/intents/${initiatingSessionId}/result/${sessionId}`, {
283
+ const resultResponse = await this.#authenticatedFetch(`${this.#url}/api/intents/${initiatingSessionId}/result/${sessionId}`, {
266
284
  method: 'POST',
267
- headers: await getRequestHeaders(this.#connectionParams),
268
285
  body: JSON.stringify({ result }),
269
286
  });
270
287
  if (!resultResponse.ok) {
@@ -353,6 +370,7 @@ class CloudInteropAPI {
353
370
  };
354
371
  #reconnectRetries = 0;
355
372
  #connectionParams;
373
+ #tokenClient;
356
374
  #attemptingToReconnect = false;
357
375
  #events = new EventController();
358
376
  #intents;
@@ -374,17 +392,29 @@ class CloudInteropAPI {
374
392
  * @memberof CloudInteropAPI
375
393
  * @throws CloudInteropAPIError - If an error occurs during connection
376
394
  * @throws AuthorizationError - If the connection is unauthorized
395
+ * @throws OAuthAuthenticationError - If OAuth parameters are invalid, the client credentials are rejected, or an access token cannot be obtained
377
396
  */
378
397
  async connect(parameters) {
379
398
  this.#validateConnectParams(parameters);
399
+ const oauthParameters = parameters.oauthAuthenticationParameters;
400
+ if (parameters.authenticationType === 'oauth' && oauthParameters) {
401
+ try {
402
+ this.#tokenClient = Je.fromServiceUrl(this.#cloudInteropSettings.url, oauthParameters.clientId, oauthParameters.clientSecret);
403
+ }
404
+ catch (error) {
405
+ rethrowAsOAuthAuthenticationError(error);
406
+ }
407
+ }
408
+ else {
409
+ this.#tokenClient = undefined;
410
+ }
380
411
  this.#connectionParams = parameters;
381
412
  this.#reconnectRetryLimit = parameters.reconnectRetryLimit || this.#reconnectRetryLimit;
382
413
  this.#keepAliveIntervalSeconds = parameters.keepAliveIntervalSeconds || this.#keepAliveIntervalSeconds;
383
414
  this.#logger = parameters.logger || this.#logger;
384
415
  const { sourceId, platformId } = this.#connectionParams;
385
- const createSessionResponse = await fetch(`${this.#cloudInteropSettings.url}/api/sessions`, {
416
+ const createSessionResponse = await this.#authenticatedFetch(`${this.#cloudInteropSettings.url}/api/sessions`, {
386
417
  method: 'POST',
387
- headers: await getRequestHeaders(this.#connectionParams),
388
418
  body: JSON.stringify({ sourceId: sourceId.trim(), platformId }),
389
419
  });
390
420
  if (!createSessionResponse.ok) {
@@ -427,7 +457,7 @@ class CloudInteropAPI {
427
457
  // We will receive errors for each failed reconnection attempt
428
458
  // We don't want to disconnect on these else we will never reconnect
429
459
  if (!this.#attemptingToReconnect) {
430
- await this.#disconnect(false);
460
+ await this.#disconnectAndLogFailure();
431
461
  }
432
462
  if (error instanceof mqtt.ErrorWithReasonCode) {
433
463
  switch (error.code) {
@@ -453,15 +483,15 @@ class CloudInteropAPI {
453
483
  }
454
484
  }
455
485
  });
456
- this.#mqttClient.on('reconnect', () => {
486
+ this.#mqttClient.on('reconnect', async () => {
457
487
  this.#attemptingToReconnect = true;
458
488
  this.#reconnectRetries += 1;
459
489
  this.#logger('debug', `Cloud Interop attempting reconnection - ${this.#reconnectRetries}...`);
490
+ this.#events.emitEvent('reconnecting', this.#reconnectRetries);
460
491
  if (this.#reconnectRetries === this.#reconnectRetryLimit) {
461
492
  this.#logger('warn', `Cloud Interop reached max reconnection attempts - ${this.#reconnectRetryLimit}...`);
462
- this.#disconnect(true);
493
+ await this.#disconnectAndLogFailure(true);
463
494
  }
464
- this.#events.emitEvent('reconnecting', this.#reconnectRetries);
465
495
  });
466
496
  // Does not fire on initial connection, only successful reconnection attempts
467
497
  this.#mqttClient.on('connect', () => {
@@ -481,7 +511,7 @@ class CloudInteropAPI {
481
511
  this.#mqttClient.subscribe(`${sessionRootTopic}/context-groups/#`);
482
512
  // Listen out for global commands
483
513
  this.#mqttClient.subscribe(`${sessionRootTopic}/commands`);
484
- this.#initControllers(this.#mqttClient, this.#sessionDetails, this.#connectionParams);
514
+ this.#initControllers(this.#mqttClient, this.#sessionDetails);
485
515
  }
486
516
  /**
487
517
  * Disconnects from the Cloud Interop service
@@ -513,9 +543,8 @@ class CloudInteropAPI {
513
543
  context,
514
544
  timestamp: Date.now(),
515
545
  };
516
- const postResponse = await fetch(`${this.#cloudInteropSettings.url}/api/context-groups/${this.#sessionDetails.sessionId}/${contextGroup}`, {
546
+ const postResponse = await this.#authenticatedFetch(`${this.#cloudInteropSettings.url}/api/context-groups/${this.#sessionDetails.sessionId}/${contextGroup}`, {
517
547
  method: 'POST',
518
- headers: await getRequestHeaders(this.#connectionParams),
519
548
  body: JSON.stringify(payload),
520
549
  });
521
550
  if (!postResponse.ok) {
@@ -573,9 +602,8 @@ class CloudInteropAPI {
573
602
  clearTimeout(this.#sessionTimer);
574
603
  this.#sessionTimer = undefined;
575
604
  }
576
- const disconnectResponse = await fetch(`${this.#cloudInteropSettings.url}/api/sessions/${this.#sessionDetails.sessionId}`, {
605
+ const disconnectResponse = await this.#authenticatedFetch(`${this.#cloudInteropSettings.url}/api/sessions/${this.#sessionDetails.sessionId}`, {
577
606
  method: 'DELETE',
578
- headers: await getRequestHeaders(this.#connectionParams),
579
607
  });
580
608
  if (disconnectResponse.status !== 200) {
581
609
  throw new CloudInteropAPIError('Error during session tear down - unexpected status', 'ERR_DISCONNECT', new Error(disconnectResponse.statusText));
@@ -657,10 +685,35 @@ class CloudInteropAPI {
657
685
  (!parameters.basicAuthenticationParameters?.username || !parameters.basicAuthenticationParameters?.password)) {
658
686
  throw new Error('basicAuthenticationParameters must be provided when using basic authentication');
659
687
  }
688
+ if (parameters.authenticationType === 'oauth') {
689
+ if (!parameters.oauthAuthenticationParameters?.clientId?.trim() || !parameters.oauthAuthenticationParameters?.clientSecret?.trim()) {
690
+ throw new OAuthAuthenticationError('oauthAuthenticationParameters must be provided when using oauth authentication');
691
+ }
692
+ try {
693
+ $n(parameters.oauthAuthenticationParameters);
694
+ }
695
+ catch (error) {
696
+ rethrowAsOAuthAuthenticationError(error);
697
+ }
698
+ }
660
699
  };
661
- #initControllers(mqttClient, sessionDetails, connectionParameters) {
662
- this.#intents = new IntentController(this.#cloudInteropSettings.url, mqttClient, sessionDetails, connectionParameters, this.#events, this.#logger);
700
+ #initControllers(mqttClient, sessionDetails) {
701
+ this.#intents = new IntentController(this.#cloudInteropSettings.url, mqttClient, sessionDetails, this.#authenticatedFetch, this.#events, this.#logger);
663
702
  }
703
+ #authenticatedFetch = async (url, { method, body }) => {
704
+ const connectionParameters = this.#connectionParams;
705
+ if (!connectionParameters) {
706
+ throw new Error('Connect parameters must be provided');
707
+ }
708
+ const attempt = async () => {
709
+ const headers = await getRequestHeaders(connectionParameters, this.#tokenClient);
710
+ return fetch(url, { method, headers, body });
711
+ };
712
+ if (connectionParameters.authenticationType === 'oauth' && this.#tokenClient) {
713
+ return Fn(this.#tokenClient, attempt);
714
+ }
715
+ return attempt();
716
+ };
664
717
  #destroyControllers() {
665
718
  this.#intents = undefined;
666
719
  }
@@ -688,8 +741,8 @@ class CloudInteropAPI {
688
741
  return null;
689
742
  }
690
743
  const payload = parts[1];
691
- // Decode base64url encoded payload
692
- const decodedBytes = Buffer.from(d(payload), 'base64');
744
+ // 'base64' also decodes unpadded base64url. The browser `buffer` polyfill has no 'base64url' encoding.
745
+ const decodedBytes = Buffer.from(payload, 'base64');
693
746
  const payloadJson = decodedBytes.toString('utf8');
694
747
  // Parse JSON to get the exp claim
695
748
  const claims = JSON.parse(payloadJson);
@@ -750,10 +803,18 @@ class CloudInteropAPI {
750
803
  * Handles session expiry by executing the same actions as the BadUserNamePasswordError case.
751
804
  */
752
805
  async #handleSessionExpiry() {
753
- await this.#disconnect(false);
806
+ await this.#disconnectAndLogFailure();
754
807
  this.#logger('warn', 'Session expired');
755
808
  this.#events.emitEvent('session-expired');
756
809
  }
810
+ async #disconnectAndLogFailure(fireDisconnectedEvent = false) {
811
+ try {
812
+ await this.#disconnect(fireDisconnectedEvent);
813
+ }
814
+ catch (error) {
815
+ this.#logger('error', `Session teardown failed: ${error instanceof Error ? error.message : String(error)}`);
816
+ }
817
+ }
757
818
  }
758
819
 
759
- export { AuthorizationError, CloudInteropAPI, CloudInteropAPIError };
820
+ 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": "15.2.15",
3
+ "version": "16.0.0",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "main": "./index.cjs",
@@ -9,7 +9,7 @@
9
9
  "author": "support@here.io",
10
10
  "license": "SEE LICENSE IN LICENSE.md",
11
11
  "dependencies": {
12
- "mqtt": "catalog:",
13
- "zod": "catalog:"
12
+ "mqtt": "^5.15.2",
13
+ "zod": "^3.25.76"
14
14
  }
15
15
  }