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.

🔧 chore: update business interface and test fixes (#11077)

YuTengjingb96363d8c0cf
diff --git a/packages/database/src/models/asyncTask.ts b/packages/database/src/models/asyncTask.ts
index 54fefaf8b9a..8bcfd5c9053 100644
--- a/packages/database/src/models/asyncTask.ts
+++ b/packages/database/src/models/asyncTask.ts
@@ -5,7 +5,7 @@ import {
AsyncTaskStatus,
AsyncTaskType,
} from '@lobechat/types';
-import { and, eq, inArray, lt } from 'drizzle-orm';
+import { and, eq, inArray, lt, or } from 'drizzle-orm';
import { AsyncTaskSelectItem, NewAsyncTaskItem, asyncTasks } from '../schemas';
import { LobeChatDatabase } from '../type';
@@ -68,7 +68,10 @@ export class AsyncTaskModel {
.where(
and(
inArray(asyncTasks.id, ids),
- eq(asyncTasks.status, AsyncTaskStatus.Processing),
+ or(
+ eq(asyncTasks.status, AsyncTaskStatus.Pending),
+ eq(asyncTasks.status, AsyncTaskStatus.Processing),
+ ),
lt(asyncTasks.createdAt, new Date(Date.now() - ASYNC_TASK_TIMEOUT)),
),
);
diff --git a/src/app/(backend)/webapi/chat/[provider]/route.test.ts b/src/app/(backend)/webapi/chat/[provider]/route.test.ts
index 46f6893cf64..878d7fed48f 100644
--- a/src/app/(backend)/webapi/chat/[provider]/route.test.ts
+++ b/src/app/(backend)/webapi/chat/[provider]/route.test.ts
@@ -22,8 +22,8 @@ vi.mock('@lobechat/utils/server', () => ({
getXorPayload: vi.fn(),
}));
-// 定义一个变量来存储 enableAuth 的值
-let enableClerk = false;
+// Use vi.hoisted to ensure mockState is initialized before mocks are set up
+const mockState = vi.hoisted(() => ({ enableClerk: false }));
// 模拟 @/const/auth 模块
vi.mock('@/const/auth', async (importOriginal) => {
@@ -31,7 +31,7 @@ vi.mock('@/const/auth', async (importOriginal) => {
return {
...(modules as any),
get enableClerk() {
- return enableClerk;
+ return mockState.enableClerk;
},
};
});
@@ -52,7 +52,7 @@ beforeEach(() => {
afterEach(() => {
// 清除模拟调用历史
vi.clearAllMocks();
- enableClerk = false;
+ mockState.enableClerk = false;
});
describe('POST handler', () => {
@@ -102,7 +102,7 @@ describe('POST handler', () => {
});
it('should have pass clerk Auth when enable clerk', async () => {
- enableClerk = true;
+ mockState.enableClerk = true;
vi.mocked(getXorPayload).mockReturnValueOnce({
accessCode: 'test-access-code',
diff --git a/src/business/server/better-auth.ts b/src/business/server/better-auth.ts
new file mode 100644
index 00000000000..ba05fe00bc2
--- /dev/null
+++ b/src/business/server/better-auth.ts
@@ -0,0 +1,4 @@
+// eslint-disable-next-line unused-imports/no-unused-vars, @typescript-eslint/no-unused-vars
+export async function businessEmailValidator(email: string): Promise<boolean> {
+ return true;
+}
diff --git a/src/business/server/image-generation/chargeBeforeGenerate.ts b/src/business/server/image-generation/chargeBeforeGenerate.ts
index 1eb69827588..6258a787811 100644
--- a/src/business/server/image-generation/chargeBeforeGenerate.ts
+++ b/src/business/server/image-generation/chargeBeforeGenerate.ts
@@ -2,6 +2,7 @@ import { type NewGeneration, type NewGenerationBatch } from '@/database/schemas'
import type { CreateImageServicePayload } from '@/server/routers/lambda/image';
interface ChargeParams {
+ clientIp?: string | null;
configForDatabase: CreateImageServicePayload['params'];
generationParams: CreateImageServicePayload['params'];
generationTopicId: string;
diff --git a/src/libs/better-auth/define-config.ts b/src/libs/better-auth/define-config.ts
index 397a451f589..03abb5cb400 100644
--- a/src/libs/better-auth/define-config.ts
+++ b/src/libs/better-auth/define-config.ts
@@ -1,16 +1,19 @@
/* eslint-disable sort-keys-fix/sort-keys-fix, typescript-sort-keys/interface */
import { expo } from '@better-auth/expo';
import { passkey } from '@better-auth/passkey';
+import { ENABLE_BUSINESS_FEATURES } from '@lobechat/business-const';
import { createNanoId, idGenerator, serverDB } from '@lobechat/database';
import * as schema from '@lobechat/database/schemas';
import bcrypt from 'bcryptjs';
import { emailHarmony } from 'better-auth-harmony';
+import { validateEmail } from 'better-auth-harmony/email';
import { drizzleAdapter } from 'better-auth/adapters/drizzle';
import { verifyPassword as defaultVerifyPassword } from 'better-auth/crypto';
import { type BetterAuthOptions, betterAuth } from 'better-auth/minimal';
import { admin, emailOTP, genericOAuth, magicLink } from 'better-auth/plugins';
import { type BetterAuthPlugin } from 'better-auth/types';
+import { businessEmailValidator } from '@/business/server/better-auth';
import { authEnv } from '@/envs/auth';
import {
getMagicLinkEmailTemplate,
@@ -60,6 +63,13 @@ const enabledSSOProviders = parseSSOProviders(authEnv.AUTH_SSO_PROVIDERS);
const { socialProviders, genericOAuthProviders } = initBetterAuthSSOProviders();
+async function customEmailValidator(email: string): Promise<boolean> {
+ if (ENABLE_BUSINESS_FEATURES && !(await businessEmailValidator(email))) {
+ return false;
+ }
+ return validateEmail(email);
+}
+
interface CustomBetterAuthOptions {
plugins: BetterAuthPlugin[];
}
@@ -209,7 +219,7 @@ export function defineConfig(customOptions: CustomBetterAuthOptions) {
plugins: [
...customOptions.plugins,
expo(),
- emailHarmony({ allowNormalizedSignin: false }),
+ emailHarmony({ allowNormalizedSignin: false, validator: customEmailValidator }),
admin(),
// Email OTP plugin for mobile verification
emailOTP({
diff --git a/src/server/routers/async/__tests__/caller.test.ts b/src/server/routers/async/__tests__/caller.test.ts
index e2886129311..b0edbe7494a 100644
--- a/src/server/routers/async/__tests__/caller.test.ts
+++ b/src/server/routers/async/__tests__/caller.test.ts
@@ -41,6 +41,10 @@ vi.mock('@/const/version', () => ({
isDesktop: false,
}));
+vi.mock('@/libs/trpc/utils/internalJwt', () => ({
+ signInternalJWT: vi.fn().mockResolvedValue('mock-internal-jwt-token'),
+}));
+
describe('createAsyncServerClient - INTERNAL_APP_URL Tests', () => {
beforeEach(() => {
vi.clearAllMocks();
@@ -134,14 +138,14 @@ describe('createAsyncServerClient - INTERNAL_APP_URL Tests', () => {
});
describe('authentication and headers', () => {
- it('should include Authorization header with KEY_VAULTS_SECRET', async () => {
+ it('should include Authorization header with internal JWT token', async () => {
await createAsyncServerClient('user-auth', {});
const config = vi.mocked(createTRPCClient).mock.calls[0][0];
const httpLinkOptions = config.links[0] as any;
expect(httpLinkOptions.headers).toHaveProperty('Authorization');
- expect(httpLinkOptions.headers.Authorization).toBe('Bearer test-secret-key');
+ expect(httpLinkOptions.headers.Authorization).toBe('mock-internal-jwt-token');
});
it('should encrypt and include user payload in x-lobe-chat-auth header', async () => {
diff --git a/src/server/routers/async/image.ts b/src/server/routers/async/image.ts
index 7fa7e3c2eec..27cc0561f73 100644
--- a/src/server/routers/async/image.ts
+++ b/src/server/routers/async/image.ts
@@ -2,6 +2,7 @@ import { ASYNC_TASK_TIMEOUT } from '@lobechat/business-config/server';
import { ENABLE_BUSINESS_FEATURES } from '@lobechat/business-const';
import { AgentRuntimeErrorType } from '@lobechat/model-runtime';
import { AsyncTaskError, AsyncTaskErrorType, AsyncTaskStatus } from '@lobechat/types';
+import { TRPCError } from '@trpc/server';
import debug from 'debug';
import { type RuntimeImageGenParams } from 'model-bank';
import { z } from 'zod';
@@ -11,6 +12,7 @@ import { createImageBusinessMiddleware } from '@/business/server/trpc-middleware
import { AsyncTaskModel } from '@/database/models/asyncTask';
import { FileModel } from '@/database/models/file';
import { GenerationModel } from '@/database/models/generation';
+import { GenerationBatchModel } from '@/database/models/generationBatch';
import { asyncAuthedProcedure, asyncRouter as router } from '@/libs/trpc/async';
import { initModelRuntimeWithUserPayload } from '@/server/modules/ModelRuntime';
import { GenerationService } from '@/server/services/generation';
@@ -28,6 +30,7 @@ const imageProcedure = asyncAuthedProcedure.use(async (opts) => {
ctx: {
asyncTaskModel: new AsyncTaskModel(ctx.serverDB, ctx.userId),
fileModel: new FileModel(ctx.serverDB, ctx.userId),
+ generationBatchModel: new GenerationBatchModel(ctx.serverDB, ctx.userId),
generationModel: new GenerationModel(ctx.serverDB, ctx.userId),
generationService: new GenerationService(ctx.serverDB, ctx.userId),
},
@@ -216,6 +219,13 @@ export const imageRouter = router({
taskId,
});
+ // Check if generationBatch exists before processing
+ const generationBatch = await ctx.generationBatchModel.findById(generationBatchId);
+ if (!generationBatch) {
+ log('Generation batch not found: %s, skipping image generation', generationBatchId);
+ throw new TRPCError({ code: 'FORBIDDEN', message: 'Invalid Request!' });
+ }
+
log('Updating task status to Processing: %s', taskId);
await ctx.asyncTaskModel.update(taskId, { status: AsyncTaskStatus.Processing });
diff --git a/src/server/routers/lambda/image.ts b/src/server/routers/lambda/image.ts
index baa67970ca4..1b7487348a4 100644
--- a/src/server/routers/lambda/image.ts
+++ b/src/server/routers/lambda/image.ts
@@ -135,6 +135,7 @@ export const imageRouter = router({
validateNoUrlsInConfig(configForDatabase, 'configForDatabase');
const chargeResult = await chargeBeforeGenerate({
+ clientIp: ctx.clientIp,
configForDatabase,
generationParams: params,
generationTopicId,