@openfin/cloud-interop-core-api 0.0.1-alpha.fde0e27 → 0.0.1-alpha.fe19a6f
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 +1 -0
- package/bundle.d.ts +43 -2
- package/index.cjs +102 -31
- package/index.mjs +102 -32
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -10,5 +10,6 @@ It is callable via browser or node applications.
|
|
|
10
10
|
The library supports authentication with the HERE Cloud Interop Service using the following methods:
|
|
11
11
|
- Basic Authentication
|
|
12
12
|
- JWT Token Authentication
|
|
13
|
+
- OAuth client credentials, for a server-side application. The service URL must be absolute and use `https:`, such as `https://host/interop`. `http:` is only accepted for `localhost` and `127.0.0.1` during local development, and a path such as `/interop` is not enough. A client secret is rejected in the browser.
|
|
13
14
|
- Default Authentication i.e. Interactive session based authentication using cookies
|
|
14
15
|
|
package/bundle.d.ts
CHANGED
|
@@ -250,6 +250,7 @@ export declare class CloudInteropAPI {
|
|
|
250
250
|
* @memberof CloudInteropAPI
|
|
251
251
|
* @throws CloudInteropAPIError - If an error occurs during connection
|
|
252
252
|
* @throws AuthorizationError - If the connection is unauthorized
|
|
253
|
+
* @throws OAuthAuthenticationError - If OAuth parameters are invalid, the client credentials are rejected, or an access token cannot be obtained
|
|
253
254
|
*/
|
|
254
255
|
connect(parameters: ConnectParameters): Promise<void>;
|
|
255
256
|
/**
|
|
@@ -341,9 +342,10 @@ export declare type ConnectParameters = {
|
|
|
341
342
|
*
|
|
342
343
|
* 'jwt' - Use JWT authentication, in this case jwtAuthenticationParameters must also be provided
|
|
343
344
|
* 'basic' - Use basic authentication, in this case basicAuthenticationParameters must also be provided
|
|
345
|
+
* 'oauth' - Use OAuth client credentials, in this case oauthAuthenticationParameters must also be provided
|
|
344
346
|
* 'default' - Authentication will be inherited from the current session
|
|
345
347
|
*/
|
|
346
|
-
authenticationType?: 'jwt' | 'basic' | 'default';
|
|
348
|
+
authenticationType?: 'jwt' | 'basic' | 'oauth' | 'default';
|
|
347
349
|
/**
|
|
348
350
|
* Optional parameters for basic authentication
|
|
349
351
|
*/
|
|
@@ -364,7 +366,7 @@ export declare type ConnectParameters = {
|
|
|
364
366
|
/**
|
|
365
367
|
* When JWT authentication is being used, this will be invoked just whenever a JWT token is required for a request
|
|
366
368
|
*/
|
|
367
|
-
jwtRequestCallback: () => string | object
|
|
369
|
+
jwtRequestCallback: () => string | object | Promise<string | object>;
|
|
368
370
|
/**
|
|
369
371
|
* The id of the service gateway JWT authentication definition to use
|
|
370
372
|
*
|
|
@@ -372,6 +374,11 @@ export declare type ConnectParameters = {
|
|
|
372
374
|
*/
|
|
373
375
|
authenticationId: string;
|
|
374
376
|
};
|
|
377
|
+
/**
|
|
378
|
+
* Optional parameters for OAuth client-credentials authentication.
|
|
379
|
+
* Server-side only. A client secret is rejected in the browser.
|
|
380
|
+
*/
|
|
381
|
+
oauthAuthenticationParameters?: OAuthAuthenticationParameters;
|
|
375
382
|
};
|
|
376
383
|
|
|
377
384
|
/**
|
|
@@ -714,6 +721,40 @@ declare const intentResultSchema: z.ZodUnion<[z.ZodObject<{
|
|
|
714
721
|
|
|
715
722
|
export declare type LogLevel = 'log' | 'debug' | 'info' | 'warn' | 'error';
|
|
716
723
|
|
|
724
|
+
export declare class OAuthAuthenticationError extends CloudInteropAPIError {
|
|
725
|
+
constructor(message: string, cause?: unknown);
|
|
726
|
+
}
|
|
727
|
+
|
|
728
|
+
/**
|
|
729
|
+
* Parameters for OAuth client-credentials authentication.
|
|
730
|
+
*
|
|
731
|
+
* Use these from a server-side application only. A client secret is rejected when the library runs in a browser.
|
|
732
|
+
* Load the secret from the environment or a secret store rather than hard-coding it.
|
|
733
|
+
*
|
|
734
|
+
* @example
|
|
735
|
+
* ```typescript
|
|
736
|
+
* const oauthAuthenticationParameters: OAuthAuthenticationParameters = {
|
|
737
|
+
* grantType: 'client_credentials',
|
|
738
|
+
* clientId: 'your-client-id',
|
|
739
|
+
* clientSecret,
|
|
740
|
+
* };
|
|
741
|
+
* ```
|
|
742
|
+
*/
|
|
743
|
+
export declare type OAuthAuthenticationParameters = {
|
|
744
|
+
/**
|
|
745
|
+
* Only `client_credentials` is supported.
|
|
746
|
+
*/
|
|
747
|
+
grantType: 'client_credentials';
|
|
748
|
+
/**
|
|
749
|
+
* The client id of an OAuth application an admin already registered.
|
|
750
|
+
*/
|
|
751
|
+
clientId: string;
|
|
752
|
+
/**
|
|
753
|
+
* The client secret for that application. Not accepted from a browser page.
|
|
754
|
+
*/
|
|
755
|
+
clientSecret: string;
|
|
756
|
+
};
|
|
757
|
+
|
|
717
758
|
/**
|
|
718
759
|
* Options used to raise an Intent
|
|
719
760
|
* @public
|
package/index.cjs
CHANGED
|
@@ -1,9 +1,13 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
3
|
var buffer = require('buffer');
|
|
4
|
+
require('fs');
|
|
5
|
+
require('path');
|
|
4
6
|
var mqtt = require('mqtt');
|
|
5
7
|
|
|
6
|
-
var l=t=>{let e=t.replaceAll("-","+").replaceAll("_","/");return e.padEnd(e.length+(4-e.length%4)%4,"=")};
|
|
8
|
+
var Y;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(Y="oauth4webapi/v3.8.8");function q(e,t){if(e==null)return false;try{return e instanceof t||Object.getPrototypeOf(e)[Symbol.toStringTag]===t.prototype[Symbol.toStringTag]}catch{return false}}var y$1="ERR_INVALID_ARG_VALUE",_="ERR_INVALID_ARG_TYPE";function l(e,t,n){let r=new TypeError(e,{cause:n});return Object.assign(r,{code:t}),r}var L=Symbol(),W=Symbol(),M=Symbol(),O=Symbol();var qe=new TextEncoder,We=new TextDecoder;function le(e){return typeof e=="string"?qe.encode(e):We.decode(e)}var Q;Uint8Array.prototype.toBase64?Q=e=>(e instanceof ArrayBuffer&&(e=new Uint8Array(e)),e.toBase64({alphabet:"base64url",omitPadding:true})):Q=t=>{t instanceof ArrayBuffer&&(t=new Uint8Array(t));let n=[];for(let r=0;r<t.byteLength;r+=32768)n.push(String.fromCharCode.apply(null,t.subarray(r,r+32768)));return btoa(n.join("")).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")};var X;Uint8Array.fromBase64?X=e=>{try{return Uint8Array.fromBase64(e,{alphabet:"base64url"})}catch(t){throw l("The input to be decoded is not correctly encoded.",y$1,t)}}:X=e=>{try{let t=atob(e.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"")),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n}catch(t){throw l("The input to be decoded is not correctly encoded.",y$1,t)}};function fe(e){return typeof e=="string"?X(e):Q(e)}var T=class extends Error{code;constructor(t,n){super(t,n),this.name=this.constructor.name,this.code=K,Error.captureStackTrace?.(this,this.constructor);}},D=class extends Error{code;constructor(t,n){super(t,n),this.name=this.constructor.name,n?.code&&(this.code=n?.code),Error.captureStackTrace?.(this,this.constructor);}};function i(e,t,n){return new D(e,{code:t,cause:n})}function H(e){return !(e===null||typeof e!="object"||Array.isArray(e))}function me(e){q(e,Headers)&&(e=Object.fromEntries(e.entries()));let t=new Headers(e??{});if(Y&&!t.has("user-agent")&&t.set("user-agent",Y),t.has("authorization"))throw l('"options.headers" must not include the "authorization" header name',y$1);return t}function ye(e,t){if(t!==void 0){if(typeof t=="function"&&(t=t(e.href)),!(t instanceof AbortSignal))throw l('"options.signal" must return or be an instance of AbortSignal',_);return t}}function _e(e){return e.includes("//")?e.replace("//","/"):e}function Me(e,t,n=false){return e.pathname==="/"?e.pathname=t:e.pathname=_e(`${t}/${n?e.pathname:e.pathname.replace(/(\/)$/,"")}`),e}function ze(e,t){return e.pathname=_e(`${e.pathname}/${t}`),e}async function Ke(e,t,n,r){if(!(e instanceof URL))throw l(`"${t}" must be an instance of URL`,_);z(e,r?.[L]!==true);let o=n(new URL(e.href)),s=me(r?.headers);return s.set("accept","application/json"),(r?.[O]||fetch)(o.href,{body:void 0,headers:Object.fromEntries(s.entries()),method:"GET",redirect:"manual",signal:ye(o,r?.signal)})}async function ge(e,t){return Ke(e,"issuerIdentifier",n=>{switch(t?.algorithm){case void 0:case "oidc":ze(n,".well-known/openid-configuration");break;case "oauth2":Me(n,".well-known/oauth-authorization-server");break;default:throw l('"options.algorithm" must be "oidc" (default), or "oauth2"',y$1)}return n},t)}function Z(e,t,n,r,o){try{if(typeof e!="number"||!Number.isFinite(e))throw l(`${n} must be a number`,_,o);if(e>0)return;if(t){if(e!==0)throw l(`${n} must be a non-negative number`,y$1,o);return}throw l(`${n} must be a positive number`,y$1,o)}catch(s){throw r?i(s.message,r,o):s}}function b(e,t,n,r){try{if(typeof e!="string")throw l(`${t} must be a string`,_,r);if(e.length===0)throw l(`${t} must not be empty`,y$1,r)}catch(o){throw n?i(o.message,n,r):o}}async function Re(e,t){let n=e;if(!(n instanceof URL)&&n!==J)throw l('"expectedIssuerIdentifier" must be an instance of URL',_);if(!q(t,Response))throw l('"response" must be an instance of Response',_);if(t.status!==200)throw i('"response" is not a conform Authorization Server Metadata response (unexpected HTTP status code)',$,t);oe(t);let r=await Ie(t);if(b(r.issuer,'"response" body "issuer" property',d,{body:r}),n!==J&&new URL(r.issuer).href!==n.href)throw i('"response" body "issuer" property does not match the expected value',F,{expected:n.href,body:r,attribute:"issuer"});return r}function be(e){Fe(e,"application/json");}function $e(e,...t){let n='"response" content-type must be ';if(t.length>2){let r=t.pop();n+=`${t.join(", ")}, or ${r}`;}else t.length===2?n+=`${t[0]} or ${t[1]}`:n+=t[0];return i(n,te,e)}function Fe(e,t){if(Ee(e)!==t)throw $e(e,t)}function Be(e){let t=e?.[W];return typeof t=="number"&&Number.isFinite(t)?t:0}function Ge(e){let t=e?.[M];return typeof t=="number"&&Number.isFinite(t)&&Math.sign(t)!==-1?t:30}function Ve(){return Math.floor(Date.now()/1e3)}function Se(e){if(typeof e!="object"||e===null)throw l('"as" must be an object',_);b(e.issuer,'"as.issuer"');}function Pe(e){if(typeof e!="object"||e===null)throw l('"client" must be an object',_);b(e.client_id,'"client.client_id"');}function ee(e){return b(e,'"clientSecret"'),(t,n,r,o)=>{r.set("client_id",n.client_id),r.set("client_secret",e);}}function Ae(){return (e,t,n,r)=>{n.set("client_id",t.client_id);}}var Ye=URL.parse?(e,t)=>URL.parse(e,t):(e,t)=>{try{return new URL(e,t)}catch{return null}};function z(e,t){if(t&&e.protocol!=="https:")throw i("only requests to HTTPS are allowed",ne,e);if(e.protocol!=="https:"&&e.protocol!=="http:")throw i("only HTTP and HTTPS requests are allowed",re,e)}function pe(e,t,n,r){let o;if(typeof e!="string"||!(o=Ye(e)))throw i(`authorization server metadata does not contain a valid ${n?`"as.mtls_endpoint_aliases.${t}"`:`"as.${t}"`}`,e===void 0?Tt:kt,{attribute:n?`mtls_endpoint_aliases.${t}`:t});return z(o,r),o}function Te(e,t,n,r){return n&&e.mtls_endpoint_aliases&&t in e.mtls_endpoint_aliases?pe(e.mtls_endpoint_aliases[t],t,n,r):pe(e[t],t,n,r)}var g=class extends Error{cause;code;error;status;error_description;response;constructor(t,n){super(t,n),this.name=this.constructor.name,this.code=Pt,this.cause=n.cause,this.error=n.cause.error,this.status=n.response.status,this.error_description=n.cause.error_description,Object.defineProperty(this,"response",{enumerable:false,value:n.response}),Error.captureStackTrace?.(this,this.constructor);}},I=class extends Error{cause;code;error;error_description;constructor(t,n){super(t,n),this.name=this.constructor.name,this.code=At,this.cause=n.cause,this.error=n.cause.get("error"),this.error_description=n.cause.get("error_description")??void 0,Error.captureStackTrace?.(this,this.constructor);}},k=class extends Error{cause;code;response;status;constructor(t,n){super(t,n),this.name=this.constructor.name,this.code=St,this.cause=n.cause,this.status=n.response.status,this.response=n.response,Object.defineProperty(this,"response",{enumerable:false}),Error.captureStackTrace?.(this,this.constructor);}},N="[a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+",Qe="[a-zA-Z0-9\\-\\._\\~\\+\\/]+={0,2}",Xe='"((?:[^"\\\\]|\\\\[\\s\\S])*)"',Ze="("+N+")\\s*=\\s*"+Xe,et="("+N+")\\s*=\\s*("+N+")",tt=new RegExp("^[,\\s]*("+N+")"),nt=new RegExp("^[,\\s]*"+Ze+"[,\\s]*(.*)"),rt=new RegExp("^[,\\s]*"+et+"[,\\s]*(.*)"),ot=new RegExp("^("+Qe+")(?:$|[,\\s])(.*)");function at(e){if(!q(e,Response))throw l('"response" must be an instance of Response',_);let t=e.headers.get("www-authenticate");if(t===null)return;let n=[],r=t;for(;r;){let o=r.match(tt),s=o?.[1].toLowerCase();if(!s)return;let a=r.substring(o[0].length);if(a&&!a.match(/^[\s,]/))return;let u=a.match(/^\s+(.*)$/),h=!!u;r=u?u[1]:void 0;let c={},p;if(h)for(;r;){let P,A;if(o=r.match(nt)){[,P,A,r]=o,A.includes("\\")&&(A=A.replace(/\\([\s\S])/g,"$1")),c[P.toLowerCase()]=A;continue}if(o=r.match(rt)){[,P,A,r]=o,c[P.toLowerCase()]=A;continue}if(o=r.match(ot)){if(Object.keys(c).length)break;[,p,r]=o;break}return}else r=a||void 0;let m={scheme:s,parameters:c};p&&(m.token68=p),n.push(m);}if(n.length)return n}async function st(e){if(e.status>399&&e.status<500){oe(e),be(e);try{let t=await e.clone().json();if(H(t)&&typeof t.error=="string"&&t.error.length)return t}catch{}}}async function it(e,t,n){if(e.status!==t){ft(e);let r;throw (r=await st(e))?(await e.body?.cancel(),new g("server responded with an error in the response body",{cause:r,response:e})):i(`"response" is not a conform ${n} response (unexpected HTTP status code)`,$,e)}}function Ee(e){return e.headers.get("content-type")?.split(";")[0]}async function ut(e,t,n,r,o,s,a){return await n(e,t,o,s),s.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"),(a?.[O]||fetch)(r.href,{body:o,headers:Object.fromEntries(s.entries()),method:"POST",redirect:"manual",signal:ye(r,a?.signal)})}async function dt(e,t,n,r,o,s){let a=Te(e,"token_endpoint",t.use_mtls_endpoint_aliases,s?.[L]!==true);o.set("grant_type",r);let u=me(s?.headers);u.set("accept","application/json");let h=await ut(e,t,n,a,o,u,s);return h}var xe=new WeakMap,ht=new WeakMap;function Oe(e){if(!e.id_token)return;let t=xe.get(e);if(!t)throw l('"ref" was already garbage collected or did not resolve from the proper sources',y$1);return t}async function lt(e,t,n,r,o,s){if(Se(e),Pe(t),!q(n,Response))throw l('"response" must be an instance of Response',_);await it(n,200,"Token Endpoint"),oe(n);let a=await Ie(n);if(b(a.access_token,'"response" body "access_token" property',d,{body:a}),b(a.token_type,'"response" body "token_type" property',d,{body:a}),a.token_type=a.token_type.toLowerCase(),a.expires_in!==void 0){let u=typeof a.expires_in!="number"?parseFloat(a.expires_in):a.expires_in;Z(u,true,'"response" body "expires_in" property',d,{body:a}),a.expires_in=u;}if(a.refresh_token!==void 0&&b(a.refresh_token,'"response" body "refresh_token" property',d,{body:a}),a.scope!==void 0&&typeof a.scope!="string")throw i('"response" body "scope" property must be a string',d,{body:a});if(a.id_token!==void 0){b(a.id_token,'"response" body "id_token" property',d,{body:a});let u=[];t.require_auth_time===true&&u.push("auth_time"),t.default_max_age!==void 0&&(Z(t.default_max_age,true,'"client.default_max_age"'),u.push("auth_time"));let{claims:h,jwt:c}=await gt(e,t,a.id_token,u);bt(t,h),Rt(h),ht.set(n,c),xe.set(a,h);}if(a.token_type!=="dpop"&&a.token_type!=="bearer")throw new T("unsupported `token_type` value",{cause:{body:a}});return a}function ft(e){let t;if(t=at(e))throw new k("server responded with a challenge in the WWW-Authenticate HTTP Header",{cause:t,response:e})}function pt(e,t){if(Array.isArray(t.claims.aud)){if(!t.claims.aud.includes(e))throw i('unexpected JWT "aud" (audience) claim value',E,{expected:e,claims:t.claims,claim:"aud"})}else if(t.claims.aud!==e)throw i('unexpected JWT "aud" (audience) claim value',E,{expected:e,claims:t.claims,claim:"aud"});return t}function wt(e,t){let n=e[ae]?.(t)??e.issuer;if(t.claims.iss!==n)throw i('unexpected JWT "iss" (issuer) claim value',E,{expected:n,claims:t.claims,claim:"iss"});return t}var Ce={aud:"audience",c_hash:"code hash",client_id:"client id",exp:"expiration time",iat:"issued at",iss:"issuer",jti:"jwt id",nonce:"nonce",s_hash:"state hash",sub:"subject",ath:"access token hash",htm:"http method",htu:"http uri",cnf:"confirmation",auth_time:"authentication time"};function yt(e,t){for(let n of e)if(t.claims[n]===void 0)throw i(`JWT "${n}" (${Ce[n]}) claim missing`,d,{claims:t.claims});return t}function _t(e,t){if(typeof t.claims[e]!="string")throw i(`unexpected JWT "${e}" (${Ce[e]}) claim type`,d,{claims:t.claims});return t}function gt(e,t,n,r,o){return Et(n,xt.bind(void 0,t.id_token_signed_response_alg,e.id_token_signing_alg_values_supported,"RS256"),Be(t),Ge(t)).then(yt.bind(void 0,["aud","exp","iat","iss","sub",...r])).then(wt.bind(void 0,e)).then(pt.bind(void 0,t.client_id)).then(_t.bind(void 0,"sub"))}function Rt(e){e.auth_time!==void 0&&Z(e.auth_time,true,'ID Token "auth_time" (authentication time)',d,{claims:e});}function bt(e,t){if(Array.isArray(t.aud)&&t.aud.length!==1){if(t.azp===void 0)throw i('ID Token "aud" (audience) claim includes additional untrusted audiences',E,{claims:t,claim:"aud"});if(t.azp!==e.client_id)throw i('unexpected ID Token "azp" (authorized party) claim value',E,{expected:e.client_id,claims:t,claim:"azp"})}}var St="OAUTH_WWW_AUTHENTICATE_CHALLENGE",Pt="OAUTH_RESPONSE_BODY_ERROR",K="OAUTH_UNSUPPORTED_OPERATION",At="OAUTH_AUTHORIZATION_RESPONSE_ERROR";var U="OAUTH_PARSE_ERROR",d="OAUTH_INVALID_RESPONSE";var te="OAUTH_RESPONSE_IS_NOT_JSON",$="OAUTH_RESPONSE_IS_NOT_CONFORM",ne="OAUTH_HTTP_REQUEST_FORBIDDEN",re="OAUTH_REQUEST_PROTOCOL_FORBIDDEN",j="OAUTH_JWT_TIMESTAMP_CHECK_FAILED",E="OAUTH_JWT_CLAIM_COMPARISON_FAILED",F="OAUTH_JSON_ATTRIBUTE_COMPARISON_FAILED";var Tt="OAUTH_MISSING_SERVER_METADATA",kt="OAUTH_INVALID_SERVER_METADATA";async function ve(e,t,n,r,o){return Se(e),Pe(t),dt(e,t,n,"client_credentials",new URLSearchParams(r),o)}async function De(e,t,n,r){return lt(e,t,n)}function oe(e){if(e.bodyUsed)throw l('"response" body has been used already',y$1)}async function Et(e,t,n,r,o){let{0:s,1:a,length:u}=e.split(".");if(u===5)throw new T("JWE decryption is not configured",{cause:e});if(u!==3)throw i("Invalid JWT",d,e);let h;try{h=JSON.parse(le(fe(s)));}catch(m){throw i("failed to parse JWT Header body as base64url encoded JSON",U,m)}if(!H(h))throw i("JWT Header must be a top level object",d,e);if(t(h),h.crit!==void 0)throw new T('no JWT "crit" header parameter extensions are supported',{cause:{header:h}});let c;try{c=JSON.parse(le(fe(a)));}catch(m){throw i("failed to parse JWT Payload body as base64url encoded JSON",U,m)}if(!H(c))throw i("JWT Payload must be a top level object",d,e);let p=Ve()+n;if(c.exp!==void 0){if(typeof c.exp!="number")throw i('unexpected JWT "exp" (expiration time) claim type',d,{claims:c});if(c.exp<=p-r)throw i('unexpected JWT "exp" (expiration time) claim value, expiration is past current timestamp',j,{claims:c,now:p,tolerance:r,claim:"exp"})}if(c.iat!==void 0&&typeof c.iat!="number")throw i('unexpected JWT "iat" (issued at) claim type',d,{claims:c});if(c.iss!==void 0&&typeof c.iss!="string")throw i('unexpected JWT "iss" (issuer) claim type',d,{claims:c});if(c.nbf!==void 0){if(typeof c.nbf!="number")throw i('unexpected JWT "nbf" (not before) claim type',d,{claims:c});if(c.nbf>p+r)throw i('unexpected JWT "nbf" (not before) claim value',j,{claims:c,now:p,tolerance:r,claim:"nbf"})}if(c.aud!==void 0&&typeof c.aud!="string"&&!Array.isArray(c.aud))throw i('unexpected JWT "aud" (audience) claim type',d,{claims:c});return {header:h,claims:c,jwt:e}}function xt(e,t,n,r){if(e!==void 0){if(typeof e=="string"?r.alg!==e:!e.includes(r.alg))throw i('unexpected JWT "alg" header parameter',d,{header:r,expected:e,reason:"client configuration"});return}if(Array.isArray(t)){if(!t.includes(r.alg))throw i('unexpected JWT "alg" header parameter',d,{header:r,expected:t,reason:"authorization server metadata"});return}if(n!==void 0){if(typeof n=="string"?r.alg!==n:typeof n=="function"?!n(r.alg):!n.includes(r.alg))throw i('unexpected JWT "alg" header parameter',d,{header:r,expected:n,reason:"default value"});return}throw i('missing client or server configuration to verify used JWT "alg" header parameter',void 0,{client:e,issuer:t,fallback:n})}async function Ie(e,t=be){let n;try{n=await e.json();}catch(r){throw t(e),i('failed to parse "response" body as JSON',U,r)}if(!H(n))throw i('"response" body must be a top level object',d,{body:n});return n}var J=Symbol(),ae=Symbol();var B,Ue;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(Ue="openid-client/v6.8.8",B={"user-agent":Ue});var R=e=>se.get(e),se;function ce(e){if(e!==void 0)return ee(e);let t=new WeakMap;return (n,r,o,s)=>{let a;return (a=t.get(r))||(Ct(r.client_secret,'"metadata.client_secret"'),a=ee(r.client_secret),t.set(r,a)),a(n,r,o,s)}}function Ct(e,t){if(typeof e!="string")throw x(`${t} must be a string`,V);if(e.length===0)throw x(`${t} must not be empty`,ue)}function vt(){return Ae()}var S=O;var ue="ERR_INVALID_ARG_VALUE",V="ERR_INVALID_ARG_TYPE";function x(e,t,n){let r=new TypeError(e,{cause:n});return Object.assign(r,{code:t}),r}var C=class extends Error{code;constructor(t,n){super(t,n),this.name=this.constructor.name,this.code=n?.code,Error.captureStackTrace?.(this,this.constructor);}};new TextDecoder;function f(e,t,n){return new C(e,{cause:t,code:n})}function ie(e){if(e instanceof TypeError||e instanceof C||e instanceof g||e instanceof I||e instanceof k)throw e;if(e instanceof D)switch(e.code){case ne:throw f("only requests to HTTPS are allowed",e,e.code);case re:throw f("only requests to HTTP or HTTPS are allowed",e,e.code);case $:throw f("unexpected HTTP response status code",e.cause,e.code);case te:throw f("unexpected response content-type",e.cause,e.code);case U:throw f("parsing error occured",e,e.code);case d:throw f("invalid response encountered",e,e.code);case E:throw f("unexpected JWT claim value encountered",e,e.code);case F:throw f("unexpected JSON attribute value encountered",e,e.code);case j:throw f("JWT timestamp claim value failed validation",e,e.code);default:throw f(e.message,e,e.code)}if(e instanceof T)throw f("unsupported operation",e,e.code);if(e instanceof DOMException)switch(e.name){case "OperationError":throw f("runtime operation error",e,K);case "NotSupportedError":throw f("runtime unsupported operation",e,K);case "TimeoutError":throw f("operation timed out",e,"OAUTH_TIMEOUT");case "AbortError":throw f("operation aborted",e,"OAUTH_ABORT")}throw new C("something went wrong",{cause:e})}function Dt(e,t,n){return e.origin==="https://login.microsoftonline.com"&&(!n?.algorithm||n.algorithm==="oidc")?(t[He]=true,true):false}function It(e,t){return !!(e.hostname.endsWith(".b2clogin.com")&&(!t?.algorithm||t.algorithm==="oidc"))}async function Le(e,t,n,r,o){let s=await Ut(e,o),a=new v(s,t,n,r),u=R(a);if(o?.[S]&&(u.fetch=o[S]),o?.timeout!==void 0&&(u.timeout=o.timeout),o?.execute)for(let h of o.execute)h(a);return a}async function Ut(e,t){if(!(e instanceof URL))throw x('"server" must be an instance of URL',V);let n=!e.href.includes("/.well-known/"),r=t?.timeout??30,o=AbortSignal.timeout(r*1e3),s=await(n?ge(e,{algorithm:t?.algorithm,[O]:t?.[S],[L]:t?.execute?.includes(G),signal:o,headers:new Headers(B)}):(t?.[S]||fetch)((z(e,!t?.execute?.includes(G)),e.href),{headers:Object.fromEntries(new Headers({accept:"application/json",...B}).entries()),body:void 0,method:"GET",redirect:"manual",signal:o})).then(a=>Re(J,a)).catch(ie);return n&&new URL(s.issuer).href!==e.href&&(Dt(e,s,t)||It(e,t)||(()=>{throw new C("discovered metadata issuer does not match the expected issuer",{code:F,cause:{expected:e.href,body:s,attribute:"issuer"}})})()),s}function Lt(e){return {supportsPKCE:{__proto__:null,value(t="S256"){return e.code_challenge_methods_supported?.includes(t)===true}}}}function Ht(e){Object.defineProperties(e,Lt(e));}var He=Symbol(),v=class{constructor(t,n,r,o){if(typeof n!="string"||!n.length)throw x('"clientId" must be a non-empty string',V);if(typeof r=="string"&&(r={client_secret:r}),r?.client_id!==void 0&&n!==r.client_id)throw x('"clientId" and "metadata.client_id" must be the same',ue);let s={...structuredClone(r),client_id:n};s[W]=r?.[W]??0,s[M]=r?.[M]??30;let a;o?a=o:typeof s.client_secret=="string"&&s.client_secret.length?a=ce(s.client_secret):a=vt();let u=Object.freeze(s),h=structuredClone(t);He in t&&(h[ae]=({claims:{tid:p}})=>t.issuer.replace("{tenantid}",p));let c=Object.freeze(h);se||=new WeakMap,se.set(this,{__proto__:null,as:c,c:u,auth:a,tlsOnly:true,timeout:30,jwksCache:{}});}serverMetadata(){let t=structuredClone(R(this).as);return Ht(t),t}clientMetadata(){return structuredClone(R(this).c)}get timeout(){return R(this).timeout}set timeout(t){R(this).timeout=t;}get[S](){return R(this).fetch}set[S](t){R(this).fetch=t;}};Object.freeze(v.prototype);function Nt(e){let t;return e.expires_in!==void 0&&(t=Date.now()+e.expires_in*1e3),{expiresIn:{__proto__:null,value(){if(t){let n=Date.now();return t>n?Math.floor((t-n)/1e3):0}}},claims:{__proto__:null,value(){return Oe(e)}}}}function jt(e){Object.defineProperties(e,Nt(e));}function G(e){R(e).tlsOnly=false;}async function de(e,t,n){Jt(e),t=new URLSearchParams(t);let{as:r,c:o,auth:s,fetch:a,tlsOnly:u,timeout:h}=R(e),c=await ve(r,o,s,t,{[O]:a,[L]:!u,DPoP:n?.DPoP,headers:new Headers(B),signal:qt(h)}).catch(ie),p=De(r,o,c),m;try{m=await p;}catch(P){ie(P);}return jt(m),m}function Jt(e){if(!(e instanceof v))throw x('"config" must be an instance of Configuration',V);if(Object.getPrototypeOf(e)!==v.prototype)throw x("subclassing Configuration is not allowed",ue)}function qt(e){return e?AbortSignal.timeout(e*1e3):void 0}var w=class extends Error{code;constructor(t,n){super(t,{cause:n}),this.name="OAuthClientCredentialsError",this.code="ERR_OAUTH";}};var zt=6e4,Kt=new Set(["localhost","127.0.0.1"]),je=e=>e.protocol==="http:"&&Kt.has(e.hostname),$t=e=>typeof e=="number"&&Number.isFinite(e)&&e>0,Ft=e=>{try{return new URL(e)}catch{return}},he=e=>e?`OAuth token request failed: ${e}`:"OAuth token request failed",Je=class e{#e;constructor(t,n,r,o){if(t.protocol!=="https:"&&!je(t))throw new w("OAuth client credentials require an https service URL; http is only allowed for localhost and 127.0.0.1");this.#e={issuer:t,clientId:n,clientSecret:r,fetchImpl:o?.fetch,clock:o?.clock??(()=>Date.now()),cachedToken:void 0,configuration:void 0,flight:void 0,generation:0};}static fromServiceUrl(t,n,r){let o=Ft(t);if(!o||o.protocol!=="http:"&&o.protocol!=="https:")throw new w("OAuth client credentials require an absolute service URL");return new e(new URL(o.origin),n,r)}async getAccessToken(){let{cachedToken:t,clock:n}=this.#e;if(t!==void 0&&t.expiresAt-n()>zt)return t.accessToken;if(this.#e.flight)return this.#e.flight;let r=this.#e.generation,o=this.#t(r).finally(()=>{this.#e.flight===o&&(this.#e.flight=void 0);});return this.#e.flight=o,o}invalidate(){this.#e.cachedToken=void 0,this.#e.generation+=1,this.#e.flight=void 0;}async#t(t){let n=await this.#n(),r;try{r=await de(n);}catch(s){throw s instanceof TypeError||s instanceof w?s:s instanceof g?new w(he(s.error),s):new w(he(),s)}let o=r.access_token;if(typeof o!="string"||o.length===0)throw new w(he());if(this.#e.generation===t){let s=r.expires_in;this.#e.cachedToken=$t(s)?{accessToken:o,expiresAt:this.#e.clock()+s*1e3}:void 0;}return o}async#n(){if(this.#e.configuration)return this.#e.configuration;let t=this.#e.fetchImpl??globalThis.fetch;try{let n=await Le(this.#e.issuer,this.#e.clientId,this.#e.clientSecret,ce(this.#e.clientSecret),{algorithm:"oauth2",[S]:t,...je(this.#e.issuer)?{execute:[G]}:{}});return this.#e.configuration=n,n}catch(n){throw n instanceof TypeError?n:new w("OAuth authorization server discovery failed",n)}}},$n=({grantType:e,clientSecret:t})=>{if(e!=="client_credentials")throw new w("Only the client_credentials grant is supported");if(globalThis.window!==void 0&&t.length>0)throw new w("Client credentials authentication is not supported in the browser")},Fn=async(e,t)=>{let n=await t();return n.status!==401?n:(await n.body?.cancel().catch(()=>{}),e.invalidate(),t())};
|
|
9
|
+
|
|
10
|
+
var y=e=>{let n=e.replaceAll("-","+").replaceAll("_","/");return n.padEnd(n.length+(4-n.length%4)%4,"=")};
|
|
7
11
|
|
|
8
12
|
class CloudInteropAPIError extends Error {
|
|
9
13
|
code;
|
|
@@ -18,6 +22,21 @@ class AuthorizationError extends CloudInteropAPIError {
|
|
|
18
22
|
super(message, code, undefined);
|
|
19
23
|
}
|
|
20
24
|
}
|
|
25
|
+
class OAuthAuthenticationError extends CloudInteropAPIError {
|
|
26
|
+
constructor(message, cause) {
|
|
27
|
+
super(message, 'ERR_OAUTH', cause);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const rethrowAsOAuthAuthenticationError = (error) => {
|
|
32
|
+
if (error instanceof w) {
|
|
33
|
+
throw new OAuthAuthenticationError(error.message, error);
|
|
34
|
+
}
|
|
35
|
+
if (error instanceof TypeError) {
|
|
36
|
+
throw new OAuthAuthenticationError('OAuth access token could not be obtained', error);
|
|
37
|
+
}
|
|
38
|
+
throw error;
|
|
39
|
+
};
|
|
21
40
|
|
|
22
41
|
class EventController {
|
|
23
42
|
#eventListeners = new Map();
|
|
@@ -51,11 +70,20 @@ class EventController {
|
|
|
51
70
|
const isErrorIntentResult = (result) => 'error' in result;
|
|
52
71
|
|
|
53
72
|
const APP_ID_DELIM = '::';
|
|
54
|
-
const getRequestHeaders = (connectionParameters) => {
|
|
73
|
+
const getRequestHeaders = async (connectionParameters, tokenClient) => {
|
|
55
74
|
const headers = {};
|
|
56
75
|
headers['Content-Type'] = 'application/json';
|
|
76
|
+
if (connectionParameters.authenticationType === 'oauth' && tokenClient) {
|
|
77
|
+
try {
|
|
78
|
+
const accessToken = await tokenClient.getAccessToken();
|
|
79
|
+
headers['Authorization'] = `Bearer ${accessToken}`;
|
|
80
|
+
}
|
|
81
|
+
catch (error) {
|
|
82
|
+
rethrowAsOAuthAuthenticationError(error);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
57
85
|
if (connectionParameters.authenticationType === 'jwt' && connectionParameters.jwtAuthenticationParameters) {
|
|
58
|
-
const tokenResult = connectionParameters.jwtAuthenticationParameters.jwtRequestCallback();
|
|
86
|
+
const tokenResult = await connectionParameters.jwtAuthenticationParameters.jwtRequestCallback();
|
|
59
87
|
if (!tokenResult) {
|
|
60
88
|
throw new Error('jwtRequestCallback must return a token');
|
|
61
89
|
}
|
|
@@ -137,16 +165,16 @@ class IntentController {
|
|
|
137
165
|
#url;
|
|
138
166
|
#mqttClient;
|
|
139
167
|
#sessionDetails;
|
|
140
|
-
#
|
|
168
|
+
#authenticatedFetch;
|
|
141
169
|
#events;
|
|
142
170
|
#logger;
|
|
143
171
|
#discovery = newDiscovery();
|
|
144
172
|
#discoveryTimeout;
|
|
145
|
-
constructor(url, mqttClient, sessionDetails,
|
|
173
|
+
constructor(url, mqttClient, sessionDetails, authenticatedFetch, events, logger) {
|
|
146
174
|
this.#url = url;
|
|
147
175
|
this.#mqttClient = mqttClient;
|
|
148
176
|
this.#sessionDetails = sessionDetails;
|
|
149
|
-
this.#
|
|
177
|
+
this.#authenticatedFetch = authenticatedFetch;
|
|
150
178
|
this.#events = events;
|
|
151
179
|
this.#logger = logger;
|
|
152
180
|
}
|
|
@@ -158,9 +186,8 @@ class IntentController {
|
|
|
158
186
|
// clamp min value to 500ms
|
|
159
187
|
const clampedTimeout = Math.max(timeout, MIN_TIMEOUT);
|
|
160
188
|
try {
|
|
161
|
-
const startResponse = await
|
|
189
|
+
const startResponse = await this.#authenticatedFetch(`${this.#url}/api/intents/${this.#sessionDetails.sessionId}`, {
|
|
162
190
|
method: 'POST',
|
|
163
|
-
headers: getRequestHeaders(this.#connectionParams),
|
|
164
191
|
body: JSON.stringify({ findOptions }),
|
|
165
192
|
});
|
|
166
193
|
if (!startResponse.ok) {
|
|
@@ -203,9 +230,8 @@ class IntentController {
|
|
|
203
230
|
this.#logger('warn', `Error ending intent discovery: could not unsubscribe from discovery id ${this.#discovery.id}`);
|
|
204
231
|
});
|
|
205
232
|
}
|
|
206
|
-
await
|
|
233
|
+
await this.#authenticatedFetch(`${this.#url}/api/intents/${this.#sessionDetails.sessionId}/${this.#discovery.id}`, {
|
|
207
234
|
method: 'DELETE',
|
|
208
|
-
headers: getRequestHeaders(this.#connectionParams),
|
|
209
235
|
})
|
|
210
236
|
.then((deleteResponse) => {
|
|
211
237
|
if (!deleteResponse.ok) {
|
|
@@ -224,9 +250,8 @@ class IntentController {
|
|
|
224
250
|
// TODO: should we add more info here about the format?
|
|
225
251
|
throw new CloudInteropAPIError(`Invalid AppId specified, must be encoded as a cloud-session app id`, 'ERR_INVALID_TARGET_SESSION_ID');
|
|
226
252
|
}
|
|
227
|
-
const postResponse = await
|
|
253
|
+
const postResponse = await this.#authenticatedFetch(`${this.#url}/api/intents/${this.#sessionDetails.sessionId}/sessions/${targetSessionId}`, {
|
|
228
254
|
method: 'POST',
|
|
229
|
-
headers: getRequestHeaders(this.#connectionParams),
|
|
230
255
|
body: JSON.stringify({ raiseOptions }),
|
|
231
256
|
});
|
|
232
257
|
if (!postResponse.ok) {
|
|
@@ -238,9 +263,8 @@ class IntentController {
|
|
|
238
263
|
async reportAppIntents(discoveryId, intents) {
|
|
239
264
|
intents = encodeAppIntents(intents, getSourceFromSession(this.#sessionDetails));
|
|
240
265
|
try {
|
|
241
|
-
const reportResponse = await
|
|
266
|
+
const reportResponse = await this.#authenticatedFetch(`${this.#url}/api/intents/${this.#sessionDetails.sessionId}/${discoveryId}`, {
|
|
242
267
|
method: 'POST',
|
|
243
|
-
headers: getRequestHeaders(this.#connectionParams),
|
|
244
268
|
body: JSON.stringify({ intents }),
|
|
245
269
|
});
|
|
246
270
|
if (reportResponse.ok) {
|
|
@@ -262,9 +286,8 @@ class IntentController {
|
|
|
262
286
|
result.source = typeof result.source === 'string' ? encoded : { ...result.source, appId: encoded };
|
|
263
287
|
}
|
|
264
288
|
const { sessionId } = getSourceFromSession(this.#sessionDetails);
|
|
265
|
-
const resultResponse = await
|
|
289
|
+
const resultResponse = await this.#authenticatedFetch(`${this.#url}/api/intents/${initiatingSessionId}/result/${sessionId}`, {
|
|
266
290
|
method: 'POST',
|
|
267
|
-
headers: getRequestHeaders(this.#connectionParams),
|
|
268
291
|
body: JSON.stringify({ result }),
|
|
269
292
|
});
|
|
270
293
|
if (!resultResponse.ok) {
|
|
@@ -348,10 +371,12 @@ class CloudInteropAPI {
|
|
|
348
371
|
#reconnectRetryLimit = 30;
|
|
349
372
|
#keepAliveIntervalSeconds = 30;
|
|
350
373
|
#logger = (level, message) => {
|
|
374
|
+
// eslint-disable-next-line security/detect-object-injection -- level is restricted to the LogLevel union
|
|
351
375
|
console[level](message);
|
|
352
376
|
};
|
|
353
377
|
#reconnectRetries = 0;
|
|
354
378
|
#connectionParams;
|
|
379
|
+
#tokenClient;
|
|
355
380
|
#attemptingToReconnect = false;
|
|
356
381
|
#events = new EventController();
|
|
357
382
|
#intents;
|
|
@@ -373,17 +398,29 @@ class CloudInteropAPI {
|
|
|
373
398
|
* @memberof CloudInteropAPI
|
|
374
399
|
* @throws CloudInteropAPIError - If an error occurs during connection
|
|
375
400
|
* @throws AuthorizationError - If the connection is unauthorized
|
|
401
|
+
* @throws OAuthAuthenticationError - If OAuth parameters are invalid, the client credentials are rejected, or an access token cannot be obtained
|
|
376
402
|
*/
|
|
377
403
|
async connect(parameters) {
|
|
378
404
|
this.#validateConnectParams(parameters);
|
|
405
|
+
const oauthParameters = parameters.oauthAuthenticationParameters;
|
|
406
|
+
if (parameters.authenticationType === 'oauth' && oauthParameters) {
|
|
407
|
+
try {
|
|
408
|
+
this.#tokenClient = Je.fromServiceUrl(this.#cloudInteropSettings.url, oauthParameters.clientId, oauthParameters.clientSecret);
|
|
409
|
+
}
|
|
410
|
+
catch (error) {
|
|
411
|
+
rethrowAsOAuthAuthenticationError(error);
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
else {
|
|
415
|
+
this.#tokenClient = undefined;
|
|
416
|
+
}
|
|
379
417
|
this.#connectionParams = parameters;
|
|
380
418
|
this.#reconnectRetryLimit = parameters.reconnectRetryLimit || this.#reconnectRetryLimit;
|
|
381
419
|
this.#keepAliveIntervalSeconds = parameters.keepAliveIntervalSeconds || this.#keepAliveIntervalSeconds;
|
|
382
420
|
this.#logger = parameters.logger || this.#logger;
|
|
383
421
|
const { sourceId, platformId } = this.#connectionParams;
|
|
384
|
-
const createSessionResponse = await
|
|
422
|
+
const createSessionResponse = await this.#authenticatedFetch(`${this.#cloudInteropSettings.url}/api/sessions`, {
|
|
385
423
|
method: 'POST',
|
|
386
|
-
headers: getRequestHeaders(this.#connectionParams),
|
|
387
424
|
body: JSON.stringify({ sourceId: sourceId.trim(), platformId }),
|
|
388
425
|
});
|
|
389
426
|
if (!createSessionResponse.ok) {
|
|
@@ -421,11 +458,12 @@ class CloudInteropAPI {
|
|
|
421
458
|
// TODO: Dynamic intent discovery
|
|
422
459
|
// search for any ongoing discoveries in DB and fire report-intents on self
|
|
423
460
|
this.#logger('log', `Cloud Interop successfully connected to ${this.#cloudInteropSettings.url}`);
|
|
461
|
+
// eslint-disable-next-line security-node/detect-unhandled-event-errors -- this callback handles MQTT error events
|
|
424
462
|
this.#mqttClient.on('error', async (error) => {
|
|
425
463
|
// We will receive errors for each failed reconnection attempt
|
|
426
464
|
// We don't want to disconnect on these else we will never reconnect
|
|
427
465
|
if (!this.#attemptingToReconnect) {
|
|
428
|
-
await this.#
|
|
466
|
+
await this.#disconnectAndLogFailure();
|
|
429
467
|
}
|
|
430
468
|
if (error instanceof mqtt.ErrorWithReasonCode) {
|
|
431
469
|
switch (error.code) {
|
|
@@ -451,15 +489,15 @@ class CloudInteropAPI {
|
|
|
451
489
|
}
|
|
452
490
|
}
|
|
453
491
|
});
|
|
454
|
-
this.#mqttClient.on('reconnect', () => {
|
|
492
|
+
this.#mqttClient.on('reconnect', async () => {
|
|
455
493
|
this.#attemptingToReconnect = true;
|
|
456
494
|
this.#reconnectRetries += 1;
|
|
457
495
|
this.#logger('debug', `Cloud Interop attempting reconnection - ${this.#reconnectRetries}...`);
|
|
496
|
+
this.#events.emitEvent('reconnecting', this.#reconnectRetries);
|
|
458
497
|
if (this.#reconnectRetries === this.#reconnectRetryLimit) {
|
|
459
498
|
this.#logger('warn', `Cloud Interop reached max reconnection attempts - ${this.#reconnectRetryLimit}...`);
|
|
460
|
-
this.#
|
|
499
|
+
await this.#disconnectAndLogFailure(true);
|
|
461
500
|
}
|
|
462
|
-
this.#events.emitEvent('reconnecting', this.#reconnectRetries);
|
|
463
501
|
});
|
|
464
502
|
// Does not fire on initial connection, only successful reconnection attempts
|
|
465
503
|
this.#mqttClient.on('connect', () => {
|
|
@@ -479,7 +517,7 @@ class CloudInteropAPI {
|
|
|
479
517
|
this.#mqttClient.subscribe(`${sessionRootTopic}/context-groups/#`);
|
|
480
518
|
// Listen out for global commands
|
|
481
519
|
this.#mqttClient.subscribe(`${sessionRootTopic}/commands`);
|
|
482
|
-
this.#initControllers(this.#mqttClient, this.#sessionDetails
|
|
520
|
+
this.#initControllers(this.#mqttClient, this.#sessionDetails);
|
|
483
521
|
}
|
|
484
522
|
/**
|
|
485
523
|
* Disconnects from the Cloud Interop service
|
|
@@ -511,9 +549,8 @@ class CloudInteropAPI {
|
|
|
511
549
|
context,
|
|
512
550
|
timestamp: Date.now(),
|
|
513
551
|
};
|
|
514
|
-
const postResponse = await
|
|
552
|
+
const postResponse = await this.#authenticatedFetch(`${this.#cloudInteropSettings.url}/api/context-groups/${this.#sessionDetails.sessionId}/${contextGroup}`, {
|
|
515
553
|
method: 'POST',
|
|
516
|
-
headers: getRequestHeaders(this.#connectionParams),
|
|
517
554
|
body: JSON.stringify(payload),
|
|
518
555
|
});
|
|
519
556
|
if (!postResponse.ok) {
|
|
@@ -571,9 +608,8 @@ class CloudInteropAPI {
|
|
|
571
608
|
clearTimeout(this.#sessionTimer);
|
|
572
609
|
this.#sessionTimer = undefined;
|
|
573
610
|
}
|
|
574
|
-
const disconnectResponse = await
|
|
611
|
+
const disconnectResponse = await this.#authenticatedFetch(`${this.#cloudInteropSettings.url}/api/sessions/${this.#sessionDetails.sessionId}`, {
|
|
575
612
|
method: 'DELETE',
|
|
576
|
-
headers: getRequestHeaders(this.#connectionParams),
|
|
577
613
|
});
|
|
578
614
|
if (disconnectResponse.status !== 200) {
|
|
579
615
|
throw new CloudInteropAPIError('Error during session tear down - unexpected status', 'ERR_DISCONNECT', new Error(disconnectResponse.statusText));
|
|
@@ -596,6 +632,7 @@ class CloudInteropAPI {
|
|
|
596
632
|
}
|
|
597
633
|
}
|
|
598
634
|
#handleMessage(topic, message, sessionDetails) {
|
|
635
|
+
this.#logger('debug', `Received message on topic: ${topic}`);
|
|
599
636
|
if (message.length === 0 || !sessionDetails) {
|
|
600
637
|
// Ignore clean up messages
|
|
601
638
|
return;
|
|
@@ -654,10 +691,35 @@ class CloudInteropAPI {
|
|
|
654
691
|
(!parameters.basicAuthenticationParameters?.username || !parameters.basicAuthenticationParameters?.password)) {
|
|
655
692
|
throw new Error('basicAuthenticationParameters must be provided when using basic authentication');
|
|
656
693
|
}
|
|
694
|
+
if (parameters.authenticationType === 'oauth') {
|
|
695
|
+
if (!parameters.oauthAuthenticationParameters?.clientId?.trim() || !parameters.oauthAuthenticationParameters?.clientSecret?.trim()) {
|
|
696
|
+
throw new OAuthAuthenticationError('oauthAuthenticationParameters must be provided when using oauth authentication');
|
|
697
|
+
}
|
|
698
|
+
try {
|
|
699
|
+
$n(parameters.oauthAuthenticationParameters);
|
|
700
|
+
}
|
|
701
|
+
catch (error) {
|
|
702
|
+
rethrowAsOAuthAuthenticationError(error);
|
|
703
|
+
}
|
|
704
|
+
}
|
|
657
705
|
};
|
|
658
|
-
#initControllers(mqttClient, sessionDetails
|
|
659
|
-
this.#intents = new IntentController(this.#cloudInteropSettings.url, mqttClient, sessionDetails,
|
|
706
|
+
#initControllers(mqttClient, sessionDetails) {
|
|
707
|
+
this.#intents = new IntentController(this.#cloudInteropSettings.url, mqttClient, sessionDetails, this.#authenticatedFetch, this.#events, this.#logger);
|
|
660
708
|
}
|
|
709
|
+
#authenticatedFetch = async (url, { method, body }) => {
|
|
710
|
+
const connectionParameters = this.#connectionParams;
|
|
711
|
+
if (!connectionParameters) {
|
|
712
|
+
throw new Error('Connect parameters must be provided');
|
|
713
|
+
}
|
|
714
|
+
const attempt = async () => {
|
|
715
|
+
const headers = await getRequestHeaders(connectionParameters, this.#tokenClient);
|
|
716
|
+
return fetch(url, { method, headers, body });
|
|
717
|
+
};
|
|
718
|
+
if (connectionParameters.authenticationType === 'oauth' && this.#tokenClient) {
|
|
719
|
+
return Fn(this.#tokenClient, attempt);
|
|
720
|
+
}
|
|
721
|
+
return attempt();
|
|
722
|
+
};
|
|
661
723
|
#destroyControllers() {
|
|
662
724
|
this.#intents = undefined;
|
|
663
725
|
}
|
|
@@ -686,7 +748,7 @@ class CloudInteropAPI {
|
|
|
686
748
|
}
|
|
687
749
|
const payload = parts[1];
|
|
688
750
|
// Decode base64url encoded payload
|
|
689
|
-
const decodedBytes = buffer.Buffer.from(
|
|
751
|
+
const decodedBytes = buffer.Buffer.from(y(payload), 'base64');
|
|
690
752
|
const payloadJson = decodedBytes.toString('utf8');
|
|
691
753
|
// Parse JSON to get the exp claim
|
|
692
754
|
const claims = JSON.parse(payloadJson);
|
|
@@ -747,12 +809,21 @@ class CloudInteropAPI {
|
|
|
747
809
|
* Handles session expiry by executing the same actions as the BadUserNamePasswordError case.
|
|
748
810
|
*/
|
|
749
811
|
async #handleSessionExpiry() {
|
|
750
|
-
await this.#
|
|
812
|
+
await this.#disconnectAndLogFailure();
|
|
751
813
|
this.#logger('warn', 'Session expired');
|
|
752
814
|
this.#events.emitEvent('session-expired');
|
|
753
815
|
}
|
|
816
|
+
async #disconnectAndLogFailure(fireDisconnectedEvent = false) {
|
|
817
|
+
try {
|
|
818
|
+
await this.#disconnect(fireDisconnectedEvent);
|
|
819
|
+
}
|
|
820
|
+
catch (error) {
|
|
821
|
+
this.#logger('error', `Session teardown failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
822
|
+
}
|
|
823
|
+
}
|
|
754
824
|
}
|
|
755
825
|
|
|
756
826
|
exports.AuthorizationError = AuthorizationError;
|
|
757
827
|
exports.CloudInteropAPI = CloudInteropAPI;
|
|
758
828
|
exports.CloudInteropAPIError = CloudInteropAPIError;
|
|
829
|
+
exports.OAuthAuthenticationError = OAuthAuthenticationError;
|
package/index.mjs
CHANGED
|
@@ -1,7 +1,11 @@
|
|
|
1
1
|
import { Buffer } from 'buffer';
|
|
2
|
+
import 'fs';
|
|
3
|
+
import 'path';
|
|
2
4
|
import mqtt from 'mqtt';
|
|
3
5
|
|
|
4
|
-
var l=t=>{let e=t.replaceAll("-","+").replaceAll("_","/");return e.padEnd(e.length+(4-e.length%4)%4,"=")};
|
|
6
|
+
var Y;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(Y="oauth4webapi/v3.8.8");function q(e,t){if(e==null)return false;try{return e instanceof t||Object.getPrototypeOf(e)[Symbol.toStringTag]===t.prototype[Symbol.toStringTag]}catch{return false}}var y$1="ERR_INVALID_ARG_VALUE",_="ERR_INVALID_ARG_TYPE";function l(e,t,n){let r=new TypeError(e,{cause:n});return Object.assign(r,{code:t}),r}var L=Symbol(),W=Symbol(),M=Symbol(),O=Symbol();var qe=new TextEncoder,We=new TextDecoder;function le(e){return typeof e=="string"?qe.encode(e):We.decode(e)}var Q;Uint8Array.prototype.toBase64?Q=e=>(e instanceof ArrayBuffer&&(e=new Uint8Array(e)),e.toBase64({alphabet:"base64url",omitPadding:true})):Q=t=>{t instanceof ArrayBuffer&&(t=new Uint8Array(t));let n=[];for(let r=0;r<t.byteLength;r+=32768)n.push(String.fromCharCode.apply(null,t.subarray(r,r+32768)));return btoa(n.join("")).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")};var X;Uint8Array.fromBase64?X=e=>{try{return Uint8Array.fromBase64(e,{alphabet:"base64url"})}catch(t){throw l("The input to be decoded is not correctly encoded.",y$1,t)}}:X=e=>{try{let t=atob(e.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"")),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n}catch(t){throw l("The input to be decoded is not correctly encoded.",y$1,t)}};function fe(e){return typeof e=="string"?X(e):Q(e)}var T=class extends Error{code;constructor(t,n){super(t,n),this.name=this.constructor.name,this.code=K,Error.captureStackTrace?.(this,this.constructor);}},D=class extends Error{code;constructor(t,n){super(t,n),this.name=this.constructor.name,n?.code&&(this.code=n?.code),Error.captureStackTrace?.(this,this.constructor);}};function i(e,t,n){return new D(e,{code:t,cause:n})}function H(e){return !(e===null||typeof e!="object"||Array.isArray(e))}function me(e){q(e,Headers)&&(e=Object.fromEntries(e.entries()));let t=new Headers(e??{});if(Y&&!t.has("user-agent")&&t.set("user-agent",Y),t.has("authorization"))throw l('"options.headers" must not include the "authorization" header name',y$1);return t}function ye(e,t){if(t!==void 0){if(typeof t=="function"&&(t=t(e.href)),!(t instanceof AbortSignal))throw l('"options.signal" must return or be an instance of AbortSignal',_);return t}}function _e(e){return e.includes("//")?e.replace("//","/"):e}function Me(e,t,n=false){return e.pathname==="/"?e.pathname=t:e.pathname=_e(`${t}/${n?e.pathname:e.pathname.replace(/(\/)$/,"")}`),e}function ze(e,t){return e.pathname=_e(`${e.pathname}/${t}`),e}async function Ke(e,t,n,r){if(!(e instanceof URL))throw l(`"${t}" must be an instance of URL`,_);z(e,r?.[L]!==true);let o=n(new URL(e.href)),s=me(r?.headers);return s.set("accept","application/json"),(r?.[O]||fetch)(o.href,{body:void 0,headers:Object.fromEntries(s.entries()),method:"GET",redirect:"manual",signal:ye(o,r?.signal)})}async function ge(e,t){return Ke(e,"issuerIdentifier",n=>{switch(t?.algorithm){case void 0:case "oidc":ze(n,".well-known/openid-configuration");break;case "oauth2":Me(n,".well-known/oauth-authorization-server");break;default:throw l('"options.algorithm" must be "oidc" (default), or "oauth2"',y$1)}return n},t)}function Z(e,t,n,r,o){try{if(typeof e!="number"||!Number.isFinite(e))throw l(`${n} must be a number`,_,o);if(e>0)return;if(t){if(e!==0)throw l(`${n} must be a non-negative number`,y$1,o);return}throw l(`${n} must be a positive number`,y$1,o)}catch(s){throw r?i(s.message,r,o):s}}function b(e,t,n,r){try{if(typeof e!="string")throw l(`${t} must be a string`,_,r);if(e.length===0)throw l(`${t} must not be empty`,y$1,r)}catch(o){throw n?i(o.message,n,r):o}}async function Re(e,t){let n=e;if(!(n instanceof URL)&&n!==J)throw l('"expectedIssuerIdentifier" must be an instance of URL',_);if(!q(t,Response))throw l('"response" must be an instance of Response',_);if(t.status!==200)throw i('"response" is not a conform Authorization Server Metadata response (unexpected HTTP status code)',$,t);oe(t);let r=await Ie(t);if(b(r.issuer,'"response" body "issuer" property',d,{body:r}),n!==J&&new URL(r.issuer).href!==n.href)throw i('"response" body "issuer" property does not match the expected value',F,{expected:n.href,body:r,attribute:"issuer"});return r}function be(e){Fe(e,"application/json");}function $e(e,...t){let n='"response" content-type must be ';if(t.length>2){let r=t.pop();n+=`${t.join(", ")}, or ${r}`;}else t.length===2?n+=`${t[0]} or ${t[1]}`:n+=t[0];return i(n,te,e)}function Fe(e,t){if(Ee(e)!==t)throw $e(e,t)}function Be(e){let t=e?.[W];return typeof t=="number"&&Number.isFinite(t)?t:0}function Ge(e){let t=e?.[M];return typeof t=="number"&&Number.isFinite(t)&&Math.sign(t)!==-1?t:30}function Ve(){return Math.floor(Date.now()/1e3)}function Se(e){if(typeof e!="object"||e===null)throw l('"as" must be an object',_);b(e.issuer,'"as.issuer"');}function Pe(e){if(typeof e!="object"||e===null)throw l('"client" must be an object',_);b(e.client_id,'"client.client_id"');}function ee(e){return b(e,'"clientSecret"'),(t,n,r,o)=>{r.set("client_id",n.client_id),r.set("client_secret",e);}}function Ae(){return (e,t,n,r)=>{n.set("client_id",t.client_id);}}var Ye=URL.parse?(e,t)=>URL.parse(e,t):(e,t)=>{try{return new URL(e,t)}catch{return null}};function z(e,t){if(t&&e.protocol!=="https:")throw i("only requests to HTTPS are allowed",ne,e);if(e.protocol!=="https:"&&e.protocol!=="http:")throw i("only HTTP and HTTPS requests are allowed",re,e)}function pe(e,t,n,r){let o;if(typeof e!="string"||!(o=Ye(e)))throw i(`authorization server metadata does not contain a valid ${n?`"as.mtls_endpoint_aliases.${t}"`:`"as.${t}"`}`,e===void 0?Tt:kt,{attribute:n?`mtls_endpoint_aliases.${t}`:t});return z(o,r),o}function Te(e,t,n,r){return n&&e.mtls_endpoint_aliases&&t in e.mtls_endpoint_aliases?pe(e.mtls_endpoint_aliases[t],t,n,r):pe(e[t],t,n,r)}var g=class extends Error{cause;code;error;status;error_description;response;constructor(t,n){super(t,n),this.name=this.constructor.name,this.code=Pt,this.cause=n.cause,this.error=n.cause.error,this.status=n.response.status,this.error_description=n.cause.error_description,Object.defineProperty(this,"response",{enumerable:false,value:n.response}),Error.captureStackTrace?.(this,this.constructor);}},I=class extends Error{cause;code;error;error_description;constructor(t,n){super(t,n),this.name=this.constructor.name,this.code=At,this.cause=n.cause,this.error=n.cause.get("error"),this.error_description=n.cause.get("error_description")??void 0,Error.captureStackTrace?.(this,this.constructor);}},k=class extends Error{cause;code;response;status;constructor(t,n){super(t,n),this.name=this.constructor.name,this.code=St,this.cause=n.cause,this.status=n.response.status,this.response=n.response,Object.defineProperty(this,"response",{enumerable:false}),Error.captureStackTrace?.(this,this.constructor);}},N="[a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+",Qe="[a-zA-Z0-9\\-\\._\\~\\+\\/]+={0,2}",Xe='"((?:[^"\\\\]|\\\\[\\s\\S])*)"',Ze="("+N+")\\s*=\\s*"+Xe,et="("+N+")\\s*=\\s*("+N+")",tt=new RegExp("^[,\\s]*("+N+")"),nt=new RegExp("^[,\\s]*"+Ze+"[,\\s]*(.*)"),rt=new RegExp("^[,\\s]*"+et+"[,\\s]*(.*)"),ot=new RegExp("^("+Qe+")(?:$|[,\\s])(.*)");function at(e){if(!q(e,Response))throw l('"response" must be an instance of Response',_);let t=e.headers.get("www-authenticate");if(t===null)return;let n=[],r=t;for(;r;){let o=r.match(tt),s=o?.[1].toLowerCase();if(!s)return;let a=r.substring(o[0].length);if(a&&!a.match(/^[\s,]/))return;let u=a.match(/^\s+(.*)$/),h=!!u;r=u?u[1]:void 0;let c={},p;if(h)for(;r;){let P,A;if(o=r.match(nt)){[,P,A,r]=o,A.includes("\\")&&(A=A.replace(/\\([\s\S])/g,"$1")),c[P.toLowerCase()]=A;continue}if(o=r.match(rt)){[,P,A,r]=o,c[P.toLowerCase()]=A;continue}if(o=r.match(ot)){if(Object.keys(c).length)break;[,p,r]=o;break}return}else r=a||void 0;let m={scheme:s,parameters:c};p&&(m.token68=p),n.push(m);}if(n.length)return n}async function st(e){if(e.status>399&&e.status<500){oe(e),be(e);try{let t=await e.clone().json();if(H(t)&&typeof t.error=="string"&&t.error.length)return t}catch{}}}async function it(e,t,n){if(e.status!==t){ft(e);let r;throw (r=await st(e))?(await e.body?.cancel(),new g("server responded with an error in the response body",{cause:r,response:e})):i(`"response" is not a conform ${n} response (unexpected HTTP status code)`,$,e)}}function Ee(e){return e.headers.get("content-type")?.split(";")[0]}async function ut(e,t,n,r,o,s,a){return await n(e,t,o,s),s.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"),(a?.[O]||fetch)(r.href,{body:o,headers:Object.fromEntries(s.entries()),method:"POST",redirect:"manual",signal:ye(r,a?.signal)})}async function dt(e,t,n,r,o,s){let a=Te(e,"token_endpoint",t.use_mtls_endpoint_aliases,s?.[L]!==true);o.set("grant_type",r);let u=me(s?.headers);u.set("accept","application/json");let h=await ut(e,t,n,a,o,u,s);return h}var xe=new WeakMap,ht=new WeakMap;function Oe(e){if(!e.id_token)return;let t=xe.get(e);if(!t)throw l('"ref" was already garbage collected or did not resolve from the proper sources',y$1);return t}async function lt(e,t,n,r,o,s){if(Se(e),Pe(t),!q(n,Response))throw l('"response" must be an instance of Response',_);await it(n,200,"Token Endpoint"),oe(n);let a=await Ie(n);if(b(a.access_token,'"response" body "access_token" property',d,{body:a}),b(a.token_type,'"response" body "token_type" property',d,{body:a}),a.token_type=a.token_type.toLowerCase(),a.expires_in!==void 0){let u=typeof a.expires_in!="number"?parseFloat(a.expires_in):a.expires_in;Z(u,true,'"response" body "expires_in" property',d,{body:a}),a.expires_in=u;}if(a.refresh_token!==void 0&&b(a.refresh_token,'"response" body "refresh_token" property',d,{body:a}),a.scope!==void 0&&typeof a.scope!="string")throw i('"response" body "scope" property must be a string',d,{body:a});if(a.id_token!==void 0){b(a.id_token,'"response" body "id_token" property',d,{body:a});let u=[];t.require_auth_time===true&&u.push("auth_time"),t.default_max_age!==void 0&&(Z(t.default_max_age,true,'"client.default_max_age"'),u.push("auth_time"));let{claims:h,jwt:c}=await gt(e,t,a.id_token,u);bt(t,h),Rt(h),ht.set(n,c),xe.set(a,h);}if(a.token_type!=="dpop"&&a.token_type!=="bearer")throw new T("unsupported `token_type` value",{cause:{body:a}});return a}function ft(e){let t;if(t=at(e))throw new k("server responded with a challenge in the WWW-Authenticate HTTP Header",{cause:t,response:e})}function pt(e,t){if(Array.isArray(t.claims.aud)){if(!t.claims.aud.includes(e))throw i('unexpected JWT "aud" (audience) claim value',E,{expected:e,claims:t.claims,claim:"aud"})}else if(t.claims.aud!==e)throw i('unexpected JWT "aud" (audience) claim value',E,{expected:e,claims:t.claims,claim:"aud"});return t}function wt(e,t){let n=e[ae]?.(t)??e.issuer;if(t.claims.iss!==n)throw i('unexpected JWT "iss" (issuer) claim value',E,{expected:n,claims:t.claims,claim:"iss"});return t}var Ce={aud:"audience",c_hash:"code hash",client_id:"client id",exp:"expiration time",iat:"issued at",iss:"issuer",jti:"jwt id",nonce:"nonce",s_hash:"state hash",sub:"subject",ath:"access token hash",htm:"http method",htu:"http uri",cnf:"confirmation",auth_time:"authentication time"};function yt(e,t){for(let n of e)if(t.claims[n]===void 0)throw i(`JWT "${n}" (${Ce[n]}) claim missing`,d,{claims:t.claims});return t}function _t(e,t){if(typeof t.claims[e]!="string")throw i(`unexpected JWT "${e}" (${Ce[e]}) claim type`,d,{claims:t.claims});return t}function gt(e,t,n,r,o){return Et(n,xt.bind(void 0,t.id_token_signed_response_alg,e.id_token_signing_alg_values_supported,"RS256"),Be(t),Ge(t)).then(yt.bind(void 0,["aud","exp","iat","iss","sub",...r])).then(wt.bind(void 0,e)).then(pt.bind(void 0,t.client_id)).then(_t.bind(void 0,"sub"))}function Rt(e){e.auth_time!==void 0&&Z(e.auth_time,true,'ID Token "auth_time" (authentication time)',d,{claims:e});}function bt(e,t){if(Array.isArray(t.aud)&&t.aud.length!==1){if(t.azp===void 0)throw i('ID Token "aud" (audience) claim includes additional untrusted audiences',E,{claims:t,claim:"aud"});if(t.azp!==e.client_id)throw i('unexpected ID Token "azp" (authorized party) claim value',E,{expected:e.client_id,claims:t,claim:"azp"})}}var St="OAUTH_WWW_AUTHENTICATE_CHALLENGE",Pt="OAUTH_RESPONSE_BODY_ERROR",K="OAUTH_UNSUPPORTED_OPERATION",At="OAUTH_AUTHORIZATION_RESPONSE_ERROR";var U="OAUTH_PARSE_ERROR",d="OAUTH_INVALID_RESPONSE";var te="OAUTH_RESPONSE_IS_NOT_JSON",$="OAUTH_RESPONSE_IS_NOT_CONFORM",ne="OAUTH_HTTP_REQUEST_FORBIDDEN",re="OAUTH_REQUEST_PROTOCOL_FORBIDDEN",j="OAUTH_JWT_TIMESTAMP_CHECK_FAILED",E="OAUTH_JWT_CLAIM_COMPARISON_FAILED",F="OAUTH_JSON_ATTRIBUTE_COMPARISON_FAILED";var Tt="OAUTH_MISSING_SERVER_METADATA",kt="OAUTH_INVALID_SERVER_METADATA";async function ve(e,t,n,r,o){return Se(e),Pe(t),dt(e,t,n,"client_credentials",new URLSearchParams(r),o)}async function De(e,t,n,r){return lt(e,t,n)}function oe(e){if(e.bodyUsed)throw l('"response" body has been used already',y$1)}async function Et(e,t,n,r,o){let{0:s,1:a,length:u}=e.split(".");if(u===5)throw new T("JWE decryption is not configured",{cause:e});if(u!==3)throw i("Invalid JWT",d,e);let h;try{h=JSON.parse(le(fe(s)));}catch(m){throw i("failed to parse JWT Header body as base64url encoded JSON",U,m)}if(!H(h))throw i("JWT Header must be a top level object",d,e);if(t(h),h.crit!==void 0)throw new T('no JWT "crit" header parameter extensions are supported',{cause:{header:h}});let c;try{c=JSON.parse(le(fe(a)));}catch(m){throw i("failed to parse JWT Payload body as base64url encoded JSON",U,m)}if(!H(c))throw i("JWT Payload must be a top level object",d,e);let p=Ve()+n;if(c.exp!==void 0){if(typeof c.exp!="number")throw i('unexpected JWT "exp" (expiration time) claim type',d,{claims:c});if(c.exp<=p-r)throw i('unexpected JWT "exp" (expiration time) claim value, expiration is past current timestamp',j,{claims:c,now:p,tolerance:r,claim:"exp"})}if(c.iat!==void 0&&typeof c.iat!="number")throw i('unexpected JWT "iat" (issued at) claim type',d,{claims:c});if(c.iss!==void 0&&typeof c.iss!="string")throw i('unexpected JWT "iss" (issuer) claim type',d,{claims:c});if(c.nbf!==void 0){if(typeof c.nbf!="number")throw i('unexpected JWT "nbf" (not before) claim type',d,{claims:c});if(c.nbf>p+r)throw i('unexpected JWT "nbf" (not before) claim value',j,{claims:c,now:p,tolerance:r,claim:"nbf"})}if(c.aud!==void 0&&typeof c.aud!="string"&&!Array.isArray(c.aud))throw i('unexpected JWT "aud" (audience) claim type',d,{claims:c});return {header:h,claims:c,jwt:e}}function xt(e,t,n,r){if(e!==void 0){if(typeof e=="string"?r.alg!==e:!e.includes(r.alg))throw i('unexpected JWT "alg" header parameter',d,{header:r,expected:e,reason:"client configuration"});return}if(Array.isArray(t)){if(!t.includes(r.alg))throw i('unexpected JWT "alg" header parameter',d,{header:r,expected:t,reason:"authorization server metadata"});return}if(n!==void 0){if(typeof n=="string"?r.alg!==n:typeof n=="function"?!n(r.alg):!n.includes(r.alg))throw i('unexpected JWT "alg" header parameter',d,{header:r,expected:n,reason:"default value"});return}throw i('missing client or server configuration to verify used JWT "alg" header parameter',void 0,{client:e,issuer:t,fallback:n})}async function Ie(e,t=be){let n;try{n=await e.json();}catch(r){throw t(e),i('failed to parse "response" body as JSON',U,r)}if(!H(n))throw i('"response" body must be a top level object',d,{body:n});return n}var J=Symbol(),ae=Symbol();var B,Ue;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(Ue="openid-client/v6.8.8",B={"user-agent":Ue});var R=e=>se.get(e),se;function ce(e){if(e!==void 0)return ee(e);let t=new WeakMap;return (n,r,o,s)=>{let a;return (a=t.get(r))||(Ct(r.client_secret,'"metadata.client_secret"'),a=ee(r.client_secret),t.set(r,a)),a(n,r,o,s)}}function Ct(e,t){if(typeof e!="string")throw x(`${t} must be a string`,V);if(e.length===0)throw x(`${t} must not be empty`,ue)}function vt(){return Ae()}var S=O;var ue="ERR_INVALID_ARG_VALUE",V="ERR_INVALID_ARG_TYPE";function x(e,t,n){let r=new TypeError(e,{cause:n});return Object.assign(r,{code:t}),r}var C=class extends Error{code;constructor(t,n){super(t,n),this.name=this.constructor.name,this.code=n?.code,Error.captureStackTrace?.(this,this.constructor);}};new TextDecoder;function f(e,t,n){return new C(e,{cause:t,code:n})}function ie(e){if(e instanceof TypeError||e instanceof C||e instanceof g||e instanceof I||e instanceof k)throw e;if(e instanceof D)switch(e.code){case ne:throw f("only requests to HTTPS are allowed",e,e.code);case re:throw f("only requests to HTTP or HTTPS are allowed",e,e.code);case $:throw f("unexpected HTTP response status code",e.cause,e.code);case te:throw f("unexpected response content-type",e.cause,e.code);case U:throw f("parsing error occured",e,e.code);case d:throw f("invalid response encountered",e,e.code);case E:throw f("unexpected JWT claim value encountered",e,e.code);case F:throw f("unexpected JSON attribute value encountered",e,e.code);case j:throw f("JWT timestamp claim value failed validation",e,e.code);default:throw f(e.message,e,e.code)}if(e instanceof T)throw f("unsupported operation",e,e.code);if(e instanceof DOMException)switch(e.name){case "OperationError":throw f("runtime operation error",e,K);case "NotSupportedError":throw f("runtime unsupported operation",e,K);case "TimeoutError":throw f("operation timed out",e,"OAUTH_TIMEOUT");case "AbortError":throw f("operation aborted",e,"OAUTH_ABORT")}throw new C("something went wrong",{cause:e})}function Dt(e,t,n){return e.origin==="https://login.microsoftonline.com"&&(!n?.algorithm||n.algorithm==="oidc")?(t[He]=true,true):false}function It(e,t){return !!(e.hostname.endsWith(".b2clogin.com")&&(!t?.algorithm||t.algorithm==="oidc"))}async function Le(e,t,n,r,o){let s=await Ut(e,o),a=new v(s,t,n,r),u=R(a);if(o?.[S]&&(u.fetch=o[S]),o?.timeout!==void 0&&(u.timeout=o.timeout),o?.execute)for(let h of o.execute)h(a);return a}async function Ut(e,t){if(!(e instanceof URL))throw x('"server" must be an instance of URL',V);let n=!e.href.includes("/.well-known/"),r=t?.timeout??30,o=AbortSignal.timeout(r*1e3),s=await(n?ge(e,{algorithm:t?.algorithm,[O]:t?.[S],[L]:t?.execute?.includes(G),signal:o,headers:new Headers(B)}):(t?.[S]||fetch)((z(e,!t?.execute?.includes(G)),e.href),{headers:Object.fromEntries(new Headers({accept:"application/json",...B}).entries()),body:void 0,method:"GET",redirect:"manual",signal:o})).then(a=>Re(J,a)).catch(ie);return n&&new URL(s.issuer).href!==e.href&&(Dt(e,s,t)||It(e,t)||(()=>{throw new C("discovered metadata issuer does not match the expected issuer",{code:F,cause:{expected:e.href,body:s,attribute:"issuer"}})})()),s}function Lt(e){return {supportsPKCE:{__proto__:null,value(t="S256"){return e.code_challenge_methods_supported?.includes(t)===true}}}}function Ht(e){Object.defineProperties(e,Lt(e));}var He=Symbol(),v=class{constructor(t,n,r,o){if(typeof n!="string"||!n.length)throw x('"clientId" must be a non-empty string',V);if(typeof r=="string"&&(r={client_secret:r}),r?.client_id!==void 0&&n!==r.client_id)throw x('"clientId" and "metadata.client_id" must be the same',ue);let s={...structuredClone(r),client_id:n};s[W]=r?.[W]??0,s[M]=r?.[M]??30;let a;o?a=o:typeof s.client_secret=="string"&&s.client_secret.length?a=ce(s.client_secret):a=vt();let u=Object.freeze(s),h=structuredClone(t);He in t&&(h[ae]=({claims:{tid:p}})=>t.issuer.replace("{tenantid}",p));let c=Object.freeze(h);se||=new WeakMap,se.set(this,{__proto__:null,as:c,c:u,auth:a,tlsOnly:true,timeout:30,jwksCache:{}});}serverMetadata(){let t=structuredClone(R(this).as);return Ht(t),t}clientMetadata(){return structuredClone(R(this).c)}get timeout(){return R(this).timeout}set timeout(t){R(this).timeout=t;}get[S](){return R(this).fetch}set[S](t){R(this).fetch=t;}};Object.freeze(v.prototype);function Nt(e){let t;return e.expires_in!==void 0&&(t=Date.now()+e.expires_in*1e3),{expiresIn:{__proto__:null,value(){if(t){let n=Date.now();return t>n?Math.floor((t-n)/1e3):0}}},claims:{__proto__:null,value(){return Oe(e)}}}}function jt(e){Object.defineProperties(e,Nt(e));}function G(e){R(e).tlsOnly=false;}async function de(e,t,n){Jt(e),t=new URLSearchParams(t);let{as:r,c:o,auth:s,fetch:a,tlsOnly:u,timeout:h}=R(e),c=await ve(r,o,s,t,{[O]:a,[L]:!u,DPoP:n?.DPoP,headers:new Headers(B),signal:qt(h)}).catch(ie),p=De(r,o,c),m;try{m=await p;}catch(P){ie(P);}return jt(m),m}function Jt(e){if(!(e instanceof v))throw x('"config" must be an instance of Configuration',V);if(Object.getPrototypeOf(e)!==v.prototype)throw x("subclassing Configuration is not allowed",ue)}function qt(e){return e?AbortSignal.timeout(e*1e3):void 0}var w=class extends Error{code;constructor(t,n){super(t,{cause:n}),this.name="OAuthClientCredentialsError",this.code="ERR_OAUTH";}};var zt=6e4,Kt=new Set(["localhost","127.0.0.1"]),je=e=>e.protocol==="http:"&&Kt.has(e.hostname),$t=e=>typeof e=="number"&&Number.isFinite(e)&&e>0,Ft=e=>{try{return new URL(e)}catch{return}},he=e=>e?`OAuth token request failed: ${e}`:"OAuth token request failed",Je=class e{#e;constructor(t,n,r,o){if(t.protocol!=="https:"&&!je(t))throw new w("OAuth client credentials require an https service URL; http is only allowed for localhost and 127.0.0.1");this.#e={issuer:t,clientId:n,clientSecret:r,fetchImpl:o?.fetch,clock:o?.clock??(()=>Date.now()),cachedToken:void 0,configuration:void 0,flight:void 0,generation:0};}static fromServiceUrl(t,n,r){let o=Ft(t);if(!o||o.protocol!=="http:"&&o.protocol!=="https:")throw new w("OAuth client credentials require an absolute service URL");return new e(new URL(o.origin),n,r)}async getAccessToken(){let{cachedToken:t,clock:n}=this.#e;if(t!==void 0&&t.expiresAt-n()>zt)return t.accessToken;if(this.#e.flight)return this.#e.flight;let r=this.#e.generation,o=this.#t(r).finally(()=>{this.#e.flight===o&&(this.#e.flight=void 0);});return this.#e.flight=o,o}invalidate(){this.#e.cachedToken=void 0,this.#e.generation+=1,this.#e.flight=void 0;}async#t(t){let n=await this.#n(),r;try{r=await de(n);}catch(s){throw s instanceof TypeError||s instanceof w?s:s instanceof g?new w(he(s.error),s):new w(he(),s)}let o=r.access_token;if(typeof o!="string"||o.length===0)throw new w(he());if(this.#e.generation===t){let s=r.expires_in;this.#e.cachedToken=$t(s)?{accessToken:o,expiresAt:this.#e.clock()+s*1e3}:void 0;}return o}async#n(){if(this.#e.configuration)return this.#e.configuration;let t=this.#e.fetchImpl??globalThis.fetch;try{let n=await Le(this.#e.issuer,this.#e.clientId,this.#e.clientSecret,ce(this.#e.clientSecret),{algorithm:"oauth2",[S]:t,...je(this.#e.issuer)?{execute:[G]}:{}});return this.#e.configuration=n,n}catch(n){throw n instanceof TypeError?n:new w("OAuth authorization server discovery failed",n)}}},$n=({grantType:e,clientSecret:t})=>{if(e!=="client_credentials")throw new w("Only the client_credentials grant is supported");if(globalThis.window!==void 0&&t.length>0)throw new w("Client credentials authentication is not supported in the browser")},Fn=async(e,t)=>{let n=await t();return n.status!==401?n:(await n.body?.cancel().catch(()=>{}),e.invalidate(),t())};
|
|
7
|
+
|
|
8
|
+
var y=e=>{let n=e.replaceAll("-","+").replaceAll("_","/");return n.padEnd(n.length+(4-n.length%4)%4,"=")};
|
|
5
9
|
|
|
6
10
|
class CloudInteropAPIError extends Error {
|
|
7
11
|
code;
|
|
@@ -16,6 +20,21 @@ class AuthorizationError extends CloudInteropAPIError {
|
|
|
16
20
|
super(message, code, undefined);
|
|
17
21
|
}
|
|
18
22
|
}
|
|
23
|
+
class OAuthAuthenticationError extends CloudInteropAPIError {
|
|
24
|
+
constructor(message, cause) {
|
|
25
|
+
super(message, 'ERR_OAUTH', cause);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const rethrowAsOAuthAuthenticationError = (error) => {
|
|
30
|
+
if (error instanceof w) {
|
|
31
|
+
throw new OAuthAuthenticationError(error.message, error);
|
|
32
|
+
}
|
|
33
|
+
if (error instanceof TypeError) {
|
|
34
|
+
throw new OAuthAuthenticationError('OAuth access token could not be obtained', error);
|
|
35
|
+
}
|
|
36
|
+
throw error;
|
|
37
|
+
};
|
|
19
38
|
|
|
20
39
|
class EventController {
|
|
21
40
|
#eventListeners = new Map();
|
|
@@ -49,11 +68,20 @@ class EventController {
|
|
|
49
68
|
const isErrorIntentResult = (result) => 'error' in result;
|
|
50
69
|
|
|
51
70
|
const APP_ID_DELIM = '::';
|
|
52
|
-
const getRequestHeaders = (connectionParameters) => {
|
|
71
|
+
const getRequestHeaders = async (connectionParameters, tokenClient) => {
|
|
53
72
|
const headers = {};
|
|
54
73
|
headers['Content-Type'] = 'application/json';
|
|
74
|
+
if (connectionParameters.authenticationType === 'oauth' && tokenClient) {
|
|
75
|
+
try {
|
|
76
|
+
const accessToken = await tokenClient.getAccessToken();
|
|
77
|
+
headers['Authorization'] = `Bearer ${accessToken}`;
|
|
78
|
+
}
|
|
79
|
+
catch (error) {
|
|
80
|
+
rethrowAsOAuthAuthenticationError(error);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
55
83
|
if (connectionParameters.authenticationType === 'jwt' && connectionParameters.jwtAuthenticationParameters) {
|
|
56
|
-
const tokenResult = connectionParameters.jwtAuthenticationParameters.jwtRequestCallback();
|
|
84
|
+
const tokenResult = await connectionParameters.jwtAuthenticationParameters.jwtRequestCallback();
|
|
57
85
|
if (!tokenResult) {
|
|
58
86
|
throw new Error('jwtRequestCallback must return a token');
|
|
59
87
|
}
|
|
@@ -135,16 +163,16 @@ class IntentController {
|
|
|
135
163
|
#url;
|
|
136
164
|
#mqttClient;
|
|
137
165
|
#sessionDetails;
|
|
138
|
-
#
|
|
166
|
+
#authenticatedFetch;
|
|
139
167
|
#events;
|
|
140
168
|
#logger;
|
|
141
169
|
#discovery = newDiscovery();
|
|
142
170
|
#discoveryTimeout;
|
|
143
|
-
constructor(url, mqttClient, sessionDetails,
|
|
171
|
+
constructor(url, mqttClient, sessionDetails, authenticatedFetch, events, logger) {
|
|
144
172
|
this.#url = url;
|
|
145
173
|
this.#mqttClient = mqttClient;
|
|
146
174
|
this.#sessionDetails = sessionDetails;
|
|
147
|
-
this.#
|
|
175
|
+
this.#authenticatedFetch = authenticatedFetch;
|
|
148
176
|
this.#events = events;
|
|
149
177
|
this.#logger = logger;
|
|
150
178
|
}
|
|
@@ -156,9 +184,8 @@ class IntentController {
|
|
|
156
184
|
// clamp min value to 500ms
|
|
157
185
|
const clampedTimeout = Math.max(timeout, MIN_TIMEOUT);
|
|
158
186
|
try {
|
|
159
|
-
const startResponse = await
|
|
187
|
+
const startResponse = await this.#authenticatedFetch(`${this.#url}/api/intents/${this.#sessionDetails.sessionId}`, {
|
|
160
188
|
method: 'POST',
|
|
161
|
-
headers: getRequestHeaders(this.#connectionParams),
|
|
162
189
|
body: JSON.stringify({ findOptions }),
|
|
163
190
|
});
|
|
164
191
|
if (!startResponse.ok) {
|
|
@@ -201,9 +228,8 @@ class IntentController {
|
|
|
201
228
|
this.#logger('warn', `Error ending intent discovery: could not unsubscribe from discovery id ${this.#discovery.id}`);
|
|
202
229
|
});
|
|
203
230
|
}
|
|
204
|
-
await
|
|
231
|
+
await this.#authenticatedFetch(`${this.#url}/api/intents/${this.#sessionDetails.sessionId}/${this.#discovery.id}`, {
|
|
205
232
|
method: 'DELETE',
|
|
206
|
-
headers: getRequestHeaders(this.#connectionParams),
|
|
207
233
|
})
|
|
208
234
|
.then((deleteResponse) => {
|
|
209
235
|
if (!deleteResponse.ok) {
|
|
@@ -222,9 +248,8 @@ class IntentController {
|
|
|
222
248
|
// TODO: should we add more info here about the format?
|
|
223
249
|
throw new CloudInteropAPIError(`Invalid AppId specified, must be encoded as a cloud-session app id`, 'ERR_INVALID_TARGET_SESSION_ID');
|
|
224
250
|
}
|
|
225
|
-
const postResponse = await
|
|
251
|
+
const postResponse = await this.#authenticatedFetch(`${this.#url}/api/intents/${this.#sessionDetails.sessionId}/sessions/${targetSessionId}`, {
|
|
226
252
|
method: 'POST',
|
|
227
|
-
headers: getRequestHeaders(this.#connectionParams),
|
|
228
253
|
body: JSON.stringify({ raiseOptions }),
|
|
229
254
|
});
|
|
230
255
|
if (!postResponse.ok) {
|
|
@@ -236,9 +261,8 @@ class IntentController {
|
|
|
236
261
|
async reportAppIntents(discoveryId, intents) {
|
|
237
262
|
intents = encodeAppIntents(intents, getSourceFromSession(this.#sessionDetails));
|
|
238
263
|
try {
|
|
239
|
-
const reportResponse = await
|
|
264
|
+
const reportResponse = await this.#authenticatedFetch(`${this.#url}/api/intents/${this.#sessionDetails.sessionId}/${discoveryId}`, {
|
|
240
265
|
method: 'POST',
|
|
241
|
-
headers: getRequestHeaders(this.#connectionParams),
|
|
242
266
|
body: JSON.stringify({ intents }),
|
|
243
267
|
});
|
|
244
268
|
if (reportResponse.ok) {
|
|
@@ -260,9 +284,8 @@ class IntentController {
|
|
|
260
284
|
result.source = typeof result.source === 'string' ? encoded : { ...result.source, appId: encoded };
|
|
261
285
|
}
|
|
262
286
|
const { sessionId } = getSourceFromSession(this.#sessionDetails);
|
|
263
|
-
const resultResponse = await
|
|
287
|
+
const resultResponse = await this.#authenticatedFetch(`${this.#url}/api/intents/${initiatingSessionId}/result/${sessionId}`, {
|
|
264
288
|
method: 'POST',
|
|
265
|
-
headers: getRequestHeaders(this.#connectionParams),
|
|
266
289
|
body: JSON.stringify({ result }),
|
|
267
290
|
});
|
|
268
291
|
if (!resultResponse.ok) {
|
|
@@ -346,10 +369,12 @@ class CloudInteropAPI {
|
|
|
346
369
|
#reconnectRetryLimit = 30;
|
|
347
370
|
#keepAliveIntervalSeconds = 30;
|
|
348
371
|
#logger = (level, message) => {
|
|
372
|
+
// eslint-disable-next-line security/detect-object-injection -- level is restricted to the LogLevel union
|
|
349
373
|
console[level](message);
|
|
350
374
|
};
|
|
351
375
|
#reconnectRetries = 0;
|
|
352
376
|
#connectionParams;
|
|
377
|
+
#tokenClient;
|
|
353
378
|
#attemptingToReconnect = false;
|
|
354
379
|
#events = new EventController();
|
|
355
380
|
#intents;
|
|
@@ -371,17 +396,29 @@ class CloudInteropAPI {
|
|
|
371
396
|
* @memberof CloudInteropAPI
|
|
372
397
|
* @throws CloudInteropAPIError - If an error occurs during connection
|
|
373
398
|
* @throws AuthorizationError - If the connection is unauthorized
|
|
399
|
+
* @throws OAuthAuthenticationError - If OAuth parameters are invalid, the client credentials are rejected, or an access token cannot be obtained
|
|
374
400
|
*/
|
|
375
401
|
async connect(parameters) {
|
|
376
402
|
this.#validateConnectParams(parameters);
|
|
403
|
+
const oauthParameters = parameters.oauthAuthenticationParameters;
|
|
404
|
+
if (parameters.authenticationType === 'oauth' && oauthParameters) {
|
|
405
|
+
try {
|
|
406
|
+
this.#tokenClient = Je.fromServiceUrl(this.#cloudInteropSettings.url, oauthParameters.clientId, oauthParameters.clientSecret);
|
|
407
|
+
}
|
|
408
|
+
catch (error) {
|
|
409
|
+
rethrowAsOAuthAuthenticationError(error);
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
else {
|
|
413
|
+
this.#tokenClient = undefined;
|
|
414
|
+
}
|
|
377
415
|
this.#connectionParams = parameters;
|
|
378
416
|
this.#reconnectRetryLimit = parameters.reconnectRetryLimit || this.#reconnectRetryLimit;
|
|
379
417
|
this.#keepAliveIntervalSeconds = parameters.keepAliveIntervalSeconds || this.#keepAliveIntervalSeconds;
|
|
380
418
|
this.#logger = parameters.logger || this.#logger;
|
|
381
419
|
const { sourceId, platformId } = this.#connectionParams;
|
|
382
|
-
const createSessionResponse = await
|
|
420
|
+
const createSessionResponse = await this.#authenticatedFetch(`${this.#cloudInteropSettings.url}/api/sessions`, {
|
|
383
421
|
method: 'POST',
|
|
384
|
-
headers: getRequestHeaders(this.#connectionParams),
|
|
385
422
|
body: JSON.stringify({ sourceId: sourceId.trim(), platformId }),
|
|
386
423
|
});
|
|
387
424
|
if (!createSessionResponse.ok) {
|
|
@@ -419,11 +456,12 @@ class CloudInteropAPI {
|
|
|
419
456
|
// TODO: Dynamic intent discovery
|
|
420
457
|
// search for any ongoing discoveries in DB and fire report-intents on self
|
|
421
458
|
this.#logger('log', `Cloud Interop successfully connected to ${this.#cloudInteropSettings.url}`);
|
|
459
|
+
// eslint-disable-next-line security-node/detect-unhandled-event-errors -- this callback handles MQTT error events
|
|
422
460
|
this.#mqttClient.on('error', async (error) => {
|
|
423
461
|
// We will receive errors for each failed reconnection attempt
|
|
424
462
|
// We don't want to disconnect on these else we will never reconnect
|
|
425
463
|
if (!this.#attemptingToReconnect) {
|
|
426
|
-
await this.#
|
|
464
|
+
await this.#disconnectAndLogFailure();
|
|
427
465
|
}
|
|
428
466
|
if (error instanceof mqtt.ErrorWithReasonCode) {
|
|
429
467
|
switch (error.code) {
|
|
@@ -449,15 +487,15 @@ class CloudInteropAPI {
|
|
|
449
487
|
}
|
|
450
488
|
}
|
|
451
489
|
});
|
|
452
|
-
this.#mqttClient.on('reconnect', () => {
|
|
490
|
+
this.#mqttClient.on('reconnect', async () => {
|
|
453
491
|
this.#attemptingToReconnect = true;
|
|
454
492
|
this.#reconnectRetries += 1;
|
|
455
493
|
this.#logger('debug', `Cloud Interop attempting reconnection - ${this.#reconnectRetries}...`);
|
|
494
|
+
this.#events.emitEvent('reconnecting', this.#reconnectRetries);
|
|
456
495
|
if (this.#reconnectRetries === this.#reconnectRetryLimit) {
|
|
457
496
|
this.#logger('warn', `Cloud Interop reached max reconnection attempts - ${this.#reconnectRetryLimit}...`);
|
|
458
|
-
this.#
|
|
497
|
+
await this.#disconnectAndLogFailure(true);
|
|
459
498
|
}
|
|
460
|
-
this.#events.emitEvent('reconnecting', this.#reconnectRetries);
|
|
461
499
|
});
|
|
462
500
|
// Does not fire on initial connection, only successful reconnection attempts
|
|
463
501
|
this.#mqttClient.on('connect', () => {
|
|
@@ -477,7 +515,7 @@ class CloudInteropAPI {
|
|
|
477
515
|
this.#mqttClient.subscribe(`${sessionRootTopic}/context-groups/#`);
|
|
478
516
|
// Listen out for global commands
|
|
479
517
|
this.#mqttClient.subscribe(`${sessionRootTopic}/commands`);
|
|
480
|
-
this.#initControllers(this.#mqttClient, this.#sessionDetails
|
|
518
|
+
this.#initControllers(this.#mqttClient, this.#sessionDetails);
|
|
481
519
|
}
|
|
482
520
|
/**
|
|
483
521
|
* Disconnects from the Cloud Interop service
|
|
@@ -509,9 +547,8 @@ class CloudInteropAPI {
|
|
|
509
547
|
context,
|
|
510
548
|
timestamp: Date.now(),
|
|
511
549
|
};
|
|
512
|
-
const postResponse = await
|
|
550
|
+
const postResponse = await this.#authenticatedFetch(`${this.#cloudInteropSettings.url}/api/context-groups/${this.#sessionDetails.sessionId}/${contextGroup}`, {
|
|
513
551
|
method: 'POST',
|
|
514
|
-
headers: getRequestHeaders(this.#connectionParams),
|
|
515
552
|
body: JSON.stringify(payload),
|
|
516
553
|
});
|
|
517
554
|
if (!postResponse.ok) {
|
|
@@ -569,9 +606,8 @@ class CloudInteropAPI {
|
|
|
569
606
|
clearTimeout(this.#sessionTimer);
|
|
570
607
|
this.#sessionTimer = undefined;
|
|
571
608
|
}
|
|
572
|
-
const disconnectResponse = await
|
|
609
|
+
const disconnectResponse = await this.#authenticatedFetch(`${this.#cloudInteropSettings.url}/api/sessions/${this.#sessionDetails.sessionId}`, {
|
|
573
610
|
method: 'DELETE',
|
|
574
|
-
headers: getRequestHeaders(this.#connectionParams),
|
|
575
611
|
});
|
|
576
612
|
if (disconnectResponse.status !== 200) {
|
|
577
613
|
throw new CloudInteropAPIError('Error during session tear down - unexpected status', 'ERR_DISCONNECT', new Error(disconnectResponse.statusText));
|
|
@@ -594,6 +630,7 @@ class CloudInteropAPI {
|
|
|
594
630
|
}
|
|
595
631
|
}
|
|
596
632
|
#handleMessage(topic, message, sessionDetails) {
|
|
633
|
+
this.#logger('debug', `Received message on topic: ${topic}`);
|
|
597
634
|
if (message.length === 0 || !sessionDetails) {
|
|
598
635
|
// Ignore clean up messages
|
|
599
636
|
return;
|
|
@@ -652,10 +689,35 @@ class CloudInteropAPI {
|
|
|
652
689
|
(!parameters.basicAuthenticationParameters?.username || !parameters.basicAuthenticationParameters?.password)) {
|
|
653
690
|
throw new Error('basicAuthenticationParameters must be provided when using basic authentication');
|
|
654
691
|
}
|
|
692
|
+
if (parameters.authenticationType === 'oauth') {
|
|
693
|
+
if (!parameters.oauthAuthenticationParameters?.clientId?.trim() || !parameters.oauthAuthenticationParameters?.clientSecret?.trim()) {
|
|
694
|
+
throw new OAuthAuthenticationError('oauthAuthenticationParameters must be provided when using oauth authentication');
|
|
695
|
+
}
|
|
696
|
+
try {
|
|
697
|
+
$n(parameters.oauthAuthenticationParameters);
|
|
698
|
+
}
|
|
699
|
+
catch (error) {
|
|
700
|
+
rethrowAsOAuthAuthenticationError(error);
|
|
701
|
+
}
|
|
702
|
+
}
|
|
655
703
|
};
|
|
656
|
-
#initControllers(mqttClient, sessionDetails
|
|
657
|
-
this.#intents = new IntentController(this.#cloudInteropSettings.url, mqttClient, sessionDetails,
|
|
704
|
+
#initControllers(mqttClient, sessionDetails) {
|
|
705
|
+
this.#intents = new IntentController(this.#cloudInteropSettings.url, mqttClient, sessionDetails, this.#authenticatedFetch, this.#events, this.#logger);
|
|
658
706
|
}
|
|
707
|
+
#authenticatedFetch = async (url, { method, body }) => {
|
|
708
|
+
const connectionParameters = this.#connectionParams;
|
|
709
|
+
if (!connectionParameters) {
|
|
710
|
+
throw new Error('Connect parameters must be provided');
|
|
711
|
+
}
|
|
712
|
+
const attempt = async () => {
|
|
713
|
+
const headers = await getRequestHeaders(connectionParameters, this.#tokenClient);
|
|
714
|
+
return fetch(url, { method, headers, body });
|
|
715
|
+
};
|
|
716
|
+
if (connectionParameters.authenticationType === 'oauth' && this.#tokenClient) {
|
|
717
|
+
return Fn(this.#tokenClient, attempt);
|
|
718
|
+
}
|
|
719
|
+
return attempt();
|
|
720
|
+
};
|
|
659
721
|
#destroyControllers() {
|
|
660
722
|
this.#intents = undefined;
|
|
661
723
|
}
|
|
@@ -684,7 +746,7 @@ class CloudInteropAPI {
|
|
|
684
746
|
}
|
|
685
747
|
const payload = parts[1];
|
|
686
748
|
// Decode base64url encoded payload
|
|
687
|
-
const decodedBytes = Buffer.from(
|
|
749
|
+
const decodedBytes = Buffer.from(y(payload), 'base64');
|
|
688
750
|
const payloadJson = decodedBytes.toString('utf8');
|
|
689
751
|
// Parse JSON to get the exp claim
|
|
690
752
|
const claims = JSON.parse(payloadJson);
|
|
@@ -745,10 +807,18 @@ class CloudInteropAPI {
|
|
|
745
807
|
* Handles session expiry by executing the same actions as the BadUserNamePasswordError case.
|
|
746
808
|
*/
|
|
747
809
|
async #handleSessionExpiry() {
|
|
748
|
-
await this.#
|
|
810
|
+
await this.#disconnectAndLogFailure();
|
|
749
811
|
this.#logger('warn', 'Session expired');
|
|
750
812
|
this.#events.emitEvent('session-expired');
|
|
751
813
|
}
|
|
814
|
+
async #disconnectAndLogFailure(fireDisconnectedEvent = false) {
|
|
815
|
+
try {
|
|
816
|
+
await this.#disconnect(fireDisconnectedEvent);
|
|
817
|
+
}
|
|
818
|
+
catch (error) {
|
|
819
|
+
this.#logger('error', `Session teardown failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
820
|
+
}
|
|
821
|
+
}
|
|
752
822
|
}
|
|
753
823
|
|
|
754
|
-
export { AuthorizationError, CloudInteropAPI, CloudInteropAPIError };
|
|
824
|
+
export { AuthorizationError, CloudInteropAPI, CloudInteropAPIError, OAuthAuthenticationError };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@openfin/cloud-interop-core-api",
|
|
3
|
-
"version": "0.0.1-alpha.
|
|
3
|
+
"version": "0.0.1-alpha.fe19a6f",
|
|
4
4
|
"description": "",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./index.cjs",
|
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
"author": "support@here.io",
|
|
10
10
|
"license": "SEE LICENSE IN LICENSE.md",
|
|
11
11
|
"dependencies": {
|
|
12
|
-
"mqtt": "
|
|
12
|
+
"mqtt": "catalog:",
|
|
13
13
|
"zod": "catalog:"
|
|
14
14
|
}
|
|
15
15
|
}
|