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: move async jwt auth to async auth middleware

YuTengjing39aa01b444db
diff --git a/src/libs/trpc/async/asyncAuth.ts b/src/libs/trpc/async/asyncAuth.ts
index ff33456c040..1a04051618c 100644
--- a/src/libs/trpc/async/asyncAuth.ts
+++ b/src/libs/trpc/async/asyncAuth.ts
@@ -3,6 +3,7 @@ import { TRPCError } from '@trpc/server';
import debug from 'debug';
import { UserModel } from '@/database/models/user';
+import { validateInternalJWT } from '@/libs/trpc/utils/internalJwt';
import { asyncTrpc } from './init';
@@ -13,6 +14,20 @@ export const asyncAuth = asyncTrpc.middleware(async (opts) => {
log('Async auth middleware called for userId: %s', ctx.userId);
+ // Validate JWT token to verify request is from lambda
+ if (!ctx.authorizationToken) {
+ log('Async auth failed - missing authorization token');
+ throw new TRPCError({ code: 'UNAUTHORIZED' });
+ }
+
+ log('Validating internal JWT token');
+ const isValid = await validateInternalJWT(ctx.authorizationToken);
+ if (!isValid) {
+ log('JWT validation failed');
+ throw new TRPCError({ code: 'UNAUTHORIZED', message: 'Invalid JWT token' });
+ }
+ log('JWT validation successful');
+
if (!ctx.userId) {
log('Async auth failed - missing userId');
throw new TRPCError({ code: 'UNAUTHORIZED' });
diff --git a/src/libs/trpc/async/context.ts b/src/libs/trpc/async/context.ts
index 6f9d846c10d..398075bcbec 100644
--- a/src/libs/trpc/async/context.ts
+++ b/src/libs/trpc/async/context.ts
@@ -4,12 +4,12 @@ import debug from 'debug';
import { type NextRequest } from 'next/server';
import { LOBE_CHAT_AUTH_HEADER } from '@/const/auth';
-import { validateInternalJWT } from '@/libs/trpc/utils/internalJwt';
import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';
const log = debug('lobe-async:context');
export interface AsyncAuthContext {
+ authorizationToken?: string;
jwtPayload: ClientSecretPayload;
serverDB?: LobeChatDatabase;
userId?: string | null;
@@ -20,9 +20,11 @@ export interface AsyncAuthContext {
* This is useful for testing when we don't want to mock Next.js' request/response
*/
export const createAsyncContextInner = async (params?: {
+ authorizationToken?: string;
jwtPayload?: ClientSecretPayload;
userId?: string | null;
}): Promise<AsyncAuthContext> => ({
+ authorizationToken: params?.authorizationToken,
jwtPayload: params?.jwtPayload || {},
userId: params?.userId,
});
@@ -50,15 +52,6 @@ export const createAsyncRouteContext = async (request: NextRequest): Promise<Asy
throw new Error('No LobeChat authorization header found');
}
- // Validate JWT token to verify request is from lambda
- log('Validating internal JWT token');
- const isValid = await validateInternalJWT(authorization);
- if (!isValid) {
- log('JWT validation failed');
- throw new Error('Invalid JWT token');
- }
- log('JWT validation successful');
-
try {
log('Initializing KeyVaultsGateKeeper');
const gateKeeper = await KeyVaultsGateKeeper.initWithEnvKey();
@@ -75,7 +68,7 @@ export const createAsyncRouteContext = async (request: NextRequest): Promise<Asy
Object.keys(payload || {}),
);
- return createAsyncContextInner({ jwtPayload: payload, userId });
+ return createAsyncContextInner({ authorizationToken: authorization, jwtPayload: payload, userId });
} catch (error) {
log('Error creating async route context: %O', error);
throw error;