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.

πŸ”’ fix(server): fail closed on unauthenticated workflow callbacks (#22864)

Mochabc938da476a3
diff --git a/apps/server/src/router-hono/workflows/agent-eval-run/__tests__/routes.test.ts b/apps/server/src/router-hono/workflows/agent-eval-run/__tests__/routes.test.ts
index bb9405126f9..4ccf3bd7b18 100644
--- a/apps/server/src/router-hono/workflows/agent-eval-run/__tests__/routes.test.ts
+++ b/apps/server/src/router-hono/workflows/agent-eval-run/__tests__/routes.test.ts
@@ -1,5 +1,6 @@
-import { describe, expect, it } from 'vitest';
+import { describe, expect, it, vi } from 'vitest';
+import { signInternalCallback } from '@/libs/qstash/internalSignature';
import { WORKFLOW_PATHS } from '@/server/workflows/agentEvalRun';
import workflowsApp from '../../index';
@@ -27,3 +28,49 @@ describe('agent-eval-run hono routes', () => {
expect(evalRoutes.sort()).toEqual(Object.values(WORKFLOW_PATHS).slice().sort());
});
});
+
+describe('workflow production authentication boundary', () => {
+ it('accepts internally signed eval completion callbacks when QStash is configured', async () => {
+ vi.stubEnv('NODE_ENV', 'production');
+ vi.stubEnv('QSTASH_CURRENT_SIGNING_KEY', 'current-test-key');
+ vi.stubEnv('QSTASH_NEXT_SIGNING_KEY', 'next-test-key');
+ vi.stubEnv('KEY_VAULTS_SECRET', 'synthetic-test-secret');
+ vi.stubEnv('APP_URL', 'https://app.example');
+ vi.stubEnv('INTERNAL_APP_URL', '');
+ try {
+ for (const path of [WORKFLOW_PATHS.onTrajectoryComplete, WORKFLOW_PATHS.onThreadComplete]) {
+ const url = `https://app.example${path}`;
+ const body = '{}';
+ const response = await workflowsApp.request(url, {
+ body,
+ headers: signInternalCallback(url, body),
+ method: 'POST',
+ });
+ // Auth passed; the handler rejects the empty payload before it reads the database.
+ expect(response.status, path).toBe(400);
+ }
+ } finally {
+ vi.unstubAllEnvs();
+ }
+ });
+
+ it('rejects unsigned requests across all mounted workflow POST routes without QStash', async () => {
+ vi.stubEnv('NODE_ENV', 'production');
+ vi.stubEnv('QSTASH_CURRENT_SIGNING_KEY', '');
+ vi.stubEnv('QSTASH_NEXT_SIGNING_KEY', '');
+ try {
+ const routes = new Set(
+ workflowsApp.routes.filter((route) => route.method === 'POST').map((route) => route.path),
+ );
+ for (const path of routes) {
+ const response = await workflowsApp.request(path.replace(':workflowId', 'process'), {
+ body: '{}',
+ method: 'POST',
+ });
+ expect(response.status, path).toBe(401);
+ }
+ } finally {
+ vi.unstubAllEnvs();
+ }
+ });
+});
diff --git a/apps/server/src/router-hono/workflows/agent-eval-run/index.ts b/apps/server/src/router-hono/workflows/agent-eval-run/index.ts
index cb82d854532..ef850a7a320 100644
--- a/apps/server/src/router-hono/workflows/agent-eval-run/index.ts
+++ b/apps/server/src/router-hono/workflows/agent-eval-run/index.ts
@@ -4,6 +4,7 @@ import { Hono } from 'hono';
import { qstashClient } from '@/libs/qstash';
+import { qstashAuth } from '../middlewares/qstashAuth';
import { onThreadComplete } from './handlers/onThreadComplete';
import { onTrajectoryComplete } from './handlers/onTrajectoryComplete';
import {
@@ -116,7 +117,7 @@ app.post(
);
// Plain completion webhooks posted by AgentRuntimeService β€” not Upstash workflows.
-app.post('/on-trajectory-complete', onTrajectoryComplete);
-app.post('/on-thread-complete', onThreadComplete);
+app.post('/on-trajectory-complete', qstashAuth(), onTrajectoryComplete);
+app.post('/on-thread-complete', qstashAuth(), onThreadComplete);
export default app;
diff --git a/apps/server/src/router-hono/workflows/index.ts b/apps/server/src/router-hono/workflows/index.ts
index 512278924fe..95ecec28137 100644
--- a/apps/server/src/router-hono/workflows/index.ts
+++ b/apps/server/src/router-hono/workflows/index.ts
@@ -6,6 +6,7 @@ import expertiseHistoryApp from './expertise-history';
import expertiseRejectionApp from './expertise-rejection';
import goalApp from './goal';
import memoryUserMemoryApp from './memory-user-memory';
+import { workflowAuth } from './middlewares/qstashAuth';
import onboardingTaskRecommendationApp from './onboarding-task-recommendation';
import onboardingUnderstandingApp from './onboarding-understanding';
import taskApp from './task';
@@ -16,6 +17,8 @@ import widgetApp from './widget';
const app = new Hono().basePath('/api/workflows');
+app.use('*', workflowAuth());
+
app.route('/agent-eval-run', agentEvalRunApp);
app.route('/agent-signal', agentSignalApp);
app.route('/expertise-history', expertiseHistoryApp);
diff --git a/apps/server/src/router-hono/workflows/middlewares/__tests__/callbackAuth.test.ts b/apps/server/src/router-hono/workflows/middlewares/__tests__/callbackAuth.test.ts
new file mode 100644
index 00000000000..386fe70a661
--- /dev/null
+++ b/apps/server/src/router-hono/workflows/middlewares/__tests__/callbackAuth.test.ts
@@ -0,0 +1,241 @@
+import { createHash } from 'node:crypto';
+
+import { Receiver } from '@upstash/qstash';
+import { Hono } from 'hono';
+import { SignJWT } from 'jose';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { OtelQstashClient, verifyQStashSignature } from '@/libs/qstash';
+import { signInternalCallback } from '@/libs/qstash/internalSignature';
+import { deliverWebhook } from '@/server/services/agentRuntime/hooks/httpWebhook';
+
+import { qstashAuth as agentAuth } from '../../../agent/middlewares/qstashAuth';
+import { qstashAuth, workflowAuth } from '../qstashAuth';
+
+const desktop = vi.hoisted(() => ({ isDesktop: false }));
+vi.mock('@lobechat/const', () => ({
+ get isDesktop() {
+ return desktop.isDesktop;
+ },
+}));
+vi.mock('@lobechat/observability-otel/modules/upstash-workflow', () => ({
+ recordUpstashWorkflowEvent: vi.fn(),
+}));
+
+const url = 'https://app.example/api/workflows/test';
+const body = JSON.stringify({ operationId: 'synthetic-operation' });
+const makeApp = (auth = qstashAuth) =>
+ new Hono().post('*', auth(), async (c) => c.json(await c.req.json()));
+
+describe('callback authentication across HTTP delivery and Hono', () => {
+ beforeEach(() => {
+ vi.stubEnv('NODE_ENV', 'production');
+ vi.stubEnv('QSTASH_CURRENT_SIGNING_KEY', '');
+ vi.stubEnv('QSTASH_NEXT_SIGNING_KEY', '');
+ vi.stubEnv('QSTASH_TOKEN', '');
+ vi.stubEnv('KEY_VAULTS_SECRET', 'synthetic-test-secret');
+ vi.stubEnv('APP_URL', 'https://app.example');
+ vi.stubEnv('INTERNAL_APP_URL', '');
+ desktop.isDesktop = false;
+ });
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+ });
+
+ it.each([
+ ['workflow', qstashAuth],
+ ['agent', agentAuth],
+ ] as const)('rejects unsigned production %s callbacks without signing keys', async (_, auth) => {
+ expect((await makeApp(auth).request(url, { body, method: 'POST' })).status).toBe(401);
+ });
+
+ it.each([
+ ['workflow', qstashAuth],
+ ['agent', agentAuth],
+ ] as const)(
+ 'delivers a signed internal %s notification and preserves its JSON body',
+ async (_, auth) => {
+ const app = makeApp(auth);
+ let payload: unknown;
+ let received: Response | undefined;
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async (target: string, init: RequestInit) => {
+ expect(new Headers(init.headers).get('x-lobe-callback-signature')).toBeTruthy();
+ received = await app.request(target, init);
+ payload = await received.json();
+ return new Response(null, { status: received.status });
+ }),
+ );
+ await deliverWebhook({ url }, JSON.parse(body));
+ expect(received?.status).toBe(200);
+ expect(payload).toEqual(JSON.parse(body));
+ },
+ );
+
+ it('signs the direct fallback with the internal signature when QStash is configured', async () => {
+ vi.stubEnv('QSTASH_CURRENT_SIGNING_KEY', 'current-test-key');
+ vi.stubEnv('QSTASH_NEXT_SIGNING_KEY', 'next-test-key');
+ vi.stubEnv('QSTASH_TOKEN', 'test-token');
+ const publish = vi
+ .spyOn(OtelQstashClient.prototype, 'publishJSON')
+ .mockRejectedValue(new Error('qstash unavailable'));
+ const app = makeApp();
+ let received: Response | undefined;
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async (target: string, init: RequestInit) => {
+ expect(new Headers(init.headers).get('x-lobe-callback-signature')).toBeTruthy();
+ received = await app.request(target, init);
+ return new Response(null, { status: received.status });
+ }),
+ );
+ await deliverWebhook({ delivery: 'qstash', url }, JSON.parse(body));
+ expect(publish).toHaveBeenCalledTimes(1);
+ expect(received?.status).toBe(200);
+ });
+
+ it('does not authenticate callbacks sent to a different origin', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async (target: string, init: RequestInit) => {
+ expect(await verifyQStashSignature(new Request(target, init), body)).toBe(false);
+ return new Response(null, { status: 204 });
+ }),
+ );
+ await deliverWebhook({ url: 'https://other.example/api/workflows/test' }, JSON.parse(body));
+ });
+
+ it.each(['development', 'desktop'])(
+ 'keeps %s callbacks available without QStash',
+ async (mode) => {
+ if (mode === 'development') vi.stubEnv('NODE_ENV', 'development');
+ else desktop.isDesktop = true;
+ expect(await verifyQStashSignature(new Request(url), body)).toBe(true);
+ },
+ );
+
+ it('keeps configured QStash verification and rejects missing or invalid signatures', async () => {
+ vi.stubEnv('QSTASH_CURRENT_SIGNING_KEY', 'current-test-key');
+ vi.stubEnv('QSTASH_NEXT_SIGNING_KEY', 'next-test-key');
+ const verify = vi.spyOn(Receiver.prototype, 'verify').mockResolvedValue(true);
+ expect(
+ await verifyQStashSignature(
+ new Request(url, { headers: { 'Upstash-Signature': 'signed' } }),
+ body,
+ ),
+ ).toBe(true);
+ expect(verify).toHaveBeenCalledWith({ body, signature: 'signed' });
+ expect(await verifyQStashSignature(new Request(url), body)).toBe(false);
+ verify.mockRejectedValue(new Error('invalid signature'));
+ expect(
+ await verifyQStashSignature(
+ new Request(url, { headers: { 'Upstash-Signature': 'bad' } }),
+ body,
+ ),
+ ).toBe(false);
+ });
+ it.each(['current-test-key', 'next-test-key'])(
+ 'accepts real QStash JWTs signed with %s',
+ async (key) => {
+ vi.stubEnv('QSTASH_CURRENT_SIGNING_KEY', 'current-test-key');
+ vi.stubEnv('QSTASH_NEXT_SIGNING_KEY', 'next-test-key');
+ const signature = await new SignJWT({
+ body: createHash('sha256').update(body).digest('base64url'),
+ })
+ .setProtectedHeader({ alg: 'HS256' })
+ .setIssuer('Upstash')
+ .setSubject(url)
+ .setExpirationTime('5m')
+ .sign(new TextEncoder().encode(key));
+ const request = new Request(url, {
+ body,
+ method: 'POST',
+ headers: { 'Upstash-Signature': signature },
+ });
+ expect(await verifyQStashSignature(request, body)).toBe(true);
+ expect(await verifyQStashSignature(request, '{}')).toBe(false);
+ },
+ );
+
+ it('accepts a valid internal signature alongside configured QStash keys', async () => {
+ vi.stubEnv('QSTASH_CURRENT_SIGNING_KEY', 'current-test-key');
+ vi.stubEnv('QSTASH_NEXT_SIGNING_KEY', 'next-test-key');
+ const headers = signInternalCallback(url, body);
+ expect(headers['x-lobe-callback-signature']).toBeTruthy();
+ expect(
+ await verifyQStashSignature(new Request(url, { body, headers, method: 'POST' }), body),
+ ).toBe(true);
+ });
+
+ it.each(['body', 'forged', 'expired'])(
+ 'rejects an internal signature with %s changed when QStash is configured',
+ async (change) => {
+ vi.stubEnv('QSTASH_CURRENT_SIGNING_KEY', 'current-test-key');
+ vi.stubEnv('QSTASH_NEXT_SIGNING_KEY', 'next-test-key');
+ const headers = signInternalCallback(url, body);
+ let content = body;
+ if (change === 'body') content = '{}';
+ if (change === 'forged') {
+ headers['x-lobe-callback-signature'] = `${Date.now()}.${'0'.repeat(64)}`;
+ }
+ if (change === 'expired') vi.spyOn(Date, 'now').mockReturnValue(Date.now() + 301_000);
+ expect(
+ await verifyQStashSignature(
+ new Request(url, { body: content, headers, method: 'POST' }),
+ content,
+ ),
+ ).toBe(false);
+ },
+ );
+
+ it.each(['body', 'path', 'method', 'expired', 'missing-secret', 'malformed', 'partial-qstash'])(
+ 'rejects an internal callback with %s changed',
+ async (change) => {
+ const headers = signInternalCallback(url, body);
+ let target = url;
+ let content = body;
+ let method = 'POST';
+ if (change === 'body') content = '{}';
+ if (change === 'path') target += '-other';
+ if (change === 'method') method = 'PUT';
+ if (change === 'expired') vi.spyOn(Date, 'now').mockReturnValue(Date.now() + 301_000);
+ if (change === 'missing-secret') vi.stubEnv('KEY_VAULTS_SECRET', '');
+ if (change === 'malformed') headers['x-lobe-callback-signature'] = 'invalid';
+ if (change === 'partial-qstash') vi.stubEnv('QSTASH_CURRENT_SIGNING_KEY', 'current-test-key');
+ expect(
+ await verifyQStashSignature(
+ new Request(target, { body: content, headers, method }),
+ content,
+ ),
+ ).toBe(false);
+ },
+ );
+
+ it('guards unsigned SDK workflows and preserves the raw body for authenticated workflows', async () => {
+ const app = new Hono()
+ .use('*', workflowAuth())
+ .post('*', async (c) => c.text(await c.req.raw.text()));
+ expect((await app.request(url, { body, method: 'POST' })).status).toBe(401);
+ const result = await app.request(url, {
+ body,
+ headers: signInternalCallback(url, body),
+ method: 'POST',
+ });
+ expect(result.status).toBe(200);
+ expect(await result.text()).toBe(body);
+ });
+
+ it('leaves configured SDK workflow verification to the SDK', async () => {
+ vi.stubEnv('QSTASH_CURRENT_SIGNING_KEY', 'current-test-key');
+ vi.stubEnv('QSTASH_NEXT_SIGNING_KEY', 'next-test-key');
+ const app = new Hono()
+ .use('*', workflowAuth())
+ .post('*', (c) => c.text('SDK verification boundary'));
+ expect(await (await app.request(url, { body, method: 'POST' })).text()).toBe(
+ 'SDK verification boundary',
+ );
+ });
+});
diff --git a/apps/server/src/router-hono/workflows/middlewares/qstashAuth.ts b/apps/server/src/router-hono/workflows/middlewares/qstashAuth.ts
index 60390148287..967e7fd37b3 100644
--- a/apps/server/src/router-hono/workflows/middlewares/qstashAuth.ts
+++ b/apps/server/src/router-hono/workflows/middlewares/qstashAuth.ts
@@ -11,35 +11,31 @@ const log = debug('lobe-server:workflows:qstash-auth');
* Hono middleware that verifies the `Upstash-Signature` header on incoming
* QStash webhook calls.
*
- * - When `QSTASH_CURRENT_SIGNING_KEY` is unset (dev / electron), verification
- * is skipped β€” matching the existing `verifyQStashSignature` behavior.
+ * - Without QStash keys, production requires a signed internal callback.
+ * Development and Electron retain their local execution behavior.
* - On signature mismatch, returns `401 Invalid signature` and aborts the
* handler chain.
- * - The body is consumed via `c.req.text()` to compute the HMAC; downstream
- * handlers can still call `c.req.json()` because Hono caches across body
- * formats (`bodyCache` cross-converts text ↔ json).
+ * - Read a clone so both Hono handlers and the Workflow SDK can read the body.
*
* Use for one-shot QStash webhook receivers. For Upstash *Workflow* endpoints
* (multi-step `serve()` integrations) use `@upstash/workflow/hono`'s built-in
* verification instead.
*/
export const qstashAuth = (): MiddlewareHandler => async (c, next) => {
- if (process.env.QSTASH_CURRENT_SIGNING_KEY) {
- const rawBody = await c.req.text();
+ const rawBody = await c.req.raw.clone().text();
- const ok = await verifyQStashSignature(c.req.raw, rawBody);
- if (!ok) {
- log('Rejected: invalid QStash signature on %s', c.req.path);
- recordUpstashWorkflowEvent({
- errorType: 'InvalidSignature',
- interface: 'qstash',
- operation: 'serve',
- path: c.req.path,
- status: 'error',
- });
+ const ok = await verifyQStashSignature(c.req.raw, rawBody);
+ if (!ok) {
+ log('Rejected: invalid QStash signature on %s', c.req.path);
+ recordUpstashWorkflowEvent({
+ errorType: 'InvalidSignature',
+ interface: 'qstash',
+ operation: 'serve',
+ path: c.req.path,
+ status: 'error',
+ });
- return c.json({ error: 'Invalid signature' }, 401);
- }
+ return c.json({ error: 'Invalid signature' }, 401);
}
try {
await next();
@@ -62,3 +58,12 @@ export const qstashAuth = (): MiddlewareHandler => async (c, next) => {
throw error;
}
};
+
+/** Keep the SDK's configured verification; guard its unsigned local fallback. */
+export const workflowAuth = (): MiddlewareHandler => async (c, next) => {
+ if (process.env.QSTASH_CURRENT_SIGNING_KEY && process.env.QSTASH_NEXT_SIGNING_KEY) {
+ await next();
+ return;
+ }
+ return qstashAuth()(c, next);
+};
diff --git a/apps/server/src/router-hono/workflows/widget/handlers/tick.ts b/apps/server/src/router-hono/workflows/widget/handlers/tick.ts
index 5a2f0e4db3a..79380019a01 100644
--- a/apps/server/src/router-hono/workflows/widget/handlers/tick.ts
+++ b/apps/server/src/router-hono/workflows/widget/handlers/tick.ts
@@ -39,9 +39,8 @@ interface TickPayload {
* (deduplicated per lease) for that handler to resume; inline, the tick
* claims, resumes and runs itself.
*
- * Trigger a tick by hand against a local server (the script signs the
- * request when `QSTASH_CURRENT_SIGNING_KEY` is set, as `qstashAuth` then
- * requires):
+ * Trigger a tick by hand against a local server (the script signs with the
+ * configured QStash key or the existing vault secret for same-origin calls):
*
* SERVER_URL=http://localhost:3010 bun run widget:tick [--dry-run]
*/
diff --git a/apps/server/src/routers/lambda/__tests__/integration/callbackRequest.ts b/apps/server/src/routers/lambda/__tests__/integration/callbackRequest.ts
new file mode 100644
index 00000000000..ae5e9dc3f90
--- /dev/null
+++ b/apps/server/src/routers/lambda/__tests__/integration/callbackRequest.ts
@@ -0,0 +1,12 @@
+import { signInternalCallback } from '@/libs/qstash/internalSignature';
+
+/** Exercise the real callback authentication with the exact serialized request body. */
+export const signedCallbackRequest = (path: string, payload: unknown) => {
+ const url = new URL(path, process.env.APP_URL).href;
+ const body = JSON.stringify(payload);
+ return new Request(url, {
+ body,
+ headers: { 'content-type': 'application/json', ...signInternalCallback(url, body) },
+ method: 'POST',
+ });
+};
diff --git a/apps/server/src/routers/lambda/__tests__/integration/widget.integration.test.ts b/apps/server/src/routers/lambda/__tests__/integration/widget.integration.test.ts
index 83512574359..75893e9e258 100644
--- a/apps/server/src/routers/lambda/__tests__/integration/widget.integration.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/integration/widget.integration.test.ts
@@ -29,6 +29,7 @@ import { runWidgetSchedulerTick } from '@/server/services/widget/scheduler';
import { dashboardRouter } from '../../dashboard';
import { metricRouter } from '../../metric';
import { widgetRouter } from '../../widget';
+import { signedCallbackRequest } from './callbackRequest';
import { cleanupTestUser, createTestAgent, createTestUser } from './setup';
vi.hoisted(() => {
@@ -100,6 +101,7 @@ describe('widget + dashboard routers integration', () => {
let workspaceId: string;
beforeEach(async () => {
+ vi.stubEnv('APP_URL', 'https://app.test/');
runSandbox.mockReset();
db = await getTestDB();
testDB = db;
@@ -1137,11 +1139,7 @@ describe('widget + dashboard routers integration', () => {
.set({ nextRunAt: new Date(Date.now() - 60_000) })
.where(eq(widgets.id, widget.id));
- const response = await widgetWorkflowApp.request('/tick', {
- body: '{}',
- headers: { 'content-type': 'application/json' },
- method: 'POST',
- });
+ const response = await widgetWorkflowApp.request(signedCallbackRequest('/tick', {}));
const body = await response.json();
expect(body).toMatchObject({
claimed: 1,
@@ -1161,19 +1159,13 @@ describe('widget + dashboard routers integration', () => {
expect(runs).toHaveLength(1);
// The slot moved forward, so an immediate second tick has nothing to do.
- const second = await widgetWorkflowApp.request('/tick', { body: '{}', method: 'POST' });
+ const second = await widgetWorkflowApp.request(signedCallbackRequest('/tick', {}));
expect(await second.json()).toMatchObject({ claimed: 0, due: 0 });
});
describe('dispatch and recovery', () => {
const post = async (path: string, body: unknown) =>
- (
- await widgetWorkflowApp.request(path, {
- body: JSON.stringify(body),
- headers: { 'content-type': 'application/json' },
- method: 'POST',
- })
- ).json();
+ (await widgetWorkflowApp.request(signedCallbackRequest(path, body))).json();
/** A published, scheduled widget whose slot is due. */
const dueWidget = async () => {
diff --git a/apps/server/src/routers/lambda/__tests__/integration/widget.sandboxBusy.integration.test.ts b/apps/server/src/routers/lambda/__tests__/integration/widget.sandboxBusy.integration.test.ts
index 284c2d046a6..9eea8dd0431 100644
--- a/apps/server/src/routers/lambda/__tests__/integration/widget.sandboxBusy.integration.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/integration/widget.sandboxBusy.integration.test.ts
@@ -11,6 +11,7 @@ import { WidgetSandboxError } from '@/server/services/widget/sandbox/types';
import { WIDGET_BUSY_DEFER_DEADLINE_MS } from '@/server/services/widget/sandboxBusy';
import { widgetRouter } from '../../widget';
+import { signedCallbackRequest } from './callbackRequest';
import { cleanupTestUser, createTestUser } from './setup';
let testDB: LobeChatDatabase;
@@ -82,6 +83,8 @@ describe('widget scheduled runs when the sandbox is busy', { timeout: 60_000 },
}, 300_000);
beforeEach(async () => {
+ vi.stubEnv('APP_URL', 'https://app.test/');
+ vi.stubEnv('KEY_VAULTS_SECRET', Buffer.alloc(32, 7).toString('base64'));
runSandbox.mockReset();
db = await getTestDB();
testDB = db;
@@ -96,13 +99,7 @@ describe('widget scheduled runs when the sandbox is busy', { timeout: 60_000 },
});
const post = async (path: string, body: unknown) =>
- (
- await widgetWorkflowApp.request(path, {
- body: JSON.stringify(body),
- headers: { 'content-type': 'application/json' },
- method: 'POST',
- })
- ).json();
+ (await widgetWorkflowApp.request(signedCallbackRequest(path, body))).json();
/** A published, hourly widget whose slot is due. */
const dueWidget = async () => {
diff --git a/apps/server/src/services/agentIdentity/__tests__/mailWake.test.ts b/apps/server/src/services/agentIdentity/__tests__/mailWake.test.ts
index d12e400db22..06b721a1d9a 100644
--- a/apps/server/src/services/agentIdentity/__tests__/mailWake.test.ts
+++ b/apps/server/src/services/agentIdentity/__tests__/mailWake.test.ts
@@ -80,6 +80,7 @@ vi.mock('@/server/services/queue', () => ({
},
}));
+// Isolate mail wake/digest behavior; callbackAuth.test.ts covers real signature validation.
const qstash = vi.hoisted(() => ({ valid: true }));
vi.mock('@/libs/qstash', () => ({ verifyQStashSignature: async () => qstash.valid }));
diff --git a/apps/server/src/services/agentRuntime/hooks/httpWebhook.ts b/apps/server/src/services/agentRuntime/hooks/httpWebhook.ts
index a90aaeeb7c5..1e0f6fd8803 100644
--- a/apps/server/src/services/agentRuntime/hooks/httpWebhook.ts
+++ b/apps/server/src/services/agentRuntime/hooks/httpWebhook.ts
@@ -9,6 +9,7 @@ import { QstashError } from '@upstash/qstash';
import { OtelQstashClient } from '@/libs/qstash';
import { toQStashDeduplicationId } from '@/libs/qstash/deduplicationId';
+import { signInternalCallback } from '@/libs/qstash/internalSignature';
import type { AgentHookWebhook } from './types';
@@ -96,9 +97,11 @@ async function fetchWebhook<T>(
const combinedSignal = signal ? AbortSignal.any([signal, timeout]) : timeout;
try {
combinedSignal.throwIfAborted();
- const response = await fetch(resolveUrl(webhook.url), {
- body: JSON.stringify(payload),
- headers: resolveWebhookHeaders(webhook),
+ const url = resolveUrl(webhook.url);
+ const body = JSON.stringify(payload);
+ const response = await fetch(url, {
+ body,
+ headers: { ...resolveWebhookHeaders(webhook), ...signInternalCallback(url, body) },
method: 'POST',
redirect: 'error',
signal: combinedSignal,
diff --git a/apps/server/src/services/aiAgent/hooks/threadRunHooks.ts b/apps/server/src/services/aiAgent/hooks/threadRunHooks.ts
index 66a097b4638..98340c7035f 100644
--- a/apps/server/src/services/aiAgent/hooks/threadRunHooks.ts
+++ b/apps/server/src/services/aiAgent/hooks/threadRunHooks.ts
@@ -339,23 +339,20 @@ export function createThreadHooks(
}
/**
- * Completion bridge for the server `callSubAgent` deferred-tool path.
- *
- * Fires on the sub-op's completion (success or failure) and delegates to
- * `AgentRuntimeService.completeSubAgentBridge`: backfill the parent's
- * placeholder tool message, then barrier-check + CAS-resume the parked
- * parent op.
- *
- * Transport adapts to the runtime mode like every other lifecycle hook:
- * - local mode: the `handler` runs in-process with the child's finalState.
- * - queue mode: in-memory handlers don't survive cross-process steps, so
- * the serialized `webhook` config is delivered via QStash to
- * `/api/agent/webhooks/subagent-callback`, which re-enters the same
- * bridge method. `delivery: 'qstash'` is required β€” a plain fetch would
-
-
- * be rejected by the endpoint's QStash signature auth.
- */
+ * Completion bridge for the server `callSubAgent` deferred-tool path.
+ *
+ * Fires on the sub-op's completion (success or failure) and delegates to
+ * `AgentRuntimeService.completeSubAgentBridge`: backfill the parent's
+ * placeholder tool message, then barrier-check + CAS-resume the parked
+ * parent op.
+ *
+ * Transport adapts to the runtime mode like every other lifecycle hook:
+ * - local mode: the `handler` runs in-process with the child's finalState.
+ * - queue mode: in-memory handlers don't survive cross-process steps, so
+ * the serialized `webhook` config is delivered via QStash to
+ * `/api/agent/webhooks/subagent-callback`, which re-enters the same
+ * bridge method.
+ */
export function createSubAgentBridgeHook(
agentRuntimeService: AgentRuntimeService,
parentOperationId: string,
@@ -392,9 +389,8 @@ export function createSubAgentBridgeHook(
// answer (`lastAssistantContent`) β€” and any tool-produced attachments
// the shared lifecycle event extractor inlines β€” through QStash.
eventFields: ['operationId', 'reason', 'status'],
- // The endpoint sits behind QStash signature auth, so the unsigned
- // fetch fallback could never authenticate β€” it would only mask a
- // publish failure as a silently-dropped 401, stranding the parent.
+ // A failed publish must surface instead of stranding the parent, so this
+ // critical bridge does not rely on the direct fetch fallback.
fallback: 'none' as const,
url: '/api/agent/webhooks/subagent-callback',
},
diff --git a/scripts/widgetTick/index.mts b/scripts/widgetTick/index.mts
index b7aaad9aace..993dd1f58b4 100644
--- a/scripts/widgetTick/index.mts
+++ b/scripts/widgetTick/index.mts
@@ -6,12 +6,13 @@
* bun run widget:tick --dry-run # only report how many are due
* SERVER_URL=http://localhost:3011 bun run widget:tick
*
- * When QSTASH_CURRENT_SIGNING_KEY is set the route verifies signatures, so the
- * request is signed with that key the way QStash would; otherwise it is sent
- * unsigned, which the route accepts.
+ * With QStash configured, sign with its current key. Otherwise use the existing
+ * vault secret for same-origin callbacks; unsigned requests are development-only.
*/
import { createHash, createHmac, randomUUID } from 'node:crypto';
+import { signInternalCallback } from '../../src/libs/qstash/internalSignature';
+
const serverUrl = (
process.env.SERVER_URL ||
process.env.APP_URL ||
@@ -46,9 +47,10 @@ const response = await fetch(url, {
body,
headers: {
'content-type': 'application/json',
- ...(signingKey && { 'Upstash-Signature': sign(signingKey) }),
+ ...(signingKey ? { 'Upstash-Signature': sign(signingKey) } : signInternalCallback(url, body)),
},
method: 'POST',
+ redirect: 'error',
});
console.log(`POST ${url} β†’ ${response.status}${signingKey ? ' (signed)' : ''}`);
diff --git a/src/libs/qstash/index.ts b/src/libs/qstash/index.ts
index ac71484a976..2d01dae7ede 100644
--- a/src/libs/qstash/index.ts
+++ b/src/libs/qstash/index.ts
@@ -1,9 +1,12 @@
+import { isDesktop } from '@lobechat/const';
import { recordUpstashWorkflowEvent } from '@lobechat/observability-otel/modules/upstash-workflow';
import { errorNameFrom } from '@lobechat/utils';
import { Client, type PublishRequest, type PublishResponse, Receiver } from '@upstash/qstash';
import { Client as WorkflowClient, type TriggerOptions } from '@upstash/workflow';
import debug from 'debug';
+import { verifyInternalCallback } from './internalSignature';
+
const log = debug('lobe-server:qstash');
export { toQStashDeduplicationId } from './deduplicationId';
@@ -154,29 +157,35 @@ export const workflowClient = new OtelWorkflowClient({
/**
* Verify QStash signature using Receiver.
- * Returns true if signing keys are not configured (verification skipped) or signature is valid.
+ * Without QStash keys, only development, Electron or signed internal callbacks are allowed.
+ * With complete QStash keys, either a valid QStash signature or a valid internal callback
+ * signature is accepted, so the direct HTTP fallback after a publish failure still works.
*/
export async function verifyQStashSignature(request: Request, rawBody: string): Promise<boolean> {
const currentSigningKey = process.env.QSTASH_CURRENT_SIGNING_KEY;
const nextSigningKey = process.env.QSTASH_NEXT_SIGNING_KEY;
if (!currentSigningKey || !nextSigningKey) {
- log('QStash signature verification disabled (no signing keys configured)');
- return false;
+ // A partial QStash configuration must not enable a local authentication fallback.
+ if (currentSigningKey || nextSigningKey) return false;
+ if (process.env.NODE_ENV === 'development' || isDesktop) return true;
+ return verifyInternalCallback(request, rawBody);
}
const signature = request.headers.get('Upstash-Signature');
- if (!signature) {
+ if (signature) {
+ const receiver = new Receiver({ currentSigningKey, nextSigningKey });
+
+ try {
+ if (await receiver.verify({ body: rawBody, signature })) return true;
+ } catch (error) {
+ log('QStash signature verification failed: %O', error);
+ }
+ } else {
log('Missing Upstash-Signature header');
- return false;
}
- const receiver = new Receiver({ currentSigningKey, nextSigningKey });
-
- try {
- return await receiver.verify({ body: rawBody, signature });
- } catch (error) {
- log('QStash signature verification failed: %O', error);
- return false;
- }
+ // QStash publish failures fall back to a direct HTTP callback, which is signed
+ // with the internal scheme. Either authentication method is sufficient.
+ return verifyInternalCallback(request, rawBody);
}
diff --git a/src/libs/qstash/internalSignature.ts b/src/libs/qstash/internalSignature.ts
new file mode 100644
index 00000000000..92c9ec896d6
--- /dev/null
+++ b/src/libs/qstash/internalSignature.ts
@@ -0,0 +1,57 @@
+import { createHmac, timingSafeEqual } from 'node:crypto';
+
+const SIGNATURE_HEADER = 'x-lobe-callback-signature';
+const MAX_AGE_MS = 5 * 60 * 1000;
+
+function signatureFor(
+ secret: string,
+ url: string,
+ method: string,
+ body: string,
+ timestamp: string,
+) {
+ // Separate callback authentication from other uses of the vault secret.
+ const key = createHmac('sha256', secret).update('lobehub:internal-callback:v1').digest();
+ const { pathname, search } = new URL(url);
+ return createHmac('sha256', key)
+ .update(JSON.stringify([timestamp, method, pathname + search, body]))
+ .digest('hex');
+}
+
+/**
+ * Sign same-origin callbacks with the internal scheme. This also authenticates the
+ * direct HTTP fallback used when publishing a callback to QStash fails.
+ */
+export function signInternalCallback(url: string, body: string): Record<string, string> {
+ const secret = process.env.KEY_VAULTS_SECRET;
+ if (!secret) return {};
+
+ const origin = new URL(url).origin;
+ const isApplicationOrigin = [process.env.INTERNAL_APP_URL, process.env.APP_URL].some((base) => {
+ if (!base) return false;
+ try {
+ return new URL(base).origin === origin;
+ } catch {
+ return false;
+ }
+ });
+ if (!isApplicationOrigin) return {};
+
+ const timestamp = String(Date.now());
+ return {
+ [SIGNATURE_HEADER]: `${timestamp}.${signatureFor(secret, url, 'POST', body, timestamp)}`,
+ };
+}
+
+/** Validate the body, method, destination path and freshness without exposing the vault secret. */
+export function verifyInternalCallback(request: Request, body: string): boolean {
+ const secret = process.env.KEY_VAULTS_SECRET;
+ const signature = request.headers.get(SIGNATURE_HEADER);
+ if (!secret || !signature) return false;
+ const match = /^(\d{13})\.([a-f0-9]{64})$/.exec(signature);
+ if (!match) return false;
+ const [, timestamp, mac] = match;
+ if (Math.abs(Date.now() - Number(timestamp)) > MAX_AGE_MS) return false;
+ const expected = signatureFor(secret, request.url, request.method, body, timestamp);
+ return timingSafeEqual(Buffer.from(mac, 'hex'), Buffer.from(expected, 'hex'));
+}