Repository navigation
Description
Problem
User-provided upstream AI API keys are currently stored in plaintext in the database.
Files:
src/prisma/schema.prisma(model UserAISettings)src/app/api/profile/ai-settings/route.tssrc/lib/ai/index.ts(resolveAIConfig)src/lib/ai/settings.ts(resolveAIConfigFromRequest)src/lib/ai/image.ts(image provider config)
Current schema:
model UserAISettings {
userId String @id
provider String?
model String?
apiKey String?
baseUrl String?
...
imageApiKey String?
...
}Both apiKey and imageApiKey are sensitive user secrets and are stored as raw plaintext.
Why This Matters
OSE is positioned around self-hosting and BYO API keys. That makes user-provided Anthropic/OpenAI/Gemini/custom provider keys part of the core trust boundary.
If the database is leaked or copied accidentally, for example through:
- leaked SQLite file / Docker volume,
- misconfigured backups,
- copied production database snapshots,
- weak filesystem permissions,
- future PostgreSQL dump exposure,
then every stored upstream API key can be used directly by an attacker to consume the corresponding user account quota.
The UI masks keys on read, but the database still contains the full plaintext values.
Current Read/Write Paths
Examples:
src/app/api/profile/ai-settings/route.tssavesapiKeyandimageApiKeyviaprisma.userAISettings.upsert.src/lib/ai/index.tsreadssettings.apiKeyinresolveAIConfig.src/lib/ai/settings.tsfalls back toexisting.apiKeywhen validating provider settings from request bodies.src/lib/ai/image.tsreads and reusessettings.imageApiKeyfor image generation providers.
Suggested Fix
Encrypt user-provided API keys at rest.
Recommended approach:
- Add a dedicated encryption key env var, preferably
OSE_ENCRYPTION_KEY.- Recommended format: 32 random bytes, base64-encoded.
- Example generation command:
openssl rand -base64 32-
Use Node's built-in
cryptomodule with AES-256-GCM.crypto.createCipheriv('aes-256-gcm', key, iv)for encryption.crypto.createDecipheriv('aes-256-gcm', key, iv)for decryption.- Store enough metadata to decrypt safely: version, IV, auth tag, ciphertext.
-
Prefer a small helper module, for example:
src/lib/crypto/secrets.ts
Possible helper API:
encryptSecret(plain: string): string
decryptSecret(encrypted: string): string | null
isEncryptedSecret(value: string | null | undefined): boolean- Rename fields or clearly mark encrypted fields:
apiKeyEncrypted String?
imageApiKeyEncrypted String?-
Update all read paths to decrypt before constructing AI provider config.
-
Update all write paths to encrypt before saving.
-
Handle decryption failures safely.
- Treat failed decryption as missing/unconfigured key.
- Do not log the ciphertext or plaintext.
- Return a user-facing prompt to re-enter the API key if needed.
-
Add a migration strategy for existing plaintext values.
Migration options:
- Safer/simple: add encrypted columns, stop reading plaintext columns, and require users to re-enter keys after upgrade.
- More convenient: one-time idempotent data migration that encrypts existing plaintext values when
OSE_ENCRYPTION_KEYis available. - Lazy migration: when a legacy plaintext value is successfully read, encrypt it and clear the plaintext column in the same request.
Whichever path is chosen should be explicit and documented.
- Document self-hosting requirements.
Update README/docs to explain:
Set OSE_ENCRYPTION_KEY in production. If this key is lost, stored user API keys cannot be decrypted and users must re-enter them.
Notes
- Reusing
NEXTAUTH_SECRETis possible as a fallback only if the project intentionally accepts that coupling. A dedicatedOSE_ENCRYPTION_KEYis cleaner because rotating session secrets should not necessarily invalidate encrypted API keys. - Environment-level provider keys such as
ANTHROPIC_API_KEYremain environment secrets and do not need database encryption. - Both text generation keys and image generation keys should be covered.
Acceptance Criteria
- User-provided
apiKeyvalues are no longer stored in plaintext. - User-provided
imageApiKeyvalues are no longer stored in plaintext. - AI provider resolution still works after decrypting stored keys.
- Decryption failure is handled as an unconfigured key, without leaking secret material into logs or responses.
- Existing plaintext key migration behavior is explicit and tested.
- README/docs mention
OSE_ENCRYPTION_KEYand explain backup/rotation implications. - Tests cover encryption/decryption helpers and at least one settings read/write path.
Activity
hacksynth commentedon May 2, 2026
@claude 请处理这个 issue。
请按 issue 描述和 acceptance criteria 落地修复,保持改动范围聚焦;完成后请提交 PR,并在本 issue 回复 PR 链接。
claude commentedon May 2, 2026
Claude finished @hacksynth's task in 7m 49s —— View job •
claude/issue-53-20260502-1624• Create PR ➔Implementing Issue #53: Encrypt stored user AI API keys at rest
src/lib/crypto/secrets.tshelper module (AES-256-GCM)apiKeyEncryptedandimageApiKeyEncrypted20260502160000_add_encrypted_api_key_fields)src/app/api/profile/ai-settings/route.ts) to encrypt on savesrc/lib/ai/index.ts,src/lib/ai/settings.ts,src/lib/ai/image.ts) to decrypt + lazy migratesrc/test/crypto-secrets.test.ts).env.examplewithOSE_ENCRYPTION_KEYWhat was implemented
New file:
src/lib/crypto/secrets.tscryptomoduleencryptSecret/decryptSecret— stored format:v1:<iv_hex>:<tag_hex>:<ciphertext_hex>resolveSecret(encrypted, plaintext)— decrypt if encrypted, fall back to plaintextisEncryptedSecret/isEncryptionEnabledhelpersnullsafely — no secret material in logsSchema + migration
apiKeyEncrypted String?andimageApiKeyEncrypted String?toUserAISettingsapiKey/imageApiKeycolumns kept for lazy migration compatibilityWrite path (route.ts PUT)
OSE_ENCRYPTION_KEYis set: new values are written toapiKeyEncrypted,apiKeyis clearedOSE_ENCRYPTION_KEYis absent: behaves exactly as before (plaintext inapiKey)Read paths
resolveSecret(settings.apiKeyEncrypted, settings.apiKey)used everywhere — decrypts if encrypted, falls back to plaintextresolveAIConfig,resolveAIImageConfigTests —
src/test/crypto-secrets.test.tsDocs
.env.example: newOSE_ENCRYPTION_KEYsection with generation command and warningsdocs/self-hosting.md: added to minimum production env block + dedicated "Encryption Key" section covering backup, rotation, and lazy migration behaviourhacksynth commentedon May 2, 2026
@claude
claude/issue-53-20260502-1624还不满足 issue #53 的 acceptance criteria。当前实现如果没有OSE_ENCRYPTION_KEY,PUT /api/profile/ai-settings会继续把apiKey/imageApiKey明文写入旧列,文档也写了 “Without OSE_ENCRYPTION_KEY, user API keys are stored in plaintext”。这和验收条件 “User-provided apiKey/imageApiKey values are no longer stored in plaintext” 冲突。请修改为:保存用户提供的新 API key 时必须加密;如果
OSE_ENCRYPTION_KEY缺失或无效,应返回明确错误并拒绝持久化密钥,而不是明文保存。旧apiKey/imageApiKey明文字段只能作为 legacy lazy migration 输入读取;一旦有加密密钥就迁移到 encrypted 字段并清空旧字段。没有加密密钥时,legacy plaintext 可以被当作缺失/未配置处理或提示用户配置密钥/重新输入,但不能继续写入新的明文 key。也请更新文档和测试,去掉“无密钥则明文保存可接受”的说法。claude commentedon May 2, 2026
Claude finished @hacksynth's task in 7m 48s —— View job •
claude/issue-53-20260502-1634• Create PR ➔Implemented: encrypt user AI API keys at rest with strict
OSE_ENCRYPTION_KEYrequirementsrc/lib/crypto/secrets.ts(AES-256-GCM:encryptSecret,decryptSecret,resolveSecret,isEncryptionEnabled,isEncryptedSecret)apiKeyEncrypted/imageApiKeyEncryptedcolumns20260502140000_add_encrypted_api_key_fieldsroute.tsPUT): reject new keys with HTTP 503 whenOSE_ENCRYPTION_KEYis absent — no plaintext fallback everindex.ts,image.ts,settings.ts): decrypt viaresolveSecret+ lazy-migrate legacy plaintext to encrypted on first useroute.tsGET:hasApiKey/masked display derived from encrypted columns firstsrc/test/crypto-secrets.test.ts(round-trip, unicode, tamper resistance,resolveSecretfallback behaviour).env.exampleanddocs/self-hosting.md(key setup, rotation, backup guidance)Key policy changes vs previous implementation
OSE_ENCRYPTION_KEYabsentapiKeyapiKeyEncryptedFiles changed
src/lib/crypto/secrets.ts— new AES-256-GCM helper modulesrc/prisma/schema.prisma— addedapiKeyEncrypted,imageApiKeyEncryptedsrc/prisma/migrations/20260502140000_add_encrypted_api_key_fields/migration.sql— newsrc/app/api/profile/ai-settings/route.ts— strict write-path enforcement + GET uses encrypted columnssrc/lib/ai/index.ts—resolveAIConfigdecrypts + lazy-migratessrc/lib/ai/image.ts—resolveAIImageConfigdecrypts + lazy-migratessrc/lib/ai/settings.ts—resolveAIConfigFromRequest/resolveAIImageConfigFromRequestdecrypt stored keyssrc/test/crypto-secrets.test.ts— new unit tests.env.example— addedOSE_ENCRYPTION_KEYsectiondocs/self-hosting.md— added encryption setup, rotation, and backup documentation•
claude/issue-53-20260502-1634hacksynth commentedon May 2, 2026
@claude PR #69 现在和最新 main 有 merge conflicts,GitHub 无法自动 update branch。请基于当前 main 重新整理/更新 \claude/issue-53-20260502-1634\ 或创建新的修复分支,保留 #53 的严格加密语义,同时兼容已合并的 #68 AI default model resolution 改动。修完后请让 PR #69 重新变为 mergeable,或给出新的 Create PR 链接。
claude commentedon May 2, 2026
Claude encountered an error —— View job
I'll analyze this and get back to you.
hacksynth commentedon May 2, 2026
@claude 上一轮处理 #69 冲突的 job 失败,没有推分支。我做了只读
git merge-tree分析,冲突点很小,请按下面方式基于当前main重新处理:docs/self-hosting.md:保留已合并 feat: unify AI default model resolution #68 的## AI Model Defaults整节,同时在其后追加 Encrypt stored user AI API keys at rest #53 的## Encryption Key (OSE_ENCRYPTION_KEY)整节;不要二选一。src/lib/ai/index.ts:同时保留 feat: unify AI default model resolution #68 的默认模型逻辑和 Encrypt stored user AI API keys at rest #53 的加密 key 逻辑。冲突处应使用apiKey: apiKey ?? undefined,并使用model: settings?.model || resolveDefaultModel(provider)。src/lib/ai/settings.ts:保留 feat: unify AI default model resolution #68 的resolveDefaultModelimport/用法,同时加入 Encrypt stored user AI API keys at rest #53 的resolveSecretimport,并继续从 encrypted/plaintext legacy 字段解析 stored key。.env.example、src/lib/ai/image.ts、Prisma schema/migration、src/lib/crypto/secrets.ts、src/test/crypto-secrets.test.ts应保留 Encrypt stored user AI API keys at rest #53 的新增内容。请更新
claude/issue-53-20260502-1634或创建新分支,让 PR #69 或新 PR 变为 mergeable。不要弱化“无 OSE_ENCRYPTION_KEY 时拒绝保存新 API key”的语义。claude commentedon May 2, 2026
Claude encountered an error —— View job
I'll analyze this and get back to you.
hacksynth commentedon May 2, 2026
@claude 处理 #69 冲突的 workflow 失败原因是 Claude Code 配额已用尽:\You've hit your limit · resets 7:10pm (UTC)\,没有创建或推送分支。等配额恢复后请按上方冲突说明继续处理 PR #69。
claude commentedon May 2, 2026
Claude encountered an error —— View job
I'll analyze this and get back to you.