ToolJet/plugins/packages/restapi/lib/index.ts

282 lines
8.9 KiB
TypeScript
Raw Normal View History

Move plugins to root (#1728) * feat: move plugins to root * modify tsconfig * add .gitignore * delete old plugins file * add parcel * docker compose volume mount * add gcs * add typescript to plugins folder * gcs to ts * add dynamodb * add elastic search * add firestore * add gsheets * add graphql * add mongodb * mssql * add mysql * add postgresql * add redis * add s3 * add slack * add stripe * remove plugin related packages from pkgjson * add lib folder * add gitignore * remove typescript generated files * remove generated file * remove generated files * add twilio * add dist to docker compose cache binding * add dist prefix * cleanup - 1 * delete dist * rename to index.ts + add jest config * add it.todo in tests * test fixes * test file changes * fix type checks * add @tooljet/plugins to server package json * esm vs commonjs bug, reduce got to 11.8.2 from 12.0.0 * docker file npm package version fix * add typesense * cleaup - 2 * add sendgrid * add lerna build and clean script for all packages + tsconfig * cleanup -3 * add plugins build step * add missing plugins build step in npm run build * add mssql, mysql & postgres as singleton classes * add db connection to cache only if datasourceId is available * client: add data source schema/manifest files * add query operations files * logic for wrapping form with schema * add script to create index file * add @tooljet/plugins to frontend folder * cleanup 1 -frontend * cleanup - 2 // frontend // data queries * add client and index to gitignore * update gitignore * fix lint & test * update ci * fix unit, e2e * cleanup -3 * fix test * fix tests * fix indent * try npm ci * fix tests * fix typo * fix * rename file for server entry * heroku fix * add main and types entry points in pkg json * move common to root * cleanup - 4: remove redundant $ sign prefix * cleanup - 4: remove redundant $ sign prefix * update options in-sync before DOM is painted * change type cloud to cloud storage * update readme * update ci.yml * update ci yml * add pkg-lock.json * rename index.ts to server.ts * update lock files * add server package.lock * remove unused import * revert commit: add minio * add root dep * import server.ts * remove plugins build step * add npm shrinkwrap * update version - plugins * add new version - 0.0.8 * upgrade version * move to symlinked package * add lock file * feat: add icon inside package * add plugin creation docs * Remove seed * move icons to plugins folder * install pg dep * add react to packages * add seed cmd * revert change * add plugins build in lint, e2e, unit * e2e, lint use npm ci * update dockerfile for plugins * try combining release with web * limit memory on release * try executing seed script post transpile * try executing seed from server directory * update seed execution * add minio * add correct type * add minio to pkg json * remove old file * fix provider key * add python installable + npm ^7.2.0 (#1752) * add python installable + npm ^7.2.0 * add py to prod file * pin npm version to 7.20.0 * pin npm version to 7.20.0 * split into multi stage build and remove python for buildx * copy plugins from buider stage * update dependencies * add freetds dependency * update server dockerfile * update client dockerfile * update dev dockerfile and compose file * fix entrypoint * fix server dev dockerfile * update docker-compose * remove npm install on root dir on docker build * fix heroku script * make lerna prod dependency to enable prod builds * remove redundant env setup Co-authored-by: Akshay Sasidharan <akshaysasidharan93@gmail.com> Co-authored-by: navaneeth <navaneethpk@outlook.com>
2022-01-17 07:08:17 +00:00
const urrl = require('url');
import { readFileSync } from 'fs';
import * as tls from 'tls';
import {
QueryError,
QueryResult,
QueryService,
cleanSensitiveData,
User,
App,
OAuthUnauthorizedClientError,
getRefreshedToken,
checkIfContentTypeIsURLenc,
checkIfContentTypeIsMultipartFormData,
isEmpty,
validateAndSetRequestOptionsBasedOnAuthType,
sanitizeHeaders,
sanitizeSearchParams,
getAuthUrl,
} from '@tooljet-plugins/common';
const FormData = require('form-data');
const JSON5 = require('json5');
import got, { HTTPError, OptionsOfTextResponseBody } from 'got';
import { SourceOptions } from './types';
Move plugins to root (#1728) * feat: move plugins to root * modify tsconfig * add .gitignore * delete old plugins file * add parcel * docker compose volume mount * add gcs * add typescript to plugins folder * gcs to ts * add dynamodb * add elastic search * add firestore * add gsheets * add graphql * add mongodb * mssql * add mysql * add postgresql * add redis * add s3 * add slack * add stripe * remove plugin related packages from pkgjson * add lib folder * add gitignore * remove typescript generated files * remove generated file * remove generated files * add twilio * add dist to docker compose cache binding * add dist prefix * cleanup - 1 * delete dist * rename to index.ts + add jest config * add it.todo in tests * test fixes * test file changes * fix type checks * add @tooljet/plugins to server package json * esm vs commonjs bug, reduce got to 11.8.2 from 12.0.0 * docker file npm package version fix * add typesense * cleaup - 2 * add sendgrid * add lerna build and clean script for all packages + tsconfig * cleanup -3 * add plugins build step * add missing plugins build step in npm run build * add mssql, mysql & postgres as singleton classes * add db connection to cache only if datasourceId is available * client: add data source schema/manifest files * add query operations files * logic for wrapping form with schema * add script to create index file * add @tooljet/plugins to frontend folder * cleanup 1 -frontend * cleanup - 2 // frontend // data queries * add client and index to gitignore * update gitignore * fix lint & test * update ci * fix unit, e2e * cleanup -3 * fix test * fix tests * fix indent * try npm ci * fix tests * fix typo * fix * rename file for server entry * heroku fix * add main and types entry points in pkg json * move common to root * cleanup - 4: remove redundant $ sign prefix * cleanup - 4: remove redundant $ sign prefix * update options in-sync before DOM is painted * change type cloud to cloud storage * update readme * update ci.yml * update ci yml * add pkg-lock.json * rename index.ts to server.ts * update lock files * add server package.lock * remove unused import * revert commit: add minio * add root dep * import server.ts * remove plugins build step * add npm shrinkwrap * update version - plugins * add new version - 0.0.8 * upgrade version * move to symlinked package * add lock file * feat: add icon inside package * add plugin creation docs * Remove seed * move icons to plugins folder * install pg dep * add react to packages * add seed cmd * revert change * add plugins build in lint, e2e, unit * e2e, lint use npm ci * update dockerfile for plugins * try combining release with web * limit memory on release * try executing seed script post transpile * try executing seed from server directory * update seed execution * add minio * add correct type * add minio to pkg json * remove old file * fix provider key * add python installable + npm ^7.2.0 (#1752) * add python installable + npm ^7.2.0 * add py to prod file * pin npm version to 7.20.0 * pin npm version to 7.20.0 * split into multi stage build and remove python for buildx * copy plugins from buider stage * update dependencies * add freetds dependency * update server dockerfile * update client dockerfile * update dev dockerfile and compose file * fix entrypoint * fix server dev dockerfile * update docker-compose * remove npm install on root dir on docker build * fix heroku script * make lerna prod dependency to enable prod builds * remove redundant env setup Co-authored-by: Akshay Sasidharan <akshaysasidharan93@gmail.com> Co-authored-by: navaneeth <navaneethpk@outlook.com>
2022-01-17 07:08:17 +00:00
function isFileObject(value) {
const keys = Object.keys(value);
return (
typeof value === 'object' &&
keys.length > 0 &&
keys.includes('name') && // example.zip
keys.includes('type') && // application/zip
keys.includes('content') && // raw'ish bytes (contains new lines - \n)
keys.includes('dataURL') && // data url representation
keys.includes('base64Data') && // data in base64
keys.includes('filePath')
);
}
interface RestAPIResult extends QueryResult {
request?: Array<object> | object;
response?: Array<object> | object;
responseHeaders?: Array<object> | object;
}
2021-07-17 14:22:37 +00:00
export default class RestapiQueryService implements QueryService {
/* Body params of the source will be overridden by body params of the query */
body(sourceOptions: any, queryOptions: any, hasDataSource: boolean): object {
const bodyToggle = queryOptions['body_toggle'];
if (bodyToggle) {
const jsonBody = queryOptions['json_body'];
if (!jsonBody) return undefined;
if (typeof jsonBody === 'string') return JSON5.parse(jsonBody);
else return jsonBody;
} else {
const _body = (queryOptions.body || []).filter((o) => {
return o.some((e) => !isEmpty(e));
});
if (!hasDataSource) return Object.fromEntries(_body);
const bodyParams = _body.concat(sourceOptions.body || []);
return Object.fromEntries(bodyParams);
}
}
isJson(str: string) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
async run(
sourceOptions: any,
queryOptions: any,
dataSourceId: string,
dataSourceUpdatedAt: string,
context?: { user?: User; app?: App }
): Promise<RestAPIResult> {
/* REST API queries can be adhoc or associated with a REST API datasource */
const hasDataSource = dataSourceId !== undefined;
const isUrlEncoded = checkIfContentTypeIsURLenc(queryOptions['headers']);
const isMultipartFormData = checkIfContentTypeIsMultipartFormData(queryOptions['headers']);
/* Prefixing the base url of datasource if datasource exists */
Feature - Multi Environment support (#4833) * initial commit * multi env changes * multi-env changes * entity fixes * data query changes * fix * trying to avoid conflict with EE * moved version creation to app creation function * fixing some issues * execution of data query * revert options changes * changed migration * fixed some migration issues: testing migration * multi env support * app import export fix * fixes * migration fixes * removed plugins from data query * fixing some migration issues * fixes * remove console log * fix * front end api changes * backward compatibility for app import * Fixed a bug * correcting some mistakes * Added constraints and fixed some issues * changes * fix for data source listing * fixing version operation issues * remove kind from data query * removed kind from data query * fixes * fixes * fix for version creation * migration fixes * Fixed preview and run query issues * Fix: new version and event query id issue * fixed rest api oauth issue - next test refresh token * import export changes * fixes for app import * import fix * added await for for loops * fix * fix for migration * Fixed backend oauth-envId issue * import export changes * migration fixes * fix * fix * fix for app import from 0.9.0 * test case fixes * test case fixes * making app name mandatory for import * adding type for options * fix: imported apps query linking issues * review changes * lint issue fixes * added on delete cascade Co-authored-by: Muhsin Shah <muhsinshah21@gmail.com>
2022-12-09 14:53:42 +00:00
const url = hasDataSource ? `${sourceOptions.url || ''}${queryOptions.url || ''}` : queryOptions.url;
2021-07-17 14:22:37 +00:00
const method = queryOptions['method'];
const json = method !== 'get' ? this.body(sourceOptions, queryOptions, hasDataSource) : undefined;
const paramsFromUrl = urrl.parse(url, true).query;
const searchParams = new URLSearchParams();
// Append parameters individually to preserve duplicates
for (const [key, value] of Object.entries(paramsFromUrl)) {
if (Array.isArray(value)) {
value.forEach((val) => searchParams.append(key, val));
} else {
searchParams.append(key, String(value));
}
}
for (const [key, value] of sanitizeSearchParams(sourceOptions, queryOptions, hasDataSource)) {
searchParams.append(key, String(value));
}
const _requestOptions: OptionsOfTextResponseBody = {
method,
2023-07-26 08:28:29 +00:00
...this.fetchHttpsCertsForCustomCA(sourceOptions),
headers: sanitizeHeaders(sourceOptions, queryOptions, hasDataSource),
searchParams,
...(isUrlEncoded ? { form: json } : { json }),
};
const hasFiles = (json) => {
return Object.values(json || {}).some((item) => {
return isFileObject(item);
});
};
if (isUrlEncoded) {
_requestOptions.form = json;
} else if (isMultipartFormData && hasFiles(json)) {
const form = new FormData();
for (const key in json) {
const value = json[key];
if (isFileObject(value)) {
const fileBuffer = Buffer.from(value?.base64Data || '', 'base64');
form.append(key, fileBuffer, {
filename: value?.name || '',
contentType: value?.type || '',
knownLength: fileBuffer.length,
});
} else if (value !== undefined && value !== null) {
form.append(key, value);
}
}
_requestOptions.body = form;
} else {
_requestOptions.json = json;
}
const authValidatedRequestOptions = validateAndSetRequestOptionsBasedOnAuthType(
sourceOptions,
context,
_requestOptions
);
const { status, data } = authValidatedRequestOptions;
if (status === 'needs_oauth') return authValidatedRequestOptions;
const requestOptions = data as OptionsOfTextResponseBody;
let result = {};
let requestObject = {};
let responseObject = {};
let responseHeaders = {};
2021-07-17 14:22:37 +00:00
try {
const response = await got(url, requestOptions);
result = this.getResponse(response);
requestObject = {
requestUrl: response.request.requestUrl,
method: response.request.options.method,
headers: response.request.options.headers,
params: urrl.parse(response.request.requestUrl, true).query,
};
responseObject = {
body: response.body,
statusCode: response.statusCode,
};
responseHeaders = response.headers;
2021-07-17 14:22:37 +00:00
} catch (error) {
console.error(
`Error while calling REST API end point. status code: ${error?.response?.statusCode} message: ${error?.response?.body}`
);
2021-07-17 14:22:37 +00:00
if (error instanceof HTTPError) {
2021-07-17 14:22:37 +00:00
result = {
requestObject: {
requestUrl: sourceOptions.password // Remove password from error object
? error.request.requestUrl?.replace(`${sourceOptions.password}@`, '<password>@')
: error.request.requestUrl,
requestHeaders: error.request.options.headers,
requestParams: urrl.parse(error.request.requestUrl, true).query,
},
responseObject: {
statusCode: error.response.statusCode,
responseBody: error.response.body,
},
responseHeaders: error.response.headers,
};
2021-07-17 14:22:37 +00:00
}
if (sourceOptions['auth_type'] === 'oauth2' && error?.response?.statusCode == 401) {
throw new OAuthUnauthorizedClientError('Unauthorized status from API server', error.message, result);
}
2021-07-17 14:22:37 +00:00
throw new QueryError('Query could not be completed', error.message, result);
}
requestObject['headers'] = cleanSensitiveData(requestObject['headers'], ['authorization']);
2021-07-17 14:22:37 +00:00
return {
status: 'ok',
data: result,
request: requestObject,
response: responseObject,
responseHeaders,
};
2021-07-17 14:22:37 +00:00
}
2023-07-26 08:28:29 +00:00
fetchHttpsCertsForCustomCA(sourceOptions: any) {
let httpsParams: any = {};
switch (sourceOptions.ssl_certificate) {
case 'ca_certificate':
httpsParams = {
https: {
certificateAuthority: [sourceOptions.ca_cert],
},
};
break;
case 'client_certificate':
httpsParams = {
https: {
certificateAuthority: [sourceOptions.ca_cert],
key: [sourceOptions.client_key],
certificate: [sourceOptions.client_cert],
},
};
break;
default:
break;
}
2023-07-26 08:28:29 +00:00
if (process.env.NODE_EXTRA_CA_CERTS) {
'https' in httpsParams
? (httpsParams.https.certificateAuthority = httpsParams.https?.certificateAuthority.concat([
...tls.rootCertificates,
readFileSync(process.env.NODE_EXTRA_CA_CERTS),
]))
: (httpsParams = {
https: {
certificateAuthority: [...tls.rootCertificates, readFileSync(process.env.NODE_EXTRA_CA_CERTS)].join('\n'),
},
});
}
return httpsParams;
}
private getResponse(response) {
try {
if (this.isJson(response.body)) {
return JSON.parse(response.body);
}
if (response.rawBody && response.headers?.['content-type']?.startsWith('image/')) {
return Buffer.from(response.rawBody, 'binary').toString('base64');
}
} catch (error) {
console.error('Error while parsing response', error);
}
return response.body;
}
checkIfContentTypeIsURLenc(headers: [] = []) {
const objectHeaders = Object.fromEntries(headers);
const contentType = objectHeaders['content-type'] ?? objectHeaders['Content-Type'];
return contentType === 'application/x-www-form-urlencoded';
}
authUrl(sourceOptions: SourceOptions): string {
return getAuthUrl(sourceOptions);
}
async refreshToken(sourceOptions: any, error: any, userId: string, isAppPublic: boolean) {
return getRefreshedToken(sourceOptions, error, userId, isAppPublic);
}
2021-07-17 14:22:37 +00:00
}