15 "github.com/stretchr/testify/require"
18 // chatgptTestAccount is the fake ChatGPT account ID in the fake tokens.
19 const chatgptTestAccount = "account-test"
21 // ChatGPTFake is an httptest login service. The device token endpoint answers
22 // 403 pending times before it grants the code. Each token answer has a new
23 // access token, kept in access.
24 type ChatGPTFake struct {
38 // token returns a new access token that expires after ttl, for a token file
39 // that a test writes.
40 func (f *ChatGPTFake) token(ttl time.Duration) string {
42 defer f.mutex.Unlock()
44 return f.newToken(ttl)
47 // newToken returns a new fake JWT with the expiry and the account claim, and
48 // keeps it in access. The caller holds the mutex.
49 func (f *ChatGPTFake) newToken(ttl time.Duration) string {
50 claims, err := json.Marshal(map[string]any{
51 "exp": time.Now().Add(ttl).Unix(),
52 chatgptAuthClaim: map[string]any{
53 "chatgpt_account_id": chatgptTestAccount,
55 "serial": len(f.access),
61 encode := base64.RawURLEncoding.EncodeToString
62 token := encode([]byte(`{"alg":"none"}`)) + "." + encode(claims) + "." + encode([]byte("fake"))
63 f.access = append(f.access, token)
68 func (f *ChatGPTFake) userCode(w http.ResponseWriter, r *http.Request) {
69 var body map[string]string
71 err := json.NewDecoder(r.Body).Decode(&body)
72 if err != nil || body["client_id"] != chatgptClientID {
73 http.Error(w, "bad client", http.StatusBadRequest)
78 chatgptWriteJSON(w, map[string]any{
79 "device_auth_id": "device-1",
80 "user_code": "CODE-1234",
85 func (f *ChatGPTFake) deviceToken(w http.ResponseWriter, r *http.Request) {
87 defer f.mutex.Unlock()
89 var body map[string]string
91 err := json.NewDecoder(r.Body).Decode(&body)
92 if err != nil || body["device_auth_id"] != "device-1" || body["user_code"] != "CODE-1234" {
93 http.Error(w, "bad device", http.StatusBadRequest)
100 http.Error(w, "denied", http.StatusBadRequest)
105 if f.polls <= f.pending {
106 http.Error(w, "pending", http.StatusForbidden)
111 chatgptWriteJSON(w, map[string]any{
112 "authorization_code": "auth-code",
113 "code_challenge": "challenge",
114 "code_verifier": "verifier",
118 func (f *ChatGPTFake) oauthToken(w http.ResponseWriter, r *http.Request) {
120 defer f.mutex.Unlock()
122 if r.Header.Get("Content-Type") == "application/x-www-form-urlencoded" {
125 http.Error(w, err.Error(), http.StatusBadRequest)
130 f.exchange = r.PostForm
131 chatgptWriteJSON(w, map[string]any{
132 "access_token": f.newToken(time.Hour),
133 "refresh_token": "refresh-1",
134 "id_token": f.newToken(time.Hour),
140 var body map[string]string
142 err := json.NewDecoder(r.Body).Decode(&body)
143 if err != nil || body["grant_type"] != "refresh_token" || body["client_id"] != chatgptClientID {
144 http.Error(w, "bad refresh", http.StatusBadRequest)
150 f.refreshed = body["refresh_token"]
152 http.Error(w, `{"error": "invalid_grant", "token": "`+body["refresh_token"]+`"}`, http.StatusUnauthorized)
157 answer := map[string]any{
158 "access_token": f.newToken(time.Hour),
159 "id_token": f.newToken(time.Hour),
162 if f.newRefresh != "" {
163 answer["refresh_token"] = f.newRefresh
166 chatgptWriteJSON(w, answer)
169 func newChatGPTFake(t *testing.T) *ChatGPTFake {
173 mux := http.NewServeMux()
174 mux.HandleFunc("POST /api/accounts/deviceauth/usercode", f.userCode)
175 mux.HandleFunc("POST /api/accounts/deviceauth/token", f.deviceToken)
176 mux.HandleFunc("POST /oauth/token", f.oauthToken)
178 f.Server = httptest.NewServer(mux)
184 func newTestChatGPTAuth(t *testing.T, server *ChatGPTFake) *ChatGPTAuth {
187 return newChatGPTAuth(filepath.Join(t.TempDir(), chatgptTokenFileName), server.URL)
190 func chatgptWriteTestTokens(t *testing.T, auth *ChatGPTAuth, access, refresh string) {
193 err := auth.write(ChatGPTTokenFile{
195 RefreshToken: refresh,
197 AccountID: chatgptTestAccount,
199 require.NoError(t, err)
202 func chatgptWriteJSON(w http.ResponseWriter, value any) {
203 w.Header().Set("Content-Type", "application/json")
205 err := json.NewEncoder(w).Encode(value)
207 panic(fmt.Sprint("encode answer: ", err))