@openfin/cloud-interop-core-api 0.0.1-alpha.c07aba2 → 0.0.1-alpha.c0d1041
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 +2 -2
- package/bundle.d.ts +27 -16
- package/index.cjs +165 -47
- package/index.mjs +165 -47
- package/package.json +5 -8
- package/version +0 -1
package/README.md
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
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
13
|
- Default Authentication i.e. Interactive session based authentication using cookies
|
package/bundle.d.ts
CHANGED
|
@@ -51,7 +51,7 @@ declare const appIntentSchema: z.ZodObject<{
|
|
|
51
51
|
name: string;
|
|
52
52
|
displayName: string;
|
|
53
53
|
}>;
|
|
54
|
-
apps: z.ZodArray<z.ZodObject<
|
|
54
|
+
apps: z.ZodArray<z.ZodObject<{
|
|
55
55
|
description: z.ZodOptional<z.ZodString>;
|
|
56
56
|
icons: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
57
57
|
size: z.ZodOptional<z.ZodString>;
|
|
@@ -88,10 +88,10 @@ declare const appIntentSchema: z.ZodObject<{
|
|
|
88
88
|
title: z.ZodOptional<z.ZodString>;
|
|
89
89
|
tooltip: z.ZodOptional<z.ZodString>;
|
|
90
90
|
version: z.ZodOptional<z.ZodString>;
|
|
91
|
-
}
|
|
91
|
+
} & {
|
|
92
92
|
appId: z.ZodString;
|
|
93
93
|
instanceId: z.ZodOptional<z.ZodString>;
|
|
94
|
-
}
|
|
94
|
+
}, "strip", z.ZodTypeAny, {
|
|
95
95
|
appId: string;
|
|
96
96
|
instanceId?: string | undefined;
|
|
97
97
|
description?: string | undefined;
|
|
@@ -245,36 +245,36 @@ 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
253
|
*/
|
|
254
254
|
connect(parameters: ConnectParameters): Promise<void>;
|
|
255
255
|
/**
|
|
256
256
|
* Disconnects from the Cloud Interop service
|
|
257
257
|
*
|
|
258
|
-
* @returns
|
|
258
|
+
* @returns Promise that resolves when disconnected
|
|
259
259
|
* @memberof CloudInteropAPI
|
|
260
|
-
* @throws
|
|
260
|
+
* @throws CloudInteropAPIError - If an error occurs during disconnection
|
|
261
261
|
*/
|
|
262
262
|
disconnect(): Promise<void>;
|
|
263
263
|
/**
|
|
264
264
|
* Publishes a new context for the given context group to the other connected sessions
|
|
265
265
|
*
|
|
266
|
-
* @param
|
|
267
|
-
* @param
|
|
268
|
-
* @returns
|
|
266
|
+
* @param contextGroup - The context group to publish to
|
|
267
|
+
* @param context - The context to publish
|
|
268
|
+
* @returns Promise that resolves when context is published
|
|
269
269
|
* @memberof CloudInteropAPI
|
|
270
270
|
*/
|
|
271
|
-
setContext(contextGroup: string, context:
|
|
271
|
+
setContext(contextGroup: string, context: InferredContext): Promise<void>;
|
|
272
272
|
/**
|
|
273
273
|
* Starts an intent discovery operation
|
|
274
274
|
*
|
|
275
|
-
* @returns
|
|
275
|
+
* @returns Promise that resolves when intent discovery is started
|
|
276
276
|
* @memberof CloudInteropAPI
|
|
277
|
-
* @throws
|
|
277
|
+
* @throws CloudInteropAPIError - If an error occurs during intent discovery
|
|
278
278
|
*/
|
|
279
279
|
startIntentDiscovery(options: StartIntentDiscoveryOptions): Promise<void>;
|
|
280
280
|
raiseIntent(options: RaiseIntentAPIOptions): Promise<void>;
|
|
@@ -364,7 +364,7 @@ export declare type ConnectParameters = {
|
|
|
364
364
|
/**
|
|
365
365
|
* When JWT authentication is being used, this will be invoked just whenever a JWT token is required for a request
|
|
366
366
|
*/
|
|
367
|
-
jwtRequestCallback: () => string | object
|
|
367
|
+
jwtRequestCallback: () => string | object | Promise<string | object>;
|
|
368
368
|
/**
|
|
369
369
|
* The id of the service gateway JWT authentication definition to use
|
|
370
370
|
*
|
|
@@ -418,8 +418,17 @@ export declare type CreateSessionResponse = {
|
|
|
418
418
|
sub: string;
|
|
419
419
|
platformId: string;
|
|
420
420
|
sourceId: string;
|
|
421
|
+
localSessionExpiryHandling?: boolean;
|
|
421
422
|
};
|
|
422
423
|
|
|
424
|
+
declare const errorSchema: z.ZodObject<{
|
|
425
|
+
error: z.ZodString;
|
|
426
|
+
}, "strip", z.ZodTypeAny, {
|
|
427
|
+
error: string;
|
|
428
|
+
}, {
|
|
429
|
+
error: string;
|
|
430
|
+
}>;
|
|
431
|
+
|
|
423
432
|
export declare type EventListenersMap = Map<keyof EventMap, Array<(...args: Parameters<EventMap[keyof EventMap]>) => void>>;
|
|
424
433
|
|
|
425
434
|
export declare type EventMap = {
|
|
@@ -545,6 +554,8 @@ declare type HistoryRecord = {
|
|
|
545
554
|
*/
|
|
546
555
|
export declare type InferredContext = z.infer<typeof contextSchema>;
|
|
547
556
|
|
|
557
|
+
export declare type InferredError = z.infer<typeof errorSchema>;
|
|
558
|
+
|
|
548
559
|
/**
|
|
549
560
|
* @internal
|
|
550
561
|
*/
|
package/index.cjs
CHANGED
|
@@ -1,8 +1,12 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
3
|
var buffer = require('buffer');
|
|
4
|
+
require('fs');
|
|
5
|
+
require('path');
|
|
4
6
|
var mqtt = require('mqtt');
|
|
5
7
|
|
|
8
|
+
var d=n=>{let t=n.replaceAll("-","+").replaceAll("_","/");return t.padEnd(t.length+(4-t.length%4)%4,"=")};
|
|
9
|
+
|
|
6
10
|
class CloudInteropAPIError extends Error {
|
|
7
11
|
code;
|
|
8
12
|
constructor(message = 'An unexpected error has occurred', code = 'UNEXPECTED_ERROR', cause) {
|
|
@@ -46,12 +50,14 @@ class EventController {
|
|
|
46
50
|
}
|
|
47
51
|
}
|
|
48
52
|
|
|
53
|
+
const isErrorIntentResult = (result) => 'error' in result;
|
|
54
|
+
|
|
49
55
|
const APP_ID_DELIM = '::';
|
|
50
|
-
const getRequestHeaders = (connectionParameters) => {
|
|
56
|
+
const getRequestHeaders = async (connectionParameters) => {
|
|
51
57
|
const headers = {};
|
|
52
58
|
headers['Content-Type'] = 'application/json';
|
|
53
59
|
if (connectionParameters.authenticationType === 'jwt' && connectionParameters.jwtAuthenticationParameters) {
|
|
54
|
-
const tokenResult = connectionParameters.jwtAuthenticationParameters.jwtRequestCallback();
|
|
60
|
+
const tokenResult = await connectionParameters.jwtAuthenticationParameters.jwtRequestCallback();
|
|
55
61
|
if (!tokenResult) {
|
|
56
62
|
throw new Error('jwtRequestCallback must return a token');
|
|
57
63
|
}
|
|
@@ -72,13 +78,9 @@ const getRequestHeaders = (connectionParameters) => {
|
|
|
72
78
|
* @param source
|
|
73
79
|
* @returns
|
|
74
80
|
*/
|
|
75
|
-
const encodeAppIntents = (appIntents,
|
|
81
|
+
const encodeAppIntents = (appIntents, source) => appIntents.map((intent) => ({
|
|
76
82
|
...intent,
|
|
77
|
-
apps: intent.apps.map((app) => {
|
|
78
|
-
const id = encodeURIComponent(app.appId);
|
|
79
|
-
const sId = encodeURIComponent(sourceId);
|
|
80
|
-
return { ...app, appId: `${id}${APP_ID_DELIM}${sId}${APP_ID_DELIM}${sessionId}` };
|
|
81
|
-
}),
|
|
83
|
+
apps: intent.apps.map((app) => ({ ...app, appId: encodeAppId(app.appId, source) })),
|
|
82
84
|
}));
|
|
83
85
|
/**
|
|
84
86
|
* Decodes all app intents by URI decoding the parts previously encoded by `encodeAppIntents`
|
|
@@ -87,13 +89,19 @@ const encodeAppIntents = (appIntents, { sessionId, sourceId }) => appIntents.map
|
|
|
87
89
|
*/
|
|
88
90
|
const decodeAppIntents = (appIntents) => appIntents.map((intent) => ({
|
|
89
91
|
...intent,
|
|
90
|
-
apps: intent.apps.map((app) => {
|
|
91
|
-
const [encodedAppId, encodedSourceId, sessionId] = app.appId.split(APP_ID_DELIM);
|
|
92
|
-
const id = decodeURIComponent(encodedAppId);
|
|
93
|
-
const sourceId = decodeURIComponent(encodedSourceId);
|
|
94
|
-
return { ...app, appId: `${id}${APP_ID_DELIM}${sourceId}${APP_ID_DELIM}${sessionId}` };
|
|
95
|
-
}),
|
|
92
|
+
apps: intent.apps.map((app) => ({ ...app, appId: decodeAppId(app.appId) })),
|
|
96
93
|
}));
|
|
94
|
+
const encodeAppId = (appIdString, { sessionId, sourceId }) => {
|
|
95
|
+
const id = encodeURIComponent(appIdString);
|
|
96
|
+
const sId = encodeURIComponent(sourceId);
|
|
97
|
+
return `${id}${APP_ID_DELIM}${sId}${APP_ID_DELIM}${sessionId}`;
|
|
98
|
+
};
|
|
99
|
+
const decodeAppId = (appId) => {
|
|
100
|
+
const [encodedAppId, encodedSourceId, sessionId] = appId.split(APP_ID_DELIM);
|
|
101
|
+
const id = decodeURIComponent(encodedAppId);
|
|
102
|
+
const sourceId = decodeURIComponent(encodedSourceId);
|
|
103
|
+
return `${id}${APP_ID_DELIM}${sourceId}${APP_ID_DELIM}${sessionId}`;
|
|
104
|
+
};
|
|
97
105
|
/**
|
|
98
106
|
* Decodes the AppIdentifier to extract the appId, sourceId, and sessionId.
|
|
99
107
|
* @returns an object with:
|
|
@@ -154,17 +162,22 @@ class IntentController {
|
|
|
154
162
|
try {
|
|
155
163
|
const startResponse = await fetch(`${this.#url}/api/intents/${this.#sessionDetails.sessionId}`, {
|
|
156
164
|
method: 'POST',
|
|
157
|
-
headers: getRequestHeaders(this.#connectionParams),
|
|
165
|
+
headers: await getRequestHeaders(this.#connectionParams),
|
|
158
166
|
body: JSON.stringify({ findOptions }),
|
|
159
167
|
});
|
|
160
168
|
if (!startResponse.ok) {
|
|
161
|
-
throw new Error(startResponse.statusText);
|
|
169
|
+
throw new Error(`Error creating intent discovery record: ${startResponse.statusText}`);
|
|
162
170
|
}
|
|
163
171
|
// TODO: type this response?
|
|
164
172
|
const json = await startResponse.json();
|
|
165
173
|
this.#discovery.id = json.discoveryId;
|
|
166
174
|
this.#discovery.sessionCount = json.sessionCount;
|
|
167
175
|
this.#discovery.state = 'in-progress';
|
|
176
|
+
if (this.#discovery.sessionCount === 1) {
|
|
177
|
+
// since we have no other connected sessions, we can end discovery immediately
|
|
178
|
+
await this.#endIntentDiscovery(false);
|
|
179
|
+
return;
|
|
180
|
+
}
|
|
168
181
|
// Listen out for discovery results directly sent to us
|
|
169
182
|
await this.#mqttClient.subscribeAsync(`${this.#sessionDetails.sessionRootTopic}/commands/${this.#discovery.id}`);
|
|
170
183
|
this.#discoveryTimeout = setTimeout(() => this.#endIntentDiscovery(), clampedTimeout);
|
|
@@ -175,10 +188,8 @@ class IntentController {
|
|
|
175
188
|
throw new CloudInteropAPIError('Error starting intent discovery', 'ERR_STARTING_INTENT_DISCOVERY', error);
|
|
176
189
|
}
|
|
177
190
|
}
|
|
178
|
-
async #endIntentDiscovery() {
|
|
191
|
+
async #endIntentDiscovery(mqttUnsubscribe = true) {
|
|
179
192
|
if (this.#discovery.state !== 'in-progress') {
|
|
180
|
-
// TODO: remove debug logs
|
|
181
|
-
this.#logger('debug', 'Intent discovery not in progress');
|
|
182
193
|
return;
|
|
183
194
|
}
|
|
184
195
|
if (this.#discoveryTimeout) {
|
|
@@ -188,19 +199,20 @@ class IntentController {
|
|
|
188
199
|
this.#discovery.state = 'ended';
|
|
189
200
|
// emit our aggregated events
|
|
190
201
|
this.#events.emitEvent('aggregate-intent-details', { responses: this.#discovery.pendingIntentDetailsEvents });
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
this.#
|
|
194
|
-
|
|
202
|
+
if (mqttUnsubscribe) {
|
|
203
|
+
// gracefully end discovery
|
|
204
|
+
await this.#mqttClient.unsubscribeAsync(`${this.#sessionDetails.sessionRootTopic}/commands/${this.#discovery.id}`).catch(() => {
|
|
205
|
+
this.#logger('warn', `Error ending intent discovery: could not unsubscribe from discovery id ${this.#discovery.id}`);
|
|
206
|
+
});
|
|
207
|
+
}
|
|
195
208
|
await fetch(`${this.#url}/api/intents/${this.#sessionDetails.sessionId}/${this.#discovery.id}`, {
|
|
196
209
|
method: 'DELETE',
|
|
197
|
-
headers: getRequestHeaders(this.#connectionParams),
|
|
210
|
+
headers: await getRequestHeaders(this.#connectionParams),
|
|
198
211
|
})
|
|
199
212
|
.then((deleteResponse) => {
|
|
200
213
|
if (!deleteResponse.ok) {
|
|
201
214
|
throw new Error(`Error ending intent discovery: ${deleteResponse.statusText}`);
|
|
202
215
|
}
|
|
203
|
-
this.#logger('debug', 'Intent discovery ended');
|
|
204
216
|
})
|
|
205
217
|
.catch((error) => {
|
|
206
218
|
this.#logger('warn', `Error ending intent discovery: ${error}`);
|
|
@@ -216,7 +228,7 @@ class IntentController {
|
|
|
216
228
|
}
|
|
217
229
|
const postResponse = await fetch(`${this.#url}/api/intents/${this.#sessionDetails.sessionId}/sessions/${targetSessionId}`, {
|
|
218
230
|
method: 'POST',
|
|
219
|
-
headers: getRequestHeaders(this.#connectionParams),
|
|
231
|
+
headers: await getRequestHeaders(this.#connectionParams),
|
|
220
232
|
body: JSON.stringify({ raiseOptions }),
|
|
221
233
|
});
|
|
222
234
|
if (!postResponse.ok) {
|
|
@@ -230,7 +242,7 @@ class IntentController {
|
|
|
230
242
|
try {
|
|
231
243
|
const reportResponse = await fetch(`${this.#url}/api/intents/${this.#sessionDetails.sessionId}/${discoveryId}`, {
|
|
232
244
|
method: 'POST',
|
|
233
|
-
headers: getRequestHeaders(this.#connectionParams),
|
|
245
|
+
headers: await getRequestHeaders(this.#connectionParams),
|
|
234
246
|
body: JSON.stringify({ intents }),
|
|
235
247
|
});
|
|
236
248
|
if (reportResponse.ok) {
|
|
@@ -244,10 +256,17 @@ class IntentController {
|
|
|
244
256
|
return false;
|
|
245
257
|
}
|
|
246
258
|
async sendIntentResult(initiatingSessionId, result) {
|
|
259
|
+
if (!isErrorIntentResult(result)) {
|
|
260
|
+
// cloud-encode the source app id to support chained intent actions over cloud
|
|
261
|
+
// https://fdc3.finos.org/docs/2.0/api/spec#resolution-object -> "Use metadata about the resolving app instance to target a further intent"
|
|
262
|
+
const source = getSourceFromSession(this.#sessionDetails);
|
|
263
|
+
const encoded = encodeAppId(typeof result.source === 'string' ? result.source : result.source.appId, source);
|
|
264
|
+
result.source = typeof result.source === 'string' ? encoded : { ...result.source, appId: encoded };
|
|
265
|
+
}
|
|
247
266
|
const { sessionId } = getSourceFromSession(this.#sessionDetails);
|
|
248
267
|
const resultResponse = await fetch(`${this.#url}/api/intents/${initiatingSessionId}/result/${sessionId}`, {
|
|
249
268
|
method: 'POST',
|
|
250
|
-
headers: getRequestHeaders(this.#connectionParams),
|
|
269
|
+
headers: await getRequestHeaders(this.#connectionParams),
|
|
251
270
|
body: JSON.stringify({ result }),
|
|
252
271
|
});
|
|
253
272
|
if (!resultResponse.ok) {
|
|
@@ -331,6 +350,7 @@ class CloudInteropAPI {
|
|
|
331
350
|
#reconnectRetryLimit = 30;
|
|
332
351
|
#keepAliveIntervalSeconds = 30;
|
|
333
352
|
#logger = (level, message) => {
|
|
353
|
+
// eslint-disable-next-line security/detect-object-injection -- level is restricted to the LogLevel union
|
|
334
354
|
console[level](message);
|
|
335
355
|
};
|
|
336
356
|
#reconnectRetries = 0;
|
|
@@ -338,6 +358,7 @@ class CloudInteropAPI {
|
|
|
338
358
|
#attemptingToReconnect = false;
|
|
339
359
|
#events = new EventController();
|
|
340
360
|
#intents;
|
|
361
|
+
#sessionTimer;
|
|
341
362
|
constructor(cloudInteropSettings) {
|
|
342
363
|
this.#cloudInteropSettings = cloudInteropSettings;
|
|
343
364
|
}
|
|
@@ -350,11 +371,11 @@ class CloudInteropAPI {
|
|
|
350
371
|
/**
|
|
351
372
|
* Connects and creates a session on the Cloud Interop service
|
|
352
373
|
*
|
|
353
|
-
* @param
|
|
354
|
-
* @returns
|
|
374
|
+
* @param parameters - The parameters to use to connect
|
|
375
|
+
* @returns Promise that resolves when connection is established
|
|
355
376
|
* @memberof CloudInteropAPI
|
|
356
|
-
* @throws
|
|
357
|
-
* @throws
|
|
377
|
+
* @throws CloudInteropAPIError - If an error occurs during connection
|
|
378
|
+
* @throws AuthorizationError - If the connection is unauthorized
|
|
358
379
|
*/
|
|
359
380
|
async connect(parameters) {
|
|
360
381
|
this.#validateConnectParams(parameters);
|
|
@@ -365,7 +386,7 @@ class CloudInteropAPI {
|
|
|
365
386
|
const { sourceId, platformId } = this.#connectionParams;
|
|
366
387
|
const createSessionResponse = await fetch(`${this.#cloudInteropSettings.url}/api/sessions`, {
|
|
367
388
|
method: 'POST',
|
|
368
|
-
headers: getRequestHeaders(this.#connectionParams),
|
|
389
|
+
headers: await getRequestHeaders(this.#connectionParams),
|
|
369
390
|
body: JSON.stringify({ sourceId: sourceId.trim(), platformId }),
|
|
370
391
|
});
|
|
371
392
|
if (!createSessionResponse.ok) {
|
|
@@ -378,6 +399,11 @@ class CloudInteropAPI {
|
|
|
378
399
|
throw new CloudInteropAPIError(`Failed to connect to the Cloud Interop service: ${this.#cloudInteropSettings.url}`, 'ERR_CONNECT', new Error(createSessionResponse.statusText));
|
|
379
400
|
}
|
|
380
401
|
this.#sessionDetails = (await createSessionResponse.json());
|
|
402
|
+
// If local session expiry handling is enabled, start the session timer
|
|
403
|
+
if (this.#sessionDetails.localSessionExpiryHandling) {
|
|
404
|
+
this.#logger('debug', `Local session expiry handling is enabled`);
|
|
405
|
+
this.#startSessionTimer();
|
|
406
|
+
}
|
|
381
407
|
const sessionRootTopic = this.#sessionDetails.sessionRootTopic;
|
|
382
408
|
const clientOptions = {
|
|
383
409
|
keepalive: this.#keepAliveIntervalSeconds,
|
|
@@ -398,6 +424,7 @@ class CloudInteropAPI {
|
|
|
398
424
|
// TODO: Dynamic intent discovery
|
|
399
425
|
// search for any ongoing discoveries in DB and fire report-intents on self
|
|
400
426
|
this.#logger('log', `Cloud Interop successfully connected to ${this.#cloudInteropSettings.url}`);
|
|
427
|
+
// eslint-disable-next-line security-node/detect-unhandled-event-errors -- this callback handles MQTT error events
|
|
401
428
|
this.#mqttClient.on('error', async (error) => {
|
|
402
429
|
// We will receive errors for each failed reconnection attempt
|
|
403
430
|
// We don't want to disconnect on these else we will never reconnect
|
|
@@ -407,9 +434,7 @@ class CloudInteropAPI {
|
|
|
407
434
|
if (error instanceof mqtt.ErrorWithReasonCode) {
|
|
408
435
|
switch (error.code) {
|
|
409
436
|
case BadUserNamePasswordError: {
|
|
410
|
-
|
|
411
|
-
this.#logger('warn', `Session expired`);
|
|
412
|
-
this.#events.emitEvent('session-expired');
|
|
437
|
+
this.#handleSessionExpiry();
|
|
413
438
|
return;
|
|
414
439
|
}
|
|
415
440
|
default: {
|
|
@@ -463,9 +488,9 @@ class CloudInteropAPI {
|
|
|
463
488
|
/**
|
|
464
489
|
* Disconnects from the Cloud Interop service
|
|
465
490
|
*
|
|
466
|
-
* @returns
|
|
491
|
+
* @returns Promise that resolves when disconnected
|
|
467
492
|
* @memberof CloudInteropAPI
|
|
468
|
-
* @throws
|
|
493
|
+
* @throws CloudInteropAPIError - If an error occurs during disconnection
|
|
469
494
|
*/
|
|
470
495
|
async disconnect() {
|
|
471
496
|
await this.#disconnect(true);
|
|
@@ -473,9 +498,9 @@ class CloudInteropAPI {
|
|
|
473
498
|
/**
|
|
474
499
|
* Publishes a new context for the given context group to the other connected sessions
|
|
475
500
|
*
|
|
476
|
-
* @param
|
|
477
|
-
* @param
|
|
478
|
-
* @returns
|
|
501
|
+
* @param contextGroup - The context group to publish to
|
|
502
|
+
* @param context - The context to publish
|
|
503
|
+
* @returns Promise that resolves when context is published
|
|
479
504
|
* @memberof CloudInteropAPI
|
|
480
505
|
*/
|
|
481
506
|
async setContext(contextGroup, context) {
|
|
@@ -492,7 +517,7 @@ class CloudInteropAPI {
|
|
|
492
517
|
};
|
|
493
518
|
const postResponse = await fetch(`${this.#cloudInteropSettings.url}/api/context-groups/${this.#sessionDetails.sessionId}/${contextGroup}`, {
|
|
494
519
|
method: 'POST',
|
|
495
|
-
headers: getRequestHeaders(this.#connectionParams),
|
|
520
|
+
headers: await getRequestHeaders(this.#connectionParams),
|
|
496
521
|
body: JSON.stringify(payload),
|
|
497
522
|
});
|
|
498
523
|
if (!postResponse.ok) {
|
|
@@ -502,9 +527,9 @@ class CloudInteropAPI {
|
|
|
502
527
|
/**
|
|
503
528
|
* Starts an intent discovery operation
|
|
504
529
|
*
|
|
505
|
-
* @returns
|
|
530
|
+
* @returns Promise that resolves when intent discovery is started
|
|
506
531
|
* @memberof CloudInteropAPI
|
|
507
|
-
* @throws
|
|
532
|
+
* @throws CloudInteropAPIError - If an error occurs during intent discovery
|
|
508
533
|
*/
|
|
509
534
|
async startIntentDiscovery(options) {
|
|
510
535
|
this.#throwIfNotConnected();
|
|
@@ -545,9 +570,14 @@ class CloudInteropAPI {
|
|
|
545
570
|
if (!this.#connectionParams) {
|
|
546
571
|
throw new Error('Connect parameters must be provided');
|
|
547
572
|
}
|
|
573
|
+
// Cancel session timer if it's running
|
|
574
|
+
if (this.#sessionTimer) {
|
|
575
|
+
clearTimeout(this.#sessionTimer);
|
|
576
|
+
this.#sessionTimer = undefined;
|
|
577
|
+
}
|
|
548
578
|
const disconnectResponse = await fetch(`${this.#cloudInteropSettings.url}/api/sessions/${this.#sessionDetails.sessionId}`, {
|
|
549
579
|
method: 'DELETE',
|
|
550
|
-
headers: getRequestHeaders(this.#connectionParams),
|
|
580
|
+
headers: await getRequestHeaders(this.#connectionParams),
|
|
551
581
|
});
|
|
552
582
|
if (disconnectResponse.status !== 200) {
|
|
553
583
|
throw new CloudInteropAPIError('Error during session tear down - unexpected status', 'ERR_DISCONNECT', new Error(disconnectResponse.statusText));
|
|
@@ -570,6 +600,7 @@ class CloudInteropAPI {
|
|
|
570
600
|
}
|
|
571
601
|
}
|
|
572
602
|
#handleMessage(topic, message, sessionDetails) {
|
|
603
|
+
this.#logger('debug', `Received message on topic: ${topic}`);
|
|
573
604
|
if (message.length === 0 || !sessionDetails) {
|
|
574
605
|
// Ignore clean up messages
|
|
575
606
|
return;
|
|
@@ -580,8 +611,13 @@ class CloudInteropAPI {
|
|
|
580
611
|
if (contextEvent.source.sessionId === sessionDetails.sessionId) {
|
|
581
612
|
return;
|
|
582
613
|
}
|
|
583
|
-
const { contextGroup,
|
|
584
|
-
this.#events.emitEvent('context', {
|
|
614
|
+
const { context, payload, contextGroup, channelName, source, history } = contextEvent;
|
|
615
|
+
this.#events.emitEvent('context', {
|
|
616
|
+
contextGroup: channelName || contextGroup,
|
|
617
|
+
context: payload || context,
|
|
618
|
+
source,
|
|
619
|
+
history: { ...history, clientReceived: Date.now() },
|
|
620
|
+
});
|
|
585
621
|
}
|
|
586
622
|
else if (topic.startsWith(`${sessionDetails.sessionRootTopic}/commands`)) {
|
|
587
623
|
this.#handleCommandMessage(messageEnvelope);
|
|
@@ -638,6 +674,88 @@ class CloudInteropAPI {
|
|
|
638
674
|
throw new Error('MQTT client not connected');
|
|
639
675
|
}
|
|
640
676
|
}
|
|
677
|
+
/**
|
|
678
|
+
* Extracts the expiration timestamp from a JWT token.
|
|
679
|
+
*
|
|
680
|
+
* @param token - The JWT token string
|
|
681
|
+
* @returns The expiration timestamp in seconds, or null if extraction fails
|
|
682
|
+
*/
|
|
683
|
+
#extractExpirationFromJwt(token) {
|
|
684
|
+
try {
|
|
685
|
+
// JWT tokens have three parts separated by dots: header.payload.signature
|
|
686
|
+
// The exp claim is in the payload
|
|
687
|
+
const parts = token.split('.');
|
|
688
|
+
if (parts.length < 2) {
|
|
689
|
+
this.#logger('warn', 'Invalid JWT token format: expected at least 2 parts');
|
|
690
|
+
return null;
|
|
691
|
+
}
|
|
692
|
+
const payload = parts[1];
|
|
693
|
+
// Decode base64url encoded payload
|
|
694
|
+
const decodedBytes = buffer.Buffer.from(d(payload), 'base64');
|
|
695
|
+
const payloadJson = decodedBytes.toString('utf8');
|
|
696
|
+
// Parse JSON to get the exp claim
|
|
697
|
+
const claims = JSON.parse(payloadJson);
|
|
698
|
+
const exp = claims.exp;
|
|
699
|
+
if (exp === undefined || exp === null) {
|
|
700
|
+
this.#logger('warn', "JWT token does not contain 'exp' claim");
|
|
701
|
+
return null;
|
|
702
|
+
}
|
|
703
|
+
if (typeof exp !== 'number') {
|
|
704
|
+
this.#logger('warn', `JWT token 'exp' claim is not a number: ${exp}`);
|
|
705
|
+
return null;
|
|
706
|
+
}
|
|
707
|
+
return exp;
|
|
708
|
+
}
|
|
709
|
+
catch (error) {
|
|
710
|
+
this.#logger('error', `Failed to extract expiration from JWT token: ${error instanceof Error ? error.message : error}`);
|
|
711
|
+
return null;
|
|
712
|
+
}
|
|
713
|
+
}
|
|
714
|
+
/**
|
|
715
|
+
* Start a session timer that will expire at the time specified in the JWT token's exp claim.
|
|
716
|
+
* When the timer fires, it executes the same actions as the BadUserNamePasswordError case.
|
|
717
|
+
*/
|
|
718
|
+
#startSessionTimer() {
|
|
719
|
+
if (!this.#sessionDetails?.localSessionExpiryHandling) {
|
|
720
|
+
return;
|
|
721
|
+
}
|
|
722
|
+
const token = this.#sessionDetails.token;
|
|
723
|
+
if (!token) {
|
|
724
|
+
this.#logger('warn', 'Cannot start session timer: token not available');
|
|
725
|
+
return;
|
|
726
|
+
}
|
|
727
|
+
// Extract expiration time from JWT token
|
|
728
|
+
const expTimestamp = this.#extractExpirationFromJwt(token);
|
|
729
|
+
if (expTimestamp === null) {
|
|
730
|
+
this.#logger('warn', 'Cannot start session timer: could not extract expiration from JWT token');
|
|
731
|
+
return;
|
|
732
|
+
}
|
|
733
|
+
const currentTimeSeconds = Math.floor(Date.now() / 1000);
|
|
734
|
+
const delaySeconds = expTimestamp - currentTimeSeconds;
|
|
735
|
+
if (delaySeconds <= 0) {
|
|
736
|
+
this.#logger('warn', 'JWT token has already expired or expires immediately');
|
|
737
|
+
// Execute the same actions as BadUserNamePasswordError case
|
|
738
|
+
this.#handleSessionExpiry();
|
|
739
|
+
return;
|
|
740
|
+
}
|
|
741
|
+
// Clear any existing timer
|
|
742
|
+
if (this.#sessionTimer) {
|
|
743
|
+
clearTimeout(this.#sessionTimer);
|
|
744
|
+
}
|
|
745
|
+
const expirationTimeString = new Date(expTimestamp * 1000).toISOString();
|
|
746
|
+
this.#logger('debug', `Starting session timer to expire in ${delaySeconds} seconds (at ${expirationTimeString})`);
|
|
747
|
+
this.#sessionTimer = setTimeout(async () => {
|
|
748
|
+
this.#handleSessionExpiry();
|
|
749
|
+
}, delaySeconds * 1000);
|
|
750
|
+
}
|
|
751
|
+
/**
|
|
752
|
+
* Handles session expiry by executing the same actions as the BadUserNamePasswordError case.
|
|
753
|
+
*/
|
|
754
|
+
async #handleSessionExpiry() {
|
|
755
|
+
await this.#disconnect(false);
|
|
756
|
+
this.#logger('warn', 'Session expired');
|
|
757
|
+
this.#events.emitEvent('session-expired');
|
|
758
|
+
}
|
|
641
759
|
}
|
|
642
760
|
|
|
643
761
|
exports.AuthorizationError = AuthorizationError;
|
package/index.mjs
CHANGED
|
@@ -1,6 +1,10 @@
|
|
|
1
1
|
import { Buffer } from 'buffer';
|
|
2
|
+
import 'fs';
|
|
3
|
+
import 'path';
|
|
2
4
|
import mqtt from 'mqtt';
|
|
3
5
|
|
|
6
|
+
var d=n=>{let t=n.replaceAll("-","+").replaceAll("_","/");return t.padEnd(t.length+(4-t.length%4)%4,"=")};
|
|
7
|
+
|
|
4
8
|
class CloudInteropAPIError extends Error {
|
|
5
9
|
code;
|
|
6
10
|
constructor(message = 'An unexpected error has occurred', code = 'UNEXPECTED_ERROR', cause) {
|
|
@@ -44,12 +48,14 @@ class EventController {
|
|
|
44
48
|
}
|
|
45
49
|
}
|
|
46
50
|
|
|
51
|
+
const isErrorIntentResult = (result) => 'error' in result;
|
|
52
|
+
|
|
47
53
|
const APP_ID_DELIM = '::';
|
|
48
|
-
const getRequestHeaders = (connectionParameters) => {
|
|
54
|
+
const getRequestHeaders = async (connectionParameters) => {
|
|
49
55
|
const headers = {};
|
|
50
56
|
headers['Content-Type'] = 'application/json';
|
|
51
57
|
if (connectionParameters.authenticationType === 'jwt' && connectionParameters.jwtAuthenticationParameters) {
|
|
52
|
-
const tokenResult = connectionParameters.jwtAuthenticationParameters.jwtRequestCallback();
|
|
58
|
+
const tokenResult = await connectionParameters.jwtAuthenticationParameters.jwtRequestCallback();
|
|
53
59
|
if (!tokenResult) {
|
|
54
60
|
throw new Error('jwtRequestCallback must return a token');
|
|
55
61
|
}
|
|
@@ -70,13 +76,9 @@ const getRequestHeaders = (connectionParameters) => {
|
|
|
70
76
|
* @param source
|
|
71
77
|
* @returns
|
|
72
78
|
*/
|
|
73
|
-
const encodeAppIntents = (appIntents,
|
|
79
|
+
const encodeAppIntents = (appIntents, source) => appIntents.map((intent) => ({
|
|
74
80
|
...intent,
|
|
75
|
-
apps: intent.apps.map((app) => {
|
|
76
|
-
const id = encodeURIComponent(app.appId);
|
|
77
|
-
const sId = encodeURIComponent(sourceId);
|
|
78
|
-
return { ...app, appId: `${id}${APP_ID_DELIM}${sId}${APP_ID_DELIM}${sessionId}` };
|
|
79
|
-
}),
|
|
81
|
+
apps: intent.apps.map((app) => ({ ...app, appId: encodeAppId(app.appId, source) })),
|
|
80
82
|
}));
|
|
81
83
|
/**
|
|
82
84
|
* Decodes all app intents by URI decoding the parts previously encoded by `encodeAppIntents`
|
|
@@ -85,13 +87,19 @@ const encodeAppIntents = (appIntents, { sessionId, sourceId }) => appIntents.map
|
|
|
85
87
|
*/
|
|
86
88
|
const decodeAppIntents = (appIntents) => appIntents.map((intent) => ({
|
|
87
89
|
...intent,
|
|
88
|
-
apps: intent.apps.map((app) => {
|
|
89
|
-
const [encodedAppId, encodedSourceId, sessionId] = app.appId.split(APP_ID_DELIM);
|
|
90
|
-
const id = decodeURIComponent(encodedAppId);
|
|
91
|
-
const sourceId = decodeURIComponent(encodedSourceId);
|
|
92
|
-
return { ...app, appId: `${id}${APP_ID_DELIM}${sourceId}${APP_ID_DELIM}${sessionId}` };
|
|
93
|
-
}),
|
|
90
|
+
apps: intent.apps.map((app) => ({ ...app, appId: decodeAppId(app.appId) })),
|
|
94
91
|
}));
|
|
92
|
+
const encodeAppId = (appIdString, { sessionId, sourceId }) => {
|
|
93
|
+
const id = encodeURIComponent(appIdString);
|
|
94
|
+
const sId = encodeURIComponent(sourceId);
|
|
95
|
+
return `${id}${APP_ID_DELIM}${sId}${APP_ID_DELIM}${sessionId}`;
|
|
96
|
+
};
|
|
97
|
+
const decodeAppId = (appId) => {
|
|
98
|
+
const [encodedAppId, encodedSourceId, sessionId] = appId.split(APP_ID_DELIM);
|
|
99
|
+
const id = decodeURIComponent(encodedAppId);
|
|
100
|
+
const sourceId = decodeURIComponent(encodedSourceId);
|
|
101
|
+
return `${id}${APP_ID_DELIM}${sourceId}${APP_ID_DELIM}${sessionId}`;
|
|
102
|
+
};
|
|
95
103
|
/**
|
|
96
104
|
* Decodes the AppIdentifier to extract the appId, sourceId, and sessionId.
|
|
97
105
|
* @returns an object with:
|
|
@@ -152,17 +160,22 @@ class IntentController {
|
|
|
152
160
|
try {
|
|
153
161
|
const startResponse = await fetch(`${this.#url}/api/intents/${this.#sessionDetails.sessionId}`, {
|
|
154
162
|
method: 'POST',
|
|
155
|
-
headers: getRequestHeaders(this.#connectionParams),
|
|
163
|
+
headers: await getRequestHeaders(this.#connectionParams),
|
|
156
164
|
body: JSON.stringify({ findOptions }),
|
|
157
165
|
});
|
|
158
166
|
if (!startResponse.ok) {
|
|
159
|
-
throw new Error(startResponse.statusText);
|
|
167
|
+
throw new Error(`Error creating intent discovery record: ${startResponse.statusText}`);
|
|
160
168
|
}
|
|
161
169
|
// TODO: type this response?
|
|
162
170
|
const json = await startResponse.json();
|
|
163
171
|
this.#discovery.id = json.discoveryId;
|
|
164
172
|
this.#discovery.sessionCount = json.sessionCount;
|
|
165
173
|
this.#discovery.state = 'in-progress';
|
|
174
|
+
if (this.#discovery.sessionCount === 1) {
|
|
175
|
+
// since we have no other connected sessions, we can end discovery immediately
|
|
176
|
+
await this.#endIntentDiscovery(false);
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
166
179
|
// Listen out for discovery results directly sent to us
|
|
167
180
|
await this.#mqttClient.subscribeAsync(`${this.#sessionDetails.sessionRootTopic}/commands/${this.#discovery.id}`);
|
|
168
181
|
this.#discoveryTimeout = setTimeout(() => this.#endIntentDiscovery(), clampedTimeout);
|
|
@@ -173,10 +186,8 @@ class IntentController {
|
|
|
173
186
|
throw new CloudInteropAPIError('Error starting intent discovery', 'ERR_STARTING_INTENT_DISCOVERY', error);
|
|
174
187
|
}
|
|
175
188
|
}
|
|
176
|
-
async #endIntentDiscovery() {
|
|
189
|
+
async #endIntentDiscovery(mqttUnsubscribe = true) {
|
|
177
190
|
if (this.#discovery.state !== 'in-progress') {
|
|
178
|
-
// TODO: remove debug logs
|
|
179
|
-
this.#logger('debug', 'Intent discovery not in progress');
|
|
180
191
|
return;
|
|
181
192
|
}
|
|
182
193
|
if (this.#discoveryTimeout) {
|
|
@@ -186,19 +197,20 @@ class IntentController {
|
|
|
186
197
|
this.#discovery.state = 'ended';
|
|
187
198
|
// emit our aggregated events
|
|
188
199
|
this.#events.emitEvent('aggregate-intent-details', { responses: this.#discovery.pendingIntentDetailsEvents });
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
this.#
|
|
192
|
-
|
|
200
|
+
if (mqttUnsubscribe) {
|
|
201
|
+
// gracefully end discovery
|
|
202
|
+
await this.#mqttClient.unsubscribeAsync(`${this.#sessionDetails.sessionRootTopic}/commands/${this.#discovery.id}`).catch(() => {
|
|
203
|
+
this.#logger('warn', `Error ending intent discovery: could not unsubscribe from discovery id ${this.#discovery.id}`);
|
|
204
|
+
});
|
|
205
|
+
}
|
|
193
206
|
await fetch(`${this.#url}/api/intents/${this.#sessionDetails.sessionId}/${this.#discovery.id}`, {
|
|
194
207
|
method: 'DELETE',
|
|
195
|
-
headers: getRequestHeaders(this.#connectionParams),
|
|
208
|
+
headers: await getRequestHeaders(this.#connectionParams),
|
|
196
209
|
})
|
|
197
210
|
.then((deleteResponse) => {
|
|
198
211
|
if (!deleteResponse.ok) {
|
|
199
212
|
throw new Error(`Error ending intent discovery: ${deleteResponse.statusText}`);
|
|
200
213
|
}
|
|
201
|
-
this.#logger('debug', 'Intent discovery ended');
|
|
202
214
|
})
|
|
203
215
|
.catch((error) => {
|
|
204
216
|
this.#logger('warn', `Error ending intent discovery: ${error}`);
|
|
@@ -214,7 +226,7 @@ class IntentController {
|
|
|
214
226
|
}
|
|
215
227
|
const postResponse = await fetch(`${this.#url}/api/intents/${this.#sessionDetails.sessionId}/sessions/${targetSessionId}`, {
|
|
216
228
|
method: 'POST',
|
|
217
|
-
headers: getRequestHeaders(this.#connectionParams),
|
|
229
|
+
headers: await getRequestHeaders(this.#connectionParams),
|
|
218
230
|
body: JSON.stringify({ raiseOptions }),
|
|
219
231
|
});
|
|
220
232
|
if (!postResponse.ok) {
|
|
@@ -228,7 +240,7 @@ class IntentController {
|
|
|
228
240
|
try {
|
|
229
241
|
const reportResponse = await fetch(`${this.#url}/api/intents/${this.#sessionDetails.sessionId}/${discoveryId}`, {
|
|
230
242
|
method: 'POST',
|
|
231
|
-
headers: getRequestHeaders(this.#connectionParams),
|
|
243
|
+
headers: await getRequestHeaders(this.#connectionParams),
|
|
232
244
|
body: JSON.stringify({ intents }),
|
|
233
245
|
});
|
|
234
246
|
if (reportResponse.ok) {
|
|
@@ -242,10 +254,17 @@ class IntentController {
|
|
|
242
254
|
return false;
|
|
243
255
|
}
|
|
244
256
|
async sendIntentResult(initiatingSessionId, result) {
|
|
257
|
+
if (!isErrorIntentResult(result)) {
|
|
258
|
+
// cloud-encode the source app id to support chained intent actions over cloud
|
|
259
|
+
// https://fdc3.finos.org/docs/2.0/api/spec#resolution-object -> "Use metadata about the resolving app instance to target a further intent"
|
|
260
|
+
const source = getSourceFromSession(this.#sessionDetails);
|
|
261
|
+
const encoded = encodeAppId(typeof result.source === 'string' ? result.source : result.source.appId, source);
|
|
262
|
+
result.source = typeof result.source === 'string' ? encoded : { ...result.source, appId: encoded };
|
|
263
|
+
}
|
|
245
264
|
const { sessionId } = getSourceFromSession(this.#sessionDetails);
|
|
246
265
|
const resultResponse = await fetch(`${this.#url}/api/intents/${initiatingSessionId}/result/${sessionId}`, {
|
|
247
266
|
method: 'POST',
|
|
248
|
-
headers: getRequestHeaders(this.#connectionParams),
|
|
267
|
+
headers: await getRequestHeaders(this.#connectionParams),
|
|
249
268
|
body: JSON.stringify({ result }),
|
|
250
269
|
});
|
|
251
270
|
if (!resultResponse.ok) {
|
|
@@ -329,6 +348,7 @@ class CloudInteropAPI {
|
|
|
329
348
|
#reconnectRetryLimit = 30;
|
|
330
349
|
#keepAliveIntervalSeconds = 30;
|
|
331
350
|
#logger = (level, message) => {
|
|
351
|
+
// eslint-disable-next-line security/detect-object-injection -- level is restricted to the LogLevel union
|
|
332
352
|
console[level](message);
|
|
333
353
|
};
|
|
334
354
|
#reconnectRetries = 0;
|
|
@@ -336,6 +356,7 @@ class CloudInteropAPI {
|
|
|
336
356
|
#attemptingToReconnect = false;
|
|
337
357
|
#events = new EventController();
|
|
338
358
|
#intents;
|
|
359
|
+
#sessionTimer;
|
|
339
360
|
constructor(cloudInteropSettings) {
|
|
340
361
|
this.#cloudInteropSettings = cloudInteropSettings;
|
|
341
362
|
}
|
|
@@ -348,11 +369,11 @@ class CloudInteropAPI {
|
|
|
348
369
|
/**
|
|
349
370
|
* Connects and creates a session on the Cloud Interop service
|
|
350
371
|
*
|
|
351
|
-
* @param
|
|
352
|
-
* @returns
|
|
372
|
+
* @param parameters - The parameters to use to connect
|
|
373
|
+
* @returns Promise that resolves when connection is established
|
|
353
374
|
* @memberof CloudInteropAPI
|
|
354
|
-
* @throws
|
|
355
|
-
* @throws
|
|
375
|
+
* @throws CloudInteropAPIError - If an error occurs during connection
|
|
376
|
+
* @throws AuthorizationError - If the connection is unauthorized
|
|
356
377
|
*/
|
|
357
378
|
async connect(parameters) {
|
|
358
379
|
this.#validateConnectParams(parameters);
|
|
@@ -363,7 +384,7 @@ class CloudInteropAPI {
|
|
|
363
384
|
const { sourceId, platformId } = this.#connectionParams;
|
|
364
385
|
const createSessionResponse = await fetch(`${this.#cloudInteropSettings.url}/api/sessions`, {
|
|
365
386
|
method: 'POST',
|
|
366
|
-
headers: getRequestHeaders(this.#connectionParams),
|
|
387
|
+
headers: await getRequestHeaders(this.#connectionParams),
|
|
367
388
|
body: JSON.stringify({ sourceId: sourceId.trim(), platformId }),
|
|
368
389
|
});
|
|
369
390
|
if (!createSessionResponse.ok) {
|
|
@@ -376,6 +397,11 @@ class CloudInteropAPI {
|
|
|
376
397
|
throw new CloudInteropAPIError(`Failed to connect to the Cloud Interop service: ${this.#cloudInteropSettings.url}`, 'ERR_CONNECT', new Error(createSessionResponse.statusText));
|
|
377
398
|
}
|
|
378
399
|
this.#sessionDetails = (await createSessionResponse.json());
|
|
400
|
+
// If local session expiry handling is enabled, start the session timer
|
|
401
|
+
if (this.#sessionDetails.localSessionExpiryHandling) {
|
|
402
|
+
this.#logger('debug', `Local session expiry handling is enabled`);
|
|
403
|
+
this.#startSessionTimer();
|
|
404
|
+
}
|
|
379
405
|
const sessionRootTopic = this.#sessionDetails.sessionRootTopic;
|
|
380
406
|
const clientOptions = {
|
|
381
407
|
keepalive: this.#keepAliveIntervalSeconds,
|
|
@@ -396,6 +422,7 @@ class CloudInteropAPI {
|
|
|
396
422
|
// TODO: Dynamic intent discovery
|
|
397
423
|
// search for any ongoing discoveries in DB and fire report-intents on self
|
|
398
424
|
this.#logger('log', `Cloud Interop successfully connected to ${this.#cloudInteropSettings.url}`);
|
|
425
|
+
// eslint-disable-next-line security-node/detect-unhandled-event-errors -- this callback handles MQTT error events
|
|
399
426
|
this.#mqttClient.on('error', async (error) => {
|
|
400
427
|
// We will receive errors for each failed reconnection attempt
|
|
401
428
|
// We don't want to disconnect on these else we will never reconnect
|
|
@@ -405,9 +432,7 @@ class CloudInteropAPI {
|
|
|
405
432
|
if (error instanceof mqtt.ErrorWithReasonCode) {
|
|
406
433
|
switch (error.code) {
|
|
407
434
|
case BadUserNamePasswordError: {
|
|
408
|
-
|
|
409
|
-
this.#logger('warn', `Session expired`);
|
|
410
|
-
this.#events.emitEvent('session-expired');
|
|
435
|
+
this.#handleSessionExpiry();
|
|
411
436
|
return;
|
|
412
437
|
}
|
|
413
438
|
default: {
|
|
@@ -461,9 +486,9 @@ class CloudInteropAPI {
|
|
|
461
486
|
/**
|
|
462
487
|
* Disconnects from the Cloud Interop service
|
|
463
488
|
*
|
|
464
|
-
* @returns
|
|
489
|
+
* @returns Promise that resolves when disconnected
|
|
465
490
|
* @memberof CloudInteropAPI
|
|
466
|
-
* @throws
|
|
491
|
+
* @throws CloudInteropAPIError - If an error occurs during disconnection
|
|
467
492
|
*/
|
|
468
493
|
async disconnect() {
|
|
469
494
|
await this.#disconnect(true);
|
|
@@ -471,9 +496,9 @@ class CloudInteropAPI {
|
|
|
471
496
|
/**
|
|
472
497
|
* Publishes a new context for the given context group to the other connected sessions
|
|
473
498
|
*
|
|
474
|
-
* @param
|
|
475
|
-
* @param
|
|
476
|
-
* @returns
|
|
499
|
+
* @param contextGroup - The context group to publish to
|
|
500
|
+
* @param context - The context to publish
|
|
501
|
+
* @returns Promise that resolves when context is published
|
|
477
502
|
* @memberof CloudInteropAPI
|
|
478
503
|
*/
|
|
479
504
|
async setContext(contextGroup, context) {
|
|
@@ -490,7 +515,7 @@ class CloudInteropAPI {
|
|
|
490
515
|
};
|
|
491
516
|
const postResponse = await fetch(`${this.#cloudInteropSettings.url}/api/context-groups/${this.#sessionDetails.sessionId}/${contextGroup}`, {
|
|
492
517
|
method: 'POST',
|
|
493
|
-
headers: getRequestHeaders(this.#connectionParams),
|
|
518
|
+
headers: await getRequestHeaders(this.#connectionParams),
|
|
494
519
|
body: JSON.stringify(payload),
|
|
495
520
|
});
|
|
496
521
|
if (!postResponse.ok) {
|
|
@@ -500,9 +525,9 @@ class CloudInteropAPI {
|
|
|
500
525
|
/**
|
|
501
526
|
* Starts an intent discovery operation
|
|
502
527
|
*
|
|
503
|
-
* @returns
|
|
528
|
+
* @returns Promise that resolves when intent discovery is started
|
|
504
529
|
* @memberof CloudInteropAPI
|
|
505
|
-
* @throws
|
|
530
|
+
* @throws CloudInteropAPIError - If an error occurs during intent discovery
|
|
506
531
|
*/
|
|
507
532
|
async startIntentDiscovery(options) {
|
|
508
533
|
this.#throwIfNotConnected();
|
|
@@ -543,9 +568,14 @@ class CloudInteropAPI {
|
|
|
543
568
|
if (!this.#connectionParams) {
|
|
544
569
|
throw new Error('Connect parameters must be provided');
|
|
545
570
|
}
|
|
571
|
+
// Cancel session timer if it's running
|
|
572
|
+
if (this.#sessionTimer) {
|
|
573
|
+
clearTimeout(this.#sessionTimer);
|
|
574
|
+
this.#sessionTimer = undefined;
|
|
575
|
+
}
|
|
546
576
|
const disconnectResponse = await fetch(`${this.#cloudInteropSettings.url}/api/sessions/${this.#sessionDetails.sessionId}`, {
|
|
547
577
|
method: 'DELETE',
|
|
548
|
-
headers: getRequestHeaders(this.#connectionParams),
|
|
578
|
+
headers: await getRequestHeaders(this.#connectionParams),
|
|
549
579
|
});
|
|
550
580
|
if (disconnectResponse.status !== 200) {
|
|
551
581
|
throw new CloudInteropAPIError('Error during session tear down - unexpected status', 'ERR_DISCONNECT', new Error(disconnectResponse.statusText));
|
|
@@ -568,6 +598,7 @@ class CloudInteropAPI {
|
|
|
568
598
|
}
|
|
569
599
|
}
|
|
570
600
|
#handleMessage(topic, message, sessionDetails) {
|
|
601
|
+
this.#logger('debug', `Received message on topic: ${topic}`);
|
|
571
602
|
if (message.length === 0 || !sessionDetails) {
|
|
572
603
|
// Ignore clean up messages
|
|
573
604
|
return;
|
|
@@ -578,8 +609,13 @@ class CloudInteropAPI {
|
|
|
578
609
|
if (contextEvent.source.sessionId === sessionDetails.sessionId) {
|
|
579
610
|
return;
|
|
580
611
|
}
|
|
581
|
-
const { contextGroup,
|
|
582
|
-
this.#events.emitEvent('context', {
|
|
612
|
+
const { context, payload, contextGroup, channelName, source, history } = contextEvent;
|
|
613
|
+
this.#events.emitEvent('context', {
|
|
614
|
+
contextGroup: channelName || contextGroup,
|
|
615
|
+
context: payload || context,
|
|
616
|
+
source,
|
|
617
|
+
history: { ...history, clientReceived: Date.now() },
|
|
618
|
+
});
|
|
583
619
|
}
|
|
584
620
|
else if (topic.startsWith(`${sessionDetails.sessionRootTopic}/commands`)) {
|
|
585
621
|
this.#handleCommandMessage(messageEnvelope);
|
|
@@ -636,6 +672,88 @@ class CloudInteropAPI {
|
|
|
636
672
|
throw new Error('MQTT client not connected');
|
|
637
673
|
}
|
|
638
674
|
}
|
|
675
|
+
/**
|
|
676
|
+
* Extracts the expiration timestamp from a JWT token.
|
|
677
|
+
*
|
|
678
|
+
* @param token - The JWT token string
|
|
679
|
+
* @returns The expiration timestamp in seconds, or null if extraction fails
|
|
680
|
+
*/
|
|
681
|
+
#extractExpirationFromJwt(token) {
|
|
682
|
+
try {
|
|
683
|
+
// JWT tokens have three parts separated by dots: header.payload.signature
|
|
684
|
+
// The exp claim is in the payload
|
|
685
|
+
const parts = token.split('.');
|
|
686
|
+
if (parts.length < 2) {
|
|
687
|
+
this.#logger('warn', 'Invalid JWT token format: expected at least 2 parts');
|
|
688
|
+
return null;
|
|
689
|
+
}
|
|
690
|
+
const payload = parts[1];
|
|
691
|
+
// Decode base64url encoded payload
|
|
692
|
+
const decodedBytes = Buffer.from(d(payload), 'base64');
|
|
693
|
+
const payloadJson = decodedBytes.toString('utf8');
|
|
694
|
+
// Parse JSON to get the exp claim
|
|
695
|
+
const claims = JSON.parse(payloadJson);
|
|
696
|
+
const exp = claims.exp;
|
|
697
|
+
if (exp === undefined || exp === null) {
|
|
698
|
+
this.#logger('warn', "JWT token does not contain 'exp' claim");
|
|
699
|
+
return null;
|
|
700
|
+
}
|
|
701
|
+
if (typeof exp !== 'number') {
|
|
702
|
+
this.#logger('warn', `JWT token 'exp' claim is not a number: ${exp}`);
|
|
703
|
+
return null;
|
|
704
|
+
}
|
|
705
|
+
return exp;
|
|
706
|
+
}
|
|
707
|
+
catch (error) {
|
|
708
|
+
this.#logger('error', `Failed to extract expiration from JWT token: ${error instanceof Error ? error.message : error}`);
|
|
709
|
+
return null;
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
/**
|
|
713
|
+
* Start a session timer that will expire at the time specified in the JWT token's exp claim.
|
|
714
|
+
* When the timer fires, it executes the same actions as the BadUserNamePasswordError case.
|
|
715
|
+
*/
|
|
716
|
+
#startSessionTimer() {
|
|
717
|
+
if (!this.#sessionDetails?.localSessionExpiryHandling) {
|
|
718
|
+
return;
|
|
719
|
+
}
|
|
720
|
+
const token = this.#sessionDetails.token;
|
|
721
|
+
if (!token) {
|
|
722
|
+
this.#logger('warn', 'Cannot start session timer: token not available');
|
|
723
|
+
return;
|
|
724
|
+
}
|
|
725
|
+
// Extract expiration time from JWT token
|
|
726
|
+
const expTimestamp = this.#extractExpirationFromJwt(token);
|
|
727
|
+
if (expTimestamp === null) {
|
|
728
|
+
this.#logger('warn', 'Cannot start session timer: could not extract expiration from JWT token');
|
|
729
|
+
return;
|
|
730
|
+
}
|
|
731
|
+
const currentTimeSeconds = Math.floor(Date.now() / 1000);
|
|
732
|
+
const delaySeconds = expTimestamp - currentTimeSeconds;
|
|
733
|
+
if (delaySeconds <= 0) {
|
|
734
|
+
this.#logger('warn', 'JWT token has already expired or expires immediately');
|
|
735
|
+
// Execute the same actions as BadUserNamePasswordError case
|
|
736
|
+
this.#handleSessionExpiry();
|
|
737
|
+
return;
|
|
738
|
+
}
|
|
739
|
+
// Clear any existing timer
|
|
740
|
+
if (this.#sessionTimer) {
|
|
741
|
+
clearTimeout(this.#sessionTimer);
|
|
742
|
+
}
|
|
743
|
+
const expirationTimeString = new Date(expTimestamp * 1000).toISOString();
|
|
744
|
+
this.#logger('debug', `Starting session timer to expire in ${delaySeconds} seconds (at ${expirationTimeString})`);
|
|
745
|
+
this.#sessionTimer = setTimeout(async () => {
|
|
746
|
+
this.#handleSessionExpiry();
|
|
747
|
+
}, delaySeconds * 1000);
|
|
748
|
+
}
|
|
749
|
+
/**
|
|
750
|
+
* Handles session expiry by executing the same actions as the BadUserNamePasswordError case.
|
|
751
|
+
*/
|
|
752
|
+
async #handleSessionExpiry() {
|
|
753
|
+
await this.#disconnect(false);
|
|
754
|
+
this.#logger('warn', 'Session expired');
|
|
755
|
+
this.#events.emitEvent('session-expired');
|
|
756
|
+
}
|
|
639
757
|
}
|
|
640
758
|
|
|
641
759
|
export { AuthorizationError, CloudInteropAPI, CloudInteropAPIError };
|
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.c0d1041",
|
|
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
|
-
"optionalDependencies": {
|
|
12
|
-
"@rollup/rollup-linux-x64-gnu": "*"
|
|
13
|
-
},
|
|
14
11
|
"dependencies": {
|
|
15
|
-
"mqtt": "
|
|
16
|
-
"zod": "
|
|
12
|
+
"mqtt": "catalog:",
|
|
13
|
+
"zod": "catalog:"
|
|
17
14
|
}
|
|
18
15
|
}
|
package/version
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
0.0.1-alpha.c07aba2
|