Device Authentication Bridge for Kimi CLI - Reusable module for OAuth token retrieval
Project description
🌙 Kimi Device Authentication Bridge
A reusable Python module for integrating Kimi Code CLI OAuth authentication into any application. No more hardcoded API keys - just seamless device authentication!
✨ Features
- 🔐 OAuth Token Retrieval - Reads tokens from Kimi CLI's secure storage
- 🔄 Auto-Refresh - Handles token expiration automatically
- 🚀 Zero Config - Works out of the box with existing Kimi CLI installations
- 🛡️ Secure - Never stores credentials, only reads from Kimi's secure storage
- 🔌 Framework Agnostic - Use with Flask, FastAPI, Django, or any Python app
- 📦 Easy Integration - Simple API, minimal setup required
🎯 Use Cases
This bridge solves 2 major problems:
- 🔑 No Hardcoded API Keys - Stop committing secrets to git
- 👥 User-Friendly - End users just run
kimi login, no manual key management
Perfect for:
- AI-powered developer tools
- Coding assistants
- CLI applications
- Web applications needing LLM access
- Any tool that wants to leverage Kimi's API without exposing keys
📦 Installation
pip install kimi-auth-bridge
Or install from source:
git clone https://github.com/yourusername/kimi-device-auth-bridge.git
cd kimi-device-auth-bridge
pip install -e .
🚀 Quick Start
Basic Usage
from kimi_auth_bridge import KimiAuthBridge
# Initialize the bridge
bridge = KimiAuthBridge()
# Check if user is authenticated
if bridge.is_authenticated():
# Get the access token
token = bridge.get_access_token()
print(f"Token: {token[:20]}...")
# Use with any HTTP client
import requests
response = requests.post(
"https://api.kimi.com/coding/v1/chat/completions",
headers={
"Authorization": f"Bearer {token}",
"User-Agent": bridge.get_user_agent()
},
json={
"model": "kimi-for-coding",
"messages": [{"role": "user", "content": "Hello!"}]
}
)
else:
print("Please run 'kimi login' first")
Async Support
import asyncio
from kimi_auth_bridge import AsyncKimiAuthBridge
async def main():
bridge = AsyncKimiAuthBridge()
if await bridge.is_authenticated():
token = await bridge.get_access_token()
# Use token with async HTTP client...
print(f"Got token: {token[:20]}...")
asyncio.run(main())
Web Framework Integration
Flask Example
from flask import Flask, jsonify
from kimi_auth_bridge import KimiAuthBridge
app = Flask(__name__)
bridge = KimiAuthBridge()
@app.route('/api/kimi/status')
def kimi_status():
return jsonify({
'authenticated': bridge.is_authenticated(),
'api_base': bridge.get_api_base(),
'model': bridge.get_default_model()
})
@app.route('/api/kimi/token')
def kimi_token():
if not bridge.is_authenticated():
return jsonify({'error': 'Not authenticated'}), 401
return jsonify({
'token_preview': bridge.get_token_preview(),
'api_base': bridge.get_api_base()
})
if __name__ == '__main__':
app.run(debug=True)
FastAPI Example
from fastapi import FastAPI, HTTPException
from kimi_auth_bridge import KimiAuthBridge
app = FastAPI()
bridge = KimiAuthBridge()
@app.get('/api/kimi/status')
async def kimi_status():
return {
'authenticated': bridge.is_authenticated(),
'api_base': bridge.get_api_base(),
'model': bridge.get_default_model()
}
@app.get('/api/kimi/token')
async def kimi_token():
if not bridge.is_authenticated():
raise HTTPException(status_code=401, detail='Not authenticated')
return {
'token': bridge.get_access_token(),
'api_base': bridge.get_api_base()
}
📚 API Reference
KimiAuthBridge
Main class for synchronous authentication handling.
Methods
| Method | Description | Returns |
|---|---|---|
is_authenticated() |
Check if user has valid credentials | bool |
get_access_token() |
Get the current access token | str | None |
get_token_preview() |
Get truncated token for display | str | None |
get_api_base() |
Get Kimi API base URL | str |
get_default_model() |
Get default model name | str |
get_user_agent() |
Get required User-Agent header | str |
get_auth_headers() |
Get complete headers dict | dict |
AsyncKimiAuthBridge
Async version for non-blocking operations.
Methods
Same as KimiAuthBridge, but all methods are async.
🔧 Advanced Configuration
from kimi_auth_bridge import KimiAuthBridge, KimiConfig
# Custom configuration
config = KimiConfig(
credentials_path="/custom/path/credentials.json",
api_base="https://custom-api.kimi.com/v1",
model="kimi-custom-model"
)
bridge = KimiAuthBridge(config=config)
🧪 Testing
# Run tests
pytest tests/
# Run with coverage
pytest --cov=kimi_auth_bridge tests/
🤝 Contributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
📝 License
This project is licensed under the MIT License - see the LICENSE file for details.
🙏 Acknowledgments & Credits
Special thanks to the incredible team at Moonshot AI for developing this brilliant authentication system!
Why Moonshot's Approach is Genius 🧠
The Kimi CLI authentication system represents a security breakthrough in AI API access:
- 🔑 Dynamic Token Generation - Fresh tokens on every login, no static keys
- 🛡️ Device-Bound Security - Tokens only work on authenticated devices
- 🌐 Browser-Verified - Authentication happens through kimi.com website
- 🔒 No Hardcoded Secrets - Zero risk of API keys in git repositories
- ✌️ Multi-Factor by Design - Combines device + browser + OAuth
- 🔄 Automatic Rotation - Seamless token refresh without user intervention
This is how all AI API authentication should work! Hats off to the Moonshot team for prioritizing security AND user experience.
- Built for Kimi Code CLI
- Thanks to the Moonshot AI team for the excellent API and revolutionary auth system
📞 Support
- 📧 Email: your.email@example.com
- 💬 Issues: GitHub Issues
- 📖 Docs: Full Documentation
Made with ❤️ for the AI developer community
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file kimi_auth_bridge-1.0.0.tar.gz.
File metadata
- Download URL: kimi_auth_bridge-1.0.0.tar.gz
- Upload date:
- Size: 22.3 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.11.14
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
67c7e7f6fae66edb558f9355db22b6e5ad9a035553ee60937f7063e982edf5ff
|
|
| MD5 |
cd47f444beee82d08984e53c57247ca0
|
|
| BLAKE2b-256 |
7483d6147ef85dcdf47c9b3ce8c41d6c4418a28d6437758e1923c21fb64a15a1
|
File details
Details for the file kimi_auth_bridge-1.0.0-py3-none-any.whl.
File metadata
- Download URL: kimi_auth_bridge-1.0.0-py3-none-any.whl
- Upload date:
- Size: 9.5 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.11.14
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
5441315e1c98c27fa610ac57fd2cbd84d89e961ca560ec7aa7ed5a506d76d43c
|
|
| MD5 |
736a1e05478eb73608538c2d6b9593ad
|
|
| BLAKE2b-256 |
5156e03d282ec25232fca02e3ff4e9447f91f2c37cad2060f992b4d6992aae73
|