-
Notifications
You must be signed in to change notification settings - Fork 367
/
utils.ts
460 lines (372 loc) · 14.4 KB
/
utils.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
import type { Request, Response } from 'express';
import path, { resolve } from 'path';
import { readFileSync } from 'fs';
import { fileURLToPath } from 'url';
import { NangoError } from './error.js';
import type { User, Account } from '../models/Admin.js';
import type { Environment } from '../models/Environment.js';
import environmentService from '../services/environment.service.js';
import userService from '../services/user.service.js';
import type { Connection } from '../models/Connection.js';
import type { ServiceResponse } from '../models/Generic.js';
interface PackageJson {
version: string;
}
const PORT = process.env['SERVER_PORT'] || 3003;
export const localhostUrl = `http://localhost:${PORT}`;
export const cloudHost = 'https://api.nango.dev';
export const stagingHost = 'https://api-staging.nango.dev';
const accountIdLocalsKey = 'nangoAccountId';
const environmentIdLocalsKey = 'nangoEnvironmentId';
export enum UserType {
Local = 'localhost',
SelfHosted = 'self-hosted',
Cloud = 'cloud'
}
export enum NodeEnv {
Dev = 'development',
Staging = 'staging',
Prod = 'production'
}
export const AUTH_ENABLED = isCloud() || isEnterprise();
export const MANAGED_AUTH_ENABLED = isCloud() || isLocal();
export const JAVASCRIPT_AND_TYPESCRIPT_TYPES = {
primitives: ['string', 'number', 'boolean', 'bigint', 'symbol', 'undefined', 'null'],
aliases: ['String', 'Number', 'Boolean', 'BigInt', 'Symbol', 'Undefined', 'Null', 'bool', 'char', 'integer', 'int', 'date', 'object'],
builtInObjects: ['Object', 'Array', 'Function', 'Date', 'RegExp', 'Map', 'Set', 'WeakMap', 'WeakSet', 'Promise', 'Symbol', 'Error'],
utilityTypes: ['Record', 'Partial', 'Readonly', 'Pick']
};
export function isJsOrTsType(type?: string): boolean {
if (!type) {
return false;
}
const baseType = type.replace(/\[\]$/, '');
const simpleTypes = Object.values(JAVASCRIPT_AND_TYPESCRIPT_TYPES).flat();
if (simpleTypes.includes(baseType)) {
return true;
}
const typesWithGenerics = [...JAVASCRIPT_AND_TYPESCRIPT_TYPES.builtInObjects, ...JAVASCRIPT_AND_TYPESCRIPT_TYPES.utilityTypes];
const genericTypeRegex = new RegExp(`^(${typesWithGenerics.join('|')})<.+>$`);
return genericTypeRegex.test(baseType);
}
export function getEnv() {
if (isStaging()) {
return NodeEnv.Staging;
} else if (isProd()) {
return NodeEnv.Prod;
} else {
return NodeEnv.Dev;
}
}
export function isLocal() {
return getBaseUrl() === localhostUrl;
}
export function isCloud() {
return process.env['NANGO_CLOUD']?.toLowerCase() === 'true';
}
export function isEnterprise() {
return process.env['NANGO_ENTERPRISE']?.toLowerCase() === 'true';
}
export function integrationFilesAreRemote() {
const useS3 = Boolean(process.env['AWS_REGION'] && process.env['AWS_BUCKET_NAME']);
return isEnterprise() && useS3;
}
export function isStaging() {
return process.env['NODE_ENV'] === NodeEnv.Staging;
}
export function isHosted() {
return !isCloud() && !isLocal() && !isEnterprise();
}
export function getPort() {
if (process.env['SERVER_PORT']) {
return +process.env['SERVER_PORT'];
} else if (process.env['PORT']) {
return +process.env['PORT']; // For Heroku (dynamic port)
} else if (process.env['NANGO_PORT']) {
return +process.env['NANGO_PORT']; // more friendly cli port name
} else {
return 3003;
}
}
export function getServerPort() {
if (process.env['SERVER_PORT']) {
return +process.env['SERVER_PORT'];
} else if (process.env['PORT']) {
return +process.env['PORT']; // For Heroku (dynamic port)
} else if (process.env['NANGO_PORT']) {
return +process.env['NANGO_PORT']; // more friendly cli port name
} else {
return 3003;
}
}
export function getPersistAPIUrl() {
return process.env['PERSIST_SERVICE_URL'] || 'http://localhost:3007';
}
export function isDev() {
return process.env['NODE_ENV'] === NodeEnv.Dev;
}
export function isProd() {
return process.env['NODE_ENV'] === NodeEnv.Prod;
}
export function isTest(): boolean {
return Boolean(process.env['CI'] !== undefined || process.env['VITEST']);
}
export function isBasicAuthEnabled() {
return !isCloud() && process.env['NANGO_DASHBOARD_USERNAME'] && process.env['NANGO_DASHBOARD_PASSWORD'];
}
function getServerHost() {
return process.env['SERVER_HOST'] || process.env['SERVER_RUN_MODE'] === 'DOCKERIZED' ? 'http://nango-server' : 'http://localhost';
}
export function getServerBaseUrl() {
return getServerHost() + `:${getServerPort()}`;
}
export function getRedisUrl() {
return process.env['NANGO_REDIS_URL'] || undefined;
}
export function isValidHttpUrl(str: string) {
try {
new URL(str);
return true;
} catch {
return false;
}
}
export function dirname(thisFile?: string) {
return path.dirname(fileURLToPath(thisFile || import.meta.url));
}
export function parseTokenExpirationDate(expirationDate: any): Date {
if (expirationDate instanceof Date) {
return expirationDate;
}
// UNIX timestamp
if (typeof expirationDate === 'number') {
return new Date(expirationDate * 1000);
}
// ISO 8601 string
return new Date(expirationDate);
}
export function isTokenExpired(expireDate: Date, bufferInSeconds: number): boolean {
const currDate = new Date();
const dateDiffMs = expireDate.getTime() - currDate.getTime();
return dateDiffMs < bufferInSeconds * 1000;
}
export function getBaseUrl() {
return process.env['NANGO_SERVER_URL'] || localhostUrl;
}
export function getBasePublicUrl() {
if (process.env['NANGO_SERVER_URL']) {
return process.env['NANGO_SERVER_URL'].replace('api.', 'app.');
} else {
return getBaseUrl();
}
}
/**
* Get Oauth callback url base url.
* @desc for ease of use with APIs that require a secure redirect
* redirectmeto is automatically used. This is intentioned
* for local development
* @see https://github.com/kodie/redirectmeto
*/
export function getLocalOAuthCallbackUrlBaseUrl() {
return 'https://redirectmeto.com/' + localhostUrl;
}
export function getApiUrl() {
if (isStaging()) {
return stagingHost;
} else if (isEnterprise()) {
return process.env['NANGO_SERVER_URL'] as string;
} else if (isProd()) {
return cloudHost;
}
return getServerBaseUrl();
}
export function getGlobalOAuthCallbackUrl() {
const baseUrl = process.env['NANGO_SERVER_URL'] || getLocalOAuthCallbackUrlBaseUrl();
return baseUrl + '/oauth/callback';
}
export function getGlobalAppCallbackUrl() {
const baseUrl = process.env['NANGO_SERVER_URL'] || getLocalOAuthCallbackUrlBaseUrl();
return baseUrl + '/app-auth/connect';
}
export function getGlobalWebhookReceiveUrl() {
const baseUrl = process.env['NANGO_SERVER_URL'] || getLocalOAuthCallbackUrlBaseUrl();
return baseUrl + '/webhook';
}
export async function getOauthCallbackUrl(environmentId?: number) {
const globalCallbackUrl = getGlobalOAuthCallbackUrl();
if (environmentId != null) {
const environment: Environment | null = await environmentService.getByAccountIdAndEnvironment(environmentId);
return environment?.callback_url || globalCallbackUrl;
}
return globalCallbackUrl;
}
export async function getAppCallbackUrl(_environmentId?: number) {
const globalAppCallbackUrl = getGlobalAppCallbackUrl();
// TODO add this to settings and make it configurable
return globalAppCallbackUrl;
}
/**
* Get any custom path for the websockets server.
* Defaults to '/' for backwards compatibility
*
* @returns the path for the websockets server
*/
export function getWebsocketsPath(): string {
return process.env['NANGO_SERVER_WEBSOCKETS_PATH'] || '/';
}
/**
* A helper function to interpolate a string.
* interpolateString('Hello ${name} of ${age} years", {name: 'Tester', age: 234}) -> returns 'Hello Tester of age 234 years'
*
* @remarks
* Copied from https://stackoverflow.com/a/1408373/250880
*/
export function interpolateString(str: string, replacers: Record<string, any>) {
return str.replace(/\${([^{}]*)}/g, (a, b) => {
const r = replacers[b];
return typeof r === 'string' || typeof r === 'number' ? (r as string) : a; // Typecast needed to make TypeScript happy
});
}
export function interpolateStringFromObject(str: string, replacers: Record<string, any>) {
return str.replace(/\${([^{}]*)}/g, (a, b) => {
const r = b.split('.').reduce((o: Record<string, any>, i: string) => o[i], replacers);
return typeof r === 'string' || typeof r === 'number' ? (r as string) : a;
});
}
export function connectionCopyWithParsedConnectionConfig(connection: Connection) {
const connectionCopy = Object.assign({}, connection);
const rawConfig: Record<string, string> = connectionCopy.connection_config;
if (!rawConfig || Object.keys(rawConfig).length === 0) {
return connectionCopy;
}
const parsedConfig: Record<string, string> = {};
Object.keys(rawConfig).forEach(function (key) {
const newKey = key.replace('connectionConfig.', '');
const value = rawConfig[key];
if (newKey && value) {
parsedConfig[newKey] = value;
}
});
connectionCopy.connection_config = parsedConfig;
return connectionCopy;
}
export function mapProxyBaseUrlInterpolationFormat(baseUrl: string | undefined): string | undefined {
// Maps the format that is used in providers.yaml (inherited from oauth), to the format of the Connection model.
return baseUrl ? baseUrl.replace('connectionConfig', 'connection_config') : baseUrl;
}
export function interpolateIfNeeded(str: string, replacers: Record<string, any>) {
if (str.includes('${')) {
return interpolateStringFromObject(str, replacers);
} else {
return str;
}
}
export function setAccount(accountId: number, res: Response) {
res.locals[accountIdLocalsKey] = accountId;
}
export function setEnvironmentId(environmentId: number, res: Response) {
res.locals[environmentIdLocalsKey] = environmentId;
}
export function getAccount(res: Response): number {
if (res.locals == null || !(accountIdLocalsKey in res.locals)) {
throw new NangoError('account_not_set_in_locals');
}
const accountId = res.locals[accountIdLocalsKey];
if (Number.isInteger(accountId)) {
return accountId;
} else {
throw new NangoError('account_malformed_in_locals');
}
}
export function getEnvironmentId(res: Response): number {
if (res.locals === null || !(environmentIdLocalsKey in res.locals)) {
throw new NangoError('environment_not_set_in_locals');
}
const environmentId = res.locals[environmentIdLocalsKey];
if (Number.isInteger(environmentId)) {
return environmentId;
} else {
throw new NangoError('environment_malformed_in_locals');
}
}
export async function getEnvironmentAndAccountId(
res: Response,
req: Request
): Promise<ServiceResponse<{ accountId: number; environmentId: number; isWeb: boolean }>> {
if (req.user) {
const { response: accountInfo, success, error } = await getAccountIdAndEnvironmentIdFromSession(req);
if (!success || accountInfo == null) {
return { response: null, error, success: false };
}
const response = { ...accountInfo, isWeb: true };
return { response, error: null, success: true };
} else {
const accountId = getAccount(res);
const environmentId = getEnvironmentId(res);
const response = { accountId, environmentId, isWeb: false };
return Promise.resolve({ response, error: null, success: true });
}
}
export async function getAccountIdAndEnvironmentIdFromSession(req: Request): Promise<ServiceResponse<{ accountId: number; environmentId: number }>> {
const sessionUser = req.user as User;
const currentEnvironment = req.cookies['env'] || 'dev';
if (sessionUser == null) {
const error = new NangoError('user_not_found');
return { response: null, error, success: false };
}
const user = await userService.getUserById(sessionUser.id);
if (user == null) {
const error = new NangoError('user_not_found');
return { response: null, error, success: false };
}
const environmentAndAccount = await environmentService.getAccountAndEnvironmentById(user.account_id, currentEnvironment);
if (environmentAndAccount == null) {
const error = new NangoError('account_not_found');
return { response: null, error, success: false };
}
const { account, environment } = environmentAndAccount as { account: Account; environment: Environment };
const response = { accountId: account.id, environmentId: environment.id };
return { response, error: null, success: true };
}
export function isApiAuthenticated(res: Response): boolean {
return res.locals != null && accountIdLocalsKey in res.locals && Number.isInteger(res.locals[accountIdLocalsKey]);
}
export function isUserAuthenticated(req: Request): boolean {
const user = req.user as User;
return typeof req.isAuthenticated === 'function' && req.isAuthenticated() && user != null && user.id != null;
}
export function getConnectionConfig(queryParams: any): Record<string, string> {
const arr = Object.entries(queryParams).filter(([, v]) => typeof v === 'string'); // Filter strings
return Object.fromEntries(arr) as Record<string, string>;
}
let packageJsonCache: PackageJson | undefined;
export function packageJsonFile(): PackageJson {
if (packageJsonCache) {
return packageJsonCache;
}
const localPath = '../../package.json';
packageJsonCache = JSON.parse(readFileSync(resolve(dirname(), localPath)).toString('utf-8')) as PackageJson;
return packageJsonCache;
}
export function safeStringify(obj: any): string {
const stringify = (obj: any, indent = 2) => {
const cache = new Set();
const jsonString = JSON.stringify(
obj,
(_key, value) => {
if (typeof value === 'object' && value !== null) {
if (cache.has(value)) {
return;
}
cache.add(value);
}
return value;
},
indent
);
cache.clear();
return jsonString;
};
const content = obj.map((arg: any) => (typeof arg === 'object' ? stringify(arg) : String(arg))).join(' ');
return content;
}