|
| 1 | +import { execSync } from "child_process" |
| 2 | +import os from "os" |
| 3 | +import { publicProcedure, router } from "../index" |
| 4 | + |
| 5 | +/** |
| 6 | + * Read Claude Code credentials from macOS System Keychain |
| 7 | + * This is where the Claude CLI stores its OAuth token with proper scopes |
| 8 | + */ |
| 9 | +function readSystemKeychainCredentials(): string | null { |
| 10 | + try { |
| 11 | + const username = os.userInfo().username |
| 12 | + const result = execSync( |
| 13 | + `security find-generic-password -s "Claude Code-credentials" -a "${username}" -w 2>/dev/null`, |
| 14 | + { encoding: "utf-8" } |
| 15 | + ) |
| 16 | + return result.trim() |
| 17 | + } catch { |
| 18 | + // Item not found or error |
| 19 | + return null |
| 20 | + } |
| 21 | +} |
| 22 | + |
| 23 | +/** |
| 24 | + * Extract access token from Claude CLI credentials JSON |
| 25 | + */ |
| 26 | +function extractAccessToken(jsonData: string): string | null { |
| 27 | + try { |
| 28 | + const data = JSON.parse(jsonData) |
| 29 | + return data?.claudeAiOauth?.accessToken ?? null |
| 30 | + } catch { |
| 31 | + return null |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +/** |
| 36 | + * Get OAuth token from system keychain (Claude CLI credentials) |
| 37 | + * This token has the proper scopes for usage API |
| 38 | + */ |
| 39 | +function getOAuthToken(): string | null { |
| 40 | + const keychainData = readSystemKeychainCredentials() |
| 41 | + |
| 42 | + if (!keychainData) { |
| 43 | + console.log("[ClaudeUsage] No credentials found in system keychain") |
| 44 | + return null |
| 45 | + } |
| 46 | + |
| 47 | + const token = extractAccessToken(keychainData) |
| 48 | + if (token) { |
| 49 | + console.log("[ClaudeUsage] Token from system keychain, length:", token.length) |
| 50 | + } else { |
| 51 | + console.log("[ClaudeUsage] Could not extract token from keychain data") |
| 52 | + } |
| 53 | + |
| 54 | + return token |
| 55 | +} |
| 56 | + |
| 57 | +/** |
| 58 | + * Parsed usage data returned to the client |
| 59 | + * Always includes all model breakdowns (defaulting to 0 if not used) |
| 60 | + */ |
| 61 | +export interface ClaudeUsageData { |
| 62 | + fiveHour: { |
| 63 | + utilization: number |
| 64 | + resetsAt: string | null |
| 65 | + } |
| 66 | + sevenDay: { |
| 67 | + utilization: number |
| 68 | + resetsAt: string | null |
| 69 | + } |
| 70 | + sevenDayOpus: { |
| 71 | + utilization: number |
| 72 | + } |
| 73 | + sevenDaySonnet: { |
| 74 | + utilization: number |
| 75 | + resetsAt: string | null |
| 76 | + } |
| 77 | + lastFetched: string |
| 78 | +} |
| 79 | + |
| 80 | +/** |
| 81 | + * Parse utilization value that can be Int, Double, or String |
| 82 | + * Based on claude-usage-tracker's robust parser |
| 83 | + */ |
| 84 | +function parseUtilization(value: unknown): number { |
| 85 | + if (typeof value === "number") { |
| 86 | + return value |
| 87 | + } |
| 88 | + if (typeof value === "string") { |
| 89 | + const cleaned = value.trim().replace("%", "") |
| 90 | + const parsed = parseFloat(cleaned) |
| 91 | + return isNaN(parsed) ? 0 : parsed |
| 92 | + } |
| 93 | + return 0 |
| 94 | +} |
| 95 | + |
| 96 | +/** |
| 97 | + * Claude Usage Router |
| 98 | + * Fetches usage data from Anthropic's OAuth API |
| 99 | + */ |
| 100 | +export const claudeUsageRouter = router({ |
| 101 | + /** |
| 102 | + * Get current usage stats |
| 103 | + */ |
| 104 | + getUsage: publicProcedure.query(async (): Promise<{ |
| 105 | + data: ClaudeUsageData | null |
| 106 | + error: string | null |
| 107 | + }> => { |
| 108 | + const token = getOAuthToken() |
| 109 | + |
| 110 | + if (!token) { |
| 111 | + return { |
| 112 | + data: null, |
| 113 | + error: "Not connected to Claude Code", |
| 114 | + } |
| 115 | + } |
| 116 | + |
| 117 | + try { |
| 118 | + console.log("[ClaudeUsage] Fetching from API...") |
| 119 | + const response = await fetch("https://api.anthropic.com/api/oauth/usage", { |
| 120 | + method: "GET", |
| 121 | + headers: { |
| 122 | + Authorization: `Bearer ${token}`, |
| 123 | + "Content-Type": "application/json", |
| 124 | + "User-Agent": "claude-code/2.1.5", |
| 125 | + "anthropic-beta": "oauth-2025-04-20", |
| 126 | + }, |
| 127 | + }) |
| 128 | + console.log("[ClaudeUsage] Response status:", response.status) |
| 129 | + |
| 130 | + if (response.status === 401 || response.status === 403) { |
| 131 | + const body = await response.text() |
| 132 | + console.error("[ClaudeUsage] Auth failed:", response.status, body) |
| 133 | + return { |
| 134 | + data: null, |
| 135 | + error: "Token expired or invalid. Please reconnect Claude Code.", |
| 136 | + } |
| 137 | + } |
| 138 | + |
| 139 | + if (response.status === 429) { |
| 140 | + return { |
| 141 | + data: null, |
| 142 | + error: "Rate limited. Please try again later.", |
| 143 | + } |
| 144 | + } |
| 145 | + |
| 146 | + if (!response.ok) { |
| 147 | + console.error("[ClaudeUsage] API error:", response.status, response.statusText) |
| 148 | + return { |
| 149 | + data: null, |
| 150 | + error: `API error: ${response.status}`, |
| 151 | + } |
| 152 | + } |
| 153 | + |
| 154 | + const rawData = await response.json() as Record<string, unknown> |
| 155 | + |
| 156 | + // Debug: log raw API response |
| 157 | + console.log("[ClaudeUsage] Raw API response:", JSON.stringify(rawData, null, 2)) |
| 158 | + |
| 159 | + // Parse each section with robust type handling (matching claude-usage-tracker) |
| 160 | + const fiveHour = rawData.five_hour as Record<string, unknown> | undefined |
| 161 | + const sevenDay = rawData.seven_day as Record<string, unknown> | undefined |
| 162 | + const sevenDayOpus = rawData.seven_day_opus as Record<string, unknown> | undefined |
| 163 | + const sevenDaySonnet = rawData.seven_day_sonnet as Record<string, unknown> | undefined |
| 164 | + |
| 165 | + const data: ClaudeUsageData = { |
| 166 | + fiveHour: { |
| 167 | + utilization: fiveHour ? parseUtilization(fiveHour.utilization) : 0, |
| 168 | + resetsAt: (fiveHour?.resets_at as string) ?? null, |
| 169 | + }, |
| 170 | + sevenDay: { |
| 171 | + utilization: sevenDay ? parseUtilization(sevenDay.utilization) : 0, |
| 172 | + resetsAt: (sevenDay?.resets_at as string) ?? null, |
| 173 | + }, |
| 174 | + // Always include model breakdowns (default to 0 if not present) |
| 175 | + sevenDayOpus: { |
| 176 | + utilization: sevenDayOpus ? parseUtilization(sevenDayOpus.utilization) : 0, |
| 177 | + }, |
| 178 | + sevenDaySonnet: { |
| 179 | + utilization: sevenDaySonnet ? parseUtilization(sevenDaySonnet.utilization) : 0, |
| 180 | + resetsAt: (sevenDaySonnet?.resets_at as string) ?? null, |
| 181 | + }, |
| 182 | + lastFetched: new Date().toISOString(), |
| 183 | + } |
| 184 | + |
| 185 | + return { data, error: null } |
| 186 | + } catch (error) { |
| 187 | + console.error("[ClaudeUsage] Fetch error:", error) |
| 188 | + return { |
| 189 | + data: null, |
| 190 | + error: "Network error. Please check your connection.", |
| 191 | + } |
| 192 | + } |
| 193 | + }), |
| 194 | +}) |
0 commit comments