Skip to content

Use Claude Code, Codex, VSCode, Pi, and OpenCode (and 6 other harnesses) for free (1.3B+ free tokens) from your terminal, app, IDE, or phone, and now from the browser with native browser sessions (multi-harness + multi-model) like OpenClaw (voice supported + ToS friendly)

Python

Implement optional authentication (Anthropic style) (#80)

th-chf703a0e40332
diff --git a/.env.example b/.env.example
index 3d26b1f4..c01d959c 100644
--- a/.env.example
+++ b/.env.example
@@ -36,6 +36,10 @@ HTTP_WRITE_TIMEOUT=10
HTTP_CONNECT_TIMEOUT=2
+# Optional server API key (Anthropic-style)
+ANTHROPIC_AUTH_TOKEN=
+
+
# Messaging Platform: "telegram" | "discord"
MESSAGING_PLATFORM="discord"
MESSAGING_RATE_LIMIT=1
@@ -73,4 +77,4 @@ FAST_PREFIX_DETECTION=true
ENABLE_NETWORK_PROBE_MOCK=true
ENABLE_TITLE_GENERATION_SKIP=true
ENABLE_SUGGESTION_MODE_SKIP=true
-ENABLE_FILEPATH_EXTRACTION_MOCK=true
\ No newline at end of file
+ENABLE_FILEPATH_EXTRACTION_MOCK=true
diff --git a/README.md b/README.md
index ad5216d1..334de6d4 100644
--- a/README.md
+++ b/README.md
@@ -134,6 +134,37 @@ MODEL="nvidia_nim/z-ai/glm4.7" # fallback
</details>
+<details>
+<summary><b>Optional Authentication</b> (restrict access to your proxy)</summary>
+
+Set `ANTHROPIC_AUTH_TOKEN` in `.env` to require clients to authenticate:
+
+```dotenv
+ANTHROPIC_AUTH_TOKEN="your-secret-token-here"
+```
+
+**How it works:**
+- If `ANTHROPIC_AUTH_TOKEN` is empty (default), no authentication is required (backward compatible)
+- If set, clients must provide the same token via the `ANTHROPIC_AUTH_TOKEN` header
+- The `claude-pick` script automatically reads the token from `.env` if configured
+
+**Example usage:**
+```bash
+# With authentication
+ANTHROPIC_AUTH_TOKEN="your-secret-token-here" \
+ANTHROPIC_BASE_URL="http://localhost:8082" claude
+
+# claude-pick automatically uses the configured token
+claude-pick
+```
+
+Use this feature if:
+- Running the proxy on a public network
+- Sharing the server with others but restricting access
+- Wanting an additional layer of security
+
+</details>
+
### Run It
**Terminal 1:** Start the proxy server:
diff --git a/api/dependencies.py b/api/dependencies.py
index ea3d3bd0..0131ecc5 100644
--- a/api/dependencies.py
+++ b/api/dependencies.py
@@ -1,6 +1,6 @@
"""Dependency injection for FastAPI."""
-from fastapi import HTTPException
+from fastapi import Depends, HTTPException, Request
from loguru import logger
from config.settings import Settings
@@ -110,6 +110,40 @@ def get_provider_for_type(provider_type: str) -> BaseProvider:
return _providers[provider_type]
+def require_api_key(
+ request: Request, settings: Settings = Depends(get_settings)
+) -> None:
+ """Require a server API key (Anthropic-style).
+
+ Checks `x-api-key` header or `Authorization: Bearer ...` against
+ `Settings.anthropic_auth_token`. If `ANTHROPIC_AUTH_TOKEN` is empty, this is a no-op.
+ """
+ anthropic_auth_token = settings.anthropic_auth_token
+ if not anthropic_auth_token:
+ # No API key configured -> allow
+ return
+
+ header = (
+ request.headers.get("x-api-key")
+ or request.headers.get("authorization")
+ or request.headers.get("anthropic-auth-token")
+ )
+ if not header:
+ raise HTTPException(status_code=401, detail="Missing API key")
+
+ # Support both raw key in X-API-Key and Bearer token in Authorization
+ token = header
+ if header.lower().startswith("bearer "):
+ token = header.split(" ", 1)[1]
+
+ # Strip anything after the first colon to handle tokens with appended model names
+ if token and ":" in token:
+ token = token.split(":", 1)[0]
+
+ if token != anthropic_auth_token:
+ raise HTTPException(status_code=401, detail="Invalid API key")
+
+
def get_provider() -> BaseProvider:
"""Get or create the default provider (based on MODEL env var).
diff --git a/api/routes.py b/api/routes.py
index 4c13a15c..67e1e7c8 100644
--- a/api/routes.py
+++ b/api/routes.py
@@ -11,7 +11,7 @@ from config.settings import Settings
from providers.common import get_user_facing_error_message
from providers.exceptions import InvalidRequestError, ProviderError
-from .dependencies import get_provider_for_type, get_settings
+from .dependencies import get_provider_for_type, get_settings, require_api_key
from .models.anthropic import MessagesRequest, TokenCountRequest
from .models.responses import TokenCountResponse
from .optimization_handlers import try_optimizations
@@ -28,6 +28,7 @@ async def create_message(
request_data: MessagesRequest,
raw_request: Request,
settings: Settings = Depends(get_settings),
+ _auth=Depends(require_api_key),
):
"""Create a message (always streaming)."""
@@ -83,7 +84,7 @@ async def create_message(
@router.post("/v1/messages/count_tokens")
-async def count_tokens(request_data: TokenCountRequest):
+async def count_tokens(request_data: TokenCountRequest, _auth=Depends(require_api_key)):
"""Count tokens for a request."""
request_id = f"req_{uuid.uuid4().hex[:12]}"
with logger.contextualize(request_id=request_id):
@@ -112,7 +113,9 @@ async def count_tokens(request_data: TokenCountRequest):
@router.get("/")
-async def root(settings: Settings = Depends(get_settings)):
+async def root(
+ settings: Settings = Depends(get_settings), _auth=Depends(require_api_key)
+):
"""Root endpoint."""
return {
"status": "ok",
@@ -128,7 +131,7 @@ async def health():
@router.post("/stop")
-async def stop_cli(request: Request):
+async def stop_cli(request: Request, _auth=Depends(require_api_key)):
"""Stop all CLI sessions and pending tasks."""
handler = getattr(request.app.state, "message_handler", None)
if not handler:
diff --git a/claude-pick b/claude-pick
index 4f5643dc..792c6bd7 100755
--- a/claude-pick
+++ b/claude-pick
@@ -142,7 +142,7 @@ case "$provider" in
prompt="Select an LM Studio model> "
;;
llamacpp|llama.cpp)
- # llama.cpp doesn't have a standardized /models endpoint that returns all loaded models reliably
+ # llama.cpp doesn't have a standardized /models endpoint that returns all loaded models reliably
# in the same way, but it does support Anthropic routing. We can use a stub model or query if available.
# For simple picker, we'll just allow passing a default or typing it in, but to match fzf we offer a stub.
models="local-model\nllama-server"
@@ -168,5 +168,16 @@ if [[ -z "${model:-}" ]]; then
exit 1
fi
+# Read auth token from .env or environment
+auth_token="${ANTHROPIC_AUTH_TOKEN:-$(read_env_value ANTHROPIC_AUTH_TOKEN)}"
+if [[ -z "$auth_token" ]]; then
+ auth_token="freecc"
+fi
+
+# If auth_token doesn't contain a colon, append ":$model"
+if [[ "$auth_token" != *:* ]]; then
+ auth_token="$auth_token:$model"
+fi
+
echo "Launching Claude with provider: $provider, model: $model" >&2
-ANTHROPIC_AUTH_TOKEN="freecc:$model" ANTHROPIC_BASE_URL="$BASE_URL" exec claude "$@"
+ANTHROPIC_AUTH_TOKEN="$auth_token" ANTHROPIC_BASE_URL="$BASE_URL" exec claude "$@"
diff --git a/config/settings.py b/config/settings.py
index 431fd508..b773ce9e 100644
--- a/config/settings.py
+++ b/config/settings.py
@@ -122,6 +122,11 @@ class Settings(BaseSettings):
host: str = "0.0.0.0"
port: int = 8082
log_file: str = "server.log"
+ # Optional server API key to protect endpoints (Anthropic-style)
+ # Set via env `ANTHROPIC_AUTH_TOKEN`. When empty, no auth is required.
+ anthropic_auth_token: str = Field(
+ default="", validation_alias="ANTHROPIC_AUTH_TOKEN"
+ )
# Handle empty strings for optional string fields
@field_validator(
diff --git a/tests/api/test_auth.py b/tests/api/test_auth.py
new file mode 100644
index 00000000..02e6ca36
--- /dev/null
+++ b/tests/api/test_auth.py
@@ -0,0 +1,57 @@
+from unittest.mock import patch
+
+from fastapi.testclient import TestClient
+
+from api.app import app
+from api.dependencies import get_settings
+from config.settings import Settings
+
+
+def test_anthropic_auth_token_required_and_accepts_x_api_key():
+ client = TestClient(app)
+ settings = Settings()
+ settings.anthropic_auth_token = "s3cr3t"
+ app.dependency_overrides[get_settings] = lambda: settings
+
+ payload = {
+ "model": "claude-3-sonnet",
+ "messages": [{"role": "user", "content": "hello"}],
+ }
+
+ with patch("api.routes.get_token_count", return_value=1):
+ # No header -> 401
+ r = client.post("/v1/messages/count_tokens", json=payload)
+ assert r.status_code == 401
+
+ # X-API-Key header -> 200
+ r = client.post(
+ "/v1/messages/count_tokens", json=payload, headers={"X-API-Key": "s3cr3t"}
+ )
+ assert r.status_code == 200
+ assert r.json()["input_tokens"] == 1
+
+ app.dependency_overrides.clear()
+
+
+def test_anthropic_auth_token_accepts_bearer_authorization():
+ client = TestClient(app)
+ settings = Settings()
+ settings.anthropic_auth_token = "b3artoken"
+ app.dependency_overrides[get_settings] = lambda: settings
+
+ payload = {
+ "model": "claude-3-sonnet",
+ "messages": [{"role": "user", "content": "hello"}],
+ }
+
+ with patch("api.routes.get_token_count", return_value=2):
+ # Authorization Bearer -> 200
+ r = client.post(
+ "/v1/messages/count_tokens",
+ json=payload,
+ headers={"Authorization": "Bearer b3artoken"},
+ )
+ assert r.status_code == 200
+ assert r.json()["input_tokens"] == 2
+
+ app.dependency_overrides.clear()
diff --git a/tests/conftest.py b/tests/conftest.py
index caa799b6..b0928f59 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -9,6 +9,9 @@ import pytest
os.environ.setdefault("NVIDIA_NIM_API_KEY", "test_key")
os.environ.setdefault("MODEL", "nvidia_nim/test-model")
os.environ["PTB_TIMEDELTA"] = "1"
+# Ensure tests don't pick up a server API key from the repo .env
+# (tests expect endpoints to be unauthenticated by default)
+os.environ["ANTHROPIC_AUTH_TOKEN"] = ""
from typing import Any
from unittest.mock import AsyncMock, MagicMock