Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

♻️ refactor(workflow): expose run guard webhook route (#16727)

Nekoc6336ad17a91
diff --git a/apps/server/src/globalConfig/parseWorkflowRunGuardConfig.ts b/apps/server/src/globalConfig/parseWorkflowRunGuardConfig.ts
new file mode 100644
index 00000000000..1e97506f041
--- /dev/null
+++ b/apps/server/src/globalConfig/parseWorkflowRunGuardConfig.ts
@@ -0,0 +1,23 @@
+const parseHeaders = (value?: string) =>
+ value
+ ?.split(',')
+ .filter(Boolean)
+ .reduce<Record<string, string>>((acc, pair) => {
+ const [key, headerValue] = pair.split('=').map((s) => s.trim());
+ if (key && headerValue) {
+ acc[key] = headerValue;
+ }
+ return acc;
+ }, {});
+
+/** Parses workflow run guard webhook headers and app URL settings. */
+export const parseWorkflowRunGuardConfig = () => ({
+ appUrl:
+ process.env.WORKFLOW_RUN_GUARD_WEBHOOK_BASE_URL ||
+ process.env.MEMORY_USER_MEMORY_WEBHOOK_BASE_URL ||
+ process.env.INTERNAL_APP_URL ||
+ process.env.APP_URL,
+ webhook: {
+ headers: parseHeaders(process.env.WORKFLOW_RUN_GUARD_WEBHOOK_HEADERS),
+ },
+});
diff --git a/src/app/(backend)/api/webhooks/workflows/run-guard/route.test.ts b/src/app/(backend)/api/webhooks/workflows/run-guard/route.test.ts
new file mode 100644
index 00000000000..dd96c523c51
--- /dev/null
+++ b/src/app/(backend)/api/webhooks/workflows/run-guard/route.test.ts
@@ -0,0 +1,254 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const { mockGetRedisConfig, redis, redisLib, workflowClient } = vi.hoisted(() => ({
+ mockGetRedisConfig: vi.fn(),
+ redis: {
+ set: vi.fn(),
+ },
+ redisLib: {
+ initializeRedis: vi.fn(),
+ isRedisEnabled: vi.fn(),
+ },
+ workflowClient: {
+ cancel: vi.fn(),
+ logs: vi.fn(),
+ },
+}));
+
+vi.mock('@/envs/redis', () => ({
+ getRedisConfig: mockGetRedisConfig,
+}));
+
+vi.mock('@/libs/redis', () => ({
+ initializeRedis: redisLib.initializeRedis,
+ isRedisEnabled: redisLib.isRedisEnabled,
+}));
+
+vi.mock('@/libs/qstash', () => ({
+ workflowClient,
+}));
+
+const { POST } = await import('./route');
+
+const originalEnv = {
+ APP_URL: process.env.APP_URL,
+ INTERNAL_APP_URL: process.env.INTERNAL_APP_URL,
+ MEMORY_USER_MEMORY_WEBHOOK_BASE_URL: process.env.MEMORY_USER_MEMORY_WEBHOOK_BASE_URL,
+ WORKFLOW_RUN_GUARD_WEBHOOK_HEADERS: process.env.WORKFLOW_RUN_GUARD_WEBHOOK_HEADERS,
+};
+
+const restoreEnv = () => {
+ for (const [key, value] of Object.entries(originalEnv)) {
+ if (value === undefined) {
+ delete process.env[key];
+ } else {
+ process.env[key] = value;
+ }
+ }
+};
+
+describe('workflow run guard webhook route', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockGetRedisConfig.mockReturnValue({ enabled: true, url: 'redis://test' });
+ redisLib.isRedisEnabled.mockReturnValue(true);
+ redisLib.initializeRedis.mockReturnValue(redis);
+ process.env.APP_URL = 'https://app.lobehub.com';
+ process.env.INTERNAL_APP_URL = '';
+ process.env.MEMORY_USER_MEMORY_WEBHOOK_BASE_URL = '';
+ process.env.WORKFLOW_RUN_GUARD_WEBHOOK_HEADERS = 'Authorization=Bearer webhook-secret';
+ });
+
+ afterEach(() => {
+ restoreEnv();
+ });
+
+ /**
+ * @example
+ * POST(requestWithWrongAuthorizationHeader) returns 401 and does not read Redis.
+ */
+ it('rejects invalid webhook headers', async () => {
+ const response = await POST(
+ new Request('https://app.lobehub.com/api/webhooks/workflows/run-guard', {
+ body: JSON.stringify({ scope: { type: 'global' } }),
+ headers: { Authorization: 'Bearer wrong-secret' },
+ method: 'POST',
+ }),
+ );
+
+ expect(response.status).toBe(401);
+ await expect(response.json()).resolves.toEqual({ error: 'Unauthorized' });
+ expect(redisLib.initializeRedis).not.toHaveBeenCalled();
+ });
+
+ /**
+ * @example
+ * POST(requestWhenEnvHeadersMissing) returns 401 and leaves guard state untouched.
+ */
+ it('rejects when webhook header env is missing', async () => {
+ delete process.env.WORKFLOW_RUN_GUARD_WEBHOOK_HEADERS;
+
+ const response = await POST(
+ new Request('https://app.lobehub.com/api/webhooks/workflows/run-guard', {
+ body: JSON.stringify({ scope: { type: 'global' } }),
+ headers: { Authorization: 'Bearer webhook-secret' },
+ method: 'POST',
+ }),
+ );
+
+ expect(response.status).toBe(401);
+ expect(redisLib.initializeRedis).not.toHaveBeenCalled();
+ });
+
+ /**
+ * @example
+ * POST({ scope: { type: 'global' }, ttlSeconds: 60 }) with Authorization header stores a global guard.
+ */
+ it('sets a guard from webhook payload', async () => {
+ redis.set.mockResolvedValue('OK');
+
+ const response = await POST(
+ new Request('https://app.lobehub.com/api/webhooks/workflows/run-guard', {
+ body: JSON.stringify({
+ reason: 'external stop',
+ scope: { type: 'global' },
+ ttlSeconds: 60,
+ }),
+ headers: { Authorization: 'Bearer webhook-secret' },
+ method: 'POST',
+ }),
+ );
+
+ expect(response.status).toBe(200);
+ await expect(response.json()).resolves.toMatchObject({
+ guard: {
+ key: 'workflow:run-guard:global',
+ ttlSeconds: 60,
+ value: { reason: 'external stop' },
+ },
+ success: true,
+ });
+ expect(redis.set).toHaveBeenCalledWith(
+ 'workflow:run-guard:global',
+ expect.stringContaining('external stop'),
+ { ex: 60 },
+ );
+ });
+
+ /**
+ * @example
+ * POST(validPayloadWithAllConfiguredHeaders) accepts every configured header pair.
+ */
+ it('accepts multiple configured webhook headers', async () => {
+ process.env.WORKFLOW_RUN_GUARD_WEBHOOK_HEADERS =
+ 'Authorization=Bearer webhook-secret,x-workflow-source=ops-console';
+ redis.set.mockResolvedValue('OK');
+
+ const response = await POST(
+ new Request('https://app.lobehub.com/api/webhooks/workflows/run-guard', {
+ body: JSON.stringify({ scope: { type: 'global' } }),
+ headers: {
+ 'Authorization': 'Bearer webhook-secret',
+ 'x-workflow-source': 'ops-console',
+ },
+ method: 'POST',
+ }),
+ );
+
+ expect(response.status).toBe(200);
+ await expect(response.json()).resolves.toMatchObject({ success: true });
+ });
+
+ /**
+ * @example
+ * POST(pathGuardWithCancelPolicy) stores the guard and cancels matching workflow runs.
+ */
+ it('cancels qstash runs for path guards when policy requests it', async () => {
+ process.env.MEMORY_USER_MEMORY_WEBHOOK_BASE_URL = 'https://internal.lobehub.com';
+ redis.set.mockResolvedValue('OK');
+ workflowClient.cancel.mockResolvedValue({ cancelled: 1 });
+
+ const response = await POST(
+ new Request('https://app.lobehub.com/api/webhooks/workflows/run-guard', {
+ body: JSON.stringify({
+ policy: { cancelQstash: true },
+ scope: { type: 'path', workflowPath: 'api/workflows/memory-user-memory' },
+ }),
+ headers: { Authorization: 'Bearer webhook-secret' },
+ method: 'POST',
+ }),
+ );
+
+ expect(response.status).toBe(200);
+ await expect(response.json()).resolves.toMatchObject({
+ guard: {
+ key: 'workflow:run-guard:path:api/workflows/memory-user-memory',
+ value: { policy: { cancelQstash: true } },
+ },
+ qstash: {
+ cancelled: 1,
+ workflowUrlPrefix: 'https://internal.lobehub.com/api/workflows/memory-user-memory',
+ },
+ success: true,
+ });
+ expect(workflowClient.logs).not.toHaveBeenCalled();
+ expect(workflowClient.cancel).toHaveBeenCalledWith({
+ urlStartingWith: 'https://internal.lobehub.com/api/workflows/memory-user-memory',
+ });
+ });
+
+ /**
+ * @example
+ * POST({ scope: { type: 'path' } }) returns 400 because workflowPath is required.
+ */
+ it('rejects invalid bodies before reading redis', async () => {
+ const response = await POST(
+ new Request('https://app.lobehub.com/api/webhooks/workflows/run-guard', {
+ body: JSON.stringify({ scope: { type: 'path' } }),
+ headers: { Authorization: 'Bearer webhook-secret' },
+ method: 'POST',
+ }),
+ );
+
+ expect(response.status).toBe(400);
+ expect(redisLib.initializeRedis).not.toHaveBeenCalled();
+ await expect(response.json()).resolves.toMatchObject({ error: 'Invalid request' });
+ });
+
+ /**
+ * @example
+ * POST('{broken') returns an explicit invalid JSON response.
+ */
+ it('rejects malformed json bodies', async () => {
+ const response = await POST(
+ new Request('https://app.lobehub.com/api/webhooks/workflows/run-guard', {
+ body: '{broken',
+ headers: { Authorization: 'Bearer webhook-secret' },
+ method: 'POST',
+ }),
+ );
+
+ expect(response.status).toBe(400);
+ expect(redisLib.initializeRedis).not.toHaveBeenCalled();
+ await expect(response.json()).resolves.toEqual({ error: 'Invalid JSON' });
+ });
+
+ /**
+ * @example
+ * POST(validPayload) returns 500 when Redis is unavailable.
+ */
+ it('fails closed when redis is not configured', async () => {
+ redisLib.isRedisEnabled.mockReturnValue(false);
+
+ const response = await POST(
+ new Request('https://app.lobehub.com/api/webhooks/workflows/run-guard', {
+ body: JSON.stringify({ scope: { type: 'global' } }),
+ headers: { Authorization: 'Bearer webhook-secret' },
+ method: 'POST',
+ }),
+ );
+
+ expect(response.status).toBe(500);
+ await expect(response.json()).resolves.toEqual({ error: 'Redis is not configured' });
+ });
+});
diff --git a/src/app/(backend)/api/webhooks/workflows/run-guard/route.ts b/src/app/(backend)/api/webhooks/workflows/run-guard/route.ts
new file mode 100644
index 00000000000..5a7aaf67300
--- /dev/null
+++ b/src/app/(backend)/api/webhooks/workflows/run-guard/route.ts
@@ -0,0 +1,122 @@
+import { NextResponse } from 'next/server';
+import { z } from 'zod';
+
+import { getRedisConfig } from '@/envs/redis';
+import { workflowClient } from '@/libs/qstash';
+import { initializeRedis, isRedisEnabled } from '@/libs/redis';
+import { parseWorkflowRunGuardConfig } from '@/server/globalConfig/parseWorkflowRunGuardConfig';
+import { cancelWorkflowRunsByGuardPolicy, setWorkflowRunGuard } from '@/server/workflows/runGuard';
+
+// NOTICE:
+// Next.js route segment config is required here because this operational webhook reads
+// runtime env, Redis, and QStash clients. Keep it on Node.js and force dynamic handling so
+// the route is evaluated per request instead of being statically optimized.
+// Source/context: `https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config`
+// and `node_modules/next/dist/docs/01-app/03-api-reference/03-file-conventions/02-route-segment-config/runtime.md`.
+export const runtime = 'nodejs';
+export const dynamic = 'force-dynamic';
+
+const guardScopeSchema = z.discriminatedUnion('type', [
+ z.object({ type: z.literal('global') }),
+ z.object({ type: z.literal('path'), workflowPath: z.string().trim().min(1) }),
+ z.object({ type: z.literal('user'), userId: z.string().trim().min(1) }),
+ z.object({ type: z.literal('run'), workflowRunId: z.string().trim().min(1) }),
+ z.object({
+ stepName: z.string().trim().min(1),
+ type: z.literal('step'),
+ workflowRunId: z.string().trim().min(1),
+ }),
+]);
+
+const guardPolicySchema = z
+ .object({
+ cancelQstash: z.boolean().optional(),
+ })
+ .strict();
+
+const setGuardBodySchema = z
+ .object({
+ policy: guardPolicySchema.optional(),
+ reason: z.string().trim().min(1).optional(),
+ scope: guardScopeSchema,
+ ttlSeconds: z.number().int().positive().optional(),
+ })
+ .strict();
+
+/**
+ * Creates or replaces one workflow run guard from an authenticated webhook.
+ *
+ * Use when:
+ * - External automation needs to stop workflow work by global, path, user, run, or step scope.
+ * - Path-scoped guards may also cancel matching active QStash workflow runs.
+ *
+ * Expects:
+ * - The configured webhook headers match the request headers.
+ * - Body matches the mutation schema.
+ * - Redis is configured.
+ *
+ * Returns:
+ * - JSON containing `success: true`, the stored guard, and optional QStash cancellation result.
+ */
+export const POST = async (request: Request) => {
+ const { appUrl, webhook } = parseWorkflowRunGuardConfig();
+ const headers = webhook.headers ?? {};
+
+ if (Object.keys(headers).length === 0) {
+ return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
+ }
+
+ for (const [key, value] of Object.entries(headers)) {
+ if (request.headers.get(key) !== value) {
+ return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
+ }
+ }
+
+ let body: unknown;
+ try {
+ body = await request.json();
+ } catch {
+ return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 });
+ }
+
+ const parsed = setGuardBodySchema.safeParse(body);
+ if (!parsed.success) {
+ return NextResponse.json(
+ { error: 'Invalid request', issues: parsed.error.issues },
+ { status: 400 },
+ );
+ }
+
+ try {
+ const redisConfig = getRedisConfig();
+ if (!isRedisEnabled(redisConfig)) throw new Error('Redis is not configured');
+
+ const redis = await initializeRedis(redisConfig);
+ if (!redis) throw new Error('Redis is not configured');
+
+ const { policy, reason, scope, ttlSeconds } = parsed.data;
+ const guard = await setWorkflowRunGuard(redis, {
+ scope,
+ ttlSeconds,
+ value: {
+ policy,
+ reason,
+ },
+ });
+
+ let qstash;
+
+ if (policy?.cancelQstash && scope.type === 'path') {
+ if (!appUrl) throw new Error('App URL is not configured');
+
+ qstash = await cancelWorkflowRunsByGuardPolicy(workflowClient, {
+ appUrl,
+ workflowPath: scope.workflowPath,
+ });
+ }
+
+ return NextResponse.json({ guard, qstash, success: true });
+ } catch (error) {
+ return NextResponse.json({ error: (error as Error).message }, { status: 500 });
+ }
+};