opencode-new-anthropic-auth
v0.1.0
Published
Enhanced Anthropic auth plugin for OpenCode - Makes OpenCode indistinguishable from Claude Code to Anthropic's API
Maintainers
Readme
opencode-new-anthropic-auth
Enhanced Anthropic authentication plugin for OpenCode with integrated token syncing from Claude Code CLI.
🎯 What This Is
This is a drop-in replacement for the deleted opencode-anthropic-auth npm package, enhanced with:
- 100% Claude Code request compatibility — Makes OpenCode API requests indistinguishable from official Claude Code
- Integrated token syncing — Sync OAuth tokens directly from Claude Code CLI (no browser flow needed)
- Auto-refresh scheduling — Keeps tokens fresh without manual intervention
- 🚀 Anthropic Prompt Caching — Automatic token optimization and cost reduction (see PROMPT_CACHING.md)
📦 Installation
Via NPM (Recommended)
cd ~/.config/opencode
npm install opencode-new-anthropic-authVia Bun
cd ~/.config/opencode
bun add opencode-new-anthropic-authGlobal Install (for CLI access)
# NPM
npm install -g opencode-new-anthropic-auth
# Bun
bun add -g opencode-new-anthropic-auth
# Now use the CLI
sync-claude-token --helpFrom Source
cd ~/.config/opencode
npm install ~/Documents/opencode-new-anthropic-auth🔧 Configuration
Add to ~/.config/opencode/opencode.json:
{
"plugins": ["opencode-new-anthropic-auth"],
"models": {
"anthropic": {
"default": "claude-sonnet-4-7-20251001"
}
}
}🔐 Authentication Methods
This plugin provides four ways to authenticate with Anthropic:
1. Sync from Claude Code CLI (NEW ⭐)
Best for: Users who already have Claude Code installed with Pro/Max subscription
How it works:
- Reads OAuth tokens from Claude Code's secure storage
- Copies them to OpenCode's auth file
- No browser OAuth flow required
- Works offline after initial sync
Setup:
# Ensure Claude Code is logged in
claude auth login
# Sync tokens
sync-claude-token
# Or in OpenCode, run: /auth login → choose "Sync from Claude Code CLI"Supported Platforms:
- Linux:
~/.claude/.credentials.json - macOS: Keychain (
security find-generic-password) - Windows: WSL path or
%APPDATA%/Claude/credentials.json
Auto-Refresh:
# Schedule auto-refresh before token expires (uses 'at' command)
sync-claude-token
# Or setup systemd timer for persistent background sync
sync-claude-token --setup-systemd2. Claude Pro/Max OAuth
Traditional browser-based OAuth flow for Claude.ai subscribers.
opencode auth login
# Select "Claude Pro/Max (via Claude.ai OAuth)"3. Create API Key via OAuth
One-click API key generation through OAuth.
4. Manual API Key Entry
Direct API key input for non-OAuth usage.
🔄 Token Sync CLI
The integrated sync-claude-token command provides:
# Sync tokens and schedule auto-refresh
sync-claude-token
# Check status
sync-claude-token --status
# Silent mode (for cron/systemd)
sync-claude-token --auto
# Setup persistent sync (every 6 hours)
sync-claude-token --setup-systemd
# Remove systemd timer
sync-claude-token --remove-systemdLimitations of Token Sync
Claude Code must be installed and logged in
- If Claude Code's token expires, OpenCode's will too
- Solution: Run
claude auth loginto refresh, then re-sync
Shared token state
- Both CLIs use the same OAuth token
- If you logout of Claude Code, OpenCode loses auth too
Platform-specific storage
- macOS requires Keychain access
- Linux requires read access to
~/.claude/.credentials.json
No refresh token isolation
- Unlike standalone OAuth, token refresh affects both CLIs
🎭 Claude Code Compatibility
This plugin makes OpenCode requests identical to Claude Code:
Headers Injected
User-Agent: claude-cli/2.1.88 (external, cli)
x-app: cli
X-Claude-Code-Session-Id: cc-{timestamp}-{random}
anthropic-version: 2023-06-01
anthropic-beta: oauth-2025-04-20,interleaved-thinking-2025-05-14,claude-code-20250219,...
x-anthropic-billing-header: cc_version=2.1.88; cc_entrypoint=cli;
Authorization: Bearer {oauth_access_token}Request Transformations
System Prompt Prefix
- Prepends: "You are Claude Code, Anthropic's official CLI for Claude."
Content Sanitization
- "OpenCode" → "Claude Code"
- "opencode" → "Claude"
Tool Name Prefixing
- Request:
my_tool→mcp_my_tool - Response:
mcp_my_tool→my_tool(streaming transform)
- Request:
Beta Parameters
- Adds
?beta=trueto/v1/messagesrequests
- Adds
🏗️ Architecture
┌─────────────────────────────────────────────────────────────┐
│ OpenCode Agent │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ opencode-new-anthropic-auth Plugin │ │
│ │ ┌───────────────────────────────────────────────┐ │ │
│ │ │ Token Sync Module (token-sync.mjs) │ │ │
│ │ │ • Reads Claude Code credentials │ │ │
│ │ │ • Writes to OpenCode auth.json │ │ │
│ │ │ • Auto-refresh scheduling │ │ │
│ │ └───────────────────────────────────────────────┘ │ │
│ │ ┌───────────────────────────────────────────────┐ │ │
│ │ │ Claude Code Transformer │ │ │
│ │ │ • Header injection │ │ │
│ │ │ • Request sanitization │ │ │
│ │ │ • Streaming response transform │ │ │
│ │ └───────────────────────────────────────────────┘ │ │
│ └─────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ Anthropic API │
│ (sees requests as coming from Claude Code) │
└─────────────────────────────────────────────────────────────┘📁 File Structure
opencode-new-anthropic-auth/
├── index.mjs # Main plugin (exports AnthropicAuthPlugin)
├── token-sync.mjs # Token sync module (internal utilities)
├── bin/
│ └── sync-claude-token.mjs # Standalone CLI tool
├── test.mjs # Self-test suite
├── install.sh # Installation script
├── package.json # NPM manifest
├── README.md # This file
├── MIGRATION.md # Migration guide from old plugin
└── LICENSE # MIT License🔍 How It Works
Token Sync Flow
Read Phase:
- Linux: Parses
~/.claude/.credentials.json - macOS: Executes
security find-generic-password -s "Claude Code-credentials" - Extracts:
accessToken,refreshToken,expiresAt
- Linux: Parses
Write Phase:
- Writes to
~/.config/opencode/auth.json - Preserves other provider credentials
- Sets file permissions to 0o600
- Writes to
Scheduling Phase:
- Calculates refresh time (expires - 1 hour buffer)
- Schedules with
atcommand or systemd timer - Removes old scheduled jobs before adding new
Request Transformation Flow
System Transform Hook:
"experimental.chat.system.transform": (input, output) => { // Prepend Claude Code prefix // Sanitize "OpenCode" references }Headers Hook:
"chat.headers": (input, output) => { // Inject Claude Code User-Agent // Add OAuth beta headers // Set x-anthropic-billing-header }Fetch Interceptor:
auth.loader.fetch: async (input, init) => { // Transform request body (tool prefixing) // Transform streaming response (tool unwrapping) // Handle token refresh }
🛠️ Development
Testing
cd ~/Documents/opencode-new-anthropic-auth
npm test
# or
node test.mjsManual Testing
# Test token sync
node -e "
const { syncTokens, getSyncStatus } = require('./token-sync.mjs');
console.log(await getSyncStatus());
console.log(await syncTokens());
"🐛 Troubleshooting
"Claude Code credentials not found"
Cause: Claude Code not installed or not logged in
Fix:
# Install Claude Code if needed
npm install -g @anthropic-ai/claude-code
# Login
claude auth login
# Verify
claude auth status"Token expired" after sync
Cause: Claude Code's token expired, shared state
Fix:
# Refresh Claude Code's token
claude auth login
# Re-sync
sync-claude-tokenAuto-refresh not scheduling
Cause: at command not installed
Fix:
# Install at
sudo pacman -S at # Arch
sudo apt-get install at # Debian/Ubuntu
brew install at # macOS
# Or use systemd
sync-claude-token --setup-systemdHeaders not appearing correctly
Check plugin is loaded:
# In OpenCode, check auth methods are available
opencode auth login
# Should show 4 options including "Sync from Claude Code CLI"Verify auth file:
cat ~/.config/opencode/auth.json
# Should show anthropic entry with type: "oauth"📝 Comparison: Sync vs Standalone OAuth
| Feature | Sync from Claude Code | Standalone OAuth | |---------|----------------------|------------------| | Setup time | Instant (if CC logged in) | Requires browser flow | | Works offline | Yes | No (needs OAuth callback) | | Token refresh | Shared with CC | Independent | | Auto-refresh | Scheduled via at/systemd | Handled by plugin | | CC logout impact | OpenCode loses auth | No impact | | Best for | CC power users | Clean separation |
📚 Source Analysis
This plugin was built by analyzing:
Original
[email protected]- OAuth PKCE flow
- Client ID:
9d1c250a-e61b-44d9-88ed-5944d1962f5e
Claude Code source (
@anthropic-ai/[email protected])src/services/api/client.ts— Header generationsrc/utils/http.ts— User-Agent constructionsrc/constants/betas.ts— Beta headerssrc/constants/system.ts— System prompt handlingsrc/utils/auth.ts— Token storage/retrievalsrc/utils/authFileDescriptor.ts— CCR token paths
User's existing
sync-claude-tokensetup- Linux:
~/.claude/.credentials.json - macOS: Keychain integration
- Auto-refresh scheduling logic
- Linux:
🚀 Migration from Original
If you were using the original opencode-anthropic-auth:
# Remove old (deprecated) plugin
cd ~/.config/opencode
npm uninstall opencode-anthropic-auth
# Install new
npm install ~/Documents/opencode-new-anthropic-auth
# Update config: change plugin name
sed -i 's/opencode-anthropic-auth/opencode-new-anthropic-auth/g' opencode.json
# Re-authenticate (tokens preserved)
opencode auth login
# Choose "Sync from Claude Code CLI" for instant setup⚖️ License
MIT — See LICENSE
Original auth implementation: Anthropic ([email protected])
Claude Code compatibility layer: Based on source map analysis of @anthropic-ai/claude-code
Token sync integration: Community contribution
🤝 Contributing
This is a community-maintained replacement for a deleted official package. Issues and PRs welcome.
Repository: https://github.com/hffmnnj/opencode-new-anthropic-auth
Disclaimer: This plugin makes OpenCode appear as Claude Code to Anthropic's API for compatibility purposes. Users must comply with Anthropic's Terms of Service. This is not an official Anthropic product.
