Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions config.example.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ server:
# Upstream Anthropic API
upstream:
url: https://api.anthropic.com
# proxy: "http://user:pass@host:port" # Optional: upstream proxy for API requests

# OAuth - gateway manages token lifecycle centrally
# Step 1: On admin machine, run `claude` and do browser OAuth login
Expand Down
47 changes: 47 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
"test": "tsx tests/rewriter.test.ts"
},
"dependencies": {
"https-proxy-agent": "^9.0.0",
"yaml": "^2.7.0"
},
"devDependencies": {
Expand Down
1 change: 1 addition & 0 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ export type Config = {
}
upstream: {
url: string
proxy?: string // e.g. http://user:pass@host:port
}
auth: {
tokens: TokenEntry[]
Expand Down
2 changes: 1 addition & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ try {
log('info', 'CC Gateway starting...')

// Initialize OAuth first - gateway manages the token lifecycle
await initOAuth(config.oauth.refresh_token)
await initOAuth(config.oauth.refresh_token, config.upstream.proxy)

startProxy(config)
} catch (err) {
Expand Down
7 changes: 6 additions & 1 deletion src/oauth.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { request as httpsRequest } from 'https'
import { HttpsProxyAgent } from 'https-proxy-agent'
import { log } from './logger.js'

const TOKEN_URL = 'https://platform.claude.com/v1/oauth/token'
Expand All @@ -24,7 +25,10 @@ let cachedTokens: OAuthTokens | null = null
* The gateway holds the refresh token and manages access token lifecycle.
* Client machines never need to contact platform.claude.com.
*/
export async function initOAuth(refreshToken: string): Promise<void> {
let proxyAgent: HttpsProxyAgent<string> | undefined

export async function initOAuth(refreshToken: string, proxyUrl?: string): Promise<void> {
if (proxyUrl) proxyAgent = new HttpsProxyAgent(proxyUrl)
log('info', 'Refreshing OAuth token...')
cachedTokens = await refreshOAuthToken(refreshToken)
log('info', `OAuth token acquired, expires at ${new Date(cachedTokens.expiresAt).toISOString()}`)
Expand Down Expand Up @@ -87,6 +91,7 @@ function refreshOAuthToken(refreshToken: string): Promise<OAuthTokens> {
'Content-Type': 'application/json',
'Content-Length': String(Buffer.byteLength(body)),
},
...(proxyAgent ? { agent: proxyAgent } : {}),
},
(res) => {
const chunks: Buffer[] = []
Expand Down
7 changes: 6 additions & 1 deletion src/proxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { createServer as createHttpServer, type IncomingMessage, type ServerResp
import { readFileSync } from 'fs'
import { request as httpsRequest } from 'https'
import { URL } from 'url'
import { HttpsProxyAgent } from 'https-proxy-agent'
import type { Config } from './config.js'
import { authenticate, initAuth } from './auth.js'
import { getAccessToken } from './oauth.js'
Expand All @@ -13,10 +14,12 @@ export function startProxy(config: Config) {
initAuth(config)

const upstream = new URL(config.upstream.url)
const proxyAgent = config.upstream.proxy ? new HttpsProxyAgent(config.upstream.proxy) : undefined
if (proxyAgent) log('info', `Using upstream proxy: ${config.upstream.proxy!.replace(/:([^:@]+)@/, ':***@')}`)
const useTls = config.server.tls?.cert && config.server.tls?.key

const handler = (req: IncomingMessage, res: ServerResponse) => {
handleRequest(req, res, config, upstream)
handleRequest(req, res, config, upstream, proxyAgent)
}

let server
Expand Down Expand Up @@ -46,6 +49,7 @@ async function handleRequest(
res: ServerResponse,
config: Config,
upstream: URL,
proxyAgent?: HttpsProxyAgent<string>,
) {
const method = req.method || 'GET'
const path = req.url || '/'
Expand Down Expand Up @@ -135,6 +139,7 @@ async function handleRequest(
host: upstream.host,
'content-length': String(body.length),
},
...(proxyAgent ? { agent: proxyAgent } : {}),
},
(proxyRes) => {
const status = proxyRes.statusCode || 502
Expand Down