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 func newChatGPTFake(t *testing.T) *ChatGPTFake {
42 mux := http.NewServeMux()
43 mux.HandleFunc("POST /api/accounts/deviceauth/usercode", f.userCode)
44 mux.HandleFunc("POST /api/accounts/deviceauth/token", f.deviceToken)
45 mux.HandleFunc("POST /oauth/token", f.oauthToken)
47 f.Server = httptest.NewServer(mux)
53 func newTestChatGPTAuth(t *testing.T, server *ChatGPTFake) *ChatGPTAuth {
56 return newChatGPTAuth(filepath.Join(t.TempDir(), chatgptTokenFileName), server.URL)
59 func (f *ChatGPTFake) userCode(w http.ResponseWriter, r *http.Request) {
60 var body map[string]string
62 err := json.NewDecoder(r.Body).Decode(&body)
63 if err != nil || body["client_id"] != chatgptClientID {
64 http.Error(w, "bad client", http.StatusBadRequest)
69 chatgptWriteJSON(w, map[string]any{
70 "device_auth_id": "device-1",
71 "user_code": "CODE-1234",
76 func (f *ChatGPTFake) deviceToken(w http.ResponseWriter, r *http.Request) {
78 defer f.mutex.Unlock()
80 var body map[string]string
82 err := json.NewDecoder(r.Body).Decode(&body)
83 if err != nil || body["device_auth_id"] != "device-1" || body["user_code"] != "CODE-1234" {
84 http.Error(w, "bad device", http.StatusBadRequest)
91 http.Error(w, "denied", http.StatusBadRequest)
96 if f.polls <= f.pending {
97 http.Error(w, "pending", http.StatusForbidden)
102 chatgptWriteJSON(w, map[string]any{
103 "authorization_code": "auth-code",
104 "code_challenge": "challenge",
105 "code_verifier": "verifier",
109 func (f *ChatGPTFake) oauthToken(w http.ResponseWriter, r *http.Request) {
111 defer f.mutex.Unlock()
113 if r.Header.Get("Content-Type") == "application/x-www-form-urlencoded" {
116 http.Error(w, err.Error(), http.StatusBadRequest)
121 f.exchange = r.PostForm
122 chatgptWriteJSON(w, map[string]any{
123 "access_token": f.newToken(time.Hour),
124 "refresh_token": "refresh-1",
125 "id_token": f.newToken(time.Hour),
131 var body map[string]string
133 err := json.NewDecoder(r.Body).Decode(&body)
134 if err != nil || body["grant_type"] != "refresh_token" || body["client_id"] != chatgptClientID {
135 http.Error(w, "bad refresh", http.StatusBadRequest)
141 f.refreshed = body["refresh_token"]
143 http.Error(w, `{"error": "invalid_grant", "token": "`+body["refresh_token"]+`"}`, http.StatusUnauthorized)
148 answer := map[string]any{
149 "access_token": f.newToken(time.Hour),
150 "id_token": f.newToken(time.Hour),
153 if f.newRefresh != "" {
154 answer["refresh_token"] = f.newRefresh
157 chatgptWriteJSON(w, answer)
160 // newToken returns a new fake JWT with the expiry and the account claim, and
161 // keeps it in access. The caller holds the mutex.
162 func (f *ChatGPTFake) newToken(ttl time.Duration) string {
163 claims, err := json.Marshal(map[string]any{
164 "exp": time.Now().Add(ttl).Unix(),
165 chatgptAuthClaim: map[string]any{
166 "chatgpt_account_id": chatgptTestAccount,
168 "serial": len(f.access),
174 encode := base64.RawURLEncoding.EncodeToString
175 token := encode([]byte(`{"alg":"none"}`)) + "." + encode(claims) + "." + encode([]byte("fake"))
176 f.access = append(f.access, token)
181 // token returns a new access token that expires after ttl, for a token file
182 // that a test writes.
183 func (f *ChatGPTFake) token(ttl time.Duration) string {
185 defer f.mutex.Unlock()
187 return f.newToken(ttl)
190 func chatgptWriteJSON(w http.ResponseWriter, value any) {
191 w.Header().Set("Content-Type", "application/json")
193 err := json.NewEncoder(w).Encode(value)
195 panic(fmt.Sprint("encode answer: ", err))
199 func chatgptWriteTestTokens(t *testing.T, auth *ChatGPTAuth, access, refresh string) {
202 err := auth.write(ChatGPTTokenFile{
204 RefreshToken: refresh,
206 AccountID: chatgptTestAccount,
208 require.NoError(t, err)