From f20bcd17cf95fda7ba7fe37aa516f80f87f6ae17 Mon Sep 17 00:00:00 2001 From: "claude[bot]" <41898282+claude[bot]@users.noreply.github.com> Date: Sat, 2 May 2026 16:41:52 +0000 Subject: [PATCH] feat: encrypt user AI API keys at rest with mandatory OSE_ENCRYPTION_KEY - Add src/lib/crypto/secrets.ts: AES-256-GCM helpers (encryptSecret, decryptSecret, resolveSecret, isEncryptionEnabled, isEncryptedSecret) - Add apiKeyEncrypted / imageApiKeyEncrypted columns to UserAISettings via migration 20260502140000_add_encrypted_api_key_fields - PUT /api/profile/ai-settings: reject new key submissions with HTTP 503 when OSE_ENCRYPTION_KEY is absent or invalid; never write plaintext - GET /api/profile/ai-settings: resolve hasApiKey/masked from encrypted columns first, falling back to legacy plaintext for display only - Read paths (resolveAIConfig, resolveAIImageConfig, resolveAIImageConfigFromRequest, resolveAIConfigFromRequest): decrypt via resolveSecret; lazy-migrate any legacy plaintext key to encrypted storage on first use when OSE_ENCRYPTION_KEY is available - Without OSE_ENCRYPTION_KEY, legacy plaintext keys are treated as unconfigured (not used); users must set the env var and re-enter keys - Add tests: src/test/crypto-secrets.test.ts (round-trip, unicode, tamper resistance, resolveSecret fallback behaviour) - Update .env.example and docs/self-hosting.md with key setup, rotation, and backup guidance Closes #53 Co-authored-by: hacksynth --- .env.example | 11 ++ docs/self-hosting.md | 36 ++++ src/app/api/profile/ai-settings/route.ts | 102 ++++++++-- src/lib/ai/image.ts | 36 +++- src/lib/ai/index.ts | 27 ++- src/lib/ai/settings.ts | 6 +- src/lib/crypto/secrets.ts | 76 ++++++++ .../migration.sql | 3 + src/prisma/schema.prisma | 2 + src/test/crypto-secrets.test.ts | 180 ++++++++++++++++++ 10 files changed, 447 insertions(+), 32 deletions(-) create mode 100644 src/lib/crypto/secrets.ts create mode 100644 src/prisma/migrations/20260502140000_add_encrypted_api_key_fields/migration.sql create mode 100644 src/test/crypto-secrets.test.ts diff --git a/.env.example b/.env.example index b65f940..9e2a0e4 100644 --- a/.env.example +++ b/.env.example @@ -10,6 +10,17 @@ DATABASE_URL="file:./dev.db" # PostgreSQL (recommended for production / 生产推荐) # DATABASE_URL="postgresql://user:password@localhost:5432/ose" +# --- Encryption / 加密 --- +# Required to save user-provided AI API keys. Without this key, the API will +# reject attempts to store API keys (HTTP 503). +# 存储用户 AI API Key 时必须设置。未设置时,保存 API Key 的请求会返回 503 错误。 +# Generate with: openssl rand -base64 32 +# 使用 openssl rand -base64 32 生成 +# WARNING: Back this up. If lost, all stored user API keys become unreadable and +# users must re-enter them. +# 警告:请备份此值。丢失后已存储的用户 API Key 将无法解密,用户需重新输入。 +OSE_ENCRYPTION_KEY= + # --- Authentication / 认证 --- # Generate with: openssl rand -base64 32 # 使用 openssl rand -base64 32 生成 diff --git a/docs/self-hosting.md b/docs/self-hosting.md index 018f6b7..3d747bd 100644 --- a/docs/self-hosting.md +++ b/docs/self-hosting.md @@ -19,6 +19,13 @@ Minimum production environment: DATABASE_URL=file:/data/ose.db NEXTAUTH_URL=https://your-domain.example NEXTAUTH_SECRET=replace-with-openssl-rand-base64-32 +OSE_ENCRYPTION_KEY=replace-with-openssl-rand-base64-32 +``` + +`OSE_ENCRYPTION_KEY` is required to allow users to save their AI API keys. Without it, the settings API returns HTTP 503 when a user tries to store a key. Generate it with: + +```bash +openssl rand -base64 32 ``` Optional AI variables can be added to `.env` or the Compose environment section. @@ -125,3 +132,32 @@ server { ``` Set `NEXTAUTH_URL=https://ose.example.com` when using HTTPS. + +## Encryption Key (`OSE_ENCRYPTION_KEY`) + +User-provided AI API keys (e.g. Anthropic, OpenAI, Gemini, custom provider) are encrypted at rest using AES-256-GCM before being written to the database. The `OSE_ENCRYPTION_KEY` environment variable supplies the 32-byte key. + +**Generating the key:** + +```bash +openssl rand -base64 32 +``` + +**Behavior without the key:** + +- Saving a new API key via the settings page returns HTTP 503 and the key is not persisted. +- Any legacy plaintext keys already in the database are treated as unconfigured until you set the key and they are migrated. + +**Lazy migration of existing plaintext keys:** + +If you upgrade from a deployment that stored keys in plaintext, existing `apiKey` / `imageApiKey` values are automatically encrypted on first use once `OSE_ENCRYPTION_KEY` is set. The plaintext column is cleared immediately after encryption. No manual migration step is required. + +**Key rotation:** + +1. Add a migration script that re-encrypts all stored keys with the new key. +2. Replace `OSE_ENCRYPTION_KEY` in your environment with the new value. +3. If you rotate without re-encrypting, users will need to re-enter their API keys. + +**Backup:** + +Back up `OSE_ENCRYPTION_KEY` separately from the database. Losing the key makes all stored user API keys permanently unreadable. diff --git a/src/app/api/profile/ai-settings/route.ts b/src/app/api/profile/ai-settings/route.ts index 487733a..994b5d1 100644 --- a/src/app/api/profile/ai-settings/route.ts +++ b/src/app/api/profile/ai-settings/route.ts @@ -13,6 +13,11 @@ import { DEFAULT_AI_IMAGE_RATE_LIMIT_HOURLY, DEFAULT_AI_IMAGE_RATE_LIMIT_PER_MINUTE, } from '@/lib/ai/image-rate-limit'; +import { + encryptSecret, + isEncryptionEnabled, + resolveSecret, +} from '@/lib/crypto/secrets'; const ALLOWED_PROVIDERS = new Set(['claude', 'openai', 'gemini', 'custom']); @@ -40,18 +45,27 @@ export async function GET() { const session = await auth(); if (!session?.user?.id) return NextResponse.json({ message: '请先登录' }, { status: 401 }); const settings = await prisma.userAISettings.findUnique({ where: { userId: session.user.id } }); + + // Resolve effective key values for display (decrypt if encrypted) + const effectiveApiKey = settings + ? resolveSecret(settings.apiKeyEncrypted, settings.apiKey) + : null; + const effectiveImageApiKey = settings + ? resolveSecret(settings.imageApiKeyEncrypted, settings.imageApiKey) + : null; + return NextResponse.json({ provider: settings?.provider ?? null, model: settings?.model ?? null, baseUrl: settings?.baseUrl ?? null, - apiKeyMasked: maskApiKey(settings?.apiKey), - hasApiKey: Boolean(settings?.apiKey), + apiKeyMasked: maskApiKey(effectiveApiKey), + hasApiKey: Boolean(effectiveApiKey), visionSupport: settings?.visionSupport ?? null, imageProvider: settings?.imageProvider ?? null, imageModel: settings?.imageModel ?? null, imageBaseUrl: settings?.imageBaseUrl ?? null, - imageApiKeyMasked: maskApiKey(settings?.imageApiKey), - hasImageApiKey: Boolean(settings?.imageApiKey), + imageApiKeyMasked: maskApiKey(effectiveImageApiKey), + hasImageApiKey: Boolean(effectiveImageApiKey), imageSize: settings?.imageSize ?? null, imageQuality: settings?.imageQuality ?? null, imageOutputFormat: settings?.imageOutputFormat ?? null, @@ -80,7 +94,7 @@ export async function PUT(request: Request) { const baseUrl = hasOwn(body, 'baseUrl') ? trimString(body.baseUrl, 500) : (existing?.baseUrl ?? ''); - const apiKeyRaw = typeof body.apiKey === 'string' ? body.apiKey : ''; + const apiKeyRaw = typeof body.apiKey === 'string' ? body.apiKey.trim().slice(0, 500) : ''; const clearApiKey = body.apiKey === null; if (provider === 'custom' && !baseUrl) { @@ -91,11 +105,32 @@ export async function PUT(request: Request) { const modelChanged = model !== (existing?.model ?? ''); const nextVisionSupport = providerChanged || modelChanged ? null : (existing?.visionSupport ?? null); - const nextApiKey = clearApiKey - ? null - : apiKeyRaw - ? apiKeyRaw.trim().slice(0, 500) - : (existing?.apiKey ?? null); + // Determine encrypted/plaintext columns for text AI key + let nextApiKeyEncrypted: string | null; + let nextApiKeyPlain: string | null; + + if (clearApiKey) { + nextApiKeyEncrypted = null; + nextApiKeyPlain = null; + } else if (apiKeyRaw) { + // User is setting a new key — encryption is mandatory + if (!isEncryptionEnabled()) { + return NextResponse.json( + { + message: + '服务器未配置加密密钥 (OSE_ENCRYPTION_KEY),无法安全保存 API Key,请联系管理员配置后重试', + }, + { status: 503 }, + ); + } + nextApiKeyEncrypted = encryptSecret(apiKeyRaw); + nextApiKeyPlain = null; + } else { + // Key unchanged — preserve existing values + nextApiKeyEncrypted = existing?.apiKeyEncrypted ?? null; + nextApiKeyPlain = existing?.apiKey ?? null; + } + const imageProvider = hasOwn(body, 'imageProvider') ? normalizeImageProvider(body.imageProvider) : normalizeImageProvider(existing?.imageProvider); @@ -108,13 +143,36 @@ export async function PUT(request: Request) { const imageBaseUrl = hasOwn(body, 'imageBaseUrl') ? trimString(body.imageBaseUrl, 500) : (existing?.imageBaseUrl ?? ''); - const imageApiKeyRaw = typeof body.imageApiKey === 'string' ? body.imageApiKey : ''; + const imageApiKeyRaw = + typeof body.imageApiKey === 'string' ? body.imageApiKey.trim().slice(0, 500) : ''; const clearImageApiKey = body.imageApiKey === null; - const nextImageApiKey = clearImageApiKey - ? null - : imageApiKeyRaw - ? imageApiKeyRaw.trim().slice(0, 500) - : (existing?.imageApiKey ?? null); + + // Determine encrypted/plaintext columns for image AI key + let nextImageApiKeyEncrypted: string | null; + let nextImageApiKeyPlain: string | null; + + if (clearImageApiKey) { + nextImageApiKeyEncrypted = null; + nextImageApiKeyPlain = null; + } else if (imageApiKeyRaw) { + // User is setting a new image key — encryption is mandatory + if (!isEncryptionEnabled()) { + return NextResponse.json( + { + message: + '服务器未配置加密密钥 (OSE_ENCRYPTION_KEY),无法安全保存生图 API Key,请联系管理员配置后重试', + }, + { status: 503 }, + ); + } + nextImageApiKeyEncrypted = encryptSecret(imageApiKeyRaw); + nextImageApiKeyPlain = null; + } else { + // Key unchanged — preserve existing values + nextImageApiKeyEncrypted = existing?.imageApiKeyEncrypted ?? null; + nextImageApiKeyPlain = existing?.imageApiKey ?? null; + } + const imageSize = hasOwn(body, 'imageSize') ? normalizeImageSize(body.imageSize) : normalizeImageSize(existing?.imageSize); @@ -147,12 +205,14 @@ export async function PUT(request: Request) { provider: provider || null, model: model || null, baseUrl: baseUrl || null, - apiKey: nextApiKey, + apiKeyEncrypted: nextApiKeyEncrypted, + apiKey: nextApiKeyPlain, visionSupport: nextVisionSupport, imageProvider: imageProvider || null, imageModel: imageModel || null, imageBaseUrl: imageBaseUrl || null, - imageApiKey: nextImageApiKey, + imageApiKeyEncrypted: nextImageApiKeyEncrypted, + imageApiKey: nextImageApiKeyPlain, imageSize, imageQuality, imageOutputFormat, @@ -166,12 +226,14 @@ export async function PUT(request: Request) { provider: provider || null, model: model || null, baseUrl: baseUrl || null, - apiKey: nextApiKey, + apiKeyEncrypted: nextApiKeyEncrypted, + apiKey: nextApiKeyPlain, visionSupport: nextVisionSupport, imageProvider: imageProvider || null, imageModel: imageModel || null, imageBaseUrl: imageBaseUrl || null, - imageApiKey: nextImageApiKey, + imageApiKeyEncrypted: nextImageApiKeyEncrypted, + imageApiKey: nextImageApiKeyPlain, imageSize, imageQuality, imageOutputFormat, diff --git a/src/lib/ai/image.ts b/src/lib/ai/image.ts index 02f77f9..1c8713e 100644 --- a/src/lib/ai/image.ts +++ b/src/lib/ai/image.ts @@ -12,6 +12,7 @@ import type { AIImageStyle, } from '@/lib/ai/image-types'; import { prisma } from '@/lib/prisma'; +import { encryptSecret, isEncryptionEnabled, resolveSecret } from '@/lib/crypto/secrets'; export const DEFAULT_IMAGE_MODEL = 'gpt-image-2'; export const DEFAULT_IMAGE_SIZE: AIImageSize = '1024x1536'; @@ -107,17 +108,36 @@ function resolveEnvImageConfig(): AIImageConfig | null { return null; } +function lazyMigrateImageApiKey(userId: string, plaintext: string): void { + void (async () => { + try { + const encrypted = encryptSecret(plaintext); + await prisma.userAISettings.update({ + where: { userId }, + data: { imageApiKeyEncrypted: encrypted, imageApiKey: null }, + }); + } catch { + // Silently swallow — migration retries on next request + } + })(); +} + export async function resolveAIImageConfig(userId?: string | null): Promise { if (userId) { const settings = await prisma.userAISettings.findUnique({ where: { userId } }); const provider = normalizeImageProvider(settings?.imageProvider); if (provider) { + const imageApiKey = resolveSecret(settings?.imageApiKeyEncrypted, settings?.imageApiKey); const hasRequired = - provider === 'custom' ? Boolean(settings?.imageBaseUrl) : Boolean(settings?.imageApiKey); + provider === 'custom' ? Boolean(settings?.imageBaseUrl) : Boolean(imageApiKey); if (hasRequired) { + // Lazy-migrate legacy plaintext key to encrypted storage + if (settings && !settings.imageApiKeyEncrypted && settings.imageApiKey && isEncryptionEnabled()) { + lazyMigrateImageApiKey(userId, settings.imageApiKey); + } return { provider, - apiKey: settings?.imageApiKey ?? undefined, + apiKey: imageApiKey ?? undefined, model: settings?.imageModel ?? DEFAULT_IMAGE_MODEL, baseUrl: settings?.imageBaseUrl ?? undefined, size: normalizeImageSize(settings?.imageSize), @@ -146,11 +166,10 @@ export async function resolveAIImageConfigFromRequest( const existing = await prisma.userAISettings.findUnique({ where: { userId } }); const imageApiKeyDraft = trimString(data.imageApiKey, 500); - const apiKey = - imageApiKeyDraft || - (existing?.imageProvider === requestedProvider - ? (existing.imageApiKey ?? undefined) - : undefined); + const storedImageApiKey = existing?.imageProvider === requestedProvider + ? (resolveSecret(existing.imageApiKeyEncrypted, existing.imageApiKey) ?? undefined) + : undefined; + const apiKey = imageApiKeyDraft || storedImageApiKey; const model = trimString(data.imageModel, 200) || undefined; const baseUrl = trimString(data.imageBaseUrl, 500) || undefined; @@ -244,7 +263,8 @@ async function getImageConfigSource(userId?: string | null) { const settings = await prisma.userAISettings.findUnique({ where: { userId } }); const provider = normalizeImageProvider(settings?.imageProvider); if (!provider) return 'env' as const; + const hasImageApiKey = Boolean(resolveSecret(settings?.imageApiKeyEncrypted, settings?.imageApiKey)); const hasRequired = - provider === 'custom' ? Boolean(settings?.imageBaseUrl) : Boolean(settings?.imageApiKey); + provider === 'custom' ? Boolean(settings?.imageBaseUrl) : hasImageApiKey; return hasRequired ? ('user' as const) : ('env' as const); } diff --git a/src/lib/ai/index.ts b/src/lib/ai/index.ts index 7f9fe39..f5317b1 100644 --- a/src/lib/ai/index.ts +++ b/src/lib/ai/index.ts @@ -4,6 +4,7 @@ import { createOpenAIProvider } from "@/lib/ai/providers/openai"; import { createGeminiProvider } from "@/lib/ai/providers/gemini"; import { createCustomProvider } from "@/lib/ai/providers/custom"; import { prisma } from "@/lib/prisma"; +import { encryptSecret, isEncryptionEnabled, resolveSecret } from "@/lib/crypto/secrets"; function envConfigFor(provider: AIProviderKey): AIConfig | null { if (provider === "claude") { @@ -49,16 +50,35 @@ function normalizeProvider(raw: string | null | undefined): AIProviderKey | null return null; } +function lazyMigrateApiKey(userId: string, plaintext: string): void { + void (async () => { + try { + const encrypted = encryptSecret(plaintext); + await prisma.userAISettings.update({ + where: { userId }, + data: { apiKeyEncrypted: encrypted, apiKey: null }, + }); + } catch { + // Silently swallow — migration retries on next request + } + })(); +} + export async function resolveAIConfig(userId?: string | null): Promise { if (userId) { const settings = await prisma.userAISettings.findUnique({ where: { userId } }); const provider = normalizeProvider(settings?.provider ?? null); if (provider) { - const hasRequired = provider === "custom" ? Boolean(settings?.baseUrl) : Boolean(settings?.apiKey); + const apiKey = resolveSecret(settings?.apiKeyEncrypted, settings?.apiKey); + const hasRequired = provider === "custom" ? Boolean(settings?.baseUrl) : Boolean(apiKey); if (hasRequired) { + // Lazy-migrate legacy plaintext key to encrypted storage + if (settings && !settings.apiKeyEncrypted && settings.apiKey && isEncryptionEnabled()) { + lazyMigrateApiKey(userId, settings.apiKey); + } return { provider, - apiKey: settings?.apiKey ?? undefined, + apiKey: apiKey ?? undefined, model: settings?.model ?? undefined, baseUrl: settings?.baseUrl ?? undefined, visionSupport: settings?.visionSupport ?? null, @@ -113,6 +133,7 @@ async function getConfigSource(userId?: string | null) { if (!userId) return "env" as const; const settings = await prisma.userAISettings.findUnique({ where: { userId } }); if (!settings?.provider) return "env" as const; - const hasRequired = settings.provider === "custom" ? Boolean(settings.baseUrl) : Boolean(settings.apiKey); + const hasApiKey = Boolean(resolveSecret(settings.apiKeyEncrypted, settings.apiKey)); + const hasRequired = settings.provider === "custom" ? Boolean(settings.baseUrl) : hasApiKey; return hasRequired ? ("user" as const) : ("env" as const); } diff --git a/src/lib/ai/settings.ts b/src/lib/ai/settings.ts index 342c098..4f113e5 100644 --- a/src/lib/ai/settings.ts +++ b/src/lib/ai/settings.ts @@ -6,6 +6,7 @@ import { buildAIProvider, resolveAIConfig } from "@/lib/ai"; import type { AIConfig, AIProviderKey } from "@/lib/ai/types"; import { normalizeErrorMessage } from "@/lib/ai/utils"; import { prisma } from "@/lib/prisma"; +import { resolveSecret } from "@/lib/crypto/secrets"; const DEFAULT_MODELS: Record = { claude: "claude-sonnet-4-5-20250929", @@ -43,7 +44,10 @@ export async function resolveAIConfigFromRequest(userId: string, body: unknown): const existing = await prisma.userAISettings.findUnique({ where: { userId } }); const apiKeyDraft = trimString(data.apiKey, 500); - const apiKey = apiKeyDraft || (existing?.provider === requestedProvider ? existing.apiKey ?? undefined : undefined); + const storedApiKey = existing?.provider === requestedProvider + ? (resolveSecret(existing.apiKeyEncrypted, existing.apiKey) ?? undefined) + : undefined; + const apiKey = apiKeyDraft || storedApiKey; const model = trimString(data.model, 200) || undefined; const baseUrl = trimString(data.baseUrl, 500) || undefined; diff --git a/src/lib/crypto/secrets.ts b/src/lib/crypto/secrets.ts new file mode 100644 index 0000000..9390c21 --- /dev/null +++ b/src/lib/crypto/secrets.ts @@ -0,0 +1,76 @@ +import { createCipheriv, createDecipheriv, randomBytes } from 'node:crypto'; + +const ALGORITHM = 'aes-256-gcm'; +const IV_LEN = 16; +const TAG_LEN = 16; +const KEY_LEN = 32; +const PREFIX = 'v1:'; + +function getKey(): Buffer | null { + const raw = process.env.OSE_ENCRYPTION_KEY; + if (!raw) return null; + try { + const key = Buffer.from(raw, 'base64'); + return key.length === KEY_LEN ? key : null; + } catch { + return null; + } +} + +export function isEncryptionEnabled(): boolean { + return getKey() !== null; +} + +export function isEncryptedSecret(value: string | null | undefined): boolean { + return typeof value === 'string' && value.startsWith(PREFIX); +} + +export function encryptSecret(plain: string): string { + const key = getKey(); + if (!key) throw new Error('OSE_ENCRYPTION_KEY is not configured or is invalid'); + const iv = randomBytes(IV_LEN); + const cipher = createCipheriv(ALGORITHM, key, iv); + const ciphertext = Buffer.concat([cipher.update(plain, 'utf8'), cipher.final()]); + const tag = cipher.getAuthTag(); + return `${PREFIX}${iv.toString('hex')}:${tag.toString('hex')}:${ciphertext.toString('hex')}`; +} + +export function decryptSecret(encrypted: string): string | null { + if (!isEncryptedSecret(encrypted)) return null; + const key = getKey(); + if (!key) return null; + try { + const parts = encrypted.slice(PREFIX.length).split(':'); + if (parts.length !== 3) return null; + const [ivHex, tagHex, ctHex] = parts; + const iv = Buffer.from(ivHex, 'hex'); + const tag = Buffer.from(tagHex, 'hex'); + const ct = Buffer.from(ctHex, 'hex'); + if (iv.length !== IV_LEN || tag.length !== TAG_LEN) return null; + const decipher = createDecipheriv(ALGORITHM, key, iv); + decipher.setAuthTag(tag); + return Buffer.concat([decipher.update(ct), decipher.final()]).toString('utf8'); + } catch { + return null; + } +} + +/** + * Resolve a stored key for use: + * - If an encrypted value exists, decrypt it (null on failure). + * - If only a legacy plaintext value exists AND encryption is enabled, return it + * so the caller can encrypt and migrate it. Without encryption enabled, the + * legacy plaintext is treated as unconfigured. + */ +export function resolveSecret( + encrypted: string | null | undefined, + plaintext: string | null | undefined, +): string | null { + if (encrypted) { + return decryptSecret(encrypted); + } + if (plaintext && isEncryptionEnabled()) { + return plaintext; + } + return null; +} diff --git a/src/prisma/migrations/20260502140000_add_encrypted_api_key_fields/migration.sql b/src/prisma/migrations/20260502140000_add_encrypted_api_key_fields/migration.sql new file mode 100644 index 0000000..ec4bae8 --- /dev/null +++ b/src/prisma/migrations/20260502140000_add_encrypted_api_key_fields/migration.sql @@ -0,0 +1,3 @@ +-- AlterTable: add encrypted API key columns to UserAISettings +ALTER TABLE "UserAISettings" ADD COLUMN "apiKeyEncrypted" TEXT; +ALTER TABLE "UserAISettings" ADD COLUMN "imageApiKeyEncrypted" TEXT; diff --git a/src/prisma/schema.prisma b/src/prisma/schema.prisma index 48d6792..c202488 100644 --- a/src/prisma/schema.prisma +++ b/src/prisma/schema.prisma @@ -89,11 +89,13 @@ model UserAISettings { provider String? model String? apiKey String? + apiKeyEncrypted String? baseUrl String? visionSupport Boolean? imageProvider String? imageModel String? imageApiKey String? + imageApiKeyEncrypted String? imageBaseUrl String? imageSize String? imageQuality String? diff --git a/src/test/crypto-secrets.test.ts b/src/test/crypto-secrets.test.ts new file mode 100644 index 0000000..2bececc --- /dev/null +++ b/src/test/crypto-secrets.test.ts @@ -0,0 +1,180 @@ +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { + decryptSecret, + encryptSecret, + isEncryptedSecret, + isEncryptionEnabled, + resolveSecret, +} from '@/lib/crypto/secrets'; + +const VALID_KEY = Buffer.alloc(32, 0xab).toString('base64'); // 32-byte key + +function withKey(key: string | undefined, fn: () => void) { + const prev = process.env.OSE_ENCRYPTION_KEY; + if (key === undefined) { + delete process.env.OSE_ENCRYPTION_KEY; + } else { + process.env.OSE_ENCRYPTION_KEY = key; + } + try { + fn(); + } finally { + if (prev === undefined) { + delete process.env.OSE_ENCRYPTION_KEY; + } else { + process.env.OSE_ENCRYPTION_KEY = prev; + } + } +} + +describe('isEncryptionEnabled', () => { + it('returns false when OSE_ENCRYPTION_KEY is absent', () => { + withKey(undefined, () => { + expect(isEncryptionEnabled()).toBe(false); + }); + }); + + it('returns false when key is wrong length', () => { + withKey(Buffer.alloc(16).toString('base64'), () => { + expect(isEncryptionEnabled()).toBe(false); + }); + }); + + it('returns true when a valid 32-byte key is set', () => { + withKey(VALID_KEY, () => { + expect(isEncryptionEnabled()).toBe(true); + }); + }); +}); + +describe('isEncryptedSecret', () => { + it('returns false for null/undefined', () => { + expect(isEncryptedSecret(null)).toBe(false); + expect(isEncryptedSecret(undefined)).toBe(false); + }); + + it('returns false for plaintext strings', () => { + expect(isEncryptedSecret('sk-abc123')).toBe(false); + expect(isEncryptedSecret('')).toBe(false); + }); + + it('returns true for v1: prefixed strings', () => { + expect(isEncryptedSecret('v1:aabb:ccdd:eeff')).toBe(true); + }); +}); + +describe('encryptSecret / decryptSecret round-trip', () => { + it('decrypts back to the original value', () => { + withKey(VALID_KEY, () => { + const plain = 'sk-test-secret'; + const encrypted = encryptSecret(plain); + expect(isEncryptedSecret(encrypted)).toBe(true); + expect(decryptSecret(encrypted)).toBe(plain); + }); + }); + + it('produces a different ciphertext each call (random IV)', () => { + withKey(VALID_KEY, () => { + const a = encryptSecret('same-value'); + const b = encryptSecret('same-value'); + expect(a).not.toBe(b); + }); + }); + + it('handles empty strings', () => { + withKey(VALID_KEY, () => { + const encrypted = encryptSecret(''); + expect(decryptSecret(encrypted)).toBe(''); + }); + }); + + it('handles unicode / multi-byte characters', () => { + withKey(VALID_KEY, () => { + const plain = '密钥-🔑-€100'; + expect(decryptSecret(encryptSecret(plain))).toBe(plain); + }); + }); + + it('throws when OSE_ENCRYPTION_KEY is absent', () => { + withKey(undefined, () => { + expect(() => encryptSecret('x')).toThrow(); + }); + }); +}); + +describe('decryptSecret', () => { + it('returns null for non-v1 strings', () => { + withKey(VALID_KEY, () => { + expect(decryptSecret('plaintext')).toBeNull(); + expect(decryptSecret('')).toBeNull(); + }); + }); + + it('returns null when key is absent', () => { + let encrypted!: string; + withKey(VALID_KEY, () => { + encrypted = encryptSecret('secret'); + }); + withKey(undefined, () => { + expect(decryptSecret(encrypted)).toBeNull(); + }); + }); + + it('returns null when ciphertext is tampered', () => { + withKey(VALID_KEY, () => { + const encrypted = encryptSecret('secret'); + const tampered = encrypted.slice(0, -4) + 'xxxx'; + expect(decryptSecret(tampered)).toBeNull(); + }); + }); + + it('returns null when format has wrong segment count', () => { + withKey(VALID_KEY, () => { + expect(decryptSecret('v1:onlytwoparts')).toBeNull(); + }); + }); +}); + +describe('resolveSecret', () => { + it('decrypts the encrypted value when present', () => { + withKey(VALID_KEY, () => { + const encrypted = encryptSecret('my-api-key'); + expect(resolveSecret(encrypted, null)).toBe('my-api-key'); + }); + }); + + it('returns plaintext when encryption is enabled and no encrypted value', () => { + withKey(VALID_KEY, () => { + expect(resolveSecret(null, 'legacy-key')).toBe('legacy-key'); + }); + }); + + it('returns null when only plaintext exists and encryption is NOT enabled', () => { + withKey(undefined, () => { + expect(resolveSecret(null, 'legacy-key')).toBeNull(); + }); + }); + + it('returns null when both are null', () => { + withKey(VALID_KEY, () => { + expect(resolveSecret(null, null)).toBeNull(); + }); + withKey(undefined, () => { + expect(resolveSecret(null, null)).toBeNull(); + }); + }); + + it('prefers encrypted over plaintext', () => { + withKey(VALID_KEY, () => { + const encrypted = encryptSecret('correct-key'); + expect(resolveSecret(encrypted, 'old-key')).toBe('correct-key'); + }); + }); + + it('returns null when decryption fails (tampered)', () => { + withKey(VALID_KEY, () => { + const tampered = 'v1:aabbccdd:eeff0011:22334455'; + expect(resolveSecret(tampered, 'legacy-key')).toBeNull(); + }); + }); +});