fix: use centralized credentials from ~/.claude-mem/.env to prevent API key hijacking (#733)

This fixes Issue #733 where claude-mem would incorrectly use ANTHROPIC_API_KEY from
random project .env files instead of the user's configured Claude Code CLI subscription.

Root cause: The SDK's `query()` function inherits from `process.env` when no `env`
option is passed. When users work in projects with their own .env files containing
API keys, the SDK would discover and use those keys, billing the wrong account.

Solution: Centralized credential management via ~/.claude-mem/.env

Changes:
- Add EnvManager.ts: Centralized credential storage and isolated env builder
- SDKAgent: Pass isolated env to SDK query() that only includes credentials from
  ~/.claude-mem/.env, not random keys from process.env inheritance
- GeminiAgent/OpenRouterAgent: Use getCredential() instead of process.env fallback
- SettingsDefaultsManager: Add CLAUDE_MEM_CLAUDE_AUTH_METHOD setting ('cli' | 'api')

How it works:
1. buildIsolatedEnv() creates a clean environment with only essential system vars
   (PATH, HOME, etc.) and credentials explicitly configured in ~/.claude-mem/.env
2. SDK subprocess runs with this isolated env, never seeing random API keys
3. If no ANTHROPIC_API_KEY is in ~/.claude-mem/.env, Claude Code CLI billing is used
4. Same pattern applied to Gemini/OpenRouter agents for consistency

This ensures claude-mem always uses the user's intended billing method, regardless
of what .env files exist in their working directory.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
bigphoot
2026-01-17 14:48:39 -08:00
committed by Alex Newman
parent aedee33ca9
commit 006ff40175
5 changed files with 301 additions and 8 deletions
+2
View File
@@ -20,6 +20,7 @@ export interface SettingsDefaults {
CLAUDE_MEM_SKIP_TOOLS: string;
// AI Provider Configuration
CLAUDE_MEM_PROVIDER: string; // 'claude' | 'gemini' | 'openrouter'
CLAUDE_MEM_CLAUDE_AUTH_METHOD: string; // 'cli' | 'api' - how Claude provider authenticates
CLAUDE_MEM_GEMINI_API_KEY: string;
CLAUDE_MEM_GEMINI_MODEL: string; // 'gemini-2.5-flash-lite' | 'gemini-2.5-flash' | 'gemini-3-flash'
CLAUDE_MEM_GEMINI_RATE_LIMITING_ENABLED: string; // 'true' | 'false' - enable rate limiting for free tier
@@ -64,6 +65,7 @@ export class SettingsDefaultsManager {
CLAUDE_MEM_SKIP_TOOLS: 'ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion',
// AI Provider Configuration
CLAUDE_MEM_PROVIDER: 'claude', // Default to Claude
CLAUDE_MEM_CLAUDE_AUTH_METHOD: 'cli', // Default to CLI subscription billing (not API key)
CLAUDE_MEM_GEMINI_API_KEY: '', // Empty by default, can be set via UI or env
CLAUDE_MEM_GEMINI_MODEL: 'gemini-2.5-flash-lite', // Default Gemini model (highest free tier RPM)
CLAUDE_MEM_GEMINI_RATE_LIMITING_ENABLED: 'true', // Rate limiting ON by default for free tier users