diff --git a/.env.example b/.env.example index 159e39f..0601477 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/.env.tauri b/.env.tauri index ed6a579..6dae762 100644 --- a/.env.tauri +++ b/.env.tauri @@ -1,5 +1,6 @@ # Tauri 桌面版配置 NEXTAUTH_URL=http://localhost:19898 -NEXTAUTH_SECRET=ose-desktop-secret-change-me AUTH_URL=http://localhost:19898 -AUTH_SECRET=ose-desktop-secret-change-me +# AUTH_SECRET and NEXTAUTH_SECRET are generated at runtime and injected by the +# Tauri sidecar startup code. For `tauri dev`, set them in a local .env.local +# file (which is gitignored). diff --git a/.github/workflows/android-apk.yml b/.github/workflows/android-apk.yml index 2c32b88..e7d726a 100644 --- a/.github/workflows/android-apk.yml +++ b/.github/workflows/android-apk.yml @@ -55,7 +55,7 @@ jobs: - name: Setup Node.js uses: actions/setup-node@v4 with: - node-version: '20' + node-version: '22' cache: npm - name: Setup Java diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a0a6bbd..96894f6 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -32,7 +32,7 @@ jobs: - uses: actions/checkout@v6 - uses: actions/setup-node@v4 with: - node-version: '20' + node-version: '22' cache: 'npm' - run: npm ci - run: npm run format:check || echo "Formatting drift found; run npm run format locally." @@ -43,7 +43,7 @@ jobs: - uses: actions/checkout@v6 - uses: actions/setup-node@v4 with: - node-version: '20' + node-version: '22' cache: 'npm' - run: npm ci - run: npm run lint @@ -54,7 +54,7 @@ jobs: - uses: actions/checkout@v6 - uses: actions/setup-node@v4 with: - node-version: '20' + node-version: '22' cache: 'npm' - run: npm ci - run: npx prisma generate --schema src/prisma/schema.prisma @@ -67,7 +67,7 @@ jobs: - uses: actions/checkout@v6 - uses: actions/setup-node@v4 with: - node-version: '20' + node-version: '22' cache: 'npm' - run: npm ci - run: npx prisma generate --schema src/prisma/schema.prisma @@ -80,7 +80,7 @@ jobs: - uses: actions/checkout@v6 - uses: actions/setup-node@v4 with: - node-version: '20' + node-version: '22' cache: 'npm' - run: npm ci - run: npx prisma generate --schema src/prisma/schema.prisma diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 1c20726..90ce116 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -47,7 +47,7 @@ jobs: - name: Setup Node.js uses: actions/setup-node@v4 with: - node-version: '20' + node-version: '22' cache: npm - name: Setup Rust @@ -166,7 +166,7 @@ jobs: OSE Windows Portable 1. Keep OSE.exe, portable.ini, and the resources directory together. - 2. Node.js 20+ must be installed and available in PATH. + 2. Node.js 22+ must be installed and available in PATH. 3. User data is stored in the system app data directory. 4. The bundled Next.js standalone server lives in resources/binaries/standalone. "@ | Set-Content -Path (Join-Path $portableDir 'README.txt') -Encoding UTF8 @@ -265,7 +265,7 @@ jobs: - name: Setup Node.js uses: actions/setup-node@v4 with: - node-version: '20' + node-version: '22' cache: npm - name: Setup Java @@ -399,5 +399,5 @@ jobs: - Linux: `OSE-${{ github.ref_name }}-Linux-x86_64.AppImage`, `.deb`, or `.rpm` - Android: `OSE-${{ github.ref_name }}-Android.apk` - Windows portable builds require Node.js 20+ in PATH because the Next.js standalone server is launched locally. + Windows portable builds require Node.js 22+ in PATH because the Next.js standalone server is launched locally. files: release-assets/* diff --git a/.github/workflows/security.yml b/.github/workflows/security.yml index b7237c4..f736ee1 100644 --- a/.github/workflows/security.yml +++ b/.github/workflows/security.yml @@ -36,7 +36,7 @@ jobs: - uses: actions/checkout@v6 - uses: actions/setup-node@v4 with: - node-version: '20' + node-version: '22' cache: 'npm' - run: npm ci - run: npm audit --omit=dev --audit-level=high diff --git a/.github/workflows/tauri-check.yml b/.github/workflows/tauri-check.yml index 570187d..9950daf 100644 --- a/.github/workflows/tauri-check.yml +++ b/.github/workflows/tauri-check.yml @@ -44,7 +44,7 @@ jobs: - uses: actions/setup-node@v4 with: - node-version: '20' + node-version: '22' cache: npm - uses: dtolnay/rust-toolchain@stable diff --git a/.node-version b/.node-version index 209e3ef..2bd5a0a 100644 --- a/.node-version +++ b/.node-version @@ -1 +1 @@ -20 +22 diff --git a/.nvmrc b/.nvmrc index 209e3ef..2bd5a0a 100644 --- a/.nvmrc +++ b/.nvmrc @@ -1 +1 @@ -20 +22 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 8a1b794..6281fa9 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -19,7 +19,7 @@ Thank you for your interest in OSE. We are building an open, self-hostable, AI-p Prerequisites: -- Node.js 20 recommended, Node.js 18+ supported by the project metadata. +- Node.js 20+ supported by the project metadata; Node.js 22 LTS is recommended. - npm 10+. - Git. - Optional: Rust toolchain for Tauri desktop builds. diff --git a/Dockerfile b/Dockerfile index 58c1f99..6f291dc 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ -FROM node:25-alpine AS base +FROM node:22-alpine AS base FROM base AS deps WORKDIR /app diff --git a/docs/desktop-app.md b/docs/desktop-app.md index 014ac6a..b99b586 100644 --- a/docs/desktop-app.md +++ b/docs/desktop-app.md @@ -4,7 +4,7 @@ OSE uses Tauri for desktop packaging on Windows, Linux, and macOS. ## Prerequisites -- Node.js 20 (build host). +- Node.js 22 LTS (build host). - npm. - Rust toolchain. - Tauri system dependencies for your platform. @@ -36,14 +36,14 @@ npm run tauri:build ### Bundling Node.js (no system Node.js required at runtime) -By default the desktop installer relies on the user having Node.js 20+ on `PATH`. To produce a self-contained installer that ships its own Node.js: +By default the desktop installer relies on the user having Node.js 22+ on `PATH`. To produce a self-contained installer that ships its own Node.js: ```bash BUNDLE_NODE=1 npm run tauri:prepare npm run tauri:build ``` -`BUNDLE_NODE=1` downloads the official Node.js binary for the build host's platform/architecture and places it under `src-tauri/binaries/standalone/runtime/`. The Tauri app prefers this binary over `PATH` at runtime. Override the version with `BUNDLED_NODE_VERSION=v20.18.1` (or any other Node.js dist tag) if needed. +`BUNDLE_NODE=1` downloads the official Node.js binary for the build host's platform/architecture and places it under `src-tauri/binaries/standalone/runtime/`. The Tauri app prefers this binary over `PATH` at runtime. Override the version with `BUNDLED_NODE_VERSION=v22.15.0` (or any other Node.js dist tag) if needed. > **Cross-compilation note**: the bundled Node.js matches the build host. To ship for a different OS/arch, run `tauri:prepare` on that platform (e.g. via CI matrix builds). @@ -140,9 +140,43 @@ In production desktop mode, Tauri: 1. Selects an available local port. 2. Creates an app data directory. 3. Sets `DATABASE_URL` to the local SQLite database. -4. Starts `node start.js` — preferring the bundled `runtime/node[.exe]` when present, otherwise `node` from `PATH`. -5. Polls `/api/ai/status` until the Next.js server is ready. -6. Navigates the WebView to `http://127.0.0.1:`. +4. Resolves or generates a per-install auth secret (see [Auth Secret](#auth-secret) below). +5. Starts `node start.js` — preferring the bundled `runtime/node[.exe]` when present, otherwise `node` from `PATH`. +6. Polls `/api/ai/status` until the Next.js server is ready. +7. Navigates the WebView to `http://127.0.0.1:`. + +## Auth Secret + +Each desktop installation generates a unique auth secret on first launch. The secret is used to sign Auth.js / NextAuth session tokens and is never shared between installs. + +### Storage location + +The secret is stored in a file named `auth.secret` inside the app data directory: + +- **Windows**: `%AppData%\com.ose.softwareexam\auth.secret` +- **macOS**: `~/Library/Application Support/com.ose.softwareexam/auth.secret` +- **Linux**: `~/.local/share/com.ose.softwareexam/auth.secret` + +### Format and permissions + +The file contains a 44-character Base64 string derived from 32 cryptographically random bytes. On Unix-like systems the file is created with `0600` (owner read/write only) permissions set at creation time, with no intermediate world-readable state. + +### Secret reuse across restarts + +On subsequent launches the app reads the existing `auth.secret` file and reuses the value. If the file is missing or empty, a new secret is generated automatically. + +### Impact of deleting the file + +Deleting `auth.secret` causes a new secret to be generated on the next launch. All existing sessions become invalid (users are signed out), but no study data is lost. + +### Development mode + +For `tauri dev`, `AUTH_SECRET` and `NEXTAUTH_SECRET` are **not** injected automatically. Set them in a local `.env.local` file (which is gitignored): + +```env +AUTH_SECRET=any-local-dev-value +NEXTAUTH_SECRET=any-local-dev-value +``` ## Portable Zip (Windows) diff --git a/docs/getting-started.md b/docs/getting-started.md index 0991cbe..5a4104a 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -4,7 +4,7 @@ This guide walks you from a clean machine to a running OSE development server. ## Prerequisites -- Node.js 18+; Node.js 20 is recommended. +- Node.js 20+; Node.js 22 LTS is recommended. - npm 10+. - Git. - Optional: Rust and the Tauri prerequisites if you want to build the desktop app. diff --git a/docs/self-hosting.md b/docs/self-hosting.md index 063ee01..3073fee 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. @@ -40,7 +47,7 @@ npx prisma migrate deploy ## VPS Manual Deployment -Install Node.js 20, clone the repository, then: +Install Node.js 22 LTS, clone the repository, then: ```bash npm ci @@ -132,3 +139,32 @@ explicit request/body model > saved user setting > DEFAULT__MODEL env ``` This means a user's saved model preference always wins, and the env override only applies when no model has been saved by the user. + +## 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/package-lock.json b/package-lock.json index 1847ba5..893582f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -60,7 +60,7 @@ "vitest": "^4.1.5" }, "engines": { - "node": ">=18.0.0" + "node": ">=20.0.0" } }, "node_modules/@alloc/quick-lru": { diff --git a/package.json b/package.json index 2c4c8a1..5b9d8b1 100644 --- a/package.json +++ b/package.json @@ -24,7 +24,7 @@ "self-hosted" ], "engines": { - "node": ">=18.0.0" + "node": ">=20.0.0" }, "scripts": { "dev": "next dev", diff --git a/scripts/prepare-sidecar.js b/scripts/prepare-sidecar.js index 6c2e2af..75b9e6b 100644 --- a/scripts/prepare-sidecar.js +++ b/scripts/prepare-sidecar.js @@ -334,7 +334,7 @@ async function main() { } else { fs.rmSync(runtimeTarget, { recursive: true, force: true }); console.log( - 'Using PATH Node.js mode. Install Node.js 20+ on target machines, or set BUNDLE_NODE=1 to ship a bundled runtime.' + 'Using PATH Node.js mode. Install Node.js 22+ on target machines, or set BUNDLE_NODE=1 to ship a bundled runtime.' ); } } diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 8159e02..af83ca9 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -11,6 +11,8 @@ crate-type = ["staticlib", "cdylib", "rlib"] tauri-build = { version = "2", features = [] } [dependencies] +base64 = "0.22" +getrandom = "0.2" portpicker = "0.1" serde = { version = "1", features = ["derive"] } serde_json = "1" diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 0a062f4..00ae30b 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -1,3 +1,4 @@ +use base64::Engine as _; use std::{ env, fs, io::{BufRead, BufReader, Write}, @@ -122,6 +123,7 @@ fn start_next_server(app: &AppHandle) -> Result { )); } + let auth_secret = resolve_or_create_auth_secret(&data_dir)?; let port = pick_port()?; let database_path = data_dir.join("ose.db"); let database_url = format!("file:{}", database_path.to_string_lossy()); @@ -144,6 +146,8 @@ fn start_next_server(app: &AppHandle) -> Result { .env("PORT", port.to_string()) .env("HOSTNAME", "127.0.0.1") .env("DATABASE_URL", database_url) + .env("AUTH_SECRET", &auth_secret) + .env("NEXTAUTH_SECRET", &auth_secret) .env("AUTH_URL", format!("http://127.0.0.1:{port}")) .env("NEXTAUTH_URL", format!("http://127.0.0.1:{port}")) .env("NODE_ENV", "production") @@ -163,7 +167,7 @@ fn start_next_server(app: &AppHandle) -> Result { node_binary.display() ) } else { - format!("启动 Node.js 失败:{error}。请安装 Node.js 20+ 并加入 PATH,或使用 BUNDLE_NODE=1 重新打包。") + format!("启动 Node.js 失败:{error}。请安装 Node.js 22+ 并加入 PATH,或使用 BUNDLE_NODE=1 重新打包。") }; log_line(log.as_ref(), &format!("[startup] spawn error: {msg}")); msg @@ -370,6 +374,60 @@ where } } +fn resolve_or_create_auth_secret(data_dir: &PathBuf) -> Result { + let secret_path = data_dir.join("auth.secret"); + + if secret_path.exists() { + let content = fs::read_to_string(&secret_path) + .map_err(|e| format!("读取 auth.secret 失败:{e}"))?; + let trimmed = content.trim().to_string(); + if !trimmed.is_empty() { + return Ok(trimmed); + } + // Empty file — fall through and generate a fresh secret. + } + + let mut bytes = [0u8; 32]; + getrandom::getrandom(&mut bytes).map_err(|e| format!("生成随机 secret 失败:{e}"))?; + let secret = base64::engine::general_purpose::STANDARD.encode(bytes); + write_secret_atomic(&secret_path, &secret)?; + Ok(secret) +} + +#[cfg(unix)] +fn create_secret_file(path: &std::path::Path) -> Result { + use std::os::unix::fs::OpenOptionsExt; + fs::OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .open(path) +} + +#[cfg(not(unix))] +fn create_secret_file(path: &std::path::Path) -> Result { + fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(path) +} + +fn write_secret_atomic(secret_path: &PathBuf, secret: &str) -> Result<(), String> { + let tmp_path = secret_path.with_file_name("auth.secret.tmp"); + // Remove any leftover temp file so create_new(true) can succeed. + let _ = fs::remove_file(&tmp_path); + let mut file = create_secret_file(&tmp_path) + .map_err(|e| format!("创建临时 secret 文件失败:{e}"))?; + file.write_all(secret.as_bytes()) + .map_err(|e| format!("写入 secret 失败:{e}"))?; + drop(file); + if secret_path.exists() { + fs::remove_file(secret_path) + .map_err(|e| format!("移除旧 secret 文件失败:{e}"))?; + } + fs::rename(&tmp_path, secret_path).map_err(|e| format!("移动 secret 文件失败:{e}")) +} + fn show_error_page(window: &WebviewWindow, message: &str) { let escaped = message .replace('&', "&") diff --git a/src/app/api/profile/ai-settings/route.ts b/src/app/api/profile/ai-settings/route.ts index 487733a..4f658f6 100644 --- a/src/app/api/profile/ai-settings/route.ts +++ b/src/app/api/profile/ai-settings/route.ts @@ -13,6 +13,7 @@ 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 +41,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 +90,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) { @@ -89,13 +99,35 @@ export async function PUT(request: Request) { const providerChanged = provider !== (existing?.provider ?? ''); const modelChanged = model !== (existing?.model ?? ''); - const nextVisionSupport = providerChanged || modelChanged ? null : (existing?.visionSupport ?? null); + const nextVisionSupport = + providerChanged || modelChanged ? null : (existing?.visionSupport ?? 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 nextApiKey = clearApiKey - ? null - : apiKeyRaw - ? apiKeyRaw.trim().slice(0, 500) - : (existing?.apiKey ?? null); const imageProvider = hasOwn(body, 'imageProvider') ? normalizeImageProvider(body.imageProvider) : normalizeImageProvider(existing?.imageProvider); @@ -108,13 +140,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 +202,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 +223,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..6d8abb8 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,41 @@ 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 +171,11 @@ 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 +269,9 @@ 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 hasRequired = - provider === 'custom' ? Boolean(settings?.imageBaseUrl) : Boolean(settings?.imageApiKey); + const hasImageApiKey = Boolean( + resolveSecret(settings?.imageApiKeyEncrypted, settings?.imageApiKey) + ); + const hasRequired = 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 e691ca5..c4ce0ba 100644 --- a/src/lib/ai/index.ts +++ b/src/lib/ai/index.ts @@ -1,31 +1,52 @@ -import type { AIConfig, AIProvider, AIProviderKey } from "@/lib/ai/types"; -import { createClaudeProvider } from "@/lib/ai/providers/claude"; -import { createOpenAIProvider } from "@/lib/ai/providers/openai"; -import { createGeminiProvider } from "@/lib/ai/providers/gemini"; -import { createCustomProvider } from "@/lib/ai/providers/custom"; -import { resolveDefaultModel } from "@/lib/ai/utils"; -import { prisma } from "@/lib/prisma"; +import type { AIConfig, AIProvider, AIProviderKey } from '@/lib/ai/types'; +import { createClaudeProvider } from '@/lib/ai/providers/claude'; +import { createOpenAIProvider } from '@/lib/ai/providers/openai'; +import { createGeminiProvider } from '@/lib/ai/providers/gemini'; +import { createCustomProvider } from '@/lib/ai/providers/custom'; +import { resolveDefaultModel } from '@/lib/ai/utils'; +import { prisma } from '@/lib/prisma'; +import { encryptSecret, isEncryptionEnabled, resolveSecret } from '@/lib/crypto/secrets'; function envConfigFor(provider: AIProviderKey): AIConfig | null { - if (provider === "claude") { + if (provider === 'claude') { const apiKey = process.env.ANTHROPIC_API_KEY; if (!apiKey) return null; - return { provider, apiKey, model: process.env.ANTHROPIC_MODEL || resolveDefaultModel("claude"), baseUrl: process.env.ANTHROPIC_BASE_URL }; + return { + provider, + apiKey, + model: process.env.ANTHROPIC_MODEL || resolveDefaultModel('claude'), + baseUrl: process.env.ANTHROPIC_BASE_URL, + }; } - if (provider === "openai") { + if (provider === 'openai') { const apiKey = process.env.OPENAI_API_KEY; if (!apiKey) return null; - return { provider, apiKey, model: process.env.OPENAI_MODEL || resolveDefaultModel("openai"), baseUrl: process.env.OPENAI_BASE_URL }; + return { + provider, + apiKey, + model: process.env.OPENAI_MODEL || resolveDefaultModel('openai'), + baseUrl: process.env.OPENAI_BASE_URL, + }; } - if (provider === "gemini") { + if (provider === 'gemini') { const apiKey = process.env.GEMINI_API_KEY; if (!apiKey) return null; - return { provider, apiKey, model: process.env.GEMINI_MODEL || resolveDefaultModel("gemini"), baseUrl: process.env.GEMINI_BASE_URL }; + return { + provider, + apiKey, + model: process.env.GEMINI_MODEL || resolveDefaultModel('gemini'), + baseUrl: process.env.GEMINI_BASE_URL, + }; } - if (provider === "custom") { + if (provider === 'custom') { const baseUrl = process.env.CUSTOM_BASE_URL; if (!baseUrl) return null; - return { provider, apiKey: process.env.CUSTOM_API_KEY, model: process.env.CUSTOM_MODEL || resolveDefaultModel("custom"), baseUrl }; + return { + provider, + apiKey: process.env.CUSTOM_API_KEY, + model: process.env.CUSTOM_MODEL || resolveDefaultModel('custom'), + baseUrl, + }; } return null; } @@ -36,7 +57,7 @@ function resolveEnvConfig(): AIConfig | null { const config = envConfigFor(preferred); if (config) return config; } - for (const provider of ["claude", "openai", "gemini", "custom"] as AIProviderKey[]) { + for (const provider of ['claude', 'openai', 'gemini', 'custom'] as AIProviderKey[]) { const config = envConfigFor(provider); if (config) return config; } @@ -46,20 +67,40 @@ function resolveEnvConfig(): AIConfig | null { function normalizeProvider(raw: string | null | undefined): AIProviderKey | null { if (!raw) return null; const value = raw.toLowerCase(); - if (value === "claude" || value === "openai" || value === "gemini" || value === "custom") return value; + if (value === 'claude' || value === 'openai' || value === 'gemini' || value === 'custom') + return value; 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 || resolveDefaultModel(provider), baseUrl: settings?.baseUrl ?? undefined, visionSupport: settings?.visionSupport ?? null, @@ -71,16 +112,16 @@ export async function resolveAIConfig(userId?: string | null): Promise { const config = await resolveAIConfig(userId); - if (!config) throw new Error("未配置 AI 供应商,请在个人中心填入 API Key 或设置环境变量"); + if (!config) throw new Error('未配置 AI 供应商,请在个人中心填入 API Key 或设置环境变量'); return buildAIProvider(config); } @@ -111,9 +152,10 @@ export async function getAIStatus(userId?: string | null) { } async function getConfigSource(userId?: string | null) { - if (!userId) return "env" as const; + 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); - return hasRequired ? ("user" as const) : ("env" as const); + if (!settings?.provider) return 'env' as const; + 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 136c3d2..2ef5a29 100644 --- a/src/lib/ai/settings.ts +++ b/src/lib/ai/settings.ts @@ -1,56 +1,70 @@ -import Anthropic from "@anthropic-ai/sdk"; -import { GoogleGenAI } from "@google/genai"; -import OpenAI from "openai"; +import Anthropic from '@anthropic-ai/sdk'; +import { GoogleGenAI } from '@google/genai'; +import OpenAI from 'openai'; -import { buildAIProvider, resolveAIConfig } from "@/lib/ai"; -import type { AIConfig, AIProviderKey } from "@/lib/ai/types"; -import { normalizeErrorMessage, resolveDefaultModel } from "@/lib/ai/utils"; -import { prisma } from "@/lib/prisma"; +import { buildAIProvider, resolveAIConfig } from '@/lib/ai'; +import type { AIConfig, AIProviderKey } from '@/lib/ai/types'; +import { normalizeErrorMessage, resolveDefaultModel } from '@/lib/ai/utils'; +import { prisma } from '@/lib/prisma'; +import { resolveSecret } from '@/lib/crypto/secrets'; const DEFAULT_BASE_URLS: Record = { - claude: "https://api.anthropic.com", - openai: "https://api.openai.com/v1", + claude: 'https://api.anthropic.com', + openai: 'https://api.openai.com/v1', gemini: undefined, custom: undefined, }; function normalizeProvider(value: unknown): AIProviderKey | null { - const provider = String(value ?? "").toLowerCase(); - if (provider === "claude" || provider === "openai" || provider === "gemini" || provider === "custom") return provider; + const provider = String(value ?? '').toLowerCase(); + if ( + provider === 'claude' || + provider === 'openai' || + provider === 'gemini' || + provider === 'custom' + ) + return provider; return null; } function trimString(value: unknown, maxLength: number) { - return typeof value === "string" ? value.trim().slice(0, maxLength) : ""; + return typeof value === 'string' ? value.trim().slice(0, maxLength) : ''; } export async function resolveAIConfigFromRequest(userId: string, body: unknown): Promise { - const data = body && typeof body === "object" ? body as Record : {}; + const data = body && typeof body === 'object' ? (body as Record) : {}; const requestedProvider = normalizeProvider(data.provider); if (!requestedProvider) { const config = await resolveAIConfig(userId); - if (!config) throw new Error("未找到可用的 AI 配置"); + if (!config) throw new Error('未找到可用的 AI 配置'); return config; } 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; - if (requestedProvider === "custom" && !baseUrl) { - throw new Error("自定义供应商需要填写 Base URL"); + if (requestedProvider === 'custom' && !baseUrl) { + throw new Error('自定义供应商需要填写 Base URL'); } - if (requestedProvider !== "custom" && !apiKey) { - throw new Error("请先填写或保存 API Key"); + if (requestedProvider !== 'custom' && !apiKey) { + throw new Error('请先填写或保存 API Key'); } - const visionSupport = "visionSupport" in data - ? (data.visionSupport === true || data.visionSupport === false ? data.visionSupport : null) - : null; + const visionSupport = + 'visionSupport' in data + ? data.visionSupport === true || data.visionSupport === false + ? data.visionSupport + : null + : null; return { provider: requestedProvider, @@ -62,10 +76,11 @@ export async function resolveAIConfigFromRequest(userId: string, body: unknown): } export async function listAIModels(config: AIConfig) { - if (config.provider === "openai") return listOpenAICompatibleModels(config, DEFAULT_BASE_URLS.openai); - if (config.provider === "custom") return listOpenAICompatibleModels(config, config.baseUrl); - if (config.provider === "claude") return listClaudeModels(config); - if (config.provider === "gemini") return listGeminiModels(config); + if (config.provider === 'openai') + return listOpenAICompatibleModels(config, DEFAULT_BASE_URLS.openai); + if (config.provider === 'custom') return listOpenAICompatibleModels(config, config.baseUrl); + if (config.provider === 'claude') return listClaudeModels(config); + if (config.provider === 'gemini') return listGeminiModels(config); return []; } @@ -76,8 +91,8 @@ export async function testAIConfig(config: AIConfig) { model: config.model || resolveDefaultModel(config.provider), }); const content = await provider.createCompletion({ - systemPrompt: "You are a connectivity checker. Reply with exactly: OK", - userMessage: "Reply with OK only.", + systemPrompt: 'You are a connectivity checker. Reply with exactly: OK', + userMessage: 'Reply with OK only.', maxTokens: 12, temperature: 0, }); @@ -93,9 +108,11 @@ export async function testAIConfig(config: AIConfig) { // Minimal 1×1 transparent PNG encoded as a data URL for vision smoke tests. const VISION_TEST_IMAGE = - "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=="; + 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=='; -export async function testVisionCapability(config: AIConfig): Promise<{ supportsVision: boolean; latencyMs: number }> { +export async function testVisionCapability( + config: AIConfig +): Promise<{ supportsVision: boolean; latencyMs: number }> { const startedAt = Date.now(); const provider = buildAIProvider({ ...config, @@ -104,8 +121,8 @@ export async function testVisionCapability(config: AIConfig): Promise<{ supports }); try { await provider.createCompletion({ - systemPrompt: "You are a vision checker. If you can see images, reply with exactly: OK", - userMessage: "Reply with OK only.", + systemPrompt: 'You are a vision checker. If you can see images, reply with exactly: OK', + userMessage: 'Reply with OK only.', imageUrls: [VISION_TEST_IMAGE], maxTokens: 12, temperature: 0, @@ -117,15 +134,18 @@ export async function testVisionCapability(config: AIConfig): Promise<{ supports } async function listOpenAICompatibleModels(config: AIConfig, fallbackBaseUrl: string | undefined) { - const baseUrl = (config.baseUrl || fallbackBaseUrl || "").replace(/\/$/, ""); - if (!baseUrl) throw new Error("请填写 Base URL"); + const baseUrl = (config.baseUrl || fallbackBaseUrl || '').replace(/\/$/, ''); + if (!baseUrl) throw new Error('请填写 Base URL'); - const headers: Record = { Accept: "application/json" }; + const headers: Record = { Accept: 'application/json' }; if (config.apiKey) headers.Authorization = `Bearer ${config.apiKey}`; - const response = await fetch(`${baseUrl}/models`, { headers, cache: "no-store" }); + const response = await fetch(`${baseUrl}/models`, { headers, cache: 'no-store' }); if (!response.ok) throw new Error(`模型列表获取失败:HTTP ${response.status}`); - const data = await response.json() as { data?: Array<{ id?: string; name?: string }>; models?: Array<{ id?: string; name?: string }>; }; + const data = (await response.json()) as { + data?: Array<{ id?: string; name?: string }>; + models?: Array<{ id?: string; name?: string }>; + }; const rawModels = data.data ?? data.models ?? []; return uniqueSorted(rawModels.map((item) => item.id || item.name).filter(Boolean) as string[]); } @@ -140,15 +160,20 @@ async function listClaudeModels(config: AIConfig) { } async function listGeminiModels(config: AIConfig) { - if (!config.apiKey) throw new Error("请先填写 Gemini API Key"); - const client = new GoogleGenAI(config.baseUrl ? { apiKey: config.apiKey, httpOptions: { baseUrl: config.baseUrl } } : { apiKey: config.apiKey }); + if (!config.apiKey) throw new Error('请先填写 Gemini API Key'); + const client = new GoogleGenAI( + config.baseUrl + ? { apiKey: config.apiKey, httpOptions: { baseUrl: config.baseUrl } } + : { apiKey: config.apiKey } + ); const pager = await client.models.list({ config: { pageSize: 100 } }); const models: string[] = []; for await (const model of pager) { - const supportsGenerate = !model.supportedActions?.length || model.supportedActions.includes("generateContent"); + const supportsGenerate = + !model.supportedActions?.length || model.supportedActions.includes('generateContent'); if (!supportsGenerate) continue; - const name = model.name?.replace(/^models\//, "") || model.displayName; + const name = model.name?.replace(/^models\//, '') || model.displayName; if (name) models.push(name); } @@ -156,9 +181,11 @@ async function listGeminiModels(config: AIConfig) { } function uniqueSorted(models: string[]) { - return [...new Set(models.map((model) => model.trim()).filter(Boolean))].sort((first, second) => first.localeCompare(second)); + return [...new Set(models.map((model) => model.trim()).filter(Boolean))].sort((first, second) => + first.localeCompare(second) + ); } export function aiSettingsError(error: unknown) { - return normalizeErrorMessage(error) || "AI 操作失败"; + return normalizeErrorMessage(error) || 'AI 操作失败'; } diff --git a/src/lib/crypto/secrets.ts b/src/lib/crypto/secrets.ts new file mode 100644 index 0000000..8bd1f3c --- /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/api-ai-settings-secrets.test.ts b/src/test/api-ai-settings-secrets.test.ts new file mode 100644 index 0000000..089b9f1 --- /dev/null +++ b/src/test/api-ai-settings-secrets.test.ts @@ -0,0 +1,132 @@ +import { testApiHandler } from 'next-test-api-route-handler'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { decryptSecret } from '@/lib/crypto/secrets'; +import { prisma } from '@/lib/prisma'; +import { createTestUser, resetUserData, sessionFor } from '@/test/helpers'; + +const VALID_KEY = Buffer.alloc(32, 0xcd).toString('base64'); + +async function loadAISettingsRoute(session: unknown) { + vi.resetModules(); + vi.doMock('@/lib/auth', () => ({ auth: async () => session })); + return import('@/app/api/profile/ai-settings/route'); +} + +describe('/api/profile/ai-settings secret storage', () => { + beforeEach(async () => { + delete process.env.OSE_ENCRYPTION_KEY; + await resetUserData(); + }); + + afterEach(() => { + delete process.env.OSE_ENCRYPTION_KEY; + vi.doUnmock('@/lib/auth'); + }); + + it('refuses to persist a new API key when OSE_ENCRYPTION_KEY is missing', async () => { + const user = await createTestUser({ + id: 'ai-settings-no-key', + email: 'ai-settings-no-key@example.com', + }); + const appHandler = await loadAISettingsRoute(sessionFor(user)); + + await testApiHandler({ + appHandler, + async test({ fetch }) { + const response = await fetch({ + method: 'PUT', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ + provider: 'openai', + model: 'gpt-test', + apiKey: 'sk-plaintext-should-not-save', + }), + }); + + expect(response.status).toBe(503); + }, + }); + + const saved = await prisma.userAISettings.findUnique({ where: { userId: user.id } }); + expect(saved).toBeNull(); + }); + + it('encrypts text and image API keys on write and decrypts them for settings reads', async () => { + process.env.OSE_ENCRYPTION_KEY = VALID_KEY; + const user = await createTestUser({ + id: 'ai-settings-encrypted', + email: 'ai-settings-encrypted@example.com', + }); + const appHandler = await loadAISettingsRoute(sessionFor(user)); + + await testApiHandler({ + appHandler, + async test({ fetch }) { + const putResponse = await fetch({ + method: 'PUT', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ + provider: 'openai', + model: 'gpt-test', + apiKey: 'sk-text-secret', + imageProvider: 'openai', + imageModel: 'gpt-image-test', + imageApiKey: 'sk-image-secret', + }), + }); + + expect(putResponse.status).toBe(200); + + const getResponse = await fetch(); + const body = await getResponse.json(); + + expect(getResponse.status).toBe(200); + expect(body.hasApiKey).toBe(true); + expect(body.hasImageApiKey).toBe(true); + expect(body.apiKeyMasked).not.toContain('sk-text-secret'); + expect(body.imageApiKeyMasked).not.toContain('sk-image-secret'); + }, + }); + + const saved = await prisma.userAISettings.findUnique({ where: { userId: user.id } }); + expect(saved?.apiKey).toBeNull(); + expect(saved?.imageApiKey).toBeNull(); + expect(saved?.apiKeyEncrypted).toMatch(/^v1:/); + expect(saved?.imageApiKeyEncrypted).toMatch(/^v1:/); + expect(decryptSecret(saved!.apiKeyEncrypted!)).toBe('sk-text-secret'); + expect(decryptSecret(saved!.imageApiKeyEncrypted!)).toBe('sk-image-secret'); + }); + + it('lazy-migrates legacy plaintext API keys when encryption is configured', async () => { + process.env.OSE_ENCRYPTION_KEY = VALID_KEY; + const user = await createTestUser({ + id: 'ai-settings-legacy', + email: 'ai-settings-legacy@example.com', + }); + await prisma.userAISettings.create({ + data: { + userId: user.id, + provider: 'openai', + model: 'gpt-test', + apiKey: 'sk-legacy-secret', + }, + }); + + const { resolveAIConfig } = await import('@/lib/ai'); + const config = await resolveAIConfig(user.id); + + expect(config).toMatchObject({ + provider: 'openai', + apiKey: 'sk-legacy-secret', + model: 'gpt-test', + }); + + await vi.waitFor(async () => { + const migrated = await prisma.userAISettings.findUnique({ where: { userId: user.id } }); + expect(migrated?.apiKey).toBeNull(); + expect(migrated?.apiKeyEncrypted).toMatch(/^v1:/); + expect(decryptSecret(migrated!.apiKeyEncrypted!)).toBe('sk-legacy-secret'); + }); + }); +}); 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(); + }); + }); +});