-
Notifications
You must be signed in to change notification settings - Fork 368
/
index.ts
495 lines (410 loc) · 16.8 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
/*
* Copyright (c) 2023 Nango, all rights reserved.
*/
const prodHost = 'https://api.nango.dev';
const debugLogPrefix = 'NANGO DEBUG LOG: ';
const enum WSMessageType {
ConnectionAck = 'connection_ack',
Error = 'error',
Success = 'success'
}
export class AuthError extends Error {
type: string;
constructor(message: string, type: string) {
super(message);
this.type = type;
}
}
export interface AuthResult {
providerConfigKey: string;
connectionId: string;
isPending?: boolean;
}
interface AuthOptions {
detectClosedAuthWindow?: boolean; // If true, `nango.auth()` would fail if the login window is closed before the authorization flow is completed
}
export default class Nango {
private hostBaseUrl: string;
private websocketsBaseUrl: string;
private status: AuthorizationStatus;
private publicKey: string;
private debug = false;
public win: null | AuthorizationModal = null;
private width: number | null = null;
private height: number | null = null;
private tm: null | NodeJS.Timer = null;
constructor(config: { host?: string; websocketsPath?: string; publicKey: string; width?: number; height?: number; debug?: boolean }) {
config.host = config.host || prodHost; // Default to Nango Cloud.
config.websocketsPath = config.websocketsPath || '/'; // Default to root path.
this.debug = config.debug || false;
if (this.debug) {
console.log(debugLogPrefix, `Debug mode is enabled.`);
console.log(debugLogPrefix, `Using host: ${config.host}.`);
}
if (config.width) {
this.width = config.width;
}
if (config.height) {
this.height = config.height;
}
this.hostBaseUrl = config.host.slice(-1) === '/' ? config.host.slice(0, -1) : config.host; // Remove trailing slash.
this.status = AuthorizationStatus.IDLE;
this.publicKey = config.publicKey;
if (!config.publicKey) {
throw new AuthError('You must specify a public key (cf. documentation).', 'missingPublicKey');
}
try {
const baseUrl = new URL(this.hostBaseUrl);
// Build the websockets url based on the host url.
// The websockets path is considered relative to the baseUrl, and with the protocol updated
const websocketUrl = new URL(config.websocketsPath, baseUrl);
this.websocketsBaseUrl = websocketUrl.toString().replace('https://', 'wss://').replace('http://', 'ws://');
} catch {
throw new AuthError('Invalid URL provided for the Nango host.', 'invalidHostUrl');
}
}
public async create(providerConfigKey: string, connectionId: string, connectionConfig?: ConnectionConfig): Promise<AuthResult> {
const url = this.hostBaseUrl + `/unauth/${providerConfigKey}${this.toQueryString(connectionId, connectionConfig)}`;
const res = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
});
if (!res.ok) {
const errorResponse = await res.json();
throw new AuthError(errorResponse.error, errorResponse.type);
}
return res.json();
}
public auth(
providerConfigKey: string,
connectionId: string,
options?: (ConnectionConfig | BasicApiCredentials | ApiKeyCredentials | AppStoreCredentials) & AuthOptions
): Promise<AuthResult> {
if (options && 'credentials' in options && Object.keys(options.credentials).length > 0) {
const credentials = options.credentials as BasicApiCredentials | ApiKeyCredentials;
const { credentials: _, ...connectionConfig } = options as ConnectionConfig;
return this.customAuth(providerConfigKey, connectionId, this.convertCredentialsToConfig(credentials), connectionConfig);
}
const url = this.hostBaseUrl + `/oauth/connect/${providerConfigKey}${this.toQueryString(connectionId, options as ConnectionConfig)}`;
try {
new URL(url);
} catch {
throw new AuthError('Invalid URL provided for the Nango host.', 'invalidHostUrl');
}
return new Promise((resolve, reject) => {
const successHandler = (providerConfigKey: string, connectionId: string, isPending = false) => {
if (this.status !== AuthorizationStatus.BUSY) {
return;
}
this.status = AuthorizationStatus.DONE;
return resolve({
providerConfigKey: providerConfigKey,
connectionId: connectionId,
isPending
});
};
const errorHandler = (errorType: string, errorDesc: string) => {
if (this.status !== AuthorizationStatus.BUSY) {
return;
}
this.status = AuthorizationStatus.DONE;
const error = new AuthError(errorDesc, errorType);
return reject(error);
};
if (this.status === AuthorizationStatus.BUSY) {
const error = new AuthError('The authorization window is already opened', 'windowIsOppened');
reject(error);
}
// Save authorization status (for handler)
this.status = AuthorizationStatus.BUSY;
// Open authorization modal
this.win = new AuthorizationModal(
this.websocketsBaseUrl,
url,
successHandler,
errorHandler,
{ width: this.width, height: this.height },
this.debug
);
if (options?.detectClosedAuthWindow || false) {
this.tm = setInterval(() => {
if (!this.win?.modal?.window || this.win?.modal?.window.closed) {
if (this.win?.isProcessingMessage === true) {
// Modal is still processing a web socket message from the server
// We ignore the window being closed for now
return;
}
clearTimeout(this.tm as unknown as number);
this.win = null;
this.status = AuthorizationStatus.CANCELED;
const error = new AuthError('The authorization window was closed before the authorization flow was completed', 'windowClosed');
reject(error);
}
}, 500);
}
});
}
private convertCredentialsToConfig(credentials: BasicApiCredentials | ApiKeyCredentials | AppStoreCredentials): ConnectionConfig {
const params: Record<string, string> = {};
if ('username' in credentials) {
params['username'] = credentials.username || '';
}
if ('password' in credentials) {
params['password'] = credentials.password || '';
}
if ('apiKey' in credentials) {
params['apiKey'] = credentials.apiKey || '';
}
if ('privateKeyId' in credentials && 'issuerId' in credentials && 'privateKey' in credentials) {
const appStoreCredentials: { params: Record<string, string | string[]> } = {
params: {
privateKeyId: credentials.privateKeyId,
issuerId: credentials.issuerId,
privateKey: credentials.privateKey
}
};
if (credentials.scope) {
appStoreCredentials.params['scope'] = credentials.scope;
}
return appStoreCredentials as unknown as ConnectionConfig;
}
return { params };
}
private async customAuth(
providerConfigKey: string,
connectionId: string,
connectionConfigWithCredentials: ConnectionConfig,
connectionConfig?: ConnectionConfig
): Promise<AuthResult> {
const { params: credentials } = connectionConfigWithCredentials;
if (!credentials) {
throw new AuthError('You must specify credentials.', 'missingCredentials');
}
if ('apiKey' in credentials) {
const apiKeyCredential = credentials as ApiKeyCredentials;
const url = this.hostBaseUrl + `/api-auth/api-key/${providerConfigKey}${this.toQueryString(connectionId, connectionConfig as ConnectionConfig)}`;
const res = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(apiKeyCredential)
});
if (!res.ok) {
const errorResponse = await res.json();
throw new AuthError(errorResponse.error, errorResponse.type);
}
return res.json();
}
if ('username' in credentials || 'password' in credentials) {
const basicCredentials = credentials as BasicApiCredentials;
const url = this.hostBaseUrl + `/api-auth/basic/${providerConfigKey}${this.toQueryString(connectionId, connectionConfig as ConnectionConfig)}`;
const res = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(basicCredentials)
});
if (!res.ok) {
const errorResponse = await res.json();
throw new AuthError(errorResponse.error, errorResponse.type);
}
return res.json();
}
if ('privateKeyId' in credentials && 'issuerId' in credentials && 'privateKey' in credentials) {
const appCredentials = credentials as unknown as AppStoreCredentials;
const url = this.hostBaseUrl + `/app-store-auth/${providerConfigKey}${this.toQueryString(connectionId, connectionConfig as ConnectionConfig)}`;
const res = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(appCredentials)
});
if (!res.ok) {
const errorResponse = await res.json();
throw new AuthError(errorResponse.error, errorResponse.type);
}
return res.json();
}
return Promise.reject('Something went wrong with the authorization');
}
private toQueryString(connectionId: string, connectionConfig?: ConnectionConfig): string {
const query: string[] = [];
if (connectionId) {
query.push(`connection_id=${connectionId}`);
}
query.push(`public_key=${this.publicKey}`);
if (connectionConfig) {
for (const param in connectionConfig.params) {
const val = connectionConfig.params[param];
if (typeof val === 'string') {
query.push(`params[${param}]=${val}`);
}
}
if (connectionConfig.hmac) {
query.push(`hmac=${connectionConfig.hmac}`);
}
if (connectionConfig.user_scope) {
query.push(`user_scope=${connectionConfig.user_scope.join(',')}`);
}
for (const param in connectionConfig.authorization_params) {
const val = connectionConfig.authorization_params[param];
if (typeof val === 'string') {
query.push(`authorization_params[${param}]=${val}`);
} else if (val === undefined) {
query.push(`authorization_params[${param}]=undefined`);
}
}
}
return query.length === 0 ? '' : '?' + query.join('&');
}
}
interface ConnectionConfig {
params?: Record<string, string>;
hmac?: string;
user_scope?: string[];
authorization_params?: Record<string, string | undefined>;
credentials?: BasicApiCredentials | ApiKeyCredentials | AppStoreCredentials;
}
interface BasicApiCredentials {
username?: string;
password?: string;
}
interface ApiKeyCredentials {
apiKey?: string;
}
interface AppStoreCredentials {
privateKeyId: string;
issuerId: string;
privateKey: string;
scope?: string[];
}
enum AuthorizationStatus {
IDLE,
BUSY,
CANCELED,
DONE
}
/**
* AuthorizationModal class
*/
class AuthorizationModal {
private url: string;
private features: Record<string, string | number>;
private width = 500;
private height = 600;
public modal: Window;
private swClient: WebSocket;
private debug: boolean;
public isProcessingMessage = false;
constructor(
webSocketUrl: string,
url: string,
successHandler: (providerConfigKey: string, connectionId: string) => any,
errorHandler: (errorType: string, errorDesc: string) => any,
{ width, height }: { width?: number | null; height?: number | null },
debug?: boolean
) {
// Window modal URL
this.url = url;
this.debug = debug || false;
const { left, top, computedWidth, computedHeight } = this.layout(width || this.width, height || this.height);
// Window modal features
this.features = {
width: computedWidth,
height: computedHeight,
top,
left,
scrollbars: 'yes',
resizable: 'yes',
status: 'no',
toolbar: 'no',
location: 'no',
copyhistory: 'no',
menubar: 'no',
directories: 'no'
};
this.modal = window.open('', '_blank', this.featuresToString())!;
this.swClient = new WebSocket(webSocketUrl);
this.swClient.onmessage = (message: MessageEvent<any>) => {
this.isProcessingMessage = true;
this.handleMessage(message, successHandler, errorHandler);
this.isProcessingMessage = false;
};
}
/**
* Handles the messages received from the Nango server via WebSocket.
*/
handleMessage(
message: MessageEvent<any>,
successHandler: (providerConfigKey: string, connectionId: string) => any,
errorHandler: (errorType: string, errorDesc: string) => any
) {
const data = JSON.parse(message.data);
switch (data.message_type) {
case WSMessageType.ConnectionAck: {
if (this.debug) {
console.log(debugLogPrefix, 'Connection ack received. Opening modal...');
}
const wsClientId = data.ws_client_id;
this.open(wsClientId);
break;
}
case WSMessageType.Error:
if (this.debug) {
console.log(debugLogPrefix, 'Error received. Rejecting authorization...');
}
errorHandler(data.error_type, data.error_desc);
this.swClient.close();
break;
case WSMessageType.Success:
if (this.debug) {
console.log(debugLogPrefix, 'Success received. Resolving authorization...');
}
successHandler(data.provider_config_key, data.connection_id);
this.swClient.close();
break;
default:
if (this.debug) {
console.log(debugLogPrefix, 'Unknown message type received from Nango server. Ignoring...');
}
return;
}
}
/**
* The modal is expected to be in the center of the screen.
*/
layout(expectedWidth: number, expectedHeight: number) {
const screenWidth = window.screen.width;
const screenHeight = window.screen.height;
const left = screenWidth / 2 - expectedWidth / 2;
const top = screenHeight / 2 - expectedHeight / 2;
const computedWidth = Math.min(expectedWidth, screenWidth);
const computedHeight = Math.min(expectedHeight, screenHeight);
return { left: Math.max(left, 0), top: Math.max(top, 0), computedWidth, computedHeight };
}
/**
* Open the modal
*/
open(wsClientId: string) {
this.modal.location = this.url + '&ws_client_id=' + wsClientId;
return this.modal;
}
/**
* Helper to convert the features object of this class
* to the comma-separated list of window features required
* by the window.open() function.
*/
featuresToString(): string {
const features = this.features;
const featuresAsString: string[] = [];
for (const key in features) {
featuresAsString.push(key + '=' + features[key]);
}
return featuresAsString.join(',');
}
}