opencode-kimi-auth
v0.1.0
Published
OpenCode authentication plugin for Kimi models
Maintainers
Readme
opencode-kimi-auth
OpenCode authentication plugin for Kimi models
An authentication plugin that enables seamless integration of Kimi (Kimi K2.5) models with OpenCode CLI. This plugin provides OAuth-based authentication flow, secure credential management, and streamlined configuration for accessing Kimi's powerful AI capabilities.
Table of Contents
- Features
- Installation
- Quick Start
- Usage with OpenCode
- OAuth Flow
- Configuration
- API Reference
- Troubleshooting
- Contributing
- License
Features
- 🔐 OAuth 2.0 Authentication - Secure token-based authentication with Kimi API
- 🚀 Seamless OpenCode Integration - Drop-in plugin for OpenCode CLI
- 🔄 Auto-Token Refresh - Automatic token refresh before expiration
- 🛡️ Secure Credential Storage - Encrypted local storage of credentials
- ⚡ Zero Config Setup - Sensible defaults with customization options
- 📦 TypeScript Support - Full type definitions included
Installation
Global Installation (Recommended)
npm install -g opencode-kimi-authProject-Level Installation
npm install opencode-kimi-authUsing with OpenCode Config
Add to your OpenCode configuration file (~/.opencode/config.json):
{
"plugins": [
"opencode-kimi-auth"
]
}Quick Start
1. Install the Plugin
npm install -g opencode-kimi-auth2. Configure Authentication
# Interactive setup
opencode-kimi-auth configure
# Or with CLI options
opencode-kimi-auth configure --client-id YOUR_CLIENT_ID --client-secret YOUR_CLIENT_SECRET3. Use with OpenCode
# The plugin is automatically loaded by OpenCode
opencode --model kimi-k2.5 "Your prompt here"Usage with OpenCode
Automatic Loading
Once installed globally or configured in ~/.opencode/config.json, the plugin automatically:
- Detects when Kimi models are requested
- Manages OAuth authentication flow
- Refreshes tokens automatically
- Handles credential storage securely
Manual Authentication
# Authenticate manually
opencode-kimi-auth login
# Check authentication status
opencode-kimi-auth status
# Logout and clear credentials
opencode-kimi-auth logoutEnvironment Variables
You can also configure via environment variables:
export KIMI_CLIENT_ID="your-client-id"
export KIMI_CLIENT_SECRET="your-client-secret"
export KIMI_REDIRECT_URI="http://localhost:3000/callback"
export KIMI_TOKEN_STORAGE="~/.opencode/kimi-tokens.json"Programmatic Usage
import { KimiAuthPlugin } from 'opencode-kimi-auth';
const plugin = new KimiAuthPlugin({
clientId: process.env.KIMI_CLIENT_ID,
clientSecret: process.env.KIMI_CLIENT_SECRET,
scopes: ['chat', 'completions']
});
// Initialize the plugin
await plugin.initialize();
// Get access token
const token = await plugin.getAccessToken();
// Use with OpenCode
const opencode = require('opencode');
opencode.use(plugin);OAuth Flow
Authentication Process
The plugin implements the standard OAuth 2.0 Authorization Code flow:
┌─────────────┐ ┌──────────────┐
│ User │─── 1. Request Authorization ─────▶│ Kimi Auth │
│ Browser │ │ Server │
└─────────────┘ └──────────────┘
│ │
│◀── 2. Redirect to /callback with auth code ──────│
│ │
│─── 3. Exchange code for tokens ─────────────────▶│
│ │
│◀── 4. Return access & refresh tokens ─────────────│
│ │
│─── 5. Store tokens securely locally ─────────────▶│
│ │
│◀── 6. Ready to use with OpenCode ─────────────────│
│ │Flow Steps
- Authorization Request - Plugin opens browser or provides URL for user to authorize
- User Consent - User grants permissions on Kimi authorization page
- Callback Handling - Plugin receives authorization code via redirect
- Token Exchange - Plugin exchanges code for access and refresh tokens
- Secure Storage - Tokens stored encrypted in
~/.opencode/kimi-tokens.json - Auto-Refresh - Plugin automatically refreshes tokens before expiration
Token Lifecycle
| Token Type | Lifetime | Refresh Strategy | |------------|----------|------------------| | Access Token | 1 hour | Used for API calls | | Refresh Token | 30 days | Used to get new access tokens | | ID Token | 1 hour | Used for user identification |
Configuration
Configuration File
Create or edit ~/.opencode/kimi-auth.json:
{
"auth": {
"clientId": "your-client-id",
"clientSecret": "your-client-secret",
"redirectUri": "http://localhost:3000/callback",
"scopes": ["chat", "completions", "embeddings"]
},
"storage": {
"type": "file",
"path": "~/.opencode/kimi-tokens.json",
"encryption": true
},
"refresh": {
"enabled": true,
"thresholdMinutes": 5
},
"server": {
"port": 3000,
"host": "localhost"
}
}Configuration Options
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| clientId | string | - | OAuth client ID (required) |
| clientSecret | string | - | OAuth client secret (required) |
| redirectUri | string | http://localhost:3000/callback | OAuth redirect URI |
| scopes | string[] | ["chat"] | OAuth scopes to request |
| storage.type | string | "file" | Token storage type (file/memory) |
| storage.path | string | ~/.opencode/kimi-tokens.json | Token storage path |
| storage.encryption | boolean | true | Encrypt stored tokens |
| refresh.enabled | boolean | true | Auto-refresh tokens |
| refresh.thresholdMinutes | number | 5 | Refresh before expiry (minutes) |
| server.port | number | 3000 | Local callback server port |
| server.host | string | "localhost" | Local callback server host |
CLI Configuration Commands
# Interactive configuration wizard
opencode-kimi-auth configure
# Set individual values
opencode-kimi-auth config set clientId YOUR_CLIENT_ID
opencode-kimi-auth config set clientSecret YOUR_CLIENT_SECRET
opencode-kimi-auth config set redirectUri http://localhost:3000/callback
# View current configuration
opencode-kimi-auth config show
# Reset to defaults
opencode-kimi-auth config resetAPI Reference
KimiAuthPlugin Class
class KimiAuthPlugin {
constructor(config: KimiAuthConfig);
// Initialize the plugin
initialize(): Promise<void>;
// Authenticate with Kimi
authenticate(): Promise<AuthResult>;
// Get current access token
getAccessToken(): Promise<string>;
// Refresh access token
refreshToken(): Promise<AuthResult>;
// Check authentication status
isAuthenticated(): Promise<boolean>;
// Logout and clear credentials
logout(): Promise<void>;
// Get user info
getUserInfo(): Promise<UserInfo>;
}Types
interface KimiAuthConfig {
clientId: string;
clientSecret: string;
redirectUri?: string;
scopes?: string[];
storage?: StorageConfig;
refresh?: RefreshConfig;
server?: ServerConfig;
}
interface AuthResult {
accessToken: string;
refreshToken: string;
expiresAt: number;
scope: string[];
}
interface UserInfo {
id: string;
email: string;
name: string;
}Troubleshooting
Common Issues
"Authentication failed: Invalid client credentials"
Cause: Incorrect client ID or secret
Solution:
# Verify your credentials
opencode-kimi-auth config show
# Reconfigure with correct values
opencode-kimi-auth configure --client-id YOUR_CLIENT_ID --client-secret YOUR_CLIENT_SECRET"Port 3000 is already in use"
Cause: Another process is using the callback server port
Solution:
# Change the port in configuration
opencode-kimi-auth config set server.port 3001
# Or find and kill the process using port 3000
lsof -ti:3000 | xargs kill -9"Token refresh failed"
Cause: Refresh token expired or revoked
Solution:
# Re-authenticate
opencode-kimi-auth logout
opencode-kimi-auth login"OpenCode plugin not found"
Cause: Plugin not installed globally or not in config
Solution:
# Install globally
npm install -g opencode-kimi-auth
# Or add to OpenCode config
echo '{"plugins": ["opencode-kimi-auth"]}' > ~/.opencode/config.jsonDebug Mode
Enable debug logging:
export DEBUG=opencode-kimi-auth:*
opencode --model kimi-k2.5 "test"Getting Help
Contributing
We welcome contributions! Please follow these guidelines:
Development Setup
# Clone the repository
git clone https://github.com/romancircus/opencode-kimi-auth.git
cd opencode-kimi-auth
# Install dependencies
npm install
# Build the project
npm run build
# Run type checking
npm run typecheck
# Run tests
npm testPull Request Process
- Fork the repository
- Create a feature branch:
git checkout -b feature/amazing-feature - Make your changes
- Run tests and type checking:
npm run typecheck && npm test - Commit your changes:
git commit -m 'feat: add amazing feature' - Push to the branch:
git push origin feature/amazing-feature - Open a Pull Request
Commit Message Convention
We follow Conventional Commits:
feat:New featurefix:Bug fixdocs:Documentation changesstyle:Code style changes (formatting, semicolons, etc)refactor:Code refactoringtest:Test changeschore:Build/dependency changes
Code Style
- Use TypeScript for all new code
- Follow existing code patterns
- Run
npm run typecheckbefore committing - Maintain test coverage above 80%
License
Apache-2.0 © Roman Circus
