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
package main

import (
	"context"
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"os"
	"path/filepath"
	"strings"
	"sync/atomic"
	"testing"
	"time"
)

// The plugin's test vectors, so a port that hashes differently fails here
// rather than at Anthropic.
func TestBillingHeader(t *testing.T) {
	if got := billingHeader("hey", "2.1.90", "cli"); got != "x-anthropic-billing-header: cc_version=2.1.90.b39; cc_entrypoint=cli; cch=fa690;" {
		t.Errorf("hey: %s", got)
	}
	if got := billingHeader("hey", "2.1.37", "cli"); !strings.Contains(got, "cc_version=2.1.37.0d9;") {
		t.Errorf("hey/2.1.37: %s", got)
	}
	if got := billingHeader("Hello, how are you doing today?", "2.1.90", "cli"); !strings.Contains(got, ".494;") || !strings.Contains(got, "cch=852db;") {
		t.Errorf("long: %s", got)
	}
	if got := billingHeader("", "2.1.90", "cli"); !strings.Contains(got, "cch=e3b0c;") {
		t.Errorf("empty: %s", got)
	}
}

func writeCreds(t *testing.T, path, access, refresh string, expires time.Time) {
	t.Helper()
	b, _ := json.Marshal(map[string]any{
		"claudeAiOauth": map[string]any{
			"accessToken": access, "refreshToken": refresh,
			"expiresAt": expires.UnixMilli(), "scopes": []string{"user:inference"},
			"subscriptionType": "max",
		},
		"other": "kept",
	})
	if err := os.WriteFile(path, b, 0o600); err != nil {
		t.Fatal(err)
	}
}

func fakeTokenEndpoint(t *testing.T, calls *int32) {
	t.Helper()
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		atomic.AddInt32(calls, 1)
		r.ParseForm()
		if r.PostForm.Get("grant_type") != "refresh_token" || r.PostForm.Get("client_id") != oauthClientID {
			http.Error(w, "bad form", 400)
			return
		}
		json.NewEncoder(w).Encode(map[string]any{
			"access_token":  "new-access",
			"refresh_token": "new-refresh-from-" + r.PostForm.Get("refresh_token"),
			"expires_in":    3600,
		})
	}))
	t.Cleanup(srv.Close)
	old := oauthTokenURL
	oauthTokenURL = srv.URL
	t.Cleanup(func() { oauthTokenURL = old })
}

// An expiring token is refreshed, written back with every other field kept,
// and the file stays private.
func TestOAuthRefreshWritesBack(t *testing.T) {
	var calls int32
	fakeTokenEndpoint(t, &calls)
	path := filepath.Join(t.TempDir(), ".credentials.json")
	writeCreds(t, path, "old-access", "old-refresh", time.Now().Add(time.Minute))

	a, err := newOAuthAuth(path)
	if err != nil {
		t.Fatal(err)
	}
	hs, err := a.headers(context.Background())
	if err != nil {
		t.Fatal(err)
	}
	if hs[0] != (header{"Authorization", "Bearer new-access"}) {
		t.Errorf("first header = %v", hs[0])
	}

	raw, _ := os.ReadFile(path)
	var file map[string]any
	json.Unmarshal(raw, &file)
	oauth := file["claudeAiOauth"].(map[string]any)
	if oauth["refreshToken"] != "new-refresh-from-old-refresh" || oauth["subscriptionType"] != "max" || file["other"] != "kept" {
		t.Errorf("written back: %s", raw)
	}
	if fi, _ := os.Stat(path); fi.Mode().Perm() != 0o600 {
		t.Errorf("mode = %v", fi.Mode().Perm())
	}
}

// Two processes holding the same expiring token: the first refreshes, the
// second finds the new token in the file and must not spend the (now dead)
// refresh token again.
func TestOAuthRefreshOnlyOnce(t *testing.T) {
	var calls int32
	fakeTokenEndpoint(t, &calls)
	path := filepath.Join(t.TempDir(), ".credentials.json")
	writeCreds(t, path, "old-access", "old-refresh", time.Now().Add(time.Minute))

	a, _ := newOAuthAuth(path)
	b, _ := newOAuthAuth(path)
	if _, err := a.headers(context.Background()); err != nil {
		t.Fatal(err)
	}
	hs, err := b.headers(context.Background())
	if err != nil {
		t.Fatal(err)
	}
	if calls != 1 {
		t.Errorf("token endpoint called %d times, want 1", calls)
	}
	if hs[0].value != "Bearer new-access" {
		t.Errorf("second process uses %q", hs[0].value)
	}
}

// A subscription request carries hans' instructions in the first message and
// only the billing line and identity in system, and the billing line does
// not change from turn to turn, or the system prompt would never be cached.
func TestOAuthRequestShape(t *testing.T) {
	path := filepath.Join(t.TempDir(), ".credentials.json")
	writeCreds(t, path, "a", "r", time.Now().Add(time.Hour))
	auth, _ := newOAuthAuth(path)
	b := &anthropicBackend{model: "claude-opus-5-5", auth: auth, system: "SYSTEM TEXT"}

	one := []anthropicMessage{{Role: roleUser, Content: b.UserInput("first")}}
	two := append(one,
		anthropicMessage{Role: roleAssistant, Content: []json.RawMessage{mustMarshal(map[string]any{"type": "text", "text": "ok"})}},
		anthropicMessage{Role: roleUser, Content: b.UserInput("second")})

	r1, r2 := b.request(one), b.request(two)
	if len(r1.System) != 2 || r1.System[1].Text != claudeCodeIdentity ||
		!strings.HasPrefix(r1.System[0].Text, "x-anthropic-billing-header: ") {
		t.Fatalf("system = %+v", r1.System)
	}
	// The checksum is over the user's first prompt, which does not change
	// as the conversation grows.
	if r1.System[0].Text != r2.System[0].Text {
		t.Error("billing line differs between turns")
	}
	if want := billingHeader(firstUserText(one), claudeCodeVersion, claudeCodeEntry); r1.System[0].Text != want {
		t.Errorf("billing line = %q, want the one over the prompt, %q", r1.System[0].Text, want)
	}
	if got := firstUserText(r1.Messages); got != "SYSTEM TEXT" {
		t.Errorf("first user text = %q, want the instructions", got)
	}
	if len(one[0].Content) != 1 {
		t.Error("request() modified the caller's messages")
	}
	m1, _ := json.Marshal(r1.Messages)
	m2, _ := json.Marshal(r2.Messages)
	if !strings.HasPrefix(string(m2), strings.TrimSuffix(string(m1), "]")) {
		t.Error("messages of the second request do not extend the first's")
	}
}

// The header names and order of the recorded OpenCode request.
func TestOAuthHeaderOrder(t *testing.T) {
	path := filepath.Join(t.TempDir(), ".credentials.json")
	writeCreds(t, path, "a", "r", time.Now().Add(time.Hour))
	a, _ := newOAuthAuth(path)
	hs, _ := a.headers(context.Background())
	var names []string
	for _, h := range hs {
		names = append(names, h.name)
	}
	want := "Authorization Content-Type User-Agent X-Claude-Code-Session-Id anthropic-beta anthropic-version x-app x-client-request-id x-session-affinity"
	if strings.Join(names, " ") != want {
		t.Errorf("headers = %v", names)
	}
	if !strings.HasPrefix(a.affinity, "ses_") || len(a.affinity) != 4+26 {
		t.Errorf("affinity = %q", a.affinity)
	}
}

func TestOpencodeID(t *testing.T) {
	// The recorded id ses_e61886bc5ffe… was made at about this time; a
	// descending id made later sorts lower.
	at := time.UnixMilli(int64((^uint64(0xe61886bc5ffe) & (1<<48 - 1)) / 4096))
	id := opencodeID("ses", at)
	if !strings.HasPrefix(id, "ses_e61886bc5ff") {
		t.Errorf("id = %s", id)
	}
}