@openfin/cloud-interop-core-api 0.0.1-alpha.3e5906a → 0.0.1-alpha.3e8a7a5

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
@@ -1,14 +1,15 @@
1
1
  # @openfin/cloud-interop-core-api
2
2
 
3
- This package contains the core interop library that handles all interactions with the Here™ Cloud Interop Service.
3
+ This package contains the core interop library that handles all interactions with the HERE Cloud Interop Service.
4
4
 
5
5
  It is callable via browser or node applications.
6
6
 
7
7
 
8
8
  ## Authentication
9
9
 
10
- The library supports authentication with the Here™ Cloud Interop Service using the following methods:
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
@@ -245,36 +245,37 @@ export declare class CloudInteropAPI {
245
245
  /**
246
246
  * Connects and creates a session on the Cloud Interop service
247
247
  *
248
- * @param {ConnectParameters} parameters - The parameters to use to connect
249
- * @returns {*} {Promise<void>}
248
+ * @param parameters - The parameters to use to connect
249
+ * @returns Promise that resolves when connection is established
250
250
  * @memberof CloudInteropAPI
251
- * @throws {CloudInteropAPIError} - If an error occurs during connection
252
- * @throws {AuthorizationError} - If the connection is unauthorized
251
+ * @throws CloudInteropAPIError - If an error occurs during connection
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
  /**
256
257
  * Disconnects from the Cloud Interop service
257
258
  *
258
- * @returns {*} {Promise<void>}
259
+ * @returns Promise that resolves when disconnected
259
260
  * @memberof CloudInteropAPI
260
- * @throws {CloudInteropAPIError} - If an error occurs during disconnection
261
+ * @throws CloudInteropAPIError - If an error occurs during disconnection
261
262
  */
262
263
  disconnect(): Promise<void>;
263
264
  /**
264
265
  * Publishes a new context for the given context group to the other connected sessions
265
266
  *
266
- * @param {string} contextGroup - The context group to publish to
267
- * @param {object} context - The context to publish
268
- * @returns {*} {Promise<void>}
267
+ * @param contextGroup - The context group to publish to
268
+ * @param context - The context to publish
269
+ * @returns Promise that resolves when context is published
269
270
  * @memberof CloudInteropAPI
270
271
  */
271
272
  setContext(contextGroup: string, context: InferredContext): Promise<void>;
272
273
  /**
273
274
  * Starts an intent discovery operation
274
275
  *
275
- * @returns {*} {Promise<void>}
276
+ * @returns Promise that resolves when intent discovery is started
276
277
  * @memberof CloudInteropAPI
277
- * @throws {CloudInteropAPIError} - If an error occurs during intent discovery
278
+ * @throws CloudInteropAPIError - If an error occurs during intent discovery
278
279
  */
279
280
  startIntentDiscovery(options: StartIntentDiscoveryOptions): Promise<void>;
280
281
  raiseIntent(options: RaiseIntentAPIOptions): Promise<void>;
@@ -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
  /**
@@ -418,6 +425,7 @@ export declare type CreateSessionResponse = {
418
425
  sub: string;
419
426
  platformId: string;
420
427
  sourceId: string;
428
+ localSessionExpiryHandling?: boolean;
421
429
  };
422
430
 
423
431
  declare const errorSchema: z.ZodObject<{
@@ -713,6 +721,40 @@ declare const intentResultSchema: z.ZodUnion<[z.ZodObject<{
713
721
 
714
722
  export declare type LogLevel = 'log' | 'debug' | 'info' | 'warn' | 'error';
715
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
+
716
758
  /**
717
759
  * Options used to raise an Intent
718
760
  * @public
package/index.cjs CHANGED
@@ -1,8 +1,14 @@
1
1
  'use strict';
2
2
 
3
3
  var buffer = require('buffer');
4
+ require('fs');
5
+ require('path');
4
6
  var mqtt = require('mqtt');
5
7
 
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,"=")};
11
+
6
12
  class CloudInteropAPIError extends Error {
7
13
  code;
8
14
  constructor(message = 'An unexpected error has occurred', code = 'UNEXPECTED_ERROR', cause) {
@@ -16,6 +22,21 @@ class AuthorizationError extends CloudInteropAPIError {
16
22
  super(message, code, undefined);
17
23
  }
18
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
+ };
19
40
 
20
41
  class EventController {
21
42
  #eventListeners = new Map();
@@ -49,11 +70,20 @@ class EventController {
49
70
  const isErrorIntentResult = (result) => 'error' in result;
50
71
 
51
72
  const APP_ID_DELIM = '::';
52
- const getRequestHeaders = (connectionParameters) => {
73
+ const getRequestHeaders = async (connectionParameters, tokenClient) => {
53
74
  const headers = {};
54
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
+ }
55
85
  if (connectionParameters.authenticationType === 'jwt' && connectionParameters.jwtAuthenticationParameters) {
56
- const tokenResult = connectionParameters.jwtAuthenticationParameters.jwtRequestCallback();
86
+ const tokenResult = await connectionParameters.jwtAuthenticationParameters.jwtRequestCallback();
57
87
  if (!tokenResult) {
58
88
  throw new Error('jwtRequestCallback must return a token');
59
89
  }
@@ -135,16 +165,16 @@ class IntentController {
135
165
  #url;
136
166
  #mqttClient;
137
167
  #sessionDetails;
138
- #connectionParams;
168
+ #authenticatedFetch;
139
169
  #events;
140
170
  #logger;
141
171
  #discovery = newDiscovery();
142
172
  #discoveryTimeout;
143
- constructor(url, mqttClient, sessionDetails, connectionParameters, events, logger) {
173
+ constructor(url, mqttClient, sessionDetails, authenticatedFetch, events, logger) {
144
174
  this.#url = url;
145
175
  this.#mqttClient = mqttClient;
146
176
  this.#sessionDetails = sessionDetails;
147
- this.#connectionParams = connectionParameters;
177
+ this.#authenticatedFetch = authenticatedFetch;
148
178
  this.#events = events;
149
179
  this.#logger = logger;
150
180
  }
@@ -156,9 +186,8 @@ class IntentController {
156
186
  // clamp min value to 500ms
157
187
  const clampedTimeout = Math.max(timeout, MIN_TIMEOUT);
158
188
  try {
159
- const startResponse = await fetch(`${this.#url}/api/intents/${this.#sessionDetails.sessionId}`, {
189
+ const startResponse = await this.#authenticatedFetch(`${this.#url}/api/intents/${this.#sessionDetails.sessionId}`, {
160
190
  method: 'POST',
161
- headers: getRequestHeaders(this.#connectionParams),
162
191
  body: JSON.stringify({ findOptions }),
163
192
  });
164
193
  if (!startResponse.ok) {
@@ -201,9 +230,8 @@ class IntentController {
201
230
  this.#logger('warn', `Error ending intent discovery: could not unsubscribe from discovery id ${this.#discovery.id}`);
202
231
  });
203
232
  }
204
- 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}`, {
205
234
  method: 'DELETE',
206
- headers: getRequestHeaders(this.#connectionParams),
207
235
  })
208
236
  .then((deleteResponse) => {
209
237
  if (!deleteResponse.ok) {
@@ -222,9 +250,8 @@ class IntentController {
222
250
  // TODO: should we add more info here about the format?
223
251
  throw new CloudInteropAPIError(`Invalid AppId specified, must be encoded as a cloud-session app id`, 'ERR_INVALID_TARGET_SESSION_ID');
224
252
  }
225
- 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}`, {
226
254
  method: 'POST',
227
- headers: getRequestHeaders(this.#connectionParams),
228
255
  body: JSON.stringify({ raiseOptions }),
229
256
  });
230
257
  if (!postResponse.ok) {
@@ -236,9 +263,8 @@ class IntentController {
236
263
  async reportAppIntents(discoveryId, intents) {
237
264
  intents = encodeAppIntents(intents, getSourceFromSession(this.#sessionDetails));
238
265
  try {
239
- 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}`, {
240
267
  method: 'POST',
241
- headers: getRequestHeaders(this.#connectionParams),
242
268
  body: JSON.stringify({ intents }),
243
269
  });
244
270
  if (reportResponse.ok) {
@@ -260,9 +286,8 @@ class IntentController {
260
286
  result.source = typeof result.source === 'string' ? encoded : { ...result.source, appId: encoded };
261
287
  }
262
288
  const { sessionId } = getSourceFromSession(this.#sessionDetails);
263
- const resultResponse = await fetch(`${this.#url}/api/intents/${initiatingSessionId}/result/${sessionId}`, {
289
+ const resultResponse = await this.#authenticatedFetch(`${this.#url}/api/intents/${initiatingSessionId}/result/${sessionId}`, {
264
290
  method: 'POST',
265
- headers: getRequestHeaders(this.#connectionParams),
266
291
  body: JSON.stringify({ result }),
267
292
  });
268
293
  if (!resultResponse.ok) {
@@ -346,13 +371,16 @@ class CloudInteropAPI {
346
371
  #reconnectRetryLimit = 30;
347
372
  #keepAliveIntervalSeconds = 30;
348
373
  #logger = (level, message) => {
374
+ // eslint-disable-next-line security/detect-object-injection -- level is restricted to the LogLevel union
349
375
  console[level](message);
350
376
  };
351
377
  #reconnectRetries = 0;
352
378
  #connectionParams;
379
+ #tokenClient;
353
380
  #attemptingToReconnect = false;
354
381
  #events = new EventController();
355
382
  #intents;
383
+ #sessionTimer;
356
384
  constructor(cloudInteropSettings) {
357
385
  this.#cloudInteropSettings = cloudInteropSettings;
358
386
  }
@@ -365,22 +393,34 @@ class CloudInteropAPI {
365
393
  /**
366
394
  * Connects and creates a session on the Cloud Interop service
367
395
  *
368
- * @param {ConnectParameters} parameters - The parameters to use to connect
369
- * @returns {*} {Promise<void>}
396
+ * @param parameters - The parameters to use to connect
397
+ * @returns Promise that resolves when connection is established
370
398
  * @memberof CloudInteropAPI
371
- * @throws {CloudInteropAPIError} - If an error occurs during connection
372
- * @throws {AuthorizationError} - If the connection is unauthorized
399
+ * @throws CloudInteropAPIError - If an error occurs during connection
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
373
402
  */
374
403
  async connect(parameters) {
375
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
+ }
376
417
  this.#connectionParams = parameters;
377
418
  this.#reconnectRetryLimit = parameters.reconnectRetryLimit || this.#reconnectRetryLimit;
378
419
  this.#keepAliveIntervalSeconds = parameters.keepAliveIntervalSeconds || this.#keepAliveIntervalSeconds;
379
420
  this.#logger = parameters.logger || this.#logger;
380
421
  const { sourceId, platformId } = this.#connectionParams;
381
- const createSessionResponse = await fetch(`${this.#cloudInteropSettings.url}/api/sessions`, {
422
+ const createSessionResponse = await this.#authenticatedFetch(`${this.#cloudInteropSettings.url}/api/sessions`, {
382
423
  method: 'POST',
383
- headers: getRequestHeaders(this.#connectionParams),
384
424
  body: JSON.stringify({ sourceId: sourceId.trim(), platformId }),
385
425
  });
386
426
  if (!createSessionResponse.ok) {
@@ -393,6 +433,11 @@ class CloudInteropAPI {
393
433
  throw new CloudInteropAPIError(`Failed to connect to the Cloud Interop service: ${this.#cloudInteropSettings.url}`, 'ERR_CONNECT', new Error(createSessionResponse.statusText));
394
434
  }
395
435
  this.#sessionDetails = (await createSessionResponse.json());
436
+ // If local session expiry handling is enabled, start the session timer
437
+ if (this.#sessionDetails.localSessionExpiryHandling) {
438
+ this.#logger('debug', `Local session expiry handling is enabled`);
439
+ this.#startSessionTimer();
440
+ }
396
441
  const sessionRootTopic = this.#sessionDetails.sessionRootTopic;
397
442
  const clientOptions = {
398
443
  keepalive: this.#keepAliveIntervalSeconds,
@@ -413,18 +458,17 @@ class CloudInteropAPI {
413
458
  // TODO: Dynamic intent discovery
414
459
  // search for any ongoing discoveries in DB and fire report-intents on self
415
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
416
462
  this.#mqttClient.on('error', async (error) => {
417
463
  // We will receive errors for each failed reconnection attempt
418
464
  // We don't want to disconnect on these else we will never reconnect
419
465
  if (!this.#attemptingToReconnect) {
420
- await this.#disconnect(false);
466
+ await this.#disconnectAndLogFailure();
421
467
  }
422
468
  if (error instanceof mqtt.ErrorWithReasonCode) {
423
469
  switch (error.code) {
424
470
  case BadUserNamePasswordError: {
425
- await this.#disconnect(false);
426
- this.#logger('warn', `Session expired`);
427
- this.#events.emitEvent('session-expired');
471
+ this.#handleSessionExpiry();
428
472
  return;
429
473
  }
430
474
  default: {
@@ -445,15 +489,15 @@ class CloudInteropAPI {
445
489
  }
446
490
  }
447
491
  });
448
- this.#mqttClient.on('reconnect', () => {
492
+ this.#mqttClient.on('reconnect', async () => {
449
493
  this.#attemptingToReconnect = true;
450
494
  this.#reconnectRetries += 1;
451
495
  this.#logger('debug', `Cloud Interop attempting reconnection - ${this.#reconnectRetries}...`);
496
+ this.#events.emitEvent('reconnecting', this.#reconnectRetries);
452
497
  if (this.#reconnectRetries === this.#reconnectRetryLimit) {
453
498
  this.#logger('warn', `Cloud Interop reached max reconnection attempts - ${this.#reconnectRetryLimit}...`);
454
- this.#disconnect(true);
499
+ await this.#disconnectAndLogFailure(true);
455
500
  }
456
- this.#events.emitEvent('reconnecting', this.#reconnectRetries);
457
501
  });
458
502
  // Does not fire on initial connection, only successful reconnection attempts
459
503
  this.#mqttClient.on('connect', () => {
@@ -473,14 +517,14 @@ class CloudInteropAPI {
473
517
  this.#mqttClient.subscribe(`${sessionRootTopic}/context-groups/#`);
474
518
  // Listen out for global commands
475
519
  this.#mqttClient.subscribe(`${sessionRootTopic}/commands`);
476
- this.#initControllers(this.#mqttClient, this.#sessionDetails, this.#connectionParams);
520
+ this.#initControllers(this.#mqttClient, this.#sessionDetails);
477
521
  }
478
522
  /**
479
523
  * Disconnects from the Cloud Interop service
480
524
  *
481
- * @returns {*} {Promise<void>}
525
+ * @returns Promise that resolves when disconnected
482
526
  * @memberof CloudInteropAPI
483
- * @throws {CloudInteropAPIError} - If an error occurs during disconnection
527
+ * @throws CloudInteropAPIError - If an error occurs during disconnection
484
528
  */
485
529
  async disconnect() {
486
530
  await this.#disconnect(true);
@@ -488,9 +532,9 @@ class CloudInteropAPI {
488
532
  /**
489
533
  * Publishes a new context for the given context group to the other connected sessions
490
534
  *
491
- * @param {string} contextGroup - The context group to publish to
492
- * @param {object} context - The context to publish
493
- * @returns {*} {Promise<void>}
535
+ * @param contextGroup - The context group to publish to
536
+ * @param context - The context to publish
537
+ * @returns Promise that resolves when context is published
494
538
  * @memberof CloudInteropAPI
495
539
  */
496
540
  async setContext(contextGroup, context) {
@@ -505,9 +549,8 @@ class CloudInteropAPI {
505
549
  context,
506
550
  timestamp: Date.now(),
507
551
  };
508
- 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}`, {
509
553
  method: 'POST',
510
- headers: getRequestHeaders(this.#connectionParams),
511
554
  body: JSON.stringify(payload),
512
555
  });
513
556
  if (!postResponse.ok) {
@@ -517,9 +560,9 @@ class CloudInteropAPI {
517
560
  /**
518
561
  * Starts an intent discovery operation
519
562
  *
520
- * @returns {*} {Promise<void>}
563
+ * @returns Promise that resolves when intent discovery is started
521
564
  * @memberof CloudInteropAPI
522
- * @throws {CloudInteropAPIError} - If an error occurs during intent discovery
565
+ * @throws CloudInteropAPIError - If an error occurs during intent discovery
523
566
  */
524
567
  async startIntentDiscovery(options) {
525
568
  this.#throwIfNotConnected();
@@ -560,9 +603,13 @@ class CloudInteropAPI {
560
603
  if (!this.#connectionParams) {
561
604
  throw new Error('Connect parameters must be provided');
562
605
  }
563
- const disconnectResponse = await fetch(`${this.#cloudInteropSettings.url}/api/sessions/${this.#sessionDetails.sessionId}`, {
606
+ // Cancel session timer if it's running
607
+ if (this.#sessionTimer) {
608
+ clearTimeout(this.#sessionTimer);
609
+ this.#sessionTimer = undefined;
610
+ }
611
+ const disconnectResponse = await this.#authenticatedFetch(`${this.#cloudInteropSettings.url}/api/sessions/${this.#sessionDetails.sessionId}`, {
564
612
  method: 'DELETE',
565
- headers: getRequestHeaders(this.#connectionParams),
566
613
  });
567
614
  if (disconnectResponse.status !== 200) {
568
615
  throw new CloudInteropAPIError('Error during session tear down - unexpected status', 'ERR_DISCONNECT', new Error(disconnectResponse.statusText));
@@ -585,6 +632,7 @@ class CloudInteropAPI {
585
632
  }
586
633
  }
587
634
  #handleMessage(topic, message, sessionDetails) {
635
+ this.#logger('debug', `Received message on topic: ${topic}`);
588
636
  if (message.length === 0 || !sessionDetails) {
589
637
  // Ignore clean up messages
590
638
  return;
@@ -643,10 +691,35 @@ class CloudInteropAPI {
643
691
  (!parameters.basicAuthenticationParameters?.username || !parameters.basicAuthenticationParameters?.password)) {
644
692
  throw new Error('basicAuthenticationParameters must be provided when using basic authentication');
645
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
+ }
646
705
  };
647
- #initControllers(mqttClient, sessionDetails, connectionParameters) {
648
- 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);
649
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
+ };
650
723
  #destroyControllers() {
651
724
  this.#intents = undefined;
652
725
  }
@@ -658,8 +731,99 @@ class CloudInteropAPI {
658
731
  throw new Error('MQTT client not connected');
659
732
  }
660
733
  }
734
+ /**
735
+ * Extracts the expiration timestamp from a JWT token.
736
+ *
737
+ * @param token - The JWT token string
738
+ * @returns The expiration timestamp in seconds, or null if extraction fails
739
+ */
740
+ #extractExpirationFromJwt(token) {
741
+ try {
742
+ // JWT tokens have three parts separated by dots: header.payload.signature
743
+ // The exp claim is in the payload
744
+ const parts = token.split('.');
745
+ if (parts.length < 2) {
746
+ this.#logger('warn', 'Invalid JWT token format: expected at least 2 parts');
747
+ return null;
748
+ }
749
+ const payload = parts[1];
750
+ // Decode base64url encoded payload
751
+ const decodedBytes = buffer.Buffer.from(y(payload), 'base64');
752
+ const payloadJson = decodedBytes.toString('utf8');
753
+ // Parse JSON to get the exp claim
754
+ const claims = JSON.parse(payloadJson);
755
+ const exp = claims.exp;
756
+ if (exp === undefined || exp === null) {
757
+ this.#logger('warn', "JWT token does not contain 'exp' claim");
758
+ return null;
759
+ }
760
+ if (typeof exp !== 'number') {
761
+ this.#logger('warn', `JWT token 'exp' claim is not a number: ${exp}`);
762
+ return null;
763
+ }
764
+ return exp;
765
+ }
766
+ catch (error) {
767
+ this.#logger('error', `Failed to extract expiration from JWT token: ${error instanceof Error ? error.message : error}`);
768
+ return null;
769
+ }
770
+ }
771
+ /**
772
+ * Start a session timer that will expire at the time specified in the JWT token's exp claim.
773
+ * When the timer fires, it executes the same actions as the BadUserNamePasswordError case.
774
+ */
775
+ #startSessionTimer() {
776
+ if (!this.#sessionDetails?.localSessionExpiryHandling) {
777
+ return;
778
+ }
779
+ const token = this.#sessionDetails.token;
780
+ if (!token) {
781
+ this.#logger('warn', 'Cannot start session timer: token not available');
782
+ return;
783
+ }
784
+ // Extract expiration time from JWT token
785
+ const expTimestamp = this.#extractExpirationFromJwt(token);
786
+ if (expTimestamp === null) {
787
+ this.#logger('warn', 'Cannot start session timer: could not extract expiration from JWT token');
788
+ return;
789
+ }
790
+ const currentTimeSeconds = Math.floor(Date.now() / 1000);
791
+ const delaySeconds = expTimestamp - currentTimeSeconds;
792
+ if (delaySeconds <= 0) {
793
+ this.#logger('warn', 'JWT token has already expired or expires immediately');
794
+ // Execute the same actions as BadUserNamePasswordError case
795
+ this.#handleSessionExpiry();
796
+ return;
797
+ }
798
+ // Clear any existing timer
799
+ if (this.#sessionTimer) {
800
+ clearTimeout(this.#sessionTimer);
801
+ }
802
+ const expirationTimeString = new Date(expTimestamp * 1000).toISOString();
803
+ this.#logger('debug', `Starting session timer to expire in ${delaySeconds} seconds (at ${expirationTimeString})`);
804
+ this.#sessionTimer = setTimeout(async () => {
805
+ this.#handleSessionExpiry();
806
+ }, delaySeconds * 1000);
807
+ }
808
+ /**
809
+ * Handles session expiry by executing the same actions as the BadUserNamePasswordError case.
810
+ */
811
+ async #handleSessionExpiry() {
812
+ await this.#disconnectAndLogFailure();
813
+ this.#logger('warn', 'Session expired');
814
+ this.#events.emitEvent('session-expired');
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
+ }
661
824
  }
662
825
 
663
826
  exports.AuthorizationError = AuthorizationError;
664
827
  exports.CloudInteropAPI = CloudInteropAPI;
665
828
  exports.CloudInteropAPIError = CloudInteropAPIError;
829
+ exports.OAuthAuthenticationError = OAuthAuthenticationError;
package/index.mjs CHANGED
@@ -1,6 +1,12 @@
1
1
  import { Buffer } from 'buffer';
2
+ import 'fs';
3
+ import 'path';
2
4
  import mqtt from 'mqtt';
3
5
 
6
+ var Y;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(Y="oauth4webapi/v3.8.8");function q(e,t){if(e==null)return false;try{return e instanceof t||Object.getPrototypeOf(e)[Symbol.toStringTag]===t.prototype[Symbol.toStringTag]}catch{return false}}var y$1="ERR_INVALID_ARG_VALUE",_="ERR_INVALID_ARG_TYPE";function l(e,t,n){let r=new TypeError(e,{cause:n});return Object.assign(r,{code:t}),r}var L=Symbol(),W=Symbol(),M=Symbol(),O=Symbol();var qe=new TextEncoder,We=new TextDecoder;function le(e){return typeof e=="string"?qe.encode(e):We.decode(e)}var Q;Uint8Array.prototype.toBase64?Q=e=>(e instanceof ArrayBuffer&&(e=new Uint8Array(e)),e.toBase64({alphabet:"base64url",omitPadding:true})):Q=t=>{t instanceof ArrayBuffer&&(t=new Uint8Array(t));let n=[];for(let r=0;r<t.byteLength;r+=32768)n.push(String.fromCharCode.apply(null,t.subarray(r,r+32768)));return btoa(n.join("")).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")};var X;Uint8Array.fromBase64?X=e=>{try{return Uint8Array.fromBase64(e,{alphabet:"base64url"})}catch(t){throw l("The input to be decoded is not correctly encoded.",y$1,t)}}:X=e=>{try{let t=atob(e.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"")),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n}catch(t){throw l("The input to be decoded is not correctly encoded.",y$1,t)}};function fe(e){return typeof e=="string"?X(e):Q(e)}var T=class extends Error{code;constructor(t,n){super(t,n),this.name=this.constructor.name,this.code=K,Error.captureStackTrace?.(this,this.constructor);}},D=class extends Error{code;constructor(t,n){super(t,n),this.name=this.constructor.name,n?.code&&(this.code=n?.code),Error.captureStackTrace?.(this,this.constructor);}};function i(e,t,n){return new D(e,{code:t,cause:n})}function H(e){return !(e===null||typeof e!="object"||Array.isArray(e))}function me(e){q(e,Headers)&&(e=Object.fromEntries(e.entries()));let t=new Headers(e??{});if(Y&&!t.has("user-agent")&&t.set("user-agent",Y),t.has("authorization"))throw l('"options.headers" must not include the "authorization" header name',y$1);return t}function ye(e,t){if(t!==void 0){if(typeof t=="function"&&(t=t(e.href)),!(t instanceof AbortSignal))throw l('"options.signal" must return or be an instance of AbortSignal',_);return t}}function _e(e){return e.includes("//")?e.replace("//","/"):e}function Me(e,t,n=false){return e.pathname==="/"?e.pathname=t:e.pathname=_e(`${t}/${n?e.pathname:e.pathname.replace(/(\/)$/,"")}`),e}function ze(e,t){return e.pathname=_e(`${e.pathname}/${t}`),e}async function Ke(e,t,n,r){if(!(e instanceof URL))throw l(`"${t}" must be an instance of URL`,_);z(e,r?.[L]!==true);let o=n(new URL(e.href)),s=me(r?.headers);return s.set("accept","application/json"),(r?.[O]||fetch)(o.href,{body:void 0,headers:Object.fromEntries(s.entries()),method:"GET",redirect:"manual",signal:ye(o,r?.signal)})}async function ge(e,t){return Ke(e,"issuerIdentifier",n=>{switch(t?.algorithm){case void 0:case "oidc":ze(n,".well-known/openid-configuration");break;case "oauth2":Me(n,".well-known/oauth-authorization-server");break;default:throw l('"options.algorithm" must be "oidc" (default), or "oauth2"',y$1)}return n},t)}function Z(e,t,n,r,o){try{if(typeof e!="number"||!Number.isFinite(e))throw l(`${n} must be a number`,_,o);if(e>0)return;if(t){if(e!==0)throw l(`${n} must be a non-negative number`,y$1,o);return}throw l(`${n} must be a positive number`,y$1,o)}catch(s){throw r?i(s.message,r,o):s}}function b(e,t,n,r){try{if(typeof e!="string")throw l(`${t} must be a string`,_,r);if(e.length===0)throw l(`${t} must not be empty`,y$1,r)}catch(o){throw n?i(o.message,n,r):o}}async function Re(e,t){let n=e;if(!(n instanceof URL)&&n!==J)throw l('"expectedIssuerIdentifier" must be an instance of URL',_);if(!q(t,Response))throw l('"response" must be an instance of Response',_);if(t.status!==200)throw i('"response" is not a conform Authorization Server Metadata response (unexpected HTTP status code)',$,t);oe(t);let r=await Ie(t);if(b(r.issuer,'"response" body "issuer" property',d,{body:r}),n!==J&&new URL(r.issuer).href!==n.href)throw i('"response" body "issuer" property does not match the expected value',F,{expected:n.href,body:r,attribute:"issuer"});return r}function be(e){Fe(e,"application/json");}function $e(e,...t){let n='"response" content-type must be ';if(t.length>2){let r=t.pop();n+=`${t.join(", ")}, or ${r}`;}else t.length===2?n+=`${t[0]} or ${t[1]}`:n+=t[0];return i(n,te,e)}function Fe(e,t){if(Ee(e)!==t)throw $e(e,t)}function Be(e){let t=e?.[W];return typeof t=="number"&&Number.isFinite(t)?t:0}function Ge(e){let t=e?.[M];return typeof t=="number"&&Number.isFinite(t)&&Math.sign(t)!==-1?t:30}function Ve(){return Math.floor(Date.now()/1e3)}function Se(e){if(typeof e!="object"||e===null)throw l('"as" must be an object',_);b(e.issuer,'"as.issuer"');}function Pe(e){if(typeof e!="object"||e===null)throw l('"client" must be an object',_);b(e.client_id,'"client.client_id"');}function ee(e){return b(e,'"clientSecret"'),(t,n,r,o)=>{r.set("client_id",n.client_id),r.set("client_secret",e);}}function Ae(){return (e,t,n,r)=>{n.set("client_id",t.client_id);}}var Ye=URL.parse?(e,t)=>URL.parse(e,t):(e,t)=>{try{return new URL(e,t)}catch{return null}};function z(e,t){if(t&&e.protocol!=="https:")throw i("only requests to HTTPS are allowed",ne,e);if(e.protocol!=="https:"&&e.protocol!=="http:")throw i("only HTTP and HTTPS requests are allowed",re,e)}function pe(e,t,n,r){let o;if(typeof e!="string"||!(o=Ye(e)))throw i(`authorization server metadata does not contain a valid ${n?`"as.mtls_endpoint_aliases.${t}"`:`"as.${t}"`}`,e===void 0?Tt:kt,{attribute:n?`mtls_endpoint_aliases.${t}`:t});return z(o,r),o}function Te(e,t,n,r){return n&&e.mtls_endpoint_aliases&&t in e.mtls_endpoint_aliases?pe(e.mtls_endpoint_aliases[t],t,n,r):pe(e[t],t,n,r)}var g=class extends Error{cause;code;error;status;error_description;response;constructor(t,n){super(t,n),this.name=this.constructor.name,this.code=Pt,this.cause=n.cause,this.error=n.cause.error,this.status=n.response.status,this.error_description=n.cause.error_description,Object.defineProperty(this,"response",{enumerable:false,value:n.response}),Error.captureStackTrace?.(this,this.constructor);}},I=class extends Error{cause;code;error;error_description;constructor(t,n){super(t,n),this.name=this.constructor.name,this.code=At,this.cause=n.cause,this.error=n.cause.get("error"),this.error_description=n.cause.get("error_description")??void 0,Error.captureStackTrace?.(this,this.constructor);}},k=class extends Error{cause;code;response;status;constructor(t,n){super(t,n),this.name=this.constructor.name,this.code=St,this.cause=n.cause,this.status=n.response.status,this.response=n.response,Object.defineProperty(this,"response",{enumerable:false}),Error.captureStackTrace?.(this,this.constructor);}},N="[a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+",Qe="[a-zA-Z0-9\\-\\._\\~\\+\\/]+={0,2}",Xe='"((?:[^"\\\\]|\\\\[\\s\\S])*)"',Ze="("+N+")\\s*=\\s*"+Xe,et="("+N+")\\s*=\\s*("+N+")",tt=new RegExp("^[,\\s]*("+N+")"),nt=new RegExp("^[,\\s]*"+Ze+"[,\\s]*(.*)"),rt=new RegExp("^[,\\s]*"+et+"[,\\s]*(.*)"),ot=new RegExp("^("+Qe+")(?:$|[,\\s])(.*)");function at(e){if(!q(e,Response))throw l('"response" must be an instance of Response',_);let t=e.headers.get("www-authenticate");if(t===null)return;let n=[],r=t;for(;r;){let o=r.match(tt),s=o?.[1].toLowerCase();if(!s)return;let a=r.substring(o[0].length);if(a&&!a.match(/^[\s,]/))return;let u=a.match(/^\s+(.*)$/),h=!!u;r=u?u[1]:void 0;let c={},p;if(h)for(;r;){let P,A;if(o=r.match(nt)){[,P,A,r]=o,A.includes("\\")&&(A=A.replace(/\\([\s\S])/g,"$1")),c[P.toLowerCase()]=A;continue}if(o=r.match(rt)){[,P,A,r]=o,c[P.toLowerCase()]=A;continue}if(o=r.match(ot)){if(Object.keys(c).length)break;[,p,r]=o;break}return}else r=a||void 0;let m={scheme:s,parameters:c};p&&(m.token68=p),n.push(m);}if(n.length)return n}async function st(e){if(e.status>399&&e.status<500){oe(e),be(e);try{let t=await e.clone().json();if(H(t)&&typeof t.error=="string"&&t.error.length)return t}catch{}}}async function it(e,t,n){if(e.status!==t){ft(e);let r;throw (r=await st(e))?(await e.body?.cancel(),new g("server responded with an error in the response body",{cause:r,response:e})):i(`"response" is not a conform ${n} response (unexpected HTTP status code)`,$,e)}}function Ee(e){return e.headers.get("content-type")?.split(";")[0]}async function ut(e,t,n,r,o,s,a){return await n(e,t,o,s),s.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"),(a?.[O]||fetch)(r.href,{body:o,headers:Object.fromEntries(s.entries()),method:"POST",redirect:"manual",signal:ye(r,a?.signal)})}async function dt(e,t,n,r,o,s){let a=Te(e,"token_endpoint",t.use_mtls_endpoint_aliases,s?.[L]!==true);o.set("grant_type",r);let u=me(s?.headers);u.set("accept","application/json");let h=await ut(e,t,n,a,o,u,s);return h}var xe=new WeakMap,ht=new WeakMap;function Oe(e){if(!e.id_token)return;let t=xe.get(e);if(!t)throw l('"ref" was already garbage collected or did not resolve from the proper sources',y$1);return t}async function lt(e,t,n,r,o,s){if(Se(e),Pe(t),!q(n,Response))throw l('"response" must be an instance of Response',_);await it(n,200,"Token Endpoint"),oe(n);let a=await Ie(n);if(b(a.access_token,'"response" body "access_token" property',d,{body:a}),b(a.token_type,'"response" body "token_type" property',d,{body:a}),a.token_type=a.token_type.toLowerCase(),a.expires_in!==void 0){let u=typeof a.expires_in!="number"?parseFloat(a.expires_in):a.expires_in;Z(u,true,'"response" body "expires_in" property',d,{body:a}),a.expires_in=u;}if(a.refresh_token!==void 0&&b(a.refresh_token,'"response" body "refresh_token" property',d,{body:a}),a.scope!==void 0&&typeof a.scope!="string")throw i('"response" body "scope" property must be a string',d,{body:a});if(a.id_token!==void 0){b(a.id_token,'"response" body "id_token" property',d,{body:a});let u=[];t.require_auth_time===true&&u.push("auth_time"),t.default_max_age!==void 0&&(Z(t.default_max_age,true,'"client.default_max_age"'),u.push("auth_time"));let{claims:h,jwt:c}=await gt(e,t,a.id_token,u);bt(t,h),Rt(h),ht.set(n,c),xe.set(a,h);}if(a.token_type!=="dpop"&&a.token_type!=="bearer")throw new T("unsupported `token_type` value",{cause:{body:a}});return a}function ft(e){let t;if(t=at(e))throw new k("server responded with a challenge in the WWW-Authenticate HTTP Header",{cause:t,response:e})}function pt(e,t){if(Array.isArray(t.claims.aud)){if(!t.claims.aud.includes(e))throw i('unexpected JWT "aud" (audience) claim value',E,{expected:e,claims:t.claims,claim:"aud"})}else if(t.claims.aud!==e)throw i('unexpected JWT "aud" (audience) claim value',E,{expected:e,claims:t.claims,claim:"aud"});return t}function wt(e,t){let n=e[ae]?.(t)??e.issuer;if(t.claims.iss!==n)throw i('unexpected JWT "iss" (issuer) claim value',E,{expected:n,claims:t.claims,claim:"iss"});return t}var Ce={aud:"audience",c_hash:"code hash",client_id:"client id",exp:"expiration time",iat:"issued at",iss:"issuer",jti:"jwt id",nonce:"nonce",s_hash:"state hash",sub:"subject",ath:"access token hash",htm:"http method",htu:"http uri",cnf:"confirmation",auth_time:"authentication time"};function yt(e,t){for(let n of e)if(t.claims[n]===void 0)throw i(`JWT "${n}" (${Ce[n]}) claim missing`,d,{claims:t.claims});return t}function _t(e,t){if(typeof t.claims[e]!="string")throw i(`unexpected JWT "${e}" (${Ce[e]}) claim type`,d,{claims:t.claims});return t}function gt(e,t,n,r,o){return Et(n,xt.bind(void 0,t.id_token_signed_response_alg,e.id_token_signing_alg_values_supported,"RS256"),Be(t),Ge(t)).then(yt.bind(void 0,["aud","exp","iat","iss","sub",...r])).then(wt.bind(void 0,e)).then(pt.bind(void 0,t.client_id)).then(_t.bind(void 0,"sub"))}function Rt(e){e.auth_time!==void 0&&Z(e.auth_time,true,'ID Token "auth_time" (authentication time)',d,{claims:e});}function bt(e,t){if(Array.isArray(t.aud)&&t.aud.length!==1){if(t.azp===void 0)throw i('ID Token "aud" (audience) claim includes additional untrusted audiences',E,{claims:t,claim:"aud"});if(t.azp!==e.client_id)throw i('unexpected ID Token "azp" (authorized party) claim value',E,{expected:e.client_id,claims:t,claim:"azp"})}}var St="OAUTH_WWW_AUTHENTICATE_CHALLENGE",Pt="OAUTH_RESPONSE_BODY_ERROR",K="OAUTH_UNSUPPORTED_OPERATION",At="OAUTH_AUTHORIZATION_RESPONSE_ERROR";var U="OAUTH_PARSE_ERROR",d="OAUTH_INVALID_RESPONSE";var te="OAUTH_RESPONSE_IS_NOT_JSON",$="OAUTH_RESPONSE_IS_NOT_CONFORM",ne="OAUTH_HTTP_REQUEST_FORBIDDEN",re="OAUTH_REQUEST_PROTOCOL_FORBIDDEN",j="OAUTH_JWT_TIMESTAMP_CHECK_FAILED",E="OAUTH_JWT_CLAIM_COMPARISON_FAILED",F="OAUTH_JSON_ATTRIBUTE_COMPARISON_FAILED";var Tt="OAUTH_MISSING_SERVER_METADATA",kt="OAUTH_INVALID_SERVER_METADATA";async function ve(e,t,n,r,o){return Se(e),Pe(t),dt(e,t,n,"client_credentials",new URLSearchParams(r),o)}async function De(e,t,n,r){return lt(e,t,n)}function oe(e){if(e.bodyUsed)throw l('"response" body has been used already',y$1)}async function Et(e,t,n,r,o){let{0:s,1:a,length:u}=e.split(".");if(u===5)throw new T("JWE decryption is not configured",{cause:e});if(u!==3)throw i("Invalid JWT",d,e);let h;try{h=JSON.parse(le(fe(s)));}catch(m){throw i("failed to parse JWT Header body as base64url encoded JSON",U,m)}if(!H(h))throw i("JWT Header must be a top level object",d,e);if(t(h),h.crit!==void 0)throw new T('no JWT "crit" header parameter extensions are supported',{cause:{header:h}});let c;try{c=JSON.parse(le(fe(a)));}catch(m){throw i("failed to parse JWT Payload body as base64url encoded JSON",U,m)}if(!H(c))throw i("JWT Payload must be a top level object",d,e);let p=Ve()+n;if(c.exp!==void 0){if(typeof c.exp!="number")throw i('unexpected JWT "exp" (expiration time) claim type',d,{claims:c});if(c.exp<=p-r)throw i('unexpected JWT "exp" (expiration time) claim value, expiration is past current timestamp',j,{claims:c,now:p,tolerance:r,claim:"exp"})}if(c.iat!==void 0&&typeof c.iat!="number")throw i('unexpected JWT "iat" (issued at) claim type',d,{claims:c});if(c.iss!==void 0&&typeof c.iss!="string")throw i('unexpected JWT "iss" (issuer) claim type',d,{claims:c});if(c.nbf!==void 0){if(typeof c.nbf!="number")throw i('unexpected JWT "nbf" (not before) claim type',d,{claims:c});if(c.nbf>p+r)throw i('unexpected JWT "nbf" (not before) claim value',j,{claims:c,now:p,tolerance:r,claim:"nbf"})}if(c.aud!==void 0&&typeof c.aud!="string"&&!Array.isArray(c.aud))throw i('unexpected JWT "aud" (audience) claim type',d,{claims:c});return {header:h,claims:c,jwt:e}}function xt(e,t,n,r){if(e!==void 0){if(typeof e=="string"?r.alg!==e:!e.includes(r.alg))throw i('unexpected JWT "alg" header parameter',d,{header:r,expected:e,reason:"client configuration"});return}if(Array.isArray(t)){if(!t.includes(r.alg))throw i('unexpected JWT "alg" header parameter',d,{header:r,expected:t,reason:"authorization server metadata"});return}if(n!==void 0){if(typeof n=="string"?r.alg!==n:typeof n=="function"?!n(r.alg):!n.includes(r.alg))throw i('unexpected JWT "alg" header parameter',d,{header:r,expected:n,reason:"default value"});return}throw i('missing client or server configuration to verify used JWT "alg" header parameter',void 0,{client:e,issuer:t,fallback:n})}async function Ie(e,t=be){let n;try{n=await e.json();}catch(r){throw t(e),i('failed to parse "response" body as JSON',U,r)}if(!H(n))throw i('"response" body must be a top level object',d,{body:n});return n}var J=Symbol(),ae=Symbol();var B,Ue;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(Ue="openid-client/v6.8.8",B={"user-agent":Ue});var R=e=>se.get(e),se;function ce(e){if(e!==void 0)return ee(e);let t=new WeakMap;return (n,r,o,s)=>{let a;return (a=t.get(r))||(Ct(r.client_secret,'"metadata.client_secret"'),a=ee(r.client_secret),t.set(r,a)),a(n,r,o,s)}}function Ct(e,t){if(typeof e!="string")throw x(`${t} must be a string`,V);if(e.length===0)throw x(`${t} must not be empty`,ue)}function vt(){return Ae()}var S=O;var ue="ERR_INVALID_ARG_VALUE",V="ERR_INVALID_ARG_TYPE";function x(e,t,n){let r=new TypeError(e,{cause:n});return Object.assign(r,{code:t}),r}var C=class extends Error{code;constructor(t,n){super(t,n),this.name=this.constructor.name,this.code=n?.code,Error.captureStackTrace?.(this,this.constructor);}};new TextDecoder;function f(e,t,n){return new C(e,{cause:t,code:n})}function ie(e){if(e instanceof TypeError||e instanceof C||e instanceof g||e instanceof I||e instanceof k)throw e;if(e instanceof D)switch(e.code){case ne:throw f("only requests to HTTPS are allowed",e,e.code);case re:throw f("only requests to HTTP or HTTPS are allowed",e,e.code);case $:throw f("unexpected HTTP response status code",e.cause,e.code);case te:throw f("unexpected response content-type",e.cause,e.code);case U:throw f("parsing error occured",e,e.code);case d:throw f("invalid response encountered",e,e.code);case E:throw f("unexpected JWT claim value encountered",e,e.code);case F:throw f("unexpected JSON attribute value encountered",e,e.code);case j:throw f("JWT timestamp claim value failed validation",e,e.code);default:throw f(e.message,e,e.code)}if(e instanceof T)throw f("unsupported operation",e,e.code);if(e instanceof DOMException)switch(e.name){case "OperationError":throw f("runtime operation error",e,K);case "NotSupportedError":throw f("runtime unsupported operation",e,K);case "TimeoutError":throw f("operation timed out",e,"OAUTH_TIMEOUT");case "AbortError":throw f("operation aborted",e,"OAUTH_ABORT")}throw new C("something went wrong",{cause:e})}function Dt(e,t,n){return e.origin==="https://login.microsoftonline.com"&&(!n?.algorithm||n.algorithm==="oidc")?(t[He]=true,true):false}function It(e,t){return !!(e.hostname.endsWith(".b2clogin.com")&&(!t?.algorithm||t.algorithm==="oidc"))}async function Le(e,t,n,r,o){let s=await Ut(e,o),a=new v(s,t,n,r),u=R(a);if(o?.[S]&&(u.fetch=o[S]),o?.timeout!==void 0&&(u.timeout=o.timeout),o?.execute)for(let h of o.execute)h(a);return a}async function Ut(e,t){if(!(e instanceof URL))throw x('"server" must be an instance of URL',V);let n=!e.href.includes("/.well-known/"),r=t?.timeout??30,o=AbortSignal.timeout(r*1e3),s=await(n?ge(e,{algorithm:t?.algorithm,[O]:t?.[S],[L]:t?.execute?.includes(G),signal:o,headers:new Headers(B)}):(t?.[S]||fetch)((z(e,!t?.execute?.includes(G)),e.href),{headers:Object.fromEntries(new Headers({accept:"application/json",...B}).entries()),body:void 0,method:"GET",redirect:"manual",signal:o})).then(a=>Re(J,a)).catch(ie);return n&&new URL(s.issuer).href!==e.href&&(Dt(e,s,t)||It(e,t)||(()=>{throw new C("discovered metadata issuer does not match the expected issuer",{code:F,cause:{expected:e.href,body:s,attribute:"issuer"}})})()),s}function Lt(e){return {supportsPKCE:{__proto__:null,value(t="S256"){return e.code_challenge_methods_supported?.includes(t)===true}}}}function Ht(e){Object.defineProperties(e,Lt(e));}var He=Symbol(),v=class{constructor(t,n,r,o){if(typeof n!="string"||!n.length)throw x('"clientId" must be a non-empty string',V);if(typeof r=="string"&&(r={client_secret:r}),r?.client_id!==void 0&&n!==r.client_id)throw x('"clientId" and "metadata.client_id" must be the same',ue);let s={...structuredClone(r),client_id:n};s[W]=r?.[W]??0,s[M]=r?.[M]??30;let a;o?a=o:typeof s.client_secret=="string"&&s.client_secret.length?a=ce(s.client_secret):a=vt();let u=Object.freeze(s),h=structuredClone(t);He in t&&(h[ae]=({claims:{tid:p}})=>t.issuer.replace("{tenantid}",p));let c=Object.freeze(h);se||=new WeakMap,se.set(this,{__proto__:null,as:c,c:u,auth:a,tlsOnly:true,timeout:30,jwksCache:{}});}serverMetadata(){let t=structuredClone(R(this).as);return Ht(t),t}clientMetadata(){return structuredClone(R(this).c)}get timeout(){return R(this).timeout}set timeout(t){R(this).timeout=t;}get[S](){return R(this).fetch}set[S](t){R(this).fetch=t;}};Object.freeze(v.prototype);function Nt(e){let t;return e.expires_in!==void 0&&(t=Date.now()+e.expires_in*1e3),{expiresIn:{__proto__:null,value(){if(t){let n=Date.now();return t>n?Math.floor((t-n)/1e3):0}}},claims:{__proto__:null,value(){return Oe(e)}}}}function jt(e){Object.defineProperties(e,Nt(e));}function G(e){R(e).tlsOnly=false;}async function de(e,t,n){Jt(e),t=new URLSearchParams(t);let{as:r,c:o,auth:s,fetch:a,tlsOnly:u,timeout:h}=R(e),c=await ve(r,o,s,t,{[O]:a,[L]:!u,DPoP:n?.DPoP,headers:new Headers(B),signal:qt(h)}).catch(ie),p=De(r,o,c),m;try{m=await p;}catch(P){ie(P);}return jt(m),m}function Jt(e){if(!(e instanceof v))throw x('"config" must be an instance of Configuration',V);if(Object.getPrototypeOf(e)!==v.prototype)throw x("subclassing Configuration is not allowed",ue)}function qt(e){return e?AbortSignal.timeout(e*1e3):void 0}var w=class extends Error{code;constructor(t,n){super(t,{cause:n}),this.name="OAuthClientCredentialsError",this.code="ERR_OAUTH";}};var zt=6e4,Kt=new Set(["localhost","127.0.0.1"]),je=e=>e.protocol==="http:"&&Kt.has(e.hostname),$t=e=>typeof e=="number"&&Number.isFinite(e)&&e>0,Ft=e=>{try{return new URL(e)}catch{return}},he=e=>e?`OAuth token request failed: ${e}`:"OAuth token request failed",Je=class e{#e;constructor(t,n,r,o){if(t.protocol!=="https:"&&!je(t))throw new w("OAuth client credentials require an https service URL; http is only allowed for localhost and 127.0.0.1");this.#e={issuer:t,clientId:n,clientSecret:r,fetchImpl:o?.fetch,clock:o?.clock??(()=>Date.now()),cachedToken:void 0,configuration:void 0,flight:void 0,generation:0};}static fromServiceUrl(t,n,r){let o=Ft(t);if(!o||o.protocol!=="http:"&&o.protocol!=="https:")throw new w("OAuth client credentials require an absolute service URL");return new e(new URL(o.origin),n,r)}async getAccessToken(){let{cachedToken:t,clock:n}=this.#e;if(t!==void 0&&t.expiresAt-n()>zt)return t.accessToken;if(this.#e.flight)return this.#e.flight;let r=this.#e.generation,o=this.#t(r).finally(()=>{this.#e.flight===o&&(this.#e.flight=void 0);});return this.#e.flight=o,o}invalidate(){this.#e.cachedToken=void 0,this.#e.generation+=1,this.#e.flight=void 0;}async#t(t){let n=await this.#n(),r;try{r=await de(n);}catch(s){throw s instanceof TypeError||s instanceof w?s:s instanceof g?new w(he(s.error),s):new w(he(),s)}let o=r.access_token;if(typeof o!="string"||o.length===0)throw new w(he());if(this.#e.generation===t){let s=r.expires_in;this.#e.cachedToken=$t(s)?{accessToken:o,expiresAt:this.#e.clock()+s*1e3}:void 0;}return o}async#n(){if(this.#e.configuration)return this.#e.configuration;let t=this.#e.fetchImpl??globalThis.fetch;try{let n=await Le(this.#e.issuer,this.#e.clientId,this.#e.clientSecret,ce(this.#e.clientSecret),{algorithm:"oauth2",[S]:t,...je(this.#e.issuer)?{execute:[G]}:{}});return this.#e.configuration=n,n}catch(n){throw n instanceof TypeError?n:new w("OAuth authorization server discovery failed",n)}}},$n=({grantType:e,clientSecret:t})=>{if(e!=="client_credentials")throw new w("Only the client_credentials grant is supported");if(globalThis.window!==void 0&&t.length>0)throw new w("Client credentials authentication is not supported in the browser")},Fn=async(e,t)=>{let n=await t();return n.status!==401?n:(await n.body?.cancel().catch(()=>{}),e.invalidate(),t())};
7
+
8
+ var y=e=>{let n=e.replaceAll("-","+").replaceAll("_","/");return n.padEnd(n.length+(4-n.length%4)%4,"=")};
9
+
4
10
  class CloudInteropAPIError extends Error {
5
11
  code;
6
12
  constructor(message = 'An unexpected error has occurred', code = 'UNEXPECTED_ERROR', cause) {
@@ -14,6 +20,21 @@ class AuthorizationError extends CloudInteropAPIError {
14
20
  super(message, code, undefined);
15
21
  }
16
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
+ };
17
38
 
18
39
  class EventController {
19
40
  #eventListeners = new Map();
@@ -47,11 +68,20 @@ class EventController {
47
68
  const isErrorIntentResult = (result) => 'error' in result;
48
69
 
49
70
  const APP_ID_DELIM = '::';
50
- const getRequestHeaders = (connectionParameters) => {
71
+ const getRequestHeaders = async (connectionParameters, tokenClient) => {
51
72
  const headers = {};
52
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
+ }
53
83
  if (connectionParameters.authenticationType === 'jwt' && connectionParameters.jwtAuthenticationParameters) {
54
- const tokenResult = connectionParameters.jwtAuthenticationParameters.jwtRequestCallback();
84
+ const tokenResult = await connectionParameters.jwtAuthenticationParameters.jwtRequestCallback();
55
85
  if (!tokenResult) {
56
86
  throw new Error('jwtRequestCallback must return a token');
57
87
  }
@@ -133,16 +163,16 @@ class IntentController {
133
163
  #url;
134
164
  #mqttClient;
135
165
  #sessionDetails;
136
- #connectionParams;
166
+ #authenticatedFetch;
137
167
  #events;
138
168
  #logger;
139
169
  #discovery = newDiscovery();
140
170
  #discoveryTimeout;
141
- constructor(url, mqttClient, sessionDetails, connectionParameters, events, logger) {
171
+ constructor(url, mqttClient, sessionDetails, authenticatedFetch, events, logger) {
142
172
  this.#url = url;
143
173
  this.#mqttClient = mqttClient;
144
174
  this.#sessionDetails = sessionDetails;
145
- this.#connectionParams = connectionParameters;
175
+ this.#authenticatedFetch = authenticatedFetch;
146
176
  this.#events = events;
147
177
  this.#logger = logger;
148
178
  }
@@ -154,9 +184,8 @@ class IntentController {
154
184
  // clamp min value to 500ms
155
185
  const clampedTimeout = Math.max(timeout, MIN_TIMEOUT);
156
186
  try {
157
- const startResponse = await fetch(`${this.#url}/api/intents/${this.#sessionDetails.sessionId}`, {
187
+ const startResponse = await this.#authenticatedFetch(`${this.#url}/api/intents/${this.#sessionDetails.sessionId}`, {
158
188
  method: 'POST',
159
- headers: getRequestHeaders(this.#connectionParams),
160
189
  body: JSON.stringify({ findOptions }),
161
190
  });
162
191
  if (!startResponse.ok) {
@@ -199,9 +228,8 @@ class IntentController {
199
228
  this.#logger('warn', `Error ending intent discovery: could not unsubscribe from discovery id ${this.#discovery.id}`);
200
229
  });
201
230
  }
202
- 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}`, {
203
232
  method: 'DELETE',
204
- headers: getRequestHeaders(this.#connectionParams),
205
233
  })
206
234
  .then((deleteResponse) => {
207
235
  if (!deleteResponse.ok) {
@@ -220,9 +248,8 @@ class IntentController {
220
248
  // TODO: should we add more info here about the format?
221
249
  throw new CloudInteropAPIError(`Invalid AppId specified, must be encoded as a cloud-session app id`, 'ERR_INVALID_TARGET_SESSION_ID');
222
250
  }
223
- 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}`, {
224
252
  method: 'POST',
225
- headers: getRequestHeaders(this.#connectionParams),
226
253
  body: JSON.stringify({ raiseOptions }),
227
254
  });
228
255
  if (!postResponse.ok) {
@@ -234,9 +261,8 @@ class IntentController {
234
261
  async reportAppIntents(discoveryId, intents) {
235
262
  intents = encodeAppIntents(intents, getSourceFromSession(this.#sessionDetails));
236
263
  try {
237
- 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}`, {
238
265
  method: 'POST',
239
- headers: getRequestHeaders(this.#connectionParams),
240
266
  body: JSON.stringify({ intents }),
241
267
  });
242
268
  if (reportResponse.ok) {
@@ -258,9 +284,8 @@ class IntentController {
258
284
  result.source = typeof result.source === 'string' ? encoded : { ...result.source, appId: encoded };
259
285
  }
260
286
  const { sessionId } = getSourceFromSession(this.#sessionDetails);
261
- const resultResponse = await fetch(`${this.#url}/api/intents/${initiatingSessionId}/result/${sessionId}`, {
287
+ const resultResponse = await this.#authenticatedFetch(`${this.#url}/api/intents/${initiatingSessionId}/result/${sessionId}`, {
262
288
  method: 'POST',
263
- headers: getRequestHeaders(this.#connectionParams),
264
289
  body: JSON.stringify({ result }),
265
290
  });
266
291
  if (!resultResponse.ok) {
@@ -344,13 +369,16 @@ class CloudInteropAPI {
344
369
  #reconnectRetryLimit = 30;
345
370
  #keepAliveIntervalSeconds = 30;
346
371
  #logger = (level, message) => {
372
+ // eslint-disable-next-line security/detect-object-injection -- level is restricted to the LogLevel union
347
373
  console[level](message);
348
374
  };
349
375
  #reconnectRetries = 0;
350
376
  #connectionParams;
377
+ #tokenClient;
351
378
  #attemptingToReconnect = false;
352
379
  #events = new EventController();
353
380
  #intents;
381
+ #sessionTimer;
354
382
  constructor(cloudInteropSettings) {
355
383
  this.#cloudInteropSettings = cloudInteropSettings;
356
384
  }
@@ -363,22 +391,34 @@ class CloudInteropAPI {
363
391
  /**
364
392
  * Connects and creates a session on the Cloud Interop service
365
393
  *
366
- * @param {ConnectParameters} parameters - The parameters to use to connect
367
- * @returns {*} {Promise<void>}
394
+ * @param parameters - The parameters to use to connect
395
+ * @returns Promise that resolves when connection is established
368
396
  * @memberof CloudInteropAPI
369
- * @throws {CloudInteropAPIError} - If an error occurs during connection
370
- * @throws {AuthorizationError} - If the connection is unauthorized
397
+ * @throws CloudInteropAPIError - If an error occurs during connection
398
+ * @throws AuthorizationError - If the connection is unauthorized
399
+ * @throws OAuthAuthenticationError - If OAuth parameters are invalid, the client credentials are rejected, or an access token cannot be obtained
371
400
  */
372
401
  async connect(parameters) {
373
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
+ }
374
415
  this.#connectionParams = parameters;
375
416
  this.#reconnectRetryLimit = parameters.reconnectRetryLimit || this.#reconnectRetryLimit;
376
417
  this.#keepAliveIntervalSeconds = parameters.keepAliveIntervalSeconds || this.#keepAliveIntervalSeconds;
377
418
  this.#logger = parameters.logger || this.#logger;
378
419
  const { sourceId, platformId } = this.#connectionParams;
379
- const createSessionResponse = await fetch(`${this.#cloudInteropSettings.url}/api/sessions`, {
420
+ const createSessionResponse = await this.#authenticatedFetch(`${this.#cloudInteropSettings.url}/api/sessions`, {
380
421
  method: 'POST',
381
- headers: getRequestHeaders(this.#connectionParams),
382
422
  body: JSON.stringify({ sourceId: sourceId.trim(), platformId }),
383
423
  });
384
424
  if (!createSessionResponse.ok) {
@@ -391,6 +431,11 @@ class CloudInteropAPI {
391
431
  throw new CloudInteropAPIError(`Failed to connect to the Cloud Interop service: ${this.#cloudInteropSettings.url}`, 'ERR_CONNECT', new Error(createSessionResponse.statusText));
392
432
  }
393
433
  this.#sessionDetails = (await createSessionResponse.json());
434
+ // If local session expiry handling is enabled, start the session timer
435
+ if (this.#sessionDetails.localSessionExpiryHandling) {
436
+ this.#logger('debug', `Local session expiry handling is enabled`);
437
+ this.#startSessionTimer();
438
+ }
394
439
  const sessionRootTopic = this.#sessionDetails.sessionRootTopic;
395
440
  const clientOptions = {
396
441
  keepalive: this.#keepAliveIntervalSeconds,
@@ -411,18 +456,17 @@ class CloudInteropAPI {
411
456
  // TODO: Dynamic intent discovery
412
457
  // search for any ongoing discoveries in DB and fire report-intents on self
413
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
414
460
  this.#mqttClient.on('error', async (error) => {
415
461
  // We will receive errors for each failed reconnection attempt
416
462
  // We don't want to disconnect on these else we will never reconnect
417
463
  if (!this.#attemptingToReconnect) {
418
- await this.#disconnect(false);
464
+ await this.#disconnectAndLogFailure();
419
465
  }
420
466
  if (error instanceof mqtt.ErrorWithReasonCode) {
421
467
  switch (error.code) {
422
468
  case BadUserNamePasswordError: {
423
- await this.#disconnect(false);
424
- this.#logger('warn', `Session expired`);
425
- this.#events.emitEvent('session-expired');
469
+ this.#handleSessionExpiry();
426
470
  return;
427
471
  }
428
472
  default: {
@@ -443,15 +487,15 @@ class CloudInteropAPI {
443
487
  }
444
488
  }
445
489
  });
446
- this.#mqttClient.on('reconnect', () => {
490
+ this.#mqttClient.on('reconnect', async () => {
447
491
  this.#attemptingToReconnect = true;
448
492
  this.#reconnectRetries += 1;
449
493
  this.#logger('debug', `Cloud Interop attempting reconnection - ${this.#reconnectRetries}...`);
494
+ this.#events.emitEvent('reconnecting', this.#reconnectRetries);
450
495
  if (this.#reconnectRetries === this.#reconnectRetryLimit) {
451
496
  this.#logger('warn', `Cloud Interop reached max reconnection attempts - ${this.#reconnectRetryLimit}...`);
452
- this.#disconnect(true);
497
+ await this.#disconnectAndLogFailure(true);
453
498
  }
454
- this.#events.emitEvent('reconnecting', this.#reconnectRetries);
455
499
  });
456
500
  // Does not fire on initial connection, only successful reconnection attempts
457
501
  this.#mqttClient.on('connect', () => {
@@ -471,14 +515,14 @@ class CloudInteropAPI {
471
515
  this.#mqttClient.subscribe(`${sessionRootTopic}/context-groups/#`);
472
516
  // Listen out for global commands
473
517
  this.#mqttClient.subscribe(`${sessionRootTopic}/commands`);
474
- this.#initControllers(this.#mqttClient, this.#sessionDetails, this.#connectionParams);
518
+ this.#initControllers(this.#mqttClient, this.#sessionDetails);
475
519
  }
476
520
  /**
477
521
  * Disconnects from the Cloud Interop service
478
522
  *
479
- * @returns {*} {Promise<void>}
523
+ * @returns Promise that resolves when disconnected
480
524
  * @memberof CloudInteropAPI
481
- * @throws {CloudInteropAPIError} - If an error occurs during disconnection
525
+ * @throws CloudInteropAPIError - If an error occurs during disconnection
482
526
  */
483
527
  async disconnect() {
484
528
  await this.#disconnect(true);
@@ -486,9 +530,9 @@ class CloudInteropAPI {
486
530
  /**
487
531
  * Publishes a new context for the given context group to the other connected sessions
488
532
  *
489
- * @param {string} contextGroup - The context group to publish to
490
- * @param {object} context - The context to publish
491
- * @returns {*} {Promise<void>}
533
+ * @param contextGroup - The context group to publish to
534
+ * @param context - The context to publish
535
+ * @returns Promise that resolves when context is published
492
536
  * @memberof CloudInteropAPI
493
537
  */
494
538
  async setContext(contextGroup, context) {
@@ -503,9 +547,8 @@ class CloudInteropAPI {
503
547
  context,
504
548
  timestamp: Date.now(),
505
549
  };
506
- 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}`, {
507
551
  method: 'POST',
508
- headers: getRequestHeaders(this.#connectionParams),
509
552
  body: JSON.stringify(payload),
510
553
  });
511
554
  if (!postResponse.ok) {
@@ -515,9 +558,9 @@ class CloudInteropAPI {
515
558
  /**
516
559
  * Starts an intent discovery operation
517
560
  *
518
- * @returns {*} {Promise<void>}
561
+ * @returns Promise that resolves when intent discovery is started
519
562
  * @memberof CloudInteropAPI
520
- * @throws {CloudInteropAPIError} - If an error occurs during intent discovery
563
+ * @throws CloudInteropAPIError - If an error occurs during intent discovery
521
564
  */
522
565
  async startIntentDiscovery(options) {
523
566
  this.#throwIfNotConnected();
@@ -558,9 +601,13 @@ class CloudInteropAPI {
558
601
  if (!this.#connectionParams) {
559
602
  throw new Error('Connect parameters must be provided');
560
603
  }
561
- const disconnectResponse = await fetch(`${this.#cloudInteropSettings.url}/api/sessions/${this.#sessionDetails.sessionId}`, {
604
+ // Cancel session timer if it's running
605
+ if (this.#sessionTimer) {
606
+ clearTimeout(this.#sessionTimer);
607
+ this.#sessionTimer = undefined;
608
+ }
609
+ const disconnectResponse = await this.#authenticatedFetch(`${this.#cloudInteropSettings.url}/api/sessions/${this.#sessionDetails.sessionId}`, {
562
610
  method: 'DELETE',
563
- headers: getRequestHeaders(this.#connectionParams),
564
611
  });
565
612
  if (disconnectResponse.status !== 200) {
566
613
  throw new CloudInteropAPIError('Error during session tear down - unexpected status', 'ERR_DISCONNECT', new Error(disconnectResponse.statusText));
@@ -583,6 +630,7 @@ class CloudInteropAPI {
583
630
  }
584
631
  }
585
632
  #handleMessage(topic, message, sessionDetails) {
633
+ this.#logger('debug', `Received message on topic: ${topic}`);
586
634
  if (message.length === 0 || !sessionDetails) {
587
635
  // Ignore clean up messages
588
636
  return;
@@ -641,10 +689,35 @@ class CloudInteropAPI {
641
689
  (!parameters.basicAuthenticationParameters?.username || !parameters.basicAuthenticationParameters?.password)) {
642
690
  throw new Error('basicAuthenticationParameters must be provided when using basic authentication');
643
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
+ }
644
703
  };
645
- #initControllers(mqttClient, sessionDetails, connectionParameters) {
646
- 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);
647
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
+ };
648
721
  #destroyControllers() {
649
722
  this.#intents = undefined;
650
723
  }
@@ -656,6 +729,96 @@ class CloudInteropAPI {
656
729
  throw new Error('MQTT client not connected');
657
730
  }
658
731
  }
732
+ /**
733
+ * Extracts the expiration timestamp from a JWT token.
734
+ *
735
+ * @param token - The JWT token string
736
+ * @returns The expiration timestamp in seconds, or null if extraction fails
737
+ */
738
+ #extractExpirationFromJwt(token) {
739
+ try {
740
+ // JWT tokens have three parts separated by dots: header.payload.signature
741
+ // The exp claim is in the payload
742
+ const parts = token.split('.');
743
+ if (parts.length < 2) {
744
+ this.#logger('warn', 'Invalid JWT token format: expected at least 2 parts');
745
+ return null;
746
+ }
747
+ const payload = parts[1];
748
+ // Decode base64url encoded payload
749
+ const decodedBytes = Buffer.from(y(payload), 'base64');
750
+ const payloadJson = decodedBytes.toString('utf8');
751
+ // Parse JSON to get the exp claim
752
+ const claims = JSON.parse(payloadJson);
753
+ const exp = claims.exp;
754
+ if (exp === undefined || exp === null) {
755
+ this.#logger('warn', "JWT token does not contain 'exp' claim");
756
+ return null;
757
+ }
758
+ if (typeof exp !== 'number') {
759
+ this.#logger('warn', `JWT token 'exp' claim is not a number: ${exp}`);
760
+ return null;
761
+ }
762
+ return exp;
763
+ }
764
+ catch (error) {
765
+ this.#logger('error', `Failed to extract expiration from JWT token: ${error instanceof Error ? error.message : error}`);
766
+ return null;
767
+ }
768
+ }
769
+ /**
770
+ * Start a session timer that will expire at the time specified in the JWT token's exp claim.
771
+ * When the timer fires, it executes the same actions as the BadUserNamePasswordError case.
772
+ */
773
+ #startSessionTimer() {
774
+ if (!this.#sessionDetails?.localSessionExpiryHandling) {
775
+ return;
776
+ }
777
+ const token = this.#sessionDetails.token;
778
+ if (!token) {
779
+ this.#logger('warn', 'Cannot start session timer: token not available');
780
+ return;
781
+ }
782
+ // Extract expiration time from JWT token
783
+ const expTimestamp = this.#extractExpirationFromJwt(token);
784
+ if (expTimestamp === null) {
785
+ this.#logger('warn', 'Cannot start session timer: could not extract expiration from JWT token');
786
+ return;
787
+ }
788
+ const currentTimeSeconds = Math.floor(Date.now() / 1000);
789
+ const delaySeconds = expTimestamp - currentTimeSeconds;
790
+ if (delaySeconds <= 0) {
791
+ this.#logger('warn', 'JWT token has already expired or expires immediately');
792
+ // Execute the same actions as BadUserNamePasswordError case
793
+ this.#handleSessionExpiry();
794
+ return;
795
+ }
796
+ // Clear any existing timer
797
+ if (this.#sessionTimer) {
798
+ clearTimeout(this.#sessionTimer);
799
+ }
800
+ const expirationTimeString = new Date(expTimestamp * 1000).toISOString();
801
+ this.#logger('debug', `Starting session timer to expire in ${delaySeconds} seconds (at ${expirationTimeString})`);
802
+ this.#sessionTimer = setTimeout(async () => {
803
+ this.#handleSessionExpiry();
804
+ }, delaySeconds * 1000);
805
+ }
806
+ /**
807
+ * Handles session expiry by executing the same actions as the BadUserNamePasswordError case.
808
+ */
809
+ async #handleSessionExpiry() {
810
+ await this.#disconnectAndLogFailure();
811
+ this.#logger('warn', 'Session expired');
812
+ this.#events.emitEvent('session-expired');
813
+ }
814
+ async #disconnectAndLogFailure(fireDisconnectedEvent = false) {
815
+ try {
816
+ await this.#disconnect(fireDisconnectedEvent);
817
+ }
818
+ catch (error) {
819
+ this.#logger('error', `Session teardown failed: ${error instanceof Error ? error.message : String(error)}`);
820
+ }
821
+ }
659
822
  }
660
823
 
661
- export { AuthorizationError, CloudInteropAPI, CloudInteropAPIError };
824
+ export { AuthorizationError, CloudInteropAPI, CloudInteropAPIError, OAuthAuthenticationError };
package/package.json CHANGED
@@ -1,18 +1,15 @@
1
1
  {
2
2
  "name": "@openfin/cloud-interop-core-api",
3
- "version": "0.0.1-alpha.3e5906a",
4
- "type": "module",
3
+ "version": "0.0.1-alpha.3e8a7a5",
5
4
  "description": "",
5
+ "type": "module",
6
6
  "main": "./index.cjs",
7
7
  "browser": "./index.mjs",
8
8
  "types": "./bundle.d.ts",
9
- "author": "",
9
+ "author": "support@here.io",
10
10
  "license": "SEE LICENSE IN LICENSE.md",
11
11
  "dependencies": {
12
- "mqtt": "^5.13.0",
13
- "zod": "^3.24.4"
14
- },
15
- "optionalDependencies": {
16
- "@rollup/rollup-linux-x64-gnu": "*"
12
+ "mqtt": "catalog:",
13
+ "zod": "catalog:"
17
14
  }
18
15
  }