Skip to content

πŸ”₯ πŸ”₯ πŸ”₯ A Free & Self-hostable Airtable Alternative

refactor webhook invoke to a class

Fendy Heryanto1cebc5be4a79
diff --git a/packages/nocodb/src/helpers/webhookHelpers.ts b/packages/nocodb/src/helpers/webhookHelpers.ts
index dabf1b261d..657e7d8dc1 100644
--- a/packages/nocodb/src/helpers/webhookHelpers.ts
+++ b/packages/nocodb/src/helpers/webhookHelpers.ts
@@ -8,37 +8,26 @@ import Handlebars from 'handlebars';
import handlebarsHelpers from 'handlebars-helpers-v2';
import {
ColumnHelper,
- hasInputCalls,
HookOperationCode,
isDateMonthFormat,
- NOCO_SERVICE_USERS,
UITypes,
} from 'nocodb-sdk';
-import { useAgent } from 'request-filtering-agent';
import { v4 as uuidv4 } from 'uuid';
-import NcPluginMgrv2 from './NcPluginMgrv2';
import type {
ColumnType,
FormColumnType,
- HookLogType,
HookType,
TableType,
UpdatePayload,
- UserType,
ViewType,
} from 'nocodb-sdk';
-import type { NcContext } from '~/interface/config';
-import type { Column, FormView, Hook, Model, View } from '~/models';
import type { AxiosResponse } from 'axios';
-import { Filter, HookLog, Script, Source } from '~/models';
-import { addDummyRootAndNest } from '~/services/v3/filters-v3.service';
-import { isEE, isOnPrem, populateUpdatePayloadDiff } from '~/utils';
+import type { NcContext } from '~/interface/config';
+import type { Column, FormView, Hook, Model, Source, View } from '~/models';
+import { WebhookInvoker } from '~/utils/webhook-invoker';
+import { Filter } from '~/models';
+import { isEE, populateUpdatePayloadDiff } from '~/utils';
import { parseMetaProp } from '~/utils/modelUtils';
-import { filterBuilder } from '~/utils/api-v3-data-transformation.builder';
-import { JobTypes } from '~/interface/Jobs';
-import Noco from '~/Noco';
-import { genJwt } from '~/services/users/helpers';
-import { NcError } from '~/helpers/ncError';
handlebarsHelpers({ handlebars: Handlebars });
@@ -469,128 +458,6 @@ export function constructWebHookData(
return newData;
}
-function populateAxiosReq({
- apiMeta: _apiMeta,
- hook,
- model,
- view,
- prevData,
- newData,
- user,
-}: {
- apiMeta: any;
- user: UserType;
- hook: HookType | Hook;
- model: TableType;
- view?: ViewType;
- prevData: Record<string, unknown>;
- newData: Record<string, unknown>;
-}) {
- if (!_apiMeta) {
- _apiMeta = {};
- }
-
- const contentType = _apiMeta.headers?.find(
- (header) => header.name?.toLowerCase() === 'content-type' && header.enabled,
- );
-
- if (!contentType) {
- if (!_apiMeta.headers) {
- _apiMeta.headers = [];
- }
-
- _apiMeta.headers.push({
- name: 'Content-Type',
- enabled: true,
- value: 'application/json',
- });
- }
-
- const webhookData = constructWebHookData(
- hook,
- model,
- view,
- prevData,
- newData,
- user,
- );
-
- const apiMeta = { ..._apiMeta };
- // if it's a string try to parse and apply handlebar
- // or if object then convert into JSON string and parse it
- if (apiMeta.body) {
- try {
- apiMeta.body = JSON.parse(
- typeof apiMeta.body === 'string'
- ? apiMeta.body
- : JSON.stringify(apiMeta.body),
- (_key, value) => {
- return typeof value === 'string'
- ? parseBody(value, webhookData)
- : value;
- },
- );
- } catch (e) {
- // if string parsing failed then directly apply the handlebar
- apiMeta.body = parseBody(apiMeta.body, webhookData);
- }
- }
- if (apiMeta.auth) {
- try {
- apiMeta.auth = JSON.parse(
- typeof apiMeta.auth === 'string'
- ? apiMeta.auth
- : JSON.stringify(apiMeta.auth),
- (_key, value) => {
- return typeof value === 'string'
- ? parseBody(value, webhookData)
- : value;
- },
- );
- } catch (e) {
- apiMeta.auth = parseBody(apiMeta.auth, webhookData);
- }
- }
- apiMeta.response = {};
- const url = parseBody(apiMeta.path, webhookData);
-
- const reqPayload = {
- params: apiMeta.parameters
- ? apiMeta.parameters.reduce((paramsObj, param) => {
- if (param.name && param.enabled) {
- paramsObj[param.name] = parseBody(param.value, webhookData);
- }
- return paramsObj;
- }, {})
- : {},
- url: url,
- method: apiMeta.method,
- data: apiMeta.body,
- headers: apiMeta.headers
- ? apiMeta.headers.reduce((headersObj, header) => {
- if (header.name && header.enabled) {
- headersObj[header.name] = parseBody(header.value, webhookData);
- }
- return headersObj;
- }, {})
- : {},
- withCredentials: true,
- ...(process.env.NC_ALLOW_LOCAL_HOOKS !== 'true'
- ? {
- httpAgent: useAgent(url, {
- stopPortScanningByUrlRedirection: true,
- }),
- httpsAgent: useAgent(url, {
- stopPortScanningByUrlRedirection: true,
- }),
- }
- : {}),
- timeout: 30 * 1000,
- };
-
- return reqPayload;
-}
-
function extractReqPayloadForLog(reqPayload, response?: AxiosResponse<any>) {
return {
...reqPayload,
@@ -628,53 +495,6 @@ export async function handleHttpWebHook({
};
}
-// flatten filter tree and id dummy id if no id is present
-function flattenFilter(
- filters: Filter[],
- flattenedFilters = [],
- parentId = null,
-) {
- for (const filter of filters) {
- // if parent id is present then set it as fk_parent_id
- if (parentId && !filter.fk_parent_id) {
- filter.fk_parent_id = parentId;
- }
-
- if (filter.is_group) {
- flattenedFilters.push(filter);
- // this is to group the filters
- if (!filter.id) {
- filter.id = uuidv4();
- }
- flattenFilter(filter.children, flattenedFilters, filter.id);
- } else {
- flattenedFilters.push(filter);
- }
- }
- return flattenedFilters;
-}
-
-function constructHookDataForNonURLHooks({
- newData,
- prevData,
- view,
- hook,
- model,
-}: {
- hook: Hook;
- model: Model;
- view: View;
- newData: Record<string, unknown>;
- prevData: Record<string, unknown>;
-}) {
- // for old webhooks keep the old data syntax for backward compatibility
- if (hook.version === 'v2' || hook.version === 'v1') {
- return newData;
- } else {
- return constructWebHookData(hook, model, view, prevData, newData);
- }
-}
-
export async function invokeWebhook(
context: NcContext,
param: {
@@ -692,363 +512,8 @@ export async function invokeWebhook(
addJob?: (name: string, data: any) => Promise<void>;
},
) {
- const {
- hook,
- model,
- view,
- user,
- hookName,
- prevData,
- testFilters = null,
- throwErrorOnFailure = false,
- testHook = false,
- ncSiteUrl,
- addJob,
- } = param;
-
- let { newData } = param;
-
- if (hook.version === 'v3' && hookName) {
- // since we already verified the operation in v3,
- // we'll assign the event and operation back to v2 format
- // for it to further be referenced during payload building
- const [event, operation] = hookName.split('.');
- hook.event = event as any;
- hook.operation = (operation as any as string)
- .replace('bulk', '')
- .toLowerCase() as any;
- }
-
- let hookLog: HookLogType;
- const startTime = process.hrtime();
- const source = await Source.get(context, model.source_id);
- let notification, filters;
- let reqPayload;
- try {
- notification =
- typeof hook.notification === 'string'
- ? JSON.parse(hook.notification)
- : hook.notification;
-
- const isBulkOperation = Array.isArray(newData);
-
- if (
- isBulkOperation &&
- notification?.type !== 'URL' &&
- notification?.type !== 'Script'
- ) {
- // only URL & Script hooks are supported for bulk operations
- return;
- }
-
- if (hook.condition && !testHook) {
- filters = testFilters || (await hook.getFilters(context));
-
- if (isBulkOperation) {
- const filteredData = [];
- for (let i = 0; i < newData.length; i++) {
- const data = newData[i];
-
- const pData = prevData[i] ? prevData[i] : null;
-
- // if condition is satisfied for prevData then return
- // if filters are not defined then skip the check
- if (
- pData &&
- filters.length &&
- (await validateCondition(context, filters, pData, {
- client: source?.type,
- }))
- ) {
- continue;
- }
-
- if (
- await validateCondition(
- context,
- testFilters || (await hook.getFilters(context)),
- data,
- { client: source?.type },
- )
- ) {
- filteredData.push(data);
- }
- }
- if (!filteredData.length) {
- return;
- }
- newData = filteredData;
- } else {
- // if condition is satisfied for prevData then return
- // if filters are not defined then skip the check
- if (
- prevData &&
- filters.length &&
- (await validateCondition(context, filters, prevData, {
- client: source?.type,
- }))
- ) {
- return;
- }
- if (
- !(await validateCondition(
- context,
- testFilters || (await hook.getFilters(context)),
- newData,
- { client: source?.type },
- ))
- ) {
- return;
- }
- }
- }
-
- // check if form filter applied
- if (
- notification &&
- notification.trigger_form &&
- notification.trigger_form_id
- ) {
- const formId = notification.trigger_form_id;
- if (view && formId !== view.id) {
- return;
- }
- }
-
- switch (notification?.type) {
- case 'Email':
- {
- const webhookData = constructHookDataForNonURLHooks({
- hook,
- model,
- view,
- prevData,
- newData,
- });
-
- const parsedPayload = {
- to: parseBody(notification?.payload?.to, webhookData),
- subject: parseBody(notification?.payload?.subject, webhookData),
- html: parseBody(notification?.payload?.body, webhookData),
- };
- const res = await (
- await NcPluginMgrv2.emailAdapter(false)
- )?.mailSend(parsedPayload);
- if (
- process.env.NC_AUTOMATION_LOG_LEVEL === 'ALL' ||
- (isEE && !process.env.NC_AUTOMATION_LOG_LEVEL)
- ) {
- hookLog = {
- ...hook,
- operation: hookName?.split('.')?.[1] as any,
- fk_hook_id: hook.id,
- type: notification.type,
- payload: JSON.stringify(parsedPayload),
- response: JSON.stringify(res),
- triggered_by: user?.email,
- conditions: JSON.stringify(filters),
- };
- }
- }
- break;
- case 'URL':
- {
- reqPayload = populateAxiosReq({
- apiMeta: notification?.payload,
- user,
- hook,
- model,
- view,
- prevData,
- newData,
- });
-
- const { requestPayload, responsePayload } = await handleHttpWebHook({
- reqPayload,
- });
-
- if (
- process.env.NC_AUTOMATION_LOG_LEVEL === 'ALL' ||
- (isEE && !process.env.NC_AUTOMATION_LOG_LEVEL)
- ) {
- hookLog = {
- ...hook,
- operation: hookName?.split('.')?.[1] as any,
- fk_hook_id: hook.id,
- type: notification.type,
- payload: JSON.stringify(requestPayload),
- response: JSON.stringify(responsePayload),
- triggered_by: user?.email,
- conditions: JSON.stringify(filters),
- };
- }
- }
- break;
- case 'Script':
- {
- const datas = Array.isArray(newData) ? newData : [newData];
-
- const script = await Script.get(
- context,
- notification?.payload?.scriptId,
- );
-
- if (!script.script || hasInputCalls(script.script)) {
- NcError._.notImplemented(
- 'Script with input calls is not supported',
- );
- }
-
- await addJob?.(JobTypes.ExecuteAction, {
- context,
- scriptId: notification?.payload?.scriptId,
- modelId: model.id,
- records: datas,
- req: {
- user: NOCO_SERVICE_USERS.AUTOMATION_USER,
- headers: {
- 'xc-auth': genJwt(
- {
- ...NOCO_SERVICE_USERS.AUTOMATION_USER,
- extra: {
- context: {
- ...context,
- script_id: notification?.payload?.scriptId,
- },
- },
- },
- Noco.getConfig(),
- {
- expiresIn: '10m',
- },
- ),
- },
- ncSiteUrl,
- },
- });
- }
- break;
- default:
- {
- const webhookData = constructHookDataForNonURLHooks({
- hook,
- model,
- view,
- prevData,
- newData,
- });
-
- const res = await (
- await NcPluginMgrv2.webhookNotificationAdapters(notification.type)
- ).sendMessage(
- parseBody(notification?.payload?.body, webhookData),
- JSON.parse(JSON.stringify(notification?.payload), (_key, value) => {
- return typeof value === 'string'
- ? parseBody(value, webhookData)
- : value;
- }),
- );
-
- if (
- process.env.NC_AUTOMATION_LOG_LEVEL === 'ALL' ||
- (isEE && !process.env.NC_AUTOMATION_LOG_LEVEL)
- ) {
- hookLog = {
- ...hook,
- operation: hookName?.split('.')?.[1] as any,
- fk_hook_id: hook.id,
- type: notification.type,
- payload: JSON.stringify(notification?.payload),
- response: JSON.stringify({
- status: res.status,
- statusText: res.statusText,
- headers: res.headers,
- config: {
- url: res.config.url,
- method: res.config.method,
- data: res.config.data,
- headers: res.config.headers,
- params: res.config.params,
- },
- }),
- triggered_by: user?.email,
- conditions: JSON.stringify(filters),
- };
- }
- }
- break;
- }
- } catch (e) {
- if (e.response) {
- logger.error({
- data: e.response.data,
- status: e.response.status,
- url: e.response.config?.url,
- message: e.message,
- });
- } else {
- logger.error(e.message, e.stack);
- }
- if (
- ['ERROR', 'ALL'].includes(process.env.NC_AUTOMATION_LOG_LEVEL) ||
- isEE
- ) {
- hookLog = {
- ...hook,
- operation: hookName?.split('.')?.[1] as any,
- type: notification.type,
- payload: JSON.stringify(
- reqPayload
- ? extractReqPayloadForLog(reqPayload, e.response)
- : notification?.payload,
- ),
- fk_hook_id: hook.id,
- error_code: e.error_code ?? e.code,
- error_message: e.message,
- error: JSON.stringify(e),
- triggered_by: user?.email,
- conditions: filters
- ? JSON.stringify(
- addDummyRootAndNest(
- filterBuilder().build(flattenFilter(filters)) as Filter[],
- ),
- )
- : null,
- response: e.response
- ? JSON.stringify(extractResPayloadForLog(e.response))
- : null,
- };
- }
- if (throwErrorOnFailure) {
- if (e.isAxiosError) {
- if (
- e.message.includes('private IP address') ||
- e.response?.data?.message?.includes('private IP address')
- ) {
- throw new Error(
- `Connection to a private network IP is blocked for security reasons.` +
- // shoe env var only if it's not EE or it's on-prem
- (!isEE || isOnPrem
- ? `If this is intentional, set NC_ALLOW_LOCAL_HOOKS=true to allow local network webhooks.`
- : ''),
- );
- }
- }
-
- throw e;
- }
- } finally {
- if (hookLog) {
- hookLog.execution_time = parseHrtimeToMilliSeconds(
- process.hrtime(startTime),
- );
- HookLog.insert(context, { ...hookLog, test_call: testHook }).catch(
- (e) => {
- logger.error(e.message, e.stack);
- },
- );
- }
- }
+ // backward compatibility
+ return new WebhookInvoker().invoke(context, param);
}
export function _transformSubmittedFormDataForEmail(
@@ -1137,11 +602,6 @@ export function transformDataForMailRendering(
return transformedData;
}
-function parseHrtimeToMilliSeconds(hrtime) {
- const milliseconds = (hrtime[0] + hrtime[1] / 1e6).toFixed(3);
- return milliseconds;
-}
-
export function operationArrToCode(value: HookType['operation']) {
let result = 0;
for (const operation of value) {
diff --git a/packages/nocodb/src/services/v3/views-v3.service.ts b/packages/nocodb/src/services/v3/views-v3.service.ts
index ae548bea65..3e772ccb6c 100644
--- a/packages/nocodb/src/services/v3/views-v3.service.ts
+++ b/packages/nocodb/src/services/v3/views-v3.service.ts
@@ -1,4 +1,5 @@
import { Injectable, Logger } from '@nestjs/common';
+import type { MetaService } from '~/meta/meta.service';
import type { NcContext, NcRequest } from '~/interface/config';
import type { IViewsV3Service } from '~/services/v3/views-v3.types';
@@ -10,6 +11,7 @@ export class ViewsV3Service implements IViewsV3Service {
async getView(
_context: NcContext,
_param: { viewId: string; req: NcRequest },
+ _ncMeta?: MetaService,
) {
return undefined;
}
diff --git a/packages/nocodb/src/services/v3/views-v3.types.ts b/packages/nocodb/src/services/v3/views-v3.types.ts
index 271c21d5b4..aadd3768f8 100644
--- a/packages/nocodb/src/services/v3/views-v3.types.ts
+++ b/packages/nocodb/src/services/v3/views-v3.types.ts
@@ -1,8 +1,10 @@
import type { NcContext, NcRequest } from 'nocodb-sdk';
+import type { MetaService } from '~/meta/meta.service';
export interface IViewsV3Service {
getView(
context: NcContext,
param: { viewId: string; req: NcRequest },
+ ncMeta?: MetaService,
): Promise<any>;
}
diff --git a/packages/nocodb/src/utils/view-webhook-manager.ts b/packages/nocodb/src/utils/view-webhook-manager.ts
index 9714a830bf..f1c3325145 100644
--- a/packages/nocodb/src/utils/view-webhook-manager.ts
+++ b/packages/nocodb/src/utils/view-webhook-manager.ts
@@ -1,14 +1,18 @@
import { WebhookActions, WebhookEvents } from 'nocodb-sdk';
-import type { ModelWebhookManager } from './model-webhook-manager';
+import type { ModelWebhookManager } from '~/utils/model-webhook-manager';
import type { NcContext, NcRequest } from 'nocodb-sdk';
import type { IViewsV3Service } from '~/services/v3/views-v3.types';
+import type { MetaService } from '~/meta/meta.service';
import Noco from '~/Noco';
import { Model } from '~/models';
import { NcError } from '~/helpers/ncError';
import { HANDLE_WEBHOOK } from '~/services/hook-handler.service';
export class ViewWebhookManagerBuilder {
- constructor(protected readonly context: NcContext) {}
+ constructor(
+ protected readonly context: NcContext,
+ protected readonly ncMeta?: MetaService,
+ ) {}
modelWebhookManager?: ModelWebhookManager;
model?: Model;
modelId?: string;
@@ -23,9 +27,13 @@ export class ViewWebhookManagerBuilder {
return this;
}
async withModelId(modelId: string) {
- this.model = await Model.getByIdOrName(this.context, {
- id: modelId,
- });
+ this.model = await Model.getByIdOrName(
+ this.context,
+ {
+ id: modelId,
+ },
+ this.ncMeta,
+ );
this.modelId = modelId;
return this;
}
@@ -35,10 +43,14 @@ export class ViewWebhookManagerBuilder {
async withViewId(viewId: string, req?: NcRequest) {
// needed to prevent circular dependencies
const viewsV3Service: IViewsV3Service = Noco.nestApp.get('IViewsV3Service');
- this.oldView = await viewsV3Service.getView(this.context, {
- viewId,
- req,
- });
+ this.oldView = await viewsV3Service.getView(
+ this.context,
+ {
+ viewId,
+ req,
+ },
+ this.ncMeta,
+ );
}
forCreate() {
@@ -86,13 +98,17 @@ export class ViewWebhookManagerBuilder {
`Need to call 'withView' before running 'forDelete'`,
);
}
- return new ViewWebhookManager(this.context, {
- action: WebhookActions.DELETE,
- model: this.model!,
- modelId: this.modelId!,
- oldView: this.oldView,
- modelWebhookManager: this.modelWebhookManager,
- });
+ return new ViewWebhookManager(
+ this.context,
+ {
+ action: WebhookActions.DELETE,
+ model: this.model!,
+ modelId: this.modelId!,
+ oldView: this.oldView,
+ modelWebhookManager: this.modelWebhookManager,
+ },
+ this.ncMeta,
+ );
}
}
@@ -107,6 +123,7 @@ export class ViewWebhookManager {
newView?: any;
modelWebhookManager?: ModelWebhookManager;
},
+ protected readonly ncMeta?: MetaService,
) {}
protected emitted = false;
@@ -118,10 +135,14 @@ export class ViewWebhookManager {
async withNewViewId(viewId: string, req?: NcRequest) {
// needed to prevent circular dependencies
const viewsV3Service: IViewsV3Service = Noco.nestApp.get('IViewsV3Service');
- this.params.newView = await viewsV3Service.getView(this.context, {
- viewId,
- req,
- });
+ this.params.newView = await viewsV3Service.getView(
+ this.context,
+ {
+ viewId,
+ req,
+ },
+ this.ncMeta,
+ );
return this;
}
diff --git a/packages/nocodb/src/utils/webhook-invoker.ts b/packages/nocodb/src/utils/webhook-invoker.ts
new file mode 100644
index 0000000000..3b49b72f04
--- /dev/null
+++ b/packages/nocodb/src/utils/webhook-invoker.ts
@@ -0,0 +1,625 @@
+import { Logger } from '@nestjs/common';
+import { hasInputCalls, NOCO_SERVICE_USERS } from 'nocodb-sdk';
+import { useAgent } from 'request-filtering-agent';
+import { v4 as uuidv4 } from 'uuid';
+import type { AxiosResponse } from 'axios';
+import type {
+ HookLogType,
+ HookType,
+ NcContext,
+ TableType,
+ UserType,
+ ViewType,
+} from 'nocodb-sdk';
+import type { Filter } from '~/models';
+import { NcError } from '~/helpers/ncError';
+import NcPluginMgrv2 from '~/helpers/NcPluginMgrv2';
+import {
+ constructWebHookData,
+ handleHttpWebHook,
+ parseBody,
+ validateCondition,
+} from '~/helpers/webhookHelpers';
+import { JobTypes } from '~/interface/Jobs';
+import {
+ type Hook,
+ HookLog,
+ type Model,
+ Script,
+ Source,
+ type View,
+} from '~/models';
+import Noco from '~/Noco';
+import { genJwt } from '~/services/users/helpers';
+import { addDummyRootAndNest } from '~/services/v3/filters-v3.service';
+import { isEE, isOnPrem } from '~/utils';
+import { filterBuilder } from '~/utils/api-v3-data-transformation.builder';
+
+interface WebhookResponseLog {
+ status: number;
+ statusText: string;
+ headers: Record<string, any>; // Changed to any to accommodate AxiosResponseHeaders
+ data: any;
+}
+
+export class WebhookInvoker {
+ protected logger = new Logger(WebhookInvoker.name);
+
+ populateAxiosReq({
+ apiMeta: _apiMeta,
+ hook,
+ model,
+ view,
+ prevData,
+ newData,
+ user,
+ }: {
+ apiMeta: any;
+ user: UserType;
+ hook: HookType | Hook;
+ model: TableType;
+ view?: ViewType;
+ prevData: Record<string, unknown>;
+ newData: Record<string, unknown>;
+ }) {
+ if (!_apiMeta) {
+ _apiMeta = {};
+ }
+
+ const contentType = _apiMeta.headers?.find(
+ (header) =>
+ header.name?.toLowerCase() === 'content-type' && header.enabled,
+ );
+
+ if (!contentType) {
+ if (!_apiMeta.headers) {
+ _apiMeta.headers = [];
+ }
+
+ _apiMeta.headers.push({
+ name: 'Content-Type',
+ enabled: true,
+ value: 'application/json',
+ });
+ }
+
+ const webhookData = constructWebHookData(
+ hook,
+ model,
+ view,
+ prevData,
+ newData,
+ user,
+ );
+
+ const apiMeta = { ..._apiMeta };
+ // if it's a string try to parse and apply handlebar
+ // or if object then convert into JSON string and parse it
+ if (apiMeta.body) {
+ try {
+ apiMeta.body = JSON.parse(
+ typeof apiMeta.body === 'string'
+ ? apiMeta.body
+ : JSON.stringify(apiMeta.body),
+ (_key, value) => {
+ return typeof value === 'string'
+ ? parseBody(value, webhookData)
+ : value;
+ },
+ );
+ } catch (e) {
+ // if string parsing failed then directly apply the handlebar
+ apiMeta.body = parseBody(apiMeta.body, webhookData);
+ }
+ }
+ if (apiMeta.auth) {
+ try {
+ apiMeta.auth = JSON.parse(
+ typeof apiMeta.auth === 'string'
+ ? apiMeta.auth
+ : JSON.stringify(apiMeta.auth),
+ (_key, value) => {
+ return typeof value === 'string'
+ ? parseBody(value, webhookData)
+ : value;
+ },
+ );
+ } catch (e) {
+ apiMeta.auth = parseBody(apiMeta.auth, webhookData);
+ }
+ }
+ apiMeta.response = {};
+ const url = parseBody(apiMeta.path, webhookData);
+
+ const reqPayload = {
+ params: apiMeta.parameters
+ ? apiMeta.parameters.reduce((paramsObj, param) => {
+ if (param.name && param.enabled) {
+ paramsObj[param.name] = parseBody(param.value, webhookData);
+ }
+ return paramsObj;
+ }, {})
+ : {},
+ url: url,
+ method: apiMeta.method,
+ data: apiMeta.body,
+ headers: apiMeta.headers
+ ? apiMeta.headers.reduce((headersObj, header) => {
+ if (header.name && header.enabled) {
+ headersObj[header.name] = parseBody(header.value, webhookData);
+ }
+ return headersObj;
+ }, {})
+ : {},
+ withCredentials: true,
+ ...(process.env.NC_ALLOW_LOCAL_HOOKS !== 'true'
+ ? {
+ httpAgent: useAgent(url, {
+ stopPortScanningByUrlRedirection: true,
+ }),
+ httpsAgent: useAgent(url, {
+ stopPortScanningByUrlRedirection: true,
+ }),
+ }
+ : {}),
+ timeout: 30 * 1000,
+ };
+
+ return reqPayload;
+ }
+
+ constructHookDataForNonURLHooks({
+ newData,
+ prevData,
+ view,
+ hook,
+ model,
+ }: {
+ hook: Hook;
+ model: Model;
+ view: View;
+ newData: Record<string, unknown>;
+ prevData: Record<string, unknown>;
+ }) {
+ // for old webhooks keep the old data syntax for backward compatibility
+ if (hook.version === 'v2' || hook.version === 'v1') {
+ return newData;
+ } else {
+ return constructWebHookData(hook, model, view, prevData, newData);
+ }
+ }
+
+ parseHrtimeToMilliSeconds(hrtime) {
+ const milliseconds = (hrtime[0] + hrtime[1] / 1e6).toFixed(3);
+ return milliseconds;
+ }
+
+ extractResPayloadForLog(response: AxiosResponse<any>): WebhookResponseLog {
+ return {
+ status: response.status,
+ statusText: response.statusText,
+ headers: response.headers,
+ data: response.data,
+ };
+ }
+
+ extractReqPayloadForLog(reqPayload, response?: AxiosResponse<any>) {
+ return {
+ ...reqPayload,
+ headers: {
+ ...(response?.config?.headers || {}),
+ ...(reqPayload.headers || {}),
+ },
+ // exclude http/https agent filters
+ httpAgent: undefined,
+ httpsAgent: undefined,
+ timeout: undefined,
+ withCredentials: undefined,
+ };
+ }
+
+ // flatten filter tree and id dummy id if no id is present
+ flattenFilter(filters: Filter[], flattenedFilters = [], parentId = null) {
+ for (const filter of filters) {
+ // if parent id is present then set it as fk_parent_id
+ if (parentId && !filter.fk_parent_id) {
+ filter.fk_parent_id = parentId;
+ }
+
+ if (filter.is_group) {
+ flattenedFilters.push(filter);
+ // this is to group the filters
+ if (!filter.id) {
+ filter.id = uuidv4();
+ }
+ this.flattenFilter(filter.children, flattenedFilters, filter.id);
+ } else {
+ flattenedFilters.push(filter);
+ }
+ }
+ return flattenedFilters;
+ }
+
+ public async invoke(
+ context: NcContext,
+ param: {
+ hook: Hook;
+ model: Model;
+ view: View;
+ hookName: string;
+ prevData;
+ newData;
+ user;
+ testFilters?;
+ throwErrorOnFailure?: boolean;
+ testHook?: boolean;
+ ncSiteUrl?: string;
+ addJob?: (name: string, data: any) => Promise<void>;
+ },
+ ): Promise<void> {
+ const {
+ hook,
+ model,
+ view,
+ user,
+ hookName,
+ prevData,
+ testFilters = null,
+ throwErrorOnFailure = false,
+ testHook = false,
+ ncSiteUrl,
+ addJob,
+ } = param;
+
+ let { newData } = param;
+
+ if (hook.version === 'v3' && hookName) {
+ // since we already verified the operation in v3,
+ // we'll assign the event and operation back to v2 format
+ // for it to further be referenced during payload building
+ const [event, operation] = hookName.split('.');
+ hook.event = event as any;
+ hook.operation = (operation as any as string)
+ .replace('bulk', '')
+ .toLowerCase() as any;
+ }
+
+ let hookLog: HookLogType;
+ const startTime = process.hrtime();
+ const source = await Source.get(context, model.source_id);
+ let notification, filters;
+ let reqPayload;
+ try {
+ notification =
+ typeof hook.notification === 'string'
+ ? JSON.parse(hook.notification)
+ : hook.notification;
+
+ const isBulkOperation = Array.isArray(newData);
+
+ if (
+ isBulkOperation &&
+ notification?.type !== 'URL' &&
+ notification?.type !== 'Script'
+ ) {
+ // only URL & Script hooks are supported for bulk operations
+ return;
+ }
+
+ if (hook.condition && !testHook) {
+ filters = testFilters || (await hook.getFilters(context));
+
+ if (isBulkOperation) {
+ const filteredData = [];
+ for (let i = 0; i < newData.length; i++) {
+ const data = newData[i];
+
+ const pData = prevData[i] ? prevData[i] : null;
+
+ // if condition is satisfied for prevData then return
+ // if filters are not defined then skip the check
+ if (
+ pData &&
+ filters.length &&
+ (await validateCondition(context, filters, pData, {
+ client: source?.type,
+ }))
+ ) {
+ continue;
+ }
+
+ if (
+ await validateCondition(
+ context,
+ testFilters || (await hook.getFilters(context)),
+ data,
+ { client: source?.type },
+ )
+ ) {
+ filteredData.push(data);
+ }
+ }
+ if (!filteredData.length) {
+ return;
+ }
+ newData = filteredData;
+ } else {
+ // if condition is satisfied for prevData then return
+ // if filters are not defined then skip the check
+ if (
+ prevData &&
+ filters.length &&
+ (await validateCondition(context, filters, prevData, {
+ client: source?.type,
+ }))
+ ) {
+ return;
+ }
+ if (
+ !(await validateCondition(
+ context,
+ testFilters || (await hook.getFilters(context)),
+ newData,
+ { client: source?.type },
+ ))
+ ) {
+ return;
+ }
+ }
+ }
+
+ // check if form filter applied
+ if (
+ notification &&
+ notification.trigger_form &&
+ notification.trigger_form_id
+ ) {
+ const formId = notification.trigger_form_id;
+ if (view && formId !== view.id) {
+ return;
+ }
+ }
+
+ switch (notification?.type) {
+ case 'Email':
+ {
+ const webhookData = this.constructHookDataForNonURLHooks({
+ hook,
+ model,
+ view,
+ prevData,
+ newData,
+ });
+
+ const parsedPayload = {
+ to: parseBody(notification?.payload?.to, webhookData),
+ subject: parseBody(notification?.payload?.subject, webhookData),
+ html: parseBody(notification?.payload?.body, webhookData),
+ };
+ const res = await (
+ await NcPluginMgrv2.emailAdapter(false)
+ )?.mailSend(parsedPayload);
+ if (
+ process.env.NC_AUTOMATION_LOG_LEVEL === 'ALL' ||
+ (isEE && !process.env.NC_AUTOMATION_LOG_LEVEL)
+ ) {
+ hookLog = {
+ ...hook,
+ operation: hookName?.split('.')?.[1] as any,
+ fk_hook_id: hook.id,
+ type: notification.type,
+ payload: JSON.stringify(parsedPayload),
+ response: JSON.stringify(res),
+ triggered_by: user?.email,
+ conditions: JSON.stringify(filters),
+ };
+ }
+ }
+ break;
+ case 'URL':
+ {
+ reqPayload = this.populateAxiosReq({
+ apiMeta: notification?.payload,
+ user,
+ hook,
+ model,
+ view,
+ prevData,
+ newData,
+ });
+
+ const { requestPayload, responsePayload } = await handleHttpWebHook(
+ {
+ reqPayload,
+ },
+ );
+
+ if (
+ process.env.NC_AUTOMATION_LOG_LEVEL === 'ALL' ||
+ (isEE && !process.env.NC_AUTOMATION_LOG_LEVEL)
+ ) {
+ hookLog = {
+ ...hook,
+ operation: hookName?.split('.')?.[1] as any,
+ fk_hook_id: hook.id,
+ type: notification.type,
+ payload: JSON.stringify(requestPayload),
+ response: JSON.stringify(responsePayload),
+ triggered_by: user?.email,
+ conditions: JSON.stringify(filters),
+ };
+ }
+ }
+ break;
+ case 'Script':
+ {
+ const datas = Array.isArray(newData) ? newData : [newData];
+
+ const script = await Script.get(
+ context,
+ notification?.payload?.scriptId,
+ );
+
+ if (!script.script || hasInputCalls(script.script)) {
+ NcError.get(context).notImplemented(
+ 'Script with input calls is not supported',
+ );
+ }
+
+ await addJob?.(JobTypes.ExecuteAction, {
+ context,
+ scriptId: notification?.payload?.scriptId,
+ modelId: model.id,
+ records: datas,
+ req: {
+ user: NOCO_SERVICE_USERS.AUTOMATION_USER,
+ headers: {
+ 'xc-auth': genJwt(
+ {
+ ...NOCO_SERVICE_USERS.AUTOMATION_USER,
+ extra: {
+ context: {
+ ...context,
+ script_id: notification?.payload?.scriptId,
+ },
+ },
+ },
+ Noco.getConfig(),
+ {
+ expiresIn: '10m',
+ },
+ ),
+ },
+ ncSiteUrl,
+ },
+ });
+ }
+ break;
+ default:
+ {
+ const webhookData = this.constructHookDataForNonURLHooks({
+ hook,
+ model,
+ view,
+ prevData,
+ newData,
+ });
+
+ const res = await (
+ await NcPluginMgrv2.webhookNotificationAdapters(notification.type)
+ ).sendMessage(
+ parseBody(notification?.payload?.body, webhookData),
+ JSON.parse(
+ JSON.stringify(notification?.payload),
+ (_key, value) => {
+ return typeof value === 'string'
+ ? parseBody(value, webhookData)
+ : value;
+ },
+ ),
+ );
+
+ if (
+ process.env.NC_AUTOMATION_LOG_LEVEL === 'ALL' ||
+ (isEE && !process.env.NC_AUTOMATION_LOG_LEVEL)
+ ) {
+ hookLog = {
+ ...hook,
+ operation: hookName?.split('.')?.[1] as any,
+ fk_hook_id: hook.id,
+ type: notification.type,
+ payload: JSON.stringify(notification?.payload),
+ response: JSON.stringify({
+ status: res.status,
+ statusText: res.statusText,
+ headers: res.headers,
+ config: {
+ url: res.config.url,
+ method: res.config.method,
+ data: res.config.data,
+ headers: res.config.headers,
+ params: res.config.params,
+ },
+ }),
+ triggered_by: user?.email,
+ conditions: JSON.stringify(filters),
+ };
+ }
+ }
+ break;
+ }
+ } catch (e) {
+ if (e.response) {
+ this.logger.error({
+ data: e.response.data,
+ status: e.response.status,
+ url: e.response.config?.url,
+ message: e.message,
+ });
+ } else {
+ this.logger.error(e.message, e.stack);
+ }
+ if (
+ ['ERROR', 'ALL'].includes(process.env.NC_AUTOMATION_LOG_LEVEL) ||
+ isEE
+ ) {
+ hookLog = {
+ ...hook,
+ operation: hookName?.split('.')?.[1] as any,
+ type: notification.type,
+ payload: JSON.stringify(
+ reqPayload
+ ? this.extractReqPayloadForLog(reqPayload, e.response)
+ : notification?.payload,
+ ),
+ fk_hook_id: hook.id,
+ error_code: e.error_code ?? e.code,
+ error_message: e.message,
+ error: JSON.stringify(e),
+ triggered_by: user?.email,
+ conditions: filters
+ ? JSON.stringify(
+ addDummyRootAndNest(
+ filterBuilder().build(
+ this.flattenFilter(filters),
+ ) as Filter[],
+ ),
+ )
+ : null,
+ response: e.response
+ ? JSON.stringify(this.extractResPayloadForLog(e.response))
+ : null,
+ };
+ }
+ if (throwErrorOnFailure) {
+ if (e.isAxiosError) {
+ if (
+ e.message.includes('private IP address') ||
+ e.response?.data?.message?.includes('private IP address')
+ ) {
+ throw new Error(
+ `Connection to a private network IP is blocked for security reasons.` +
+ // shoe env var only if it's not EE or it's on-prem
+ (!isEE || isOnPrem
+ ? `If this is intentional, set NC_ALLOW_LOCAL_HOOKS=true to allow local network webhooks.`
+ : ''),
+ );
+ }
+ }
+
+ throw e;
+ }
+ } finally {
+ if (hookLog) {
+ hookLog.execution_time = this.parseHrtimeToMilliSeconds(
+ process.hrtime(startTime),
+ );
+ HookLog.insert(context, { ...hookLog, test_call: testHook }).catch(
+ (e) => {
+ this.logger.error(e.message, e.stack);
+ },
+ );
+ }
+ }
+ }
+}