1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
|
// claude-usage fetches your Claude plan usage limits directly from the
// claude.ai web API and prints a human-readable summary, mirroring the
// "Usage" page in the (increasingly bloated) settings UI.
//
// Credentials (sessionKey, cf_clearance, lastActiveOrg) are read live from
// every Firefox profile's cookies.sqlite via the sqlite3 CLI. We try each
// candidate set until one authenticates.
package main
import (
"bytes"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
)
// The same User-Agent the browser used when cf_clearance was minted.
// cf_clearance is bound to UA + IP, so matching it improves our odds.
const userAgent = "Mozilla/5.0 (X11; Linux x86_64; rv:150.0) Gecko/20100101 Firefox/150.0"
// slot is one usage window (a utilization percentage + reset time).
type slot struct {
Utilization float64 `json:"utilization"`
ResetsAt time.Time `json:"resets_at"`
}
type extraUsage struct {
IsEnabled bool `json:"is_enabled"`
MonthlyLimit *float64 `json:"monthly_limit"`
UsedCredits *float64 `json:"used_credits"`
Utilization *float64 `json:"utilization"`
Currency *string `json:"currency"`
}
type usageResponse struct {
FiveHour *slot `json:"five_hour"`
SevenDay *slot `json:"seven_day"`
SevenDayOpus *slot `json:"seven_day_opus"`
SevenDaySonnet *slot `json:"seven_day_sonnet"`
SevenDayCowork *slot `json:"seven_day_cowork"`
ExtraUsage extraUsage `json:"extra_usage"`
}
// candidate is one set of cookies pulled from a Firefox profile.
type candidate struct {
profile string
sessionKey string
cfClearance string
lastActiveOrg string
}
// authError signals that the request was rejected because the cookies are
// stale or invalid (HTTP 401/403, including Cloudflare's challenge page).
type authError struct {
status string
}
func (e *authError) Error() string {
return fmt.Sprintf("authentication rejected (HTTP %s): cookies are stale or invalid", e.status)
}
// refreshHint is the actionable advice shown when authentication fails.
const refreshHint = "open https://claude.ai in Firefox (and reload the page) to refresh the sessionKey/cf_clearance cookies, then try again"
// errStaleCredentials wraps any failure caused by missing or rejected cookies,
// so callers (e.g. the varlink service) can detect it with errors.Is.
var errStaleCredentials = errors.New("claude.ai credentials are stale or missing")
func main() {
varlinkMode := flag.Bool("varlink", false, "run as a varlink service on a unix socket instead of printing once")
minInterval := flag.Duration("refresh-min-interval", 60*time.Second,
"varlink: minimum background refresh interval, also the kick floor (no on-demand fetch if a fetch happened within this window)")
maxInterval := flag.Duration("refresh-max-interval", 30*time.Minute,
"varlink: maximum background refresh interval (exponential backoff cap while usage is unchanged)")
flag.Parse()
if *varlinkMode {
runVarlinkServer(*minInterval, *maxInterval)
return
}
usage, err := getUsage()
if err != nil {
fatalf("%v", err)
}
fmt.Print(formatHuman(usage))
}
// getUsage discovers Firefox credentials and returns the parsed usage from the
// first candidate set that authenticates. Shared by the CLI and varlink modes.
func getUsage() (*usageResponse, error) {
cands, err := findFirefoxCookies()
if err != nil {
return nil, fmt.Errorf("could not read Firefox cookies: %w", err)
}
if len(cands) == 0 {
return nil, fmt.Errorf("no claude.ai sessionKey found in any Firefox profile under %s: %w.\nHint: %s",
firefoxRoot(), errStaleCredentials, refreshHint)
}
var lastErr error
allAuth := true
for _, c := range cands {
usage, err := fetchUsage(c)
if err != nil {
lastErr = fmt.Errorf("profile %s: %w", c.profile, err)
var ae *authError
if !errors.As(err, &ae) {
allAuth = false
}
continue
}
return usage, nil
}
// If every candidate failed purely on authentication, the cookies are
// stale; give the actionable refresh hint instead of a raw HTTP error.
if allAuth {
return nil, fmt.Errorf("all %d Firefox credential(s) were rejected: %w.\nHint: %s\n(last error: %v)",
len(cands), errStaleCredentials, refreshHint, lastErr)
}
return nil, fmt.Errorf("all %d credential candidate(s) failed; last error: %v", len(cands), lastErr)
}
// findFirefoxCookies scans every ~/.mozilla/firefox/*/cookies.sqlite, copies
// each into a private temp dir (the live DB is locked by a running Firefox),
// and extracts the relevant claude.ai cookies via the sqlite3 CLI.
func findFirefoxCookies() ([]candidate, error) {
dbs, _ := filepath.Glob(filepath.Join(firefoxRoot(), "*", "cookies.sqlite"))
tmpDir, err := os.MkdirTemp("", "claude-usage-cookies-")
if err != nil {
return nil, err
}
defer os.RemoveAll(tmpDir)
var cands []candidate
for _, db := range dbs {
profile := filepath.Base(filepath.Dir(db))
cookies, err := readCookiesFromDB(db, tmpDir, profile)
if err != nil {
fmt.Fprintf(os.Stderr, "warning: skipping profile %s: %v\n", profile, err)
continue
}
if cookies["sessionKey"] == "" {
continue
}
cands = append(cands, candidate{
profile: profile,
sessionKey: cookies["sessionKey"],
cfClearance: cookies["cf_clearance"],
lastActiveOrg: cookies["lastActiveOrg"],
})
}
return cands, nil
}
func readCookiesFromDB(db, tmpDir, profile string) (map[string]string, error) {
// Copy because Firefox holds a write lock on the live file.
tmpFile := filepath.Join(tmpDir, "cookies-"+profile+".sqlite")
if err := copyFile(db, tmpFile); err != nil {
return nil, err
}
defer os.Remove(tmpFile)
sqlite3Bin := os.Getenv("SQLITE3")
if sqlite3Bin == "" {
sqlite3Bin = "sqlite3"
}
const query = `SELECT name || char(9) || value FROM moz_cookies ` +
`WHERE host LIKE '%claude.ai%' ` +
`AND name IN ('sessionKey','cf_clearance','lastActiveOrg');`
out, err := exec.Command(sqlite3Bin, tmpFile, query).Output()
if err != nil {
return nil, fmt.Errorf("sqlite3 query failed: %w", err)
}
result := map[string]string{}
for _, line := range strings.Split(strings.TrimSpace(string(out)), "\n") {
if line == "" {
continue
}
name, value, found := strings.Cut(line, "\t")
if found {
result[name] = value
}
}
return result, nil
}
// fetchUsage calls the usage endpoint with the given credentials.
//
// We shell out to curl rather than using net/http: Cloudflare fingerprints
// the TLS ClientHello (JA3/JA4), and Go's stdlib fingerprint is recognised as
// non-browser and served a 403 challenge, whereas curl's passes with a valid
// cf_clearance cookie.
func fetchUsage(c candidate) (*usageResponse, error) {
org := c.lastActiveOrg
if org == "" {
return nil, fmt.Errorf("no lastActiveOrg cookie (org id) found")
}
curlBin := os.Getenv("CURL")
if curlBin == "" {
curlBin = "curl"
}
cookie := fmt.Sprintf("sessionKey=%s", c.sessionKey)
if c.cfClearance != "" {
cookie += fmt.Sprintf("; cf_clearance=%s", c.cfClearance)
}
url := fmt.Sprintf("https://claude.ai/api/organizations/%s/usage", org)
args := []string{
"--silent", "--show-error",
"--max-time", "30",
// Append the HTTP status code on its own final line so we can split it
// off from the body.
"--write-out", "\n%{http_code}",
"-H", "User-Agent: " + userAgent,
"-H", "Accept: */*",
"-H", "Accept-Language: en-US,en;q=0.9",
"-H", "Referer: https://claude.ai/new",
"-H", "anthropic-client-platform: web_claude_ai",
"--cookie", cookie,
url,
}
var stdout, stderr bytes.Buffer
cmd := exec.Command(curlBin, args...)
cmd.Stdout = &stdout
cmd.Stderr = &stderr
if err := cmd.Run(); err != nil {
return nil, fmt.Errorf("curl failed: %w: %s", err, stderr.String())
}
out := stdout.String()
nl := strings.LastIndexByte(out, '\n')
if nl < 0 {
return nil, fmt.Errorf("unexpected curl output: %q", out)
}
body := out[:nl]
status := strings.TrimSpace(out[nl+1:])
if status != "200" {
// 401/403 (and Cloudflare's "Just a moment..." 403 challenge page)
// mean the cookies are stale or were rejected. Mark these so callers
// can suggest refreshing them.
if status == "401" || status == "403" {
return nil, &authError{status: status}
}
snippet := body
if len(snippet) > 200 {
snippet = snippet[:200]
}
return nil, fmt.Errorf("HTTP %s: %s", status, snippet)
}
var usage usageResponse
if err := json.Unmarshal([]byte(body), &usage); err != nil {
return nil, fmt.Errorf("decoding response: %w", err)
}
return &usage, nil
}
func formatHuman(u *usageResponse) string {
var b strings.Builder
b.WriteString("Claude Plan Usage\n\n")
now := time.Now()
line := func(label string, s *slot) {
if s == nil {
return
}
local := s.ResetsAt.Local()
fmt.Fprintf(&b, " %-18s %5.0f%% resets %s (%s)\n",
label, s.Utilization, humanizeDelta(s.ResetsAt.Sub(now)), local.Format("Mon 15:04"))
}
line("Current session", u.FiveHour)
line("Weekly (all)", u.SevenDay)
line("Weekly (Sonnet)", u.SevenDaySonnet)
line("Weekly (Opus)", u.SevenDayOpus)
line("Weekly (Cowork)", u.SevenDayCowork)
if u.ExtraUsage.IsEnabled {
if u.ExtraUsage.Utilization != nil {
fmt.Fprintf(&b, " %-18s %5.0f%%\n", "Extra usage", *u.ExtraUsage.Utilization)
} else {
fmt.Fprintf(&b, " %-18s enabled\n", "Extra usage")
}
}
return b.String()
}
// humanizeDelta renders a duration like "in 1h 0m" or "in 2d 14h".
func humanizeDelta(d time.Duration) string {
if d < 0 {
return "now"
}
days := int(d.Hours()) / 24
hours := int(d.Hours()) % 24
mins := int(d.Minutes()) % 60
switch {
case days > 0:
return fmt.Sprintf("in %dd %dh", days, hours)
case hours > 0:
return fmt.Sprintf("in %dh %dm", hours, mins)
default:
return fmt.Sprintf("in %dm", mins)
}
}
func firefoxRoot() string {
home, _ := os.UserHomeDir()
return filepath.Join(home, ".mozilla", "firefox")
}
func copyFile(src, dst string) error {
in, err := os.Open(src)
if err != nil {
return err
}
defer in.Close()
out, err := os.Create(dst)
if err != nil {
return err
}
defer out.Close()
if _, err := io.Copy(out, in); err != nil {
return err
}
return out.Close()
}
func fatalf(format string, args ...any) {
fmt.Fprintf(os.Stderr, "claude-usage: "+format+"\n", args...)
os.Exit(1)
}
|