Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -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 生成
Expand Down
36 changes: 36 additions & 0 deletions docs/self-hosting.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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.
102 changes: 82 additions & 20 deletions src/app/api/profile/ai-settings/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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']);

Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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) {
Expand All @@ -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);
Expand All @@ -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);
Expand Down Expand Up @@ -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,
Expand All @@ -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,
Expand Down
36 changes: 28 additions & 8 deletions src/lib/ai/image.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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<AIImageConfig | null> {
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),
Expand Down Expand Up @@ -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;

Expand Down Expand Up @@ -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);
}
27 changes: 24 additions & 3 deletions src/lib/ai/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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") {
Expand Down Expand Up @@ -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<AIConfig | null> {
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,
Expand Down Expand Up @@ -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);
}
6 changes: 5 additions & 1 deletion src/lib/ai/settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<AIProviderKey, string> = {
claude: "claude-sonnet-4-5-20250929",
Expand Down Expand Up @@ -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;

Expand Down
Loading
Loading