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 // token returns a new access token that expires after ttl, for a token file
60 // that a test writes.
61 func (f *ChatGPTFake) token(ttl time.Duration) string {
63 defer f.mutex.Unlock()
65 return f.newToken(ttl)
68 // newToken returns a new fake JWT with the expiry and the account claim, and
69 // keeps it in access. The caller holds the mutex.
70 func (f *ChatGPTFake) newToken(ttl time.Duration) string {
71 claims, err := json.Marshal(map[string]any{
72 "exp": time.Now().Add(ttl).Unix(),
73 chatgptAuthClaim: map[string]any{
74 "chatgpt_account_id": chatgptTestAccount,
76 "serial": len(f.access),
82 encode := base64.RawURLEncoding.EncodeToString
83 token := encode([]byte(`{"alg":"none"}`)) + "." + encode(claims) + "." + encode([]byte("fake"))
84 f.access = append(f.access, token)
89 func (f *ChatGPTFake) userCode(w http.ResponseWriter, r *http.Request) {
90 var body map[string]string
92 err := json.NewDecoder(r.Body).Decode(&body)
93 if err != nil || body["client_id"] != chatgptClientID {
94 http.Error(w, "bad client", http.StatusBadRequest)
99 chatgptWriteJSON(w, map[string]any{
100 "device_auth_id": "device-1",
101 "user_code": "CODE-1234",
106 func (f *ChatGPTFake) deviceToken(w http.ResponseWriter, r *http.Request) {
108 defer f.mutex.Unlock()
110 var body map[string]string
112 err := json.NewDecoder(r.Body).Decode(&body)
113 if err != nil || body["device_auth_id"] != "device-1" || body["user_code"] != "CODE-1234" {
114 http.Error(w, "bad device", http.StatusBadRequest)
121 http.Error(w, "denied", http.StatusBadRequest)
126 if f.polls <= f.pending {
127 http.Error(w, "pending", http.StatusForbidden)
132 chatgptWriteJSON(w, map[string]any{
133 "authorization_code": "auth-code",
134 "code_challenge": "challenge",
135 "code_verifier": "verifier",
139 func (f *ChatGPTFake) oauthToken(w http.ResponseWriter, r *http.Request) {
141 defer f.mutex.Unlock()
143 if r.Header.Get("Content-Type") == "application/x-www-form-urlencoded" {
146 http.Error(w, err.Error(), http.StatusBadRequest)
151 f.exchange = r.PostForm
152 chatgptWriteJSON(w, map[string]any{
153 "access_token": f.newToken(time.Hour),
154 "refresh_token": "refresh-1",
155 "id_token": f.newToken(time.Hour),
161 var body map[string]string
163 err := json.NewDecoder(r.Body).Decode(&body)
164 if err != nil || body["grant_type"] != "refresh_token" || body["client_id"] != chatgptClientID {
165 http.Error(w, "bad refresh", http.StatusBadRequest)
171 f.refreshed = body["refresh_token"]
173 http.Error(w, `{"error": "invalid_grant", "token": "`+body["refresh_token"]+`"}`, http.StatusUnauthorized)
178 answer := map[string]any{
179 "access_token": f.newToken(time.Hour),
180 "id_token": f.newToken(time.Hour),
183 if f.newRefresh != "" {
184 answer["refresh_token"] = f.newRefresh
187 chatgptWriteJSON(w, answer)
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))