Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions packages/components/nodes/agentflow/Start/Start.ts
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,45 @@ class Start_Agentflow implements INode {
startInputType: 'webhookTrigger'
}
},
{
label: 'Webhook Secret',
name: 'webhookSecret',
type: 'string',
description:
'Optional secret used to verify incoming requests. When set, configure Signature Header and Signature Type below to match your sender.',
optional: true,
show: {
startInputType: 'webhookTrigger'
}
},
{
label: 'Signature Header',
name: 'webhookSignatureHeader',
type: 'string',
description:
'The request header that carries the signature. e.g. x-hub-signature-256 for GitHub, stripe-signature for Stripe, x-gitlab-token for GitLab.',
placeholder: 'x-webhook-signature',
optional: true,
show: {
startInputType: 'webhookTrigger'
}
},
{
label: 'Signature Type',
name: 'webhookSignatureType',
type: 'options',
description:
'How to verify the signature. HMAC-SHA256 for GitHub, Stripe, Slack (supports sha256=<hex> prefix automatically). Plain Token for GitLab-style plain secret comparison.',
options: [
{ label: 'HMAC-SHA256', name: 'hmac-sha256' },
{ label: 'Plain Token', name: 'plain-token' }
],
default: 'hmac-sha256',
optional: true,
show: {
startInputType: 'webhookTrigger'
}
},
{
label: 'Expected Query Parameters',
name: 'webhookQueryParams',
Expand Down
2 changes: 2 additions & 0 deletions packages/server/src/Interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,8 @@ export interface IChatFlow {
type?: ChatflowType
mcpServerConfig?: string
workspaceId: string
webhookSecret?: string | null
webhookSecretConfigured?: boolean
}

export interface IChatMessage {
Expand Down
42 changes: 41 additions & 1 deletion packages/server/src/controllers/chatflows/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,44 @@ const checkIfChatflowHasChanged = async (req: Request, res: Response, next: Next
}
}

const setWebhookSecret = async (req: Request, res: Response, next: NextFunction) => {
try {
if (!req.params.id) {
throw new InternalFlowiseError(
StatusCodes.PRECONDITION_FAILED,
`Error: chatflowsController.setWebhookSecret - id not provided!`
)
}
const workspaceId = req.user?.activeWorkspaceId
if (!workspaceId) {
throw new InternalFlowiseError(StatusCodes.UNAUTHORIZED, `Error: chatflowsController.setWebhookSecret - workspace not found!`)
}
const apiResponse = await chatflowsService.setWebhookSecret(req.params.id, workspaceId)
return res.json(apiResponse)
} catch (error) {
next(error)
}
}

const clearWebhookSecret = async (req: Request, res: Response, next: NextFunction) => {
try {
if (!req.params.id) {
throw new InternalFlowiseError(
StatusCodes.PRECONDITION_FAILED,
`Error: chatflowsController.clearWebhookSecret - id not provided!`
)
}
const workspaceId = req.user?.activeWorkspaceId
if (!workspaceId) {
throw new InternalFlowiseError(StatusCodes.UNAUTHORIZED, `Error: chatflowsController.clearWebhookSecret - workspace not found!`)
}
await chatflowsService.clearWebhookSecret(req.params.id, workspaceId)
return res.sendStatus(StatusCodes.NO_CONTENT)
} catch (error) {
next(error)
}
}

export default {
checkIfChatflowIsValidForStreaming,
checkIfChatflowIsValidForUploads,
Expand All @@ -286,5 +324,7 @@ export default {
updateChatflow,
getSinglePublicChatflow,
getSinglePublicChatbotConfig,
checkIfChatflowHasChanged
checkIfChatflowHasChanged,
setWebhookSecret,
clearWebhookSecret
}
3 changes: 2 additions & 1 deletion packages/server/src/controllers/webhook/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,8 @@ describe('createWebhook', () => {
{ foo: 'bar' },
'POST',
expect.any(Object),
expect.any(Object)
expect.any(Object),
undefined // rawBody — not set on mock request
)
})
})
12 changes: 10 additions & 2 deletions packages/server/src/controllers/webhook/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { InternalFlowiseError } from '../../errors/internalFlowiseError'

const createWebhook = async (req: Request, res: Response, next: NextFunction) => {
try {
if (req.params.id == null) {
if (typeof req.params === 'undefined' || !req.params.id) {
throw new InternalFlowiseError(StatusCodes.PRECONDITION_FAILED, `Error: webhookController.createWebhook - id not provided!`)
}

Expand All @@ -25,7 +25,15 @@ const createWebhook = async (req: Request, res: Response, next: NextFunction) =>
}
}

await webhookService.validateWebhookChatflow(req.params.id, workspaceId, body, req.method, req.headers, req.query)
await webhookService.validateWebhookChatflow(
req.params.id,
workspaceId,
body,
req.method,
req.headers,
req.query,
(req as any).rawBody
)

// Namespace the webhook payload so $webhook.body.*, $webhook.headers.*, $webhook.query.* can coexist
req.body = {
Expand Down
6 changes: 6 additions & 0 deletions packages/server/src/database/entities/ChatFlow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,12 @@ export class ChatFlow implements IChatFlow {
@Column({ nullable: true, type: 'text' })
mcpServerConfig?: string

@Column({ nullable: true, type: 'text', select: false })
webhookSecret?: string | null

@Column({ nullable: true, default: false })
webhookSecretConfigured?: boolean

@Column({ nullable: false, type: 'text' })
workspaceId: string
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { MigrationInterface, QueryRunner } from 'typeorm'

export class AddWebhookSecretToChatFlow1776240000003 implements MigrationInterface {
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query('ALTER TABLE `chat_flow` ADD COLUMN `webhookSecret` TEXT;')
await queryRunner.query('ALTER TABLE `chat_flow` ADD COLUMN `webhookSecretConfigured` BOOLEAN DEFAULT FALSE;')
await queryRunner.query('UPDATE `chat_flow` SET `webhookSecretConfigured` = TRUE WHERE `webhookSecret` IS NOT NULL;')
}

public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query('ALTER TABLE `chat_flow` DROP COLUMN `webhookSecretConfigured`;')
await queryRunner.query('ALTER TABLE `chat_flow` DROP COLUMN `webhookSecret`;')
}
}
2 changes: 2 additions & 0 deletions packages/server/src/database/migrations/mariadb/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ import { AddChatFlowNameIndex1759424809984 } from './1759424809984-AddChatFlowNa
import { FixDocumentStoreFileChunkLongText1765000000000 } from './1765000000000-FixDocumentStoreFileChunkLongText'
import { AddApiKeyPermission1765360298674 } from './1765360298674-AddApiKeyPermission'
import { AddReasonContentToChatMessage1764759496768 } from './1764759496768-AddReasonContentToChatMessage'
import { AddWebhookSecretToChatFlow1776240000003 } from './1776240000003-AddWebhookSecretToChatFlow'
import { AddMcpServerConfigToChatFlow1767000000000 } from './1767000000000-AddMcpServerConfigToChatFlow'

import { AddAuthTables1720230151482 } from '../../../enterprise/database/migrations/mariadb/1720230151482-AddAuthTables'
Expand Down Expand Up @@ -114,5 +115,6 @@ export const mariadbMigrations = [
FixDocumentStoreFileChunkLongText1765000000000,
AddApiKeyPermission1765360298674,
AddReasonContentToChatMessage1764759496768,
AddWebhookSecretToChatFlow1776240000003,
AddMcpServerConfigToChatFlow1767000000000
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { MigrationInterface, QueryRunner } from 'typeorm'

export class AddWebhookSecretToChatFlow1776240000002 implements MigrationInterface {
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query('ALTER TABLE `chat_flow` ADD COLUMN `webhookSecret` TEXT;')
await queryRunner.query('ALTER TABLE `chat_flow` ADD COLUMN `webhookSecretConfigured` BOOLEAN DEFAULT FALSE;')
await queryRunner.query('UPDATE `chat_flow` SET `webhookSecretConfigured` = TRUE WHERE `webhookSecret` IS NOT NULL;')
}

public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query('ALTER TABLE `chat_flow` DROP COLUMN `webhookSecretConfigured`;')
await queryRunner.query('ALTER TABLE `chat_flow` DROP COLUMN `webhookSecret`;')
}
}
2 changes: 2 additions & 0 deletions packages/server/src/database/migrations/mysql/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ import { AddChatFlowNameIndex1759424828558 } from './1759424828558-AddChatFlowNa
import { FixDocumentStoreFileChunkLongText1765000000000 } from './1765000000000-FixDocumentStoreFileChunkLongText'
import { AddApiKeyPermission1765360298674 } from './1765360298674-AddApiKeyPermission'
import { AddReasonContentToChatMessage1764759496768 } from './1764759496768-AddReasonContentToChatMessage'
import { AddWebhookSecretToChatFlow1776240000002 } from './1776240000002-AddWebhookSecretToChatFlow'
import { AddMcpServerConfigToChatFlow1767000000000 } from './1767000000000-AddMcpServerConfigToChatFlow'

import { AddAuthTables1720230151482 } from '../../../enterprise/database/migrations/mysql/1720230151482-AddAuthTables'
Expand Down Expand Up @@ -116,5 +117,6 @@ export const mysqlMigrations = [
FixDocumentStoreFileChunkLongText1765000000000,
AddApiKeyPermission1765360298674,
AddReasonContentToChatMessage1764759496768,
AddWebhookSecretToChatFlow1776240000002,
AddMcpServerConfigToChatFlow1767000000000
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { MigrationInterface, QueryRunner } from 'typeorm'

export class AddWebhookSecretToChatFlow1776240000001 implements MigrationInterface {
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE "chat_flow" ADD COLUMN IF NOT EXISTS "webhookSecret" TEXT;`)
await queryRunner.query(`ALTER TABLE "chat_flow" ADD COLUMN IF NOT EXISTS "webhookSecretConfigured" BOOLEAN DEFAULT FALSE;`)
await queryRunner.query(`UPDATE "chat_flow" SET "webhookSecretConfigured" = TRUE WHERE "webhookSecret" IS NOT NULL;`)
}

public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE "chat_flow" DROP COLUMN "webhookSecretConfigured";`)
await queryRunner.query(`ALTER TABLE "chat_flow" DROP COLUMN "webhookSecret";`)
}
}
2 changes: 2 additions & 0 deletions packages/server/src/database/migrations/postgres/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ import { AddTextToSpeechToChatFlow1759419194331 } from './1759419194331-AddTextT
import { AddChatFlowNameIndex1759424903973 } from './1759424903973-AddChatFlowNameIndex'
import { AddApiKeyPermission1765360298674 } from './1765360298674-AddApiKeyPermission'
import { AddReasonContentToChatMessage1764759496768 } from './1764759496768-AddReasonContentToChatMessage'
import { AddWebhookSecretToChatFlow1776240000001 } from './1776240000001-AddWebhookSecretToChatFlow'
import { AddMcpServerConfigToChatFlow1767000000000 } from './1767000000000-AddMcpServerConfigToChatFlow'

import { AddAuthTables1720230151482 } from '../../../enterprise/database/migrations/postgres/1720230151482-AddAuthTables'
Expand Down Expand Up @@ -112,5 +113,6 @@ export const postgresMigrations = [
AddChatFlowNameIndex1759424903973,
AddApiKeyPermission1765360298674,
AddReasonContentToChatMessage1764759496768,
AddWebhookSecretToChatFlow1776240000001,
AddMcpServerConfigToChatFlow1767000000000
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { MigrationInterface, QueryRunner } from 'typeorm'

export class AddWebhookSecretToChatFlow1776240000000 implements MigrationInterface {
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE "chat_flow" ADD COLUMN "webhookSecret" TEXT;`)
await queryRunner.query(`ALTER TABLE "chat_flow" ADD COLUMN "webhookSecretConfigured" BOOLEAN DEFAULT FALSE;`)
await queryRunner.query(`UPDATE "chat_flow" SET "webhookSecretConfigured" = TRUE WHERE "webhookSecret" IS NOT NULL;`)
}

public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE "chat_flow" DROP COLUMN "webhookSecretConfigured";`)
await queryRunner.query(`ALTER TABLE "chat_flow" DROP COLUMN "webhookSecret";`)
}
}
2 changes: 2 additions & 0 deletions packages/server/src/database/migrations/sqlite/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ import { AddTextToSpeechToChatFlow1759419136055 } from './1759419136055-AddTextT
import { AddChatFlowNameIndex1759424923093 } from './1759424923093-AddChatFlowNameIndex'
import { AddApiKeyPermission1765360298674 } from './1765360298674-AddApiKeyPermission'
import { AddReasonContentToChatMessage1764759496768 } from './1764759496768-AddReasonContentToChatMessage'
import { AddWebhookSecretToChatFlow1776240000000 } from './1776240000000-AddWebhookSecretToChatFlow'
import { AddMcpServerConfigToChatFlow1767000000000 } from './1767000000000-AddMcpServerConfigToChatFlow'

import { AddAuthTables1720230151482 } from '../../../enterprise/database/migrations/sqlite/1720230151482-AddAuthTables'
Expand Down Expand Up @@ -108,5 +109,6 @@ export const sqliteMigrations = [
AddChatFlowNameIndex1759424923093,
AddApiKeyPermission1765360298674,
AddReasonContentToChatMessage1764759496768,
AddWebhookSecretToChatFlow1776240000000,
AddMcpServerConfigToChatFlow1767000000000
]
9 changes: 7 additions & 2 deletions packages/server/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -162,8 +162,13 @@ export class App {
async config() {
// Limit is needed to allow sending/receiving base64 encoded string
const flowise_file_size_limit = process.env.FLOWISE_FILE_SIZE_LIMIT || '50mb'
this.app.use(express.json({ limit: flowise_file_size_limit }))
this.app.use(express.urlencoded({ limit: flowise_file_size_limit, extended: true }))

// Preserve raw bytes before JSON parsing for webhook HMAC signature verification
const captureRawBody = (req: Request, _res: Response, buf: Buffer) => {
;(req as any).rawBody = buf
}
this.app.use(express.json({ limit: flowise_file_size_limit, verify: captureRawBody }))
this.app.use(express.urlencoded({ limit: flowise_file_size_limit, extended: true, verify: captureRawBody }))

// Enhanced trust proxy settings for load balancer
let trustProxy: string | boolean | number | undefined = process.env.TRUST_PROXY
Expand Down
4 changes: 4 additions & 0 deletions packages/server/src/routes/chatflows/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,10 @@ router.put(
// DELETE
router.delete(['/', '/:id'], checkAnyPermission('chatflows:delete,agentflows:delete'), chatflowsController.deleteChatflow)

// WEBHOOK SECRET
router.post('/:id/webhook-secret', checkAnyPermission('chatflows:update,agentflows:update'), chatflowsController.setWebhookSecret)
router.delete('/:id/webhook-secret', checkAnyPermission('chatflows:update,agentflows:update'), chatflowsController.clearWebhookSecret)

// CHECK FOR CHANGE
router.get(
'/has-changed/:id/:lastUpdatedDateTime',
Expand Down
62 changes: 61 additions & 1 deletion packages/server/src/services/chatflows/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { randomBytes } from 'crypto'
import { ICommonObject, removeFolderFromStorage } from 'flowise-components'
import { StatusCodes } from 'http-status-codes'
import { Brackets, In } from 'typeorm'
Expand Down Expand Up @@ -463,6 +464,62 @@ const checkIfChatflowHasChanged = async (chatflowId: string, lastUpdatedDateTime
}
}

const setWebhookSecret = async (chatflowId: string, workspaceId: string): Promise<{ webhookSecret: string }> => {
try {
const appServer = getRunningExpressApp()
const repo = appServer.AppDataSource.getRepository(ChatFlow)
const chatflow = await repo.findOne({ where: { id: chatflowId, workspaceId } })
if (!chatflow) throw new InternalFlowiseError(StatusCodes.NOT_FOUND, `Chatflow ${chatflowId} not found`)
chatflow.webhookSecret = randomBytes(32).toString('hex')
chatflow.webhookSecretConfigured = true
await repo.save(chatflow)
return { webhookSecret: chatflow.webhookSecret }
} catch (error) {
if (error instanceof InternalFlowiseError) throw error
throw new InternalFlowiseError(
StatusCodes.INTERNAL_SERVER_ERROR,
`Error: chatflowsService.setWebhookSecret - ${getErrorMessage(error)}`
)
}
}

const clearWebhookSecret = async (chatflowId: string, workspaceId: string): Promise<void> => {
try {
const appServer = getRunningExpressApp()
const repo = appServer.AppDataSource.getRepository(ChatFlow)
const chatflow = await repo.findOne({ where: { id: chatflowId, workspaceId } })
if (!chatflow) throw new InternalFlowiseError(StatusCodes.NOT_FOUND, `Chatflow ${chatflowId} not found`)
chatflow.webhookSecret = null
chatflow.webhookSecretConfigured = false
await repo.save(chatflow)
} catch (error) {
if (error instanceof InternalFlowiseError) throw error
throw new InternalFlowiseError(
StatusCodes.INTERNAL_SERVER_ERROR,
`Error: chatflowsService.clearWebhookSecret - ${getErrorMessage(error)}`
)
}
}

const getWebhookSecret = async (chatflowId: string, workspaceId: string): Promise<string | null> => {
try {
const appServer = getRunningExpressApp()
const dbResponse = await appServer.AppDataSource.getRepository(ChatFlow)
.createQueryBuilder('chatflow')
.select('chatflow.webhookSecret')
.where('chatflow.id = :id', { id: chatflowId })
.andWhere('chatflow.workspaceId = :workspaceId', { workspaceId })
.getOne()
return dbResponse?.webhookSecret ?? null
} catch (error) {
if (error instanceof InternalFlowiseError) throw error
throw new InternalFlowiseError(
StatusCodes.INTERNAL_SERVER_ERROR,
`Error: chatflowsService.getWebhookSecret - ${getErrorMessage(error)}`
)
}
}

export default {
checkIfChatflowIsValidForStreaming,
checkIfChatflowIsValidForUploads,
Expand All @@ -475,5 +532,8 @@ export default {
updateChatflow,
getSinglePublicChatbotConfig,
checkIfChatflowHasChanged,
getAllChatflowsCountByOrganization
getAllChatflowsCountByOrganization,
setWebhookSecret,
clearWebhookSecret,
getWebhookSecret
}
Loading