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