68 lines
1.9 KiB
TypeScript
68 lines
1.9 KiB
TypeScript
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
|
import { applyByokToConfig } from '@/lib/byok';
|
|
|
|
vi.mock('@/lib/prisma', () => ({
|
|
prisma: {
|
|
userAPIKey: { findFirst: vi.fn(), update: vi.fn().mockResolvedValue({}) },
|
|
subscription: { findUnique: vi.fn() },
|
|
},
|
|
}));
|
|
|
|
vi.mock('@/lib/crypto', () => ({
|
|
decryptApiKey: vi.fn(async () => 'user-sk-plaintext'),
|
|
encryptApiKey: vi.fn(async () => 'enc'),
|
|
hashApiKey: vi.fn(() => 'hash'),
|
|
}));
|
|
|
|
vi.mock('@/lib/entitlements', () => ({
|
|
getUserInfo: vi.fn(async () => ({ tier: 'PRO', status: 'ACTIVE' })),
|
|
}));
|
|
|
|
import { prisma } from '@/lib/prisma';
|
|
|
|
describe('applyByokToConfig', () => {
|
|
beforeEach(() => {
|
|
vi.clearAllMocks();
|
|
vi.mocked(prisma.subscription.findUnique).mockResolvedValue({
|
|
userId: 'u1',
|
|
tier: 'PRO',
|
|
status: 'ACTIVE',
|
|
currentPeriodStart: new Date(),
|
|
currentPeriodEnd: new Date(),
|
|
} as any);
|
|
});
|
|
|
|
it('injects user API key into config when active row exists', async () => {
|
|
vi.mocked(prisma.userAPIKey.findFirst).mockResolvedValue({
|
|
id: 'k1',
|
|
userId: 'u1',
|
|
provider: 'openai',
|
|
encryptedKey: 'enc',
|
|
keyHash: 'hash',
|
|
alias: '',
|
|
model: null,
|
|
isActive: true,
|
|
lastUsedAt: null,
|
|
lastUsedFor: null,
|
|
createdAt: new Date(),
|
|
updatedAt: new Date(),
|
|
} as never);
|
|
|
|
const base = { OPENAI_API_KEY: 'system-key' };
|
|
const { config, usedByok } = await applyByokToConfig('u1', 'openai', base);
|
|
|
|
expect(usedByok).toBe(true);
|
|
expect(config.OPENAI_API_KEY).toBe('user-sk-plaintext');
|
|
});
|
|
|
|
it('returns unchanged config when no BYOK row', async () => {
|
|
vi.mocked(prisma.userAPIKey.findFirst).mockResolvedValue(null);
|
|
|
|
const base = { OPENAI_API_KEY: 'system-key' };
|
|
const { config, usedByok } = await applyByokToConfig('u1', 'openai', base);
|
|
|
|
expect(usedByok).toBe(false);
|
|
expect(config.OPENAI_API_KEY).toBe('system-key');
|
|
});
|
|
});
|