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.

✨ feat: add signOperationJwt with 4h expiry for hetero-agent operations (#14586)

LiJian95f41f8cece9
diff --git a/src/libs/oidc-provider/jwt.ts b/src/libs/oidc-provider/jwt.ts
index fff9d85ba8b..b014a7c3747 100644
--- a/src/libs/oidc-provider/jwt.ts
+++ b/src/libs/oidc-provider/jwt.ts
@@ -138,6 +138,7 @@ export const validateOIDCJWT = async (token: string) => {
exp: payload.exp,
iat: payload.iat,
jti: payload.jti,
+ purpose: payload.purpose as string | undefined,
scope: payload.scope,
sub: userId,
},
diff --git a/src/libs/trpc/lambda/index.ts b/src/libs/trpc/lambda/index.ts
index ad4007a2526..6d03786ce4d 100644
--- a/src/libs/trpc/lambda/index.ts
+++ b/src/libs/trpc/lambda/index.ts
@@ -11,6 +11,7 @@
import { openTelemetry } from '../middleware/openTelemetry';
import { userAuth } from '../middleware/userAuth';
import { trpc } from './init';
+import { heteroOperationAuth } from './middleware/heteroOperationAuth';
import { oidcAuth } from './middleware/oidcAuth';
/**
@@ -30,6 +31,9 @@ export const publicProcedure = baseProcedure;
// procedure that asserts that the user is logged in
export const authedProcedure = baseProcedure.use(oidcAuth).use(userAuth);
+// procedure for hetero-agent ingest/finish endpoints β€” requires a `hetero-operation` JWT
+export const heteroAuthedProcedure = baseProcedure.use(heteroOperationAuth).use(userAuth);
+
/**
* Create a server-side caller
* @link https://trpc.io/docs/v11/server/server-side-calls
diff --git a/src/libs/trpc/lambda/middleware/__tests__/heteroOperationAuth.test.ts b/src/libs/trpc/lambda/middleware/__tests__/heteroOperationAuth.test.ts
new file mode 100644
index 00000000000..4f577591287
--- /dev/null
+++ b/src/libs/trpc/lambda/middleware/__tests__/heteroOperationAuth.test.ts
@@ -0,0 +1,52 @@
+import { TRPCError } from '@trpc/server';
+import { describe, expect, it } from 'vitest';
+
+import { createCallerFactory } from '@/libs/trpc/lambda';
+import { trpc } from '@/libs/trpc/lambda/init';
+
+import { heteroOperationAuth } from '../heteroOperationAuth';
+
+// Minimal router that exercises heteroOperationAuth
+const testRouter = trpc.router({
+ ping: trpc.procedure.use(heteroOperationAuth).query(({ ctx }) => ctx.userId),
+});
+
+const createCaller = createCallerFactory(testRouter);
+
+describe('heteroOperationAuth middleware', () => {
+ it('passes through and exposes userId when purpose is hetero-operation', async () => {
+ const caller = createCaller({
+ oidcAuth: { purpose: 'hetero-operation', sub: 'user-abc' },
+ } as any);
+
+ const result = await caller.ping();
+
+ expect(result).toBe('user-abc');
+ });
+
+ it('rejects when oidcAuth is absent', async () => {
+ const caller = createCaller({} as any);
+
+ await expect(caller.ping()).rejects.toMatchObject({
+ code: 'UNAUTHORIZED',
+ });
+ });
+
+ it('rejects a cli-sandbox token (wrong purpose)', async () => {
+ const caller = createCaller({
+ oidcAuth: { purpose: 'cli-sandbox', sub: 'user-abc' },
+ } as any);
+
+ await expect(caller.ping()).rejects.toMatchObject({
+ code: 'UNAUTHORIZED',
+ });
+ });
+
+ it('rejects when purpose is undefined', async () => {
+ const caller = createCaller({
+ oidcAuth: { sub: 'user-abc' },
+ } as any);
+
+ await expect(caller.ping()).rejects.toThrow(TRPCError);
+ });
+});
diff --git a/src/libs/trpc/lambda/middleware/__tests__/oidcAuth.test.ts b/src/libs/trpc/lambda/middleware/__tests__/oidcAuth.test.ts
new file mode 100644
index 00000000000..7091f635891
--- /dev/null
+++ b/src/libs/trpc/lambda/middleware/__tests__/oidcAuth.test.ts
@@ -0,0 +1,55 @@
+import { TRPCError } from '@trpc/server';
+import { describe, expect, it } from 'vitest';
+
+import { createCallerFactory } from '@/libs/trpc/lambda';
+import { trpc } from '@/libs/trpc/lambda/init';
+
+import { oidcAuth } from '../oidcAuth';
+
+// Minimal router that exercises oidcAuth
+const testRouter = trpc.router({
+ ping: trpc.procedure.use(oidcAuth).query(({ ctx }) => ctx.userId ?? null),
+});
+
+const createCaller = createCallerFactory(testRouter);
+
+describe('oidcAuth middleware', () => {
+ it('sets userId from sub when oidcAuth is a normal token', async () => {
+ const caller = createCaller({
+ oidcAuth: { purpose: 'cli-sandbox', sub: 'user-abc' },
+ } as any);
+
+ const result = await caller.ping();
+
+ expect(result).toBe('user-abc');
+ });
+
+ it('sets userId when oidcAuth has no purpose field (standard OIDC token)', async () => {
+ const caller = createCaller({
+ oidcAuth: { sub: 'user-abc' },
+ } as any);
+
+ const result = await caller.ping();
+
+ expect(result).toBe('user-abc');
+ });
+
+ it('passes through with null userId when oidcAuth is absent', async () => {
+ const caller = createCaller({} as any);
+
+ const result = await caller.ping();
+
+ expect(result).toBeNull();
+ });
+
+ it('rejects hetero-operation tokens to block misuse on normal authed routes', async () => {
+ const caller = createCaller({
+ oidcAuth: { purpose: 'hetero-operation', sub: 'user-abc' },
+ } as any);
+
+ await expect(caller.ping()).rejects.toThrow(TRPCError);
+ await expect(caller.ping()).rejects.toMatchObject({
+ code: 'UNAUTHORIZED',
+ });
+ });
+});
diff --git a/src/libs/trpc/lambda/middleware/heteroOperationAuth.ts b/src/libs/trpc/lambda/middleware/heteroOperationAuth.ts
new file mode 100644
index 00000000000..103d5272eb1
--- /dev/null
+++ b/src/libs/trpc/lambda/middleware/heteroOperationAuth.ts
@@ -0,0 +1,25 @@
+import { TRPCError } from '@trpc/server';
+
+import { trpc } from '../init';
+
+/**
+ * Auth middleware for hetero-agent ingest/finish endpoints.
+ * Accepts ONLY tokens signed with `purpose: 'hetero-operation'` (4h expiry).
+ * All other tokens β€” including normal user OIDC tokens β€” are rejected,
+ * so this procedure cannot be called from the browser or CLI without the
+ * dedicated operation JWT issued by execAgent.
+ */
+export const heteroOperationAuth = trpc.middleware(async (opts) => {
+ const { ctx, next } = opts;
+
+ if (!ctx.oidcAuth || ctx.oidcAuth.purpose !== 'hetero-operation') {
+ throw new TRPCError({
+ code: 'UNAUTHORIZED',
+ message: 'This endpoint requires a hetero-operation token',
+ });
+ }
+
+ return next({
+ ctx: { oidcAuth: ctx.oidcAuth, userId: ctx.oidcAuth.sub as string },
+ });
+});
diff --git a/src/libs/trpc/lambda/middleware/index.ts b/src/libs/trpc/lambda/middleware/index.ts
index 9f2b92f53b5..17f284454f7 100644
--- a/src/libs/trpc/lambda/middleware/index.ts
+++ b/src/libs/trpc/lambda/middleware/index.ts
@@ -1,3 +1,4 @@
+export * from './heteroOperationAuth';
export * from './marketSDK';
export * from './marketUserInfo';
export * from './serverDatabase';
diff --git a/src/libs/trpc/lambda/middleware/oidcAuth.ts b/src/libs/trpc/lambda/middleware/oidcAuth.ts
index 3fa1259cb7e..1fee5184ce0 100644
--- a/src/libs/trpc/lambda/middleware/oidcAuth.ts
+++ b/src/libs/trpc/lambda/middleware/oidcAuth.ts
@@ -1,3 +1,5 @@
+import { TRPCError } from '@trpc/server';
+
import { trpc } from '../init';
export const oidcAuth = trpc.middleware(async (opts) => {
@@ -5,6 +7,16 @@ export const oidcAuth = trpc.middleware(async (opts) => {
// Check OIDC authentication
if (ctx.oidcAuth) {
+ // hetero-operation tokens are long-lived (4h) and scoped exclusively to
+ // heteroIngest / heteroFinish. Reject them here so a leaked sandbox JWT
+ // cannot be replayed against any other authed route.
+ if (ctx.oidcAuth.purpose === 'hetero-operation') {
+ throw new TRPCError({
+ code: 'UNAUTHORIZED',
+ message: 'hetero-operation tokens are not accepted on this endpoint',
+ });
+ }
+
return next({
ctx: { oidcAuth: ctx.oidcAuth, userId: ctx.oidcAuth.sub },
});
diff --git a/src/libs/trpc/utils/__tests__/internalJwt.test.ts b/src/libs/trpc/utils/__tests__/internalJwt.test.ts
new file mode 100644
index 00000000000..ddf39f89a49
--- /dev/null
+++ b/src/libs/trpc/utils/__tests__/internalJwt.test.ts
@@ -0,0 +1,154 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+// Must mock authEnv before importing the module under test so getJwksKey() resolves.
+vi.mock('@/envs/auth', () => ({
+ authEnv: {
+ INTERNAL_JWT_EXPIRATION: '30s',
+ JWKS_KEY: JSON.stringify({
+ keys: [
+ {
+ alg: 'RS256',
+ d: 'private-d',
+ dp: 'private-dp',
+ dq: 'private-dq',
+ e: 'AQAB',
+ kid: 'test-kid',
+ kty: 'RSA',
+ n: 'test-modulus',
+ p: 'private-p',
+ q: 'private-q',
+ qi: 'private-qi',
+ use: 'sig',
+ },
+ ],
+ }),
+ },
+}));
+
+// Mock jose so we never need real RSA keys.
+// SignJWT is a class with a fluent builder API β€” every setter must return `this`
+// so the chain (.setProtectedHeader().setSubject()…) doesn't break.
+const signMock = vi.fn().mockResolvedValue('signed.jwt.token');
+const setExpirationTimeMock = vi.fn();
+const setIssuedAtMock = vi.fn();
+const setSubjectMock = vi.fn();
+const setProtectedHeaderMock = vi.fn();
+
+const buildSignJWTChain = () => {
+ const chain = {
+ setExpirationTime: setExpirationTimeMock.mockReturnValue(undefined as any),
+ setIssuedAt: setIssuedAtMock.mockReturnValue(undefined as any),
+ setProtectedHeader: setProtectedHeaderMock.mockReturnValue(undefined as any),
+ setSubject: setSubjectMock.mockReturnValue(undefined as any),
+ sign: signMock,
+ };
+ // Make every setter return the same chain object so .method().method() works.
+ setProtectedHeaderMock.mockReturnValue(chain);
+ setSubjectMock.mockReturnValue(chain);
+ setIssuedAtMock.mockReturnValue(chain);
+ setExpirationTimeMock.mockReturnValue(chain);
+ return chain;
+};
+
+const SignJWTMock = vi.fn();
+const importJWKMock = vi.fn().mockResolvedValue('mock-crypto-key');
+
+vi.mock('jose', () => ({
+ SignJWT: SignJWTMock,
+ importJWK: (...args: unknown[]) => importJWKMock(...args),
+ jwtVerify: vi.fn(),
+}));
+
+describe('internalJwt', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ importJWKMock.mockResolvedValue('mock-crypto-key');
+ signMock.mockResolvedValue('signed.jwt.token');
+ SignJWTMock.mockImplementation(() => buildSignJWTChain());
+ });
+
+ describe('signUserJWT', () => {
+ it('signs a JWT with 5-minute expiry and cli-sandbox purpose', async () => {
+ const { signUserJWT } = await import('../internalJwt');
+
+ const token = await signUserJWT('user-123');
+
+ expect(token).toBe('signed.jwt.token');
+ expect(SignJWTMock).toHaveBeenCalledWith({ purpose: 'cli-sandbox' });
+ expect(setSubjectMock).toHaveBeenCalledWith('user-123');
+ expect(setExpirationTimeMock).toHaveBeenCalledWith('5m');
+ expect(signMock).toHaveBeenCalledWith('mock-crypto-key');
+ });
+
+ it('sets the protected header with RS256 and the key id', async () => {
+ const { signUserJWT } = await import('../internalJwt');
+
+ await signUserJWT('user-abc');
+
+ expect(setProtectedHeaderMock).toHaveBeenCalledWith({ alg: 'RS256', kid: 'test-kid' });
+ });
+
+ it('calls setIssuedAt to stamp the creation time', async () => {
+ const { signUserJWT } = await import('../internalJwt');
+
+ await signUserJWT('user-abc');
+
+ expect(setIssuedAtMock).toHaveBeenCalled();
+ });
+ });
+
+ describe('signOperationJwt', () => {
+ it('signs a JWT with 4-hour expiry and hetero-operation purpose', async () => {
+ const { signOperationJwt } = await import('../internalJwt');
+
+ const token = await signOperationJwt('user-456');
+
+ expect(token).toBe('signed.jwt.token');
+ expect(SignJWTMock).toHaveBeenCalledWith({ purpose: 'hetero-operation' });
+ expect(setSubjectMock).toHaveBeenCalledWith('user-456');
+ expect(setExpirationTimeMock).toHaveBeenCalledWith('4h');
+ expect(signMock).toHaveBeenCalledWith('mock-crypto-key');
+ });
+
+ it('sets the protected header with RS256 and the key id', async () => {
+ const { signOperationJwt } = await import('../internalJwt');
+
+ await signOperationJwt('user-456');
+
+ expect(setProtectedHeaderMock).toHaveBeenCalledWith({ alg: 'RS256', kid: 'test-kid' });
+ });
+
+ it('calls setIssuedAt to stamp the creation time', async () => {
+ const { signOperationJwt } = await import('../internalJwt');
+
+ await signOperationJwt('user-456');
+
+ expect(setIssuedAtMock).toHaveBeenCalled();
+ });
+
+ it('uses a longer expiry than signUserJWT (4h vs 5m)', async () => {
+ const { signOperationJwt, signUserJWT } = await import('../internalJwt');
+
+ await signUserJWT('user-a');
+ const userExpiry = setExpirationTimeMock.mock.calls.at(-1)?.[0];
+
+ await signOperationJwt('user-b');
+ const opExpiry = setExpirationTimeMock.mock.calls.at(-1)?.[0];
+
+ expect(userExpiry).toBe('5m');
+ expect(opExpiry).toBe('4h');
+ });
+ });
+
+ describe('signInternalJWT', () => {
+ it('signs a JWT with the internal purpose from env expiry', async () => {
+ const { signInternalJWT } = await import('../internalJwt');
+
+ const token = await signInternalJWT();
+
+ expect(token).toBe('signed.jwt.token');
+ expect(SignJWTMock).toHaveBeenCalledWith({ purpose: 'lobe-internal-call' });
+ expect(setExpirationTimeMock).toHaveBeenCalledWith('30s');
+ });
+ });
+});
diff --git a/src/libs/trpc/utils/internalJwt.ts b/src/libs/trpc/utils/internalJwt.ts
index 7a7eb42a249..e140a17e75e 100644
--- a/src/libs/trpc/utils/internalJwt.ts
+++ b/src/libs/trpc/utils/internalJwt.ts
@@ -95,6 +95,22 @@ export const signUserJWT = async (userId: string): Promise<string> => {
.sign(key);
};
+/**
+ * Sign a long-lived OIDC-compatible JWT for hetero-agent operations.
+ * Claude Code / Codex tasks can run for hours; this 4-hour token prevents
+ * heteroIngest / heteroFinish from returning 401 mid-execution.
+ */
+export const signOperationJwt = async (userId: string): Promise<string> => {
+ const { key, kid } = await getSigningKey();
+
+ return new SignJWT({ purpose: 'hetero-operation' })
+ .setProtectedHeader({ alg: 'RS256', kid })
+ .setSubject(userId)
+ .setIssuedAt()
+ .setExpirationTime('4h')
+ .sign(key);
+};
+
/**
* Validate internal JWT from lambda β†’ async calls
* Returns true if valid, false otherwise
diff --git a/src/server/routers/lambda/__tests__/aiAgent.heteroIngest.test.ts b/src/server/routers/lambda/__tests__/aiAgent.heteroIngest.test.ts
index 609eb502fc6..0f0388606ce 100644
--- a/src/server/routers/lambda/__tests__/aiAgent.heteroIngest.test.ts
+++ b/src/server/routers/lambda/__tests__/aiAgent.heteroIngest.test.ts
@@ -61,7 +61,12 @@ describe('aiAgentRouter.heteroIngest / heteroFinish', () => {
vi.clearAllMocks();
});
- const createCaller = () => aiAgentRouter.createCaller({ userId, jwtPayload: { userId } } as any);
+ const createCaller = () =>
+ aiAgentRouter.createCaller({
+ jwtPayload: { userId },
+ oidcAuth: { purpose: 'hetero-operation', sub: userId },
+ userId,
+ } as any);
describe('heteroIngest', () => {
it('delegates the batch to HeterogeneousAgentService and acks', async () => {
diff --git a/src/server/routers/lambda/aiAgent.ts b/src/server/routers/lambda/aiAgent.ts
index 7c8cd968c95..db90c5d95ab 100644
--- a/src/server/routers/lambda/aiAgent.ts
+++ b/src/server/routers/lambda/aiAgent.ts
@@ -11,7 +11,7 @@ import { z } from 'zod';
import { MessageModel } from '@/database/models/message';
import { ThreadModel } from '@/database/models/thread';
import { TopicModel } from '@/database/models/topic';
-import { authedProcedure, router } from '@/libs/trpc/lambda';
+import { authedProcedure, heteroAuthedProcedure, router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
import { AgentRuntimeService } from '@/server/services/agentRuntime';
import { AiAgentService } from '@/server/services/aiAgent';
@@ -411,6 +411,19 @@ const aiAgentProcedure = authedProcedure.use(serverDatabase).use(async (opts) =>
});
});
+// Dedicated procedure for hetero-agent ingest/finish endpoints.
+// Requires a `hetero-operation` JWT (4h expiry) β€” normal user tokens are rejected,
+// so only the sandbox/device that received the JWT from execAgent can call these.
+const heteroAgentProcedure = heteroAuthedProcedure.use(serverDatabase).use(async (opts) => {
+ const { ctx } = opts;
+
+ return opts.next({
+ ctx: {
+ heterogeneousAgentService: new HeterogeneousAgentService(ctx.serverDB, ctx.userId),
+ },
+ });
+});
+
export const aiAgentRouter = router({
/**
* Create Thread for client-side task execution in Group mode
@@ -1226,7 +1239,7 @@ export const aiAgentRouter = router({
* existing stream fanout so renderer-side gateway WS subscribers see them
* unchanged. Phase 2a: pub/sub only β€” no DB persistence (phase 2b adds it).
*/
- heteroIngest: aiAgentProcedure.input(HeteroIngestSchema).mutation(async ({ input, ctx }) => {
+ heteroIngest: heteroAgentProcedure.input(HeteroIngestSchema).mutation(async ({ input, ctx }) => {
const { agentType, events, operationId, topicId } = input;
log(
@@ -1264,7 +1277,7 @@ export const aiAgentRouter = router({
* `agent_runtime_end` so renderer subscribers can shut down even when the
* CLI's own end-event was lost mid-flight.
*/
- heteroFinish: aiAgentProcedure.input(HeteroFinishSchema).mutation(async ({ input, ctx }) => {
+ heteroFinish: heteroAgentProcedure.input(HeteroFinishSchema).mutation(async ({ input, ctx }) => {
const { agentType, error, operationId, result, sessionId, topicId } = input;
log('heteroFinish: topic=%s op=%s type=%s result=%s', topicId, operationId, agentType, result);
diff --git a/src/server/services/aiAgent/index.ts b/src/server/services/aiAgent/index.ts
index 00940b3c763..0aadc014504 100644
--- a/src/server/services/aiAgent/index.ts
+++ b/src/server/services/aiAgent/index.ts
@@ -53,7 +53,7 @@ import { UserModel } from '@/database/models/user';
import { UserPersonaModel } from '@/database/models/userMemory/persona';
import { toolsEnv } from '@/envs/tools';
import { shouldEnableBuiltinSkill } from '@/helpers/skillFilters';
-import { signUserJWT } from '@/libs/trpc/utils/internalJwt';
+import { signOperationJwt, signUserJWT } from '@/libs/trpc/utils/internalJwt';
import type { EvalContext, ServerAgentToolsContext } from '@/server/modules/Mecha';
import { createServerAgentToolsEngine } from '@/server/modules/Mecha';
import type { ServerUserMemoryConfig } from '@/server/modules/Mecha/ContextEngineering/types';
@@ -674,7 +674,7 @@ export class AiAgentService {
// heteroIngest / heteroFinish without full user credentials.
let operationJwt: string;
try {
- operationJwt = await signUserJWT(this.userId);
+ operationJwt = await signOperationJwt(this.userId);
} catch (err) {
log('execAgent: failed to sign operation JWT for hetero run: %O', err);
throw new Error('Failed to sign operation JWT for hetero agent', { cause: err });