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

391 lines
12 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,
redactHeaders,
User,
App,
OAuthUnauthorizedClientError,
getRefreshedToken,
isEmpty,
validateAndSetRequestOptionsBasedOnAuthType,
sanitizeHeaders,
sanitizeCookies,
cookiesToString,
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 {
metadata?: Array<object> | object;
}
2021-07-17 14:22:37 +00:00
export default class RestapiQueryService implements QueryService {
2025-08-03 07:09:18 +00:00
async run(
sourceOptions: any,
queryOptions: any,
dataSourceId: string,
dataSourceUpdatedAt: string,
context?: { user?: User; app?: App }
): Promise<RestAPIResult> {
const hasDataSource = dataSourceId !== undefined;
const url = this.constructUrl(sourceOptions, queryOptions, hasDataSource);
const _requestOptions = await this.constructValidatedRequestOptions(
context,
sourceOptions,
queryOptions,
hasDataSource,
url
);
2025-08-03 07:09:18 +00:00
if (_requestOptions.status === 'needs_oauth') return _requestOptions;
const requestOptions = _requestOptions.data as OptionsOfTextResponseBody;
2025-08-03 07:09:18 +00:00
try {
const response = await got(url, requestOptions);
const { result, requestObject, responseObject } = this.handleResponse(response);
return {
status: 'ok',
data: result,
metadata: {
request: requestObject,
response: responseObject,
},
};
} catch (error) {
throw this.handleError(error, sourceOptions);
}
}
2025-08-03 07:09:18 +00:00
private async constructValidatedRequestOptions(
context: { user?: User; app?: App },
sourceOptions: any,
queryOptions: any,
hasDataSource: boolean,
url: string
) {
const headers = sanitizeHeaders(sourceOptions, queryOptions, hasDataSource);
const method = queryOptions['method'];
const searchParams = this.buildSearchParams(sourceOptions, queryOptions, hasDataSource, url);
const _requestOptions: OptionsOfTextResponseBody = {
method,
...this.fetchHttpsCertsForCustomCA(sourceOptions),
headers,
searchParams,
...(queryOptions['retry_network_errors'] === true ? {} : { retry: 0 }),
};
this.addCookiesToRequest(sourceOptions, queryOptions, hasDataSource, _requestOptions);
const body = this.constructRequestBody(sourceOptions, queryOptions, hasDataSource);
this.addBodyToRequest(_requestOptions, body);
const authValidatedRequestOptions = await validateAndSetRequestOptionsBasedOnAuthType(
sourceOptions,
context,
_requestOptions
);
return authValidatedRequestOptions;
}
constructRequestBody(
sourceOptions: any,
queryOptions: any,
hasDataSource: boolean
): undefined | string | Record<string, unknown> {
if (queryOptions.method === 'get') return undefined;
if (queryOptions['body_toggle']) {
// FIXME: Remove json_body usage with data migration
// For backward compatibility, check if JSON body was previously used
queryOptions['raw_body'] ||= queryOptions['json_body'];
return queryOptions['raw_body'];
}
const _body = (queryOptions.body || []).filter((o) => {
return o.some((e) => !isEmpty(e));
});
// Body params of the source will be overridden by body params of the query
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;
}
2025-08-03 07:09:18 +00:00
private maybeParseJson(body: string): any {
try {
return JSON5.parse(body);
} catch {
return body;
}
}
2025-08-03 07:09:18 +00:00
private constructUrl(sourceOptions: any, queryOptions: any, hasDataSource: boolean): string {
return hasDataSource ? `${sourceOptions.url || ''}${queryOptions.url || ''}` : queryOptions.url;
}
2025-08-03 07:09:18 +00:00
private buildSearchParams(
sourceOptions: any,
queryOptions: any,
hasDataSource: boolean,
url: string
): URLSearchParams {
const searchParams = new URLSearchParams();
2025-08-03 07:09:18 +00:00
// Add URL parameters from source options
for (const param of sourceOptions.url_parameters || []) {
const [key, value] = param;
if (key && value) {
searchParams.append(key, value);
}
}
2025-08-03 07:09:18 +00:00
const paramsFromUrl = urrl.parse(url, true).query;
// Append parameters 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));
}
}
2025-08-03 07:09:18 +00:00
// Sanitize and append search parameters
for (const [key, value] of sanitizeSearchParams(sourceOptions, queryOptions, hasDataSource)) {
searchParams.append(key, String(value));
}
2025-08-03 07:09:18 +00:00
return searchParams;
}
2025-08-03 07:09:18 +00:00
private addCookiesToRequest(
sourceOptions: any,
queryOptions: any,
hasDataSource: boolean,
requestOptions: OptionsOfTextResponseBody
) {
const sanitizedCookies = sanitizeCookies(sourceOptions, queryOptions, hasDataSource);
const cookieString = cookiesToString(sanitizedCookies);
if (cookieString) {
2025-08-03 07:09:18 +00:00
requestOptions.headers['Cookie'] = cookieString;
}
2025-08-03 07:09:18 +00:00
}
2025-08-03 07:09:18 +00:00
private addBodyToRequest(requestOptions: OptionsOfTextResponseBody, body: any) {
const headers = requestOptions.headers as Record<string, string>;
const contentType = this.getContentType(headers);
2025-08-03 07:09:18 +00:00
switch (contentType) {
case 'application/json':
requestOptions.json = this.maybeParseJson(body);
break;
case 'application/x-www-form-urlencoded':
this.setFormUrlencodedBody(requestOptions, body);
break;
case 'multipart/form-data':
this.setMultipartFormDataBody(requestOptions, body);
break;
default:
requestOptions.body = body;
break;
}
}
private getContentType(headers: Record<string, string>): string {
const contentTypeKey = Object.keys(headers).find((key) => key.toLowerCase() === 'content-type');
return contentTypeKey ? headers[contentTypeKey].toLowerCase() : 'application/json';
}
2025-08-03 07:09:18 +00:00
private setFormUrlencodedBody(requestOptions: OptionsOfTextResponseBody, body: any) {
typeof body === 'object' ? (requestOptions.form = body) : (requestOptions.body = body);
}
private setMultipartFormDataBody(requestOptions: OptionsOfTextResponseBody, body: any) {
if (body && Object.values(body).some(isFileObject)) {
const form = new FormData();
2025-08-03 07:09:18 +00:00
Object.entries(body).forEach(([key, value]: [string, Record<string, string>]) => {
if (isFileObject(value)) {
2025-08-03 07:09:18 +00:00
const fileBuffer = Buffer.from(value.base64Data || '', 'base64');
form.append(key, fileBuffer, {
filename: value?.name || '',
contentType: value?.type || '',
knownLength: fileBuffer.length,
});
2025-08-03 07:09:18 +00:00
} else if (value != null) {
form.append(key, value);
}
2025-08-03 07:09:18 +00:00
});
requestOptions.body = form;
requestOptions.headers = { ...requestOptions.headers, ...form.getHeaders() };
}
2025-08-03 07:09:18 +00:00
}
2025-08-03 07:09:18 +00:00
private handleResponse(response: any) {
const result = this.getResponse(response);
const requestUrl = response?.request?.options?.url?.origin + response?.request?.options?.url?.pathname;
const requestObject = {
requestUrl,
url: response.requestUrl,
method: response.request.options.method,
headers: redactHeaders(response.request.options.headers),
params: urrl.parse(response.request.requestUrl, true).query,
};
2025-08-03 07:09:18 +00:00
const responseObject = {
statusCode: response.statusCode,
headers: redactHeaders(response.headers),
};
2025-08-03 07:09:18 +00:00
return { result, requestObject, responseObject };
}
2025-08-03 07:09:18 +00:00
private handleError(error: any, sourceOptions: any): Error {
console.error(
`Error while calling REST API endpoint. Status code: ${error?.response?.statusCode}, Message: ${error?.response?.body}`
);
2025-08-03 07:09:18 +00:00
let result = {};
let metadata = {};
if (error instanceof HTTPError) {
const requestUrl = error?.request?.options?.url?.origin + error?.request?.options?.url?.pathname;
const requestHeaders = cleanSensitiveData(error?.request?.options?.headers, ['authorization']);
const requestObject = {
requestUrl: requestUrl,
requestHeaders: requestHeaders,
requestParams: urrl.parse(error.request.requestUrl, true).query,
};
2025-08-03 07:09:18 +00:00
const responseObject = {
statusCode: error.response.statusCode,
responseBody: error.response.body,
headers: redactHeaders(error.response.headers),
};
metadata = {
request: requestObject,
response: responseObject,
};
2025-08-03 07:09:18 +00:00
// TODO: Need to remove the request/response related information in result in next MAJOR release.
// This is now shared in `metadata` key. Keeping this here for backward compatibility.
result = {
requestObject: requestObject,
responseObject: responseObject,
responseHeaders: error.response.headers,
};
2021-07-17 14:22:37 +00:00
}
2025-08-03 07:09:18 +00:00
if (sourceOptions['auth_type'] === 'oauth2' && error?.response?.statusCode === 401) {
throw new OAuthUnauthorizedClientError('Unauthorized status from API server', error.message, result);
}
throw new QueryError('Query could not be completed', error.message, result, metadata);
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) {
2025-02-25 06:52:50 +00:00
const contentType: string = response.headers?.['content-type'] ?? '';
try {
if (this.isJson(response.body)) {
return JSON.parse(response.body);
}
2025-02-25 06:52:50 +00:00
if (response.rawBody && this.isBinary(contentType)) {
return Buffer.from(response.rawBody, 'binary').toString('base64');
}
} catch (error) {
console.error('Error while parsing response', error);
}
return response.body;
}
2025-02-25 06:52:50 +00:00
private isBinary(contentType: string) {
const binaryPrefixes = ['application/', 'image/'];
const binaryApplicationTypes = ['application/pdf', 'application/zip'];
for (const binaryPrefix of binaryPrefixes) {
if (contentType?.startsWith(binaryPrefix)) {
if (binaryPrefix === 'application/') return binaryApplicationTypes.includes(contentType);
return true;
}
}
return false;
}
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
}