npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

opencode-new-anthropic-auth

v0.1.0

Published

Enhanced Anthropic auth plugin for OpenCode - Makes OpenCode indistinguishable from Claude Code to Anthropic's API

Readme

opencode-new-anthropic-auth

Enhanced Anthropic authentication plugin for OpenCode with integrated token syncing from Claude Code CLI.

Version License

🎯 What This Is

This is a drop-in replacement for the deleted opencode-anthropic-auth npm package, enhanced with:

  1. 100% Claude Code request compatibility — Makes OpenCode API requests indistinguishable from official Claude Code
  2. Integrated token syncing — Sync OAuth tokens directly from Claude Code CLI (no browser flow needed)
  3. Auto-refresh scheduling — Keeps tokens fresh without manual intervention
  4. 🚀 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-auth

Via Bun

cd ~/.config/opencode
bun add opencode-new-anthropic-auth

Global 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 --help

From 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-systemd

2. 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-systemd

Limitations of Token Sync

  1. Claude Code must be installed and logged in

    • If Claude Code's token expires, OpenCode's will too
    • Solution: Run claude auth login to refresh, then re-sync
  2. Shared token state

    • Both CLIs use the same OAuth token
    • If you logout of Claude Code, OpenCode loses auth too
  3. Platform-specific storage

    • macOS requires Keychain access
    • Linux requires read access to ~/.claude/.credentials.json
  4. 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

  1. System Prompt Prefix

    • Prepends: "You are Claude Code, Anthropic's official CLI for Claude."
  2. Content Sanitization

    • "OpenCode" → "Claude Code"
    • "opencode" → "Claude"
  3. Tool Name Prefixing

    • Request: my_tool → mcp_my_tool
    • Response: mcp_my_tool → my_tool (streaming transform)
  4. Beta Parameters

    • Adds ?beta=true to /v1/messages requests

🏗️ 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

  1. Read Phase:

    • Linux: Parses ~/.claude/.credentials.json
    • macOS: Executes security find-generic-password -s "Claude Code-credentials"
    • Extracts: accessToken, refreshToken, expiresAt
  2. Write Phase:

    • Writes to ~/.config/opencode/auth.json
    • Preserves other provider credentials
    • Sets file permissions to 0o600
  3. Scheduling Phase:

    • Calculates refresh time (expires - 1 hour buffer)
    • Schedules with at command or systemd timer
    • Removes old scheduled jobs before adding new

Request Transformation Flow

  1. System Transform Hook:

    "experimental.chat.system.transform": (input, output) => {
      // Prepend Claude Code prefix
      // Sanitize "OpenCode" references
    }
  2. Headers Hook:

    "chat.headers": (input, output) => {
      // Inject Claude Code User-Agent
      // Add OAuth beta headers
      // Set x-anthropic-billing-header
    }
  3. 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.mjs

Manual 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-token

Auto-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-systemd

Headers 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:

  1. Original [email protected]

    • OAuth PKCE flow
    • Client ID: 9d1c250a-e61b-44d9-88ed-5944d1962f5e
  2. Claude Code source (@anthropic-ai/[email protected])

    • src/services/api/client.ts — Header generation
    • src/utils/http.ts — User-Agent construction
    • src/constants/betas.ts — Beta headers
    • src/constants/system.ts — System prompt handling
    • src/utils/auth.ts — Token storage/retrieval
    • src/utils/authFileDescriptor.ts — CCR token paths
  3. User's existing sync-claude-token setup

    • Linux: ~/.claude/.credentials.json
    • macOS: Keychain integration
    • Auto-refresh scheduling logic

🚀 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.