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(gateway): send op meta on init and issue user-level gateway tokens (#19556)

Arvin Xu7222bf648e02
diff --git a/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts b/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts
index 2a9ad096bf1..d2cf17c8206 100644
--- a/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts
+++ b/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts
@@ -26,6 +26,47 @@ const log = debug('lobe-server:agent-runtime:gateway-notifier');
const POST_TIMEOUT = 5000; // 5s per request
const MAX_INFLIGHT = 20; // bounded concurrency
+/**
+ * Op-routing fields the Gateway persists from `init` (protocol v2 Β§3.2) so the
+ * per-user hub can describe an operation in `op_lifecycle` without the client
+ * knowing the op up front. Order is the wire order; nothing else is sent.
+ */
+const GATEWAY_INIT_META_KEYS = [
+ 'topicId',
+ 'threadId',
+ 'agentId',
+ 'groupId',
+ 'taskId',
+ 'scope',
+ 'parentOperationId',
+ 'mirrorToOperationId',
+ 'rootOperationId',
+] as const;
+
+export type GatewayInitMeta = Partial<Record<(typeof GATEWAY_INIT_META_KEYS)[number], string>>;
+
+/**
+ * Pick the `init` metadata from whatever the caller already passed as the
+ * initial state β€” no lookups. Callers differ in what they know
+ * (`AgentRuntimeCoordinator` passes the Redis op metadata, hetero dispatch
+ * passes `{ agentId, topicId, mirrorToOperationId, ... }`), so only string
+ * fields that are actually present make it onto the wire. Returns `undefined`
+ * when nothing applies so legacy inits carry no `meta` key at all.
+ */
+export const pickGatewayInitMeta = (initialState: unknown): GatewayInitMeta | undefined => {
+ if (!initialState || typeof initialState !== 'object') return undefined;
+
+ const source = initialState as Record<string, unknown>;
+ const meta: GatewayInitMeta = {};
+
+ for (const key of GATEWAY_INIT_META_KEYS) {
+ const value = source[key];
+ if (typeof value === 'string' && value) meta[key] = value;
+ }
+
+ return Object.keys(meta).length > 0 ? meta : undefined;
+};
+
/**
* Decorator that wraps an IStreamEventManager and additionally pushes events
* to the Agent Gateway via HTTP. Runtime init is an awaited ordering barrier;
@@ -181,9 +222,13 @@ export class GatewayStreamNotifier implements IStreamEventManager {
// registered here. `streamOwnerUserId` (shared-agent visitor runs) takes
// precedence: the op executes as the creator, but only the visitor may
// subscribe to its stream.
+ // `meta` (protocol v2) lets the per-user hub describe the op in its
+ // lifecycle feed; v1 gateways ignore the extra key.
+ const meta = pickGatewayInitMeta(initialState);
await this.httpPostAwait('/api/operations/init', {
operationId,
userId: initialState?.streamOwnerUserId || initialState?.userId || 'unknown',
+ ...(meta ? { meta } : {}),
});
} catch (error) {
log('Gateway /api/operations/init failed: %O', error);
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.ts
index ceb9003f974..52e8b3b6568 100644
--- a/apps/server/src/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.ts
+++ b/apps/server/src/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.ts
@@ -160,6 +160,91 @@ describe('GatewayStreamNotifier', () => {
expect(urls).toContain(`${gatewayUrl}/api/operations/push-event`);
});
+ // Protocol v2 Β§3.2: the per-user hub describes an op in its lifecycle feed
+ // from the `meta` persisted at init, so the routing fields the caller
+ // already knows must ride along β€” and nothing else (no lookups, no
+ // agentConfig / modelRuntimeConfig leakage into the gateway).
+ it('sends only the known op-routing fields as `meta` in the init body', async () => {
+ await notifier.publishAgentRuntimeInit('op-1', {
+ agentConfig: { systemRole: 'secret' },
+ agentId: 'agt_1',
+ groupId: 'grp_1',
+ mirrorToOperationId: 'op-supervisor',
+ modelRuntimeConfig: { model: 'gpt' },
+ parentOperationId: 'op-parent',
+ rootOperationId: 'op-root',
+ scope: 'group',
+ taskId: 'task_1',
+ threadId: 'thr_1',
+ topicId: 'tpc_1',
+ userId: 'user-1',
+ workspaceId: 'ws_1',
+ });
+
+ const initCall = mockFetch.mock.calls.find(
+ (call: any[]) => call[0] === `${gatewayUrl}/api/operations/init`,
+ )!;
+ expect(JSON.parse(initCall[1].body)).toEqual({
+ meta: {
+ agentId: 'agt_1',
+ groupId: 'grp_1',
+ mirrorToOperationId: 'op-supervisor',
+ parentOperationId: 'op-parent',
+ rootOperationId: 'op-root',
+ scope: 'group',
+ taskId: 'task_1',
+ threadId: 'thr_1',
+ topicId: 'tpc_1',
+ },
+ operationId: 'op-1',
+ userId: 'user-1',
+ });
+ });
+
+ it('omits absent meta keys, and the whole `meta` when nothing applies', async () => {
+ // Hetero dispatch shape: only agentId / topicId / (optional) mirror known.
+ await notifier.publishAgentRuntimeInit('op-hetero', {
+ agentId: 'agt_1',
+ mirrorToOperationId: undefined,
+ topicId: 'tpc_1',
+ userId: 'user-1',
+ });
+ // Legacy / minimal init (what the coordinator's Redis metadata yields
+ // for a plain single-agent run).
+ await notifier.publishAgentRuntimeInit('op-legacy', { userId: 'user-1' });
+
+ const bodies = mockFetch.mock.calls
+ .filter((call: any[]) => call[0] === `${gatewayUrl}/api/operations/init`)
+ .map((call: any[]) => JSON.parse(call[1].body));
+
+ expect(bodies).toEqual([
+ {
+ meta: { agentId: 'agt_1', topicId: 'tpc_1' },
+ operationId: 'op-hetero',
+ userId: 'user-1',
+ },
+ { operationId: 'op-legacy', userId: 'user-1' },
+ ]);
+ expect(bodies[1]).not.toHaveProperty('meta');
+ });
+
+ it('registers the visitor as gateway owner while still sending meta', async () => {
+ await notifier.publishAgentRuntimeInit('op-share', {
+ streamOwnerUserId: 'visitor-1',
+ topicId: 'tpc_1',
+ userId: 'creator-1',
+ });
+
+ const initCall = mockFetch.mock.calls.find(
+ (call: any[]) => call[0] === `${gatewayUrl}/api/operations/init`,
+ )!;
+ expect(JSON.parse(initCall[1].body)).toEqual({
+ meta: { topicId: 'tpc_1' },
+ operationId: 'op-share',
+ userId: 'visitor-1',
+ });
+ });
+
it('waits for gateway init before exposing the operation to subscribers', async () => {
let resolveInit!: () => void;
mockFetch.mockImplementation((url: string) => {
diff --git a/apps/server/src/routers/lambda/__tests__/aiAgent.test.ts b/apps/server/src/routers/lambda/__tests__/aiAgent.test.ts
index 24e0f79a1f1..fce50c60064 100644
--- a/apps/server/src/routers/lambda/__tests__/aiAgent.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/aiAgent.test.ts
@@ -15,6 +15,7 @@ import { eq } from 'drizzle-orm';
import type * as ModelBankModule from 'model-bank';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import type * as InternalJwtModule from '@/libs/trpc/utils/internalJwt';
import {
assertCanPerformResourceAction,
getResourceMeta,
@@ -91,6 +92,14 @@ vi.mock('@/server/services/resourcePermission', () => ({
getResourceMeta: vi.fn(),
}));
+// The user-hub token is a real RS256 signature in production; the integration
+// DB has no JWKS_KEY, so pin the signer and assert the subject it is asked for.
+const mockSignUserJWT = vi.fn();
+vi.mock('@/libs/trpc/utils/internalJwt', async (importOriginal) => ({
+ ...(await importOriginal<typeof InternalJwtModule>()),
+ signUserJWT: (...args: any[]) => mockSignUserJWT(...args),
+}));
+
// Mock model-bank with dynamic import to preserve other exports
vi.mock('model-bank', async (importOriginal) => {
const actual = await importOriginal<typeof ModelBankModule>();
@@ -482,6 +491,21 @@ describe('AI Agent Router Integration Tests', () => {
});
});
+ describe('issueGatewayUserToken', () => {
+ // Protocol v2: one Gateway WebSocket per user. The token is bound to the
+ // caller's identity only β€” no topic / running-operation precondition like
+ // `refreshGatewayToken`, because the hub authorizes each `subscribe`
+ // against the op's registered owner instead.
+ it('signs a per-user token for the caller without any operation context', async () => {
+ mockSignUserJWT.mockResolvedValue('user-hub-jwt');
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ await expect(caller.issueGatewayUserToken()).resolves.toEqual({ token: 'user-hub-jwt' });
+ expect(mockSignUserJWT).toHaveBeenCalledTimes(1);
+ expect(mockSignUserJWT).toHaveBeenCalledWith(userId);
+ });
+ });
+
describe('execAgent workspace use guard', () => {
let workspaceId: string;
let wsAgentId: string;
diff --git a/apps/server/src/routers/lambda/__tests__/shareChat.test.ts b/apps/server/src/routers/lambda/__tests__/shareChat.test.ts
index fd6fcd3c999..4517b89d7ed 100644
--- a/apps/server/src/routers/lambda/__tests__/shareChat.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/shareChat.test.ts
@@ -1,5 +1,6 @@
// @vitest-environment node
import type * as BusinessConst from '@lobechat/business-const';
+import { TRPCError } from '@trpc/server';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import type * as MessageModelModule from '@/database/models/message';
@@ -534,6 +535,56 @@ describe('shareChatRouter', () => {
});
});
+ describe('issueGatewayUserToken', () => {
+ it('signs the per-user hub token for the VISITOR, never the creator', async () => {
+ const caller = await createCaller();
+
+ await expect(caller.issueGatewayUserToken({ shareId: 'share-1' })).resolves.toEqual({
+ token: 'visitor-jwt',
+ });
+ expect(mockSignUserJWT).toHaveBeenCalledWith(VISITOR);
+ expect(mockAccessCheck).toHaveBeenCalledWith(expect.anything(), 'share-1', VISITOR);
+ });
+
+ // The v2 hub socket is per user, not per operation: the hub authorizes
+ // each `subscribe` against the op's registered owner, so minting must not
+ // depend on a topic marker or a live run (a visitor opens the socket
+ // before their first send).
+ it('does not require a topic or a running operation', async () => {
+ mockFindById.mockResolvedValue(undefined);
+ mockIsRunningOperationAlive.mockResolvedValue(false);
+ const caller = await createCaller();
+
+ await expect(caller.issueGatewayUserToken({ shareId: 'share-1' })).resolves.toEqual({
+ token: 'visitor-jwt',
+ });
+ expect(mockFindById).not.toHaveBeenCalled();
+ expect(mockIsRunningOperationAlive).not.toHaveBeenCalled();
+ });
+
+ it('rejects an unknown share without signing anything', async () => {
+ mockAccessCheck.mockRejectedValue(
+ new TRPCError({ code: 'NOT_FOUND', message: 'Share not found' }),
+ );
+ const caller = await createCaller();
+
+ await expect(caller.issueGatewayUserToken({ shareId: 'missing' })).rejects.toMatchObject({
+ code: 'NOT_FOUND',
+ });
+ expect(mockSignUserJWT).not.toHaveBeenCalled();
+ });
+
+ it('rejects a share that is not link-visible', async () => {
+ mockAccessCheck.mockResolvedValue({ ...share, visibility: 'private' });
+ const caller = await createCaller();
+
+ await expect(caller.issueGatewayUserToken({ shareId: 'share-1' })).rejects.toMatchObject({
+ code: 'FORBIDDEN',
+ });
+ expect(mockSignUserJWT).not.toHaveBeenCalled();
+ });
+ });
+
describe('refreshGatewayToken', () => {
it('signs the token for the VISITOR, never the creator', async () => {
const caller = await createCaller();
@@ -613,6 +664,9 @@ describe('shareChatRouter', () => {
await expect(
caller.refreshGatewayToken({ shareId: 'share-1', topicId: 'tpc_visitor' }),
).resolves.toEqual({ token: 'visitor-jwt' });
+ await expect(caller.issueGatewayUserToken({ shareId: 'share-1' })).resolves.toEqual({
+ token: 'visitor-jwt',
+ });
expect(mockGetFeatureFlagsState).not.toHaveBeenCalled();
},
);
diff --git a/apps/server/src/routers/lambda/aiAgent.ts b/apps/server/src/routers/lambda/aiAgent.ts
index 7327e0a19b2..7e1a48bb627 100644
--- a/apps/server/src/routers/lambda/aiAgent.ts
+++ b/apps/server/src/routers/lambda/aiAgent.ts
@@ -3736,6 +3736,24 @@ export const aiAgentRouter = router({
}
}),
+ /**
+ * Mint the per-USER Gateway JWT for the multiplexed v2 WebSocket (one
+ * socket per user, `GET /v2/ws`). Unlike `refreshGatewayToken` it is not
+ * bound to a running operation: the user hub authorizes every `subscribe`
+ * against the op's registered owner, so the token only has to carry the
+ * caller's identity. Short-lived (5m) like the v1 token; the client re-mints
+ * before every connect attempt.
+ *
+ * Blocked for restricted API keys (`TRPC_BLOCKED_PATH_PREFIXES`), like
+ * `refreshGatewayToken`: the JWT it returns passes `oidcAuth` as ordinary
+ * non-API-key auth, so a scoped key must never be able to mint one.
+ */
+ issueGatewayUserToken: aiAgentProcedure.query(async ({ ctx }) => {
+ const token = await signUserJWT(ctx.userId);
+
+ return { token };
+ }),
+
/**
* Refresh Gateway JWT token for an existing operation.
* Used when reconnecting after page reload (original token expired).
diff --git a/apps/server/src/routers/lambda/shareChat.ts b/apps/server/src/routers/lambda/shareChat.ts
index 21f285374cb..0427dd2d8a2 100644
--- a/apps/server/src/routers/lambda/shareChat.ts
+++ b/apps/server/src/routers/lambda/shareChat.ts
@@ -480,6 +480,26 @@ export const shareChatRouter = router({
}
}),
+ /**
+ * Mint the per-VISITOR Gateway JWT for the multiplexed v2 WebSocket β€” the
+ * visitor counterpart of `aiAgent.issueGatewayUserToken`. Same subject rule
+ * as `refreshGatewayToken` (sign for the visitor: share ops register their
+ * stream under `streamOwnerUserId = visitor`, and the hub keys on the JWT
+ * `sub`), but without a running-operation check: the token authenticates the
+ * user hub socket, and each `subscribe` is authorized per op by the gateway.
+ * The share must still resolve as link-visible for this caller so a revoked
+ * or private share cannot be used to open a hub socket from its page.
+ */
+ issueGatewayUserToken: shareChatProcedure
+ .input(z.object({ shareId: z.string() }))
+ .query(async ({ input, ctx }) => {
+ await resolveLinkShareOrThrow(ctx.serverDB, input.shareId, ctx.userId);
+
+ const token = await signUserJWT(ctx.userId);
+
+ return { token };
+ }),
+
/**
* Refresh the Gateway WS JWT for a running share operation β€” the visitor
* counterpart of `aiAgent.refreshGatewayToken` (which cannot serve visitors:
diff --git a/packages/const/src/apiKeyScope.test.ts b/packages/const/src/apiKeyScope.test.ts
index 2da1e011d81..7f12597fc80 100644
--- a/packages/const/src/apiKeyScope.test.ts
+++ b/packages/const/src/apiKeyScope.test.ts
@@ -166,6 +166,14 @@ describe('requiredApiKeyScopeForTrpc', () => {
blocked: true,
});
expect(requiredApiKeyScopeForTrpc('market.oidc.getToken', 'query')).toEqual({ blocked: true });
+ // gateway token minting: a restricted key must never obtain a user JWT
+ // that `oidcAuth` would accept as unscoped auth
+ expect(requiredApiKeyScopeForTrpc('aiAgent.refreshGatewayToken', 'query')).toEqual({
+ blocked: true,
+ });
+ expect(requiredApiKeyScopeForTrpc('aiAgent.issueGatewayUserToken', 'query')).toEqual({
+ blocked: true,
+ });
// the rest of the market surface keeps its agent scopes
expect(requiredApiKeyScopeForTrpc('market.getAgentsByPlugin', 'query')).toEqual({
scopes: ['agent:read'],
diff --git a/packages/const/src/apiKeyScope.ts b/packages/const/src/apiKeyScope.ts
index c2b008047b7..08dc600cff9 100644
--- a/packages/const/src/apiKeyScope.ts
+++ b/packages/const/src/apiKeyScope.ts
@@ -402,8 +402,9 @@ export const TRPC_PROCEDURE_EXTRA_SCOPES: Record<string, ApiKeyScope[]> = {
* blocked here by path prefix.
*/
export const TRPC_BLOCKED_PATH_PREFIXES: string[] = [
- // returns an unrestricted user JWT that passes `oidcAuth` as non-API-key
- // auth and would bypass the scope guard entirely
+ // both return an unrestricted user JWT that passes `oidcAuth` as
+ // non-API-key auth and would bypass the scope guard entirely
+ 'aiAgent.issueGatewayUserToken',
'aiAgent.refreshGatewayToken',
// sandbox execution mints a full LOBEHUB_JWT for `lh` commands
// (`preprocessLhCommand`), which would bypass the key's scopes entirely
diff --git a/src/services/aiAgent.ts b/src/services/aiAgent.ts
index fb72291a017..9da0cc98b3d 100644
--- a/src/services/aiAgent.ts
+++ b/src/services/aiAgent.ts
@@ -263,6 +263,15 @@ class AiAgentService {
return await lambdaClient.aiAgent.refreshGatewayToken.query({ topicId });
}
+ /**
+ * Mint the per-user JWT for the multiplexed Gateway WebSocket (v2, one
+ * socket per user). Not bound to any operation β€” the mux client calls this
+ * before every connect attempt.
+ */
+ async issueGatewayUserToken(): Promise<{ token: string }> {
+ return await lambdaClient.aiAgent.issueGatewayUserToken.query();
+ }
+
async execSubAgentTask(params: ExecSubAgentTaskParams) {
return await lambdaClient.aiAgent.execSubAgentTask.mutate(params);
}
diff --git a/src/services/shareChat.ts b/src/services/shareChat.ts
index 1882e60f939..79d79b4de8d 100644
--- a/src/services/shareChat.ts
+++ b/src/services/shareChat.ts
@@ -48,6 +48,15 @@ class ShareChatService {
async refreshGatewayToken(shareId: string, topicId: string): Promise<{ token: string }> {
return await lambdaClient.shareChat.refreshGatewayToken.query({ shareId, topicId });
}
+
+ /**
+ * Mint the visitor's per-user JWT for the multiplexed Gateway WebSocket β€”
+ * the visitor counterpart of `aiAgentService.issueGatewayUserToken`. Keyed by
+ * shareId only (no topic / running operation required).
+ */
+ async issueGatewayUserToken(shareId: string): Promise<{ token: string }> {
+ return await lambdaClient.shareChat.issueGatewayUserToken.query({ shareId });
+ }
}
export const shareChatService = new ShareChatService();