]> git.giacomolli.uk - onechat/blob - chatgpt.go
Order functions by their first use
[onechat] / chatgpt.go
1 package main
2
3 import (
4 "bytes"
5 "cmp"
6 "context"
7 "encoding/base64"
8 "encoding/json"
9 "errors"
10 "fmt"
11 "io"
12 "net/http"
13 "net/url"
14 "os"
15 "path/filepath"
16 "strconv"
17 "strings"
18 "sync"
19 "time"
20 )
21
22 const (
23 // chatgptIssuer is the OpenAI login service.
24 chatgptIssuer = "https://auth.openai.com"
25
26 // chatgptClientID is the OAuth client ID of the Codex CLI. The ChatGPT
27 // backend takes the tokens of this client only.
28 chatgptClientID = "app_EMoamEEZ73f0CkXaXp7hrann"
29
30 // chatgptAuthClaim is the JWT claim that holds the ChatGPT account ID.
31 chatgptAuthClaim = "https://api.openai.com/auth"
32
33 // chatgptRefreshMargin is how long before its expiry an access token is
34 // refreshed.
35 chatgptRefreshMargin = 60 * time.Second
36
37 // chatgptLoginTimeout is how long a device code login waits for the
38 // user.
39 chatgptLoginTimeout = 15 * time.Minute
40
41 // chatgptTokenFileName is the name of the token file in the data
42 // directory.
43 chatgptTokenFileName = "auth.json"
44
45 // chatgptDefaultPollInterval is the poll interval of a device code
46 // login when the login service gives none.
47 chatgptDefaultPollInterval = 5 * time.Second
48 )
49
50 // errChatGPTLoginNeeded tells that no valid token is available, so the user
51 // must run "onechat login".
52 var errChatGPTLoginNeeded = errors.New(`login needed: run "onechat login"`)
53
54 // ChatGPTAuth authorizes model calls to the ChatGPT backend with the tokens in
55 // the token file. The tokens belong to OneChat only. The Codex CLI rotates the
56 // refresh token on each refresh, so two programs with one token file log each
57 // other out.
58 //
59 // Before each call it reads the expiry from the access token. Within
60 // chatgptRefreshMargin of the expiry it gets new tokens with the refresh token
61 // and replaces the file atomically. A mutex lets one refresh run at a time, and
62 // a call that waits for it uses the new tokens.
63 type ChatGPTAuth struct {
64 mutex sync.Mutex
65 path string
66 issuer string
67 http *http.Client
68 }
69
70 // ChatGPTDeviceCode is the answer of the user code endpoint. The interval is a
71 // number or a string of seconds.
72 type ChatGPTDeviceCode struct {
73 DeviceAuthID string `json:"device_auth_id"`
74 UserCode string `json:"user_code"`
75 UserCodeAlt string `json:"usercode"`
76 Interval json.RawMessage `json:"interval"`
77 }
78
79 // ChatGPTTokenFile is the content of the token file.
80 type ChatGPTTokenFile struct {
81 AccessToken string `json:"access_token"`
82 RefreshToken string `json:"refresh_token"`
83 IDToken string `json:"id_token"`
84 AccountID string `json:"account_id"`
85 }
86
87 // ChatGPTTokenResponse is the answer of the token endpoint.
88 type ChatGPTTokenResponse struct {
89 AccessToken string `json:"access_token"`
90 RefreshToken string `json:"refresh_token"`
91 IDToken string `json:"id_token"`
92 }
93
94 // ChatGPTDeviceGrant is the answer of the device token endpoint after the user
95 // approves the code.
96 type ChatGPTDeviceGrant struct {
97 AuthorizationCode string `json:"authorization_code"`
98 CodeVerifier string `json:"code_verifier"`
99 }
100
101 // newChatGPTAuth returns the authorizer for the token file at path, with the
102 // login service at issuer.
103 func newChatGPTAuth(path, issuer string) *ChatGPTAuth {
104 return &ChatGPTAuth{
105 path: path,
106 issuer: issuer,
107 http: &http.Client{},
108 }
109 }
110
111 // Authorize sets the access token and the account ID, after a refresh when the
112 // token expires within chatgptRefreshMargin.
113 func (a *ChatGPTAuth) Authorize(ctx context.Context, header http.Header) error {
114 a.mutex.Lock()
115 defer a.mutex.Unlock()
116
117 tokens, err := a.read()
118 if err != nil {
119 return err
120 }
121
122 expiry, found := chatgptTokenExpiry(tokens.AccessToken)
123 if !found || !time.Now().Before(expiry.Add(-chatgptRefreshMargin)) {
124 tokens, err = a.refresh(ctx, tokens)
125 if err != nil {
126 return err
127 }
128 }
129
130 header.Set("Authorization", "Bearer "+tokens.AccessToken)
131 header.Set("ChatGPT-Account-Id", tokens.AccountID)
132
133 return nil
134 }
135
136 // read reads the token file.
137 func (a *ChatGPTAuth) read() (ChatGPTTokenFile, error) {
138 data, err := os.ReadFile(a.path)
139 if errors.Is(err, os.ErrNotExist) {
140 return ChatGPTTokenFile{}, errChatGPTLoginNeeded
141 }
142
143 if err != nil {
144 return ChatGPTTokenFile{}, fmt.Errorf("read token file: %w", err)
145 }
146
147 var tokens ChatGPTTokenFile
148
149 err = json.Unmarshal(data, &tokens)
150 if err == nil && (tokens.AccessToken == "" || tokens.RefreshToken == "" || tokens.AccountID == "") {
151 err = errors.New("a token or the account ID is missing")
152 }
153
154 if err != nil {
155 return ChatGPTTokenFile{}, fmt.Errorf("token file: %w: %w", err, errChatGPTLoginNeeded)
156 }
157
158 return tokens, nil
159 }
160
161 // refresh gets new tokens with the refresh token and replaces the token file.
162 // It keeps the old refresh token and ID token when the answer has none.
163 func (a *ChatGPTAuth) refresh(ctx context.Context, tokens ChatGPTTokenFile) (ChatGPTTokenFile, error) {
164 var response ChatGPTTokenResponse
165
166 err := a.postJSON(ctx, "/oauth/token", map[string]string{
167 "client_id": chatgptClientID,
168 "grant_type": "refresh_token",
169 "refresh_token": tokens.RefreshToken,
170 "scope": "openid profile email",
171 }, &response)
172 if err == nil && response.AccessToken == "" {
173 err = errors.New("refresh response has no access token")
174 }
175
176 if err != nil {
177 return ChatGPTTokenFile{}, fmt.Errorf("refresh tokens: %w: %w", err, errChatGPTLoginNeeded)
178 }
179
180 tokens.AccessToken = response.AccessToken
181 tokens.RefreshToken = cmp.Or(response.RefreshToken, tokens.RefreshToken)
182 tokens.IDToken = cmp.Or(response.IDToken, tokens.IDToken)
183 tokens.AccountID = cmp.Or(chatgptAccountID(tokens.AccessToken), chatgptAccountID(tokens.IDToken), tokens.AccountID)
184
185 err = a.write(tokens)
186 if err != nil {
187 return ChatGPTTokenFile{}, err
188 }
189
190 return tokens, nil
191 }
192
193 // postJSON posts body as JSON to the path of the login service and decodes the
194 // answer into result.
195 func (a *ChatGPTAuth) postJSON(ctx context.Context, path string, body, result any) error {
196 data, err := json.Marshal(body)
197 if err != nil {
198 return fmt.Errorf("encode request: %w", err)
199 }
200
201 _, err = a.post(ctx, path, "application/json", data, result)
202
203 return err
204 }
205
206 // write replaces the token file atomically. The file has mode 0600.
207 func (a *ChatGPTAuth) write(tokens ChatGPTTokenFile) error {
208 data, err := json.Marshal(tokens)
209 if err != nil {
210 return fmt.Errorf("encode tokens: %w", err)
211 }
212
213 err = writeFileAtomic(a.path, append(data, '\n'))
214 if err != nil {
215 return fmt.Errorf("write token file: %w", err)
216 }
217
218 return nil
219 }
220
221 // post posts body to the path of the login service and decodes a 200 answer
222 // into result. It returns the HTTP status, or 0 when no answer came. The error
223 // holds the status, but not the body, which can hold a token.
224 func (a *ChatGPTAuth) post(ctx context.Context, path, contentType string, body []byte, result any) (status int, err error) {
225 request, err := http.NewRequestWithContext(ctx, http.MethodPost, a.issuer+path, bytes.NewReader(body))
226 if err != nil {
227 return 0, fmt.Errorf("create request: %w", err)
228 }
229
230 request.Header.Set("Content-Type", contentType)
231
232 response, err := a.http.Do(request)
233 if err != nil {
234 return 0, fmt.Errorf("send request: %w", err)
235 }
236
237 defer func() {
238 err = errors.Join(err, response.Body.Close())
239 }()
240
241 if response.StatusCode != http.StatusOK {
242 return response.StatusCode, fmt.Errorf("HTTP %d", response.StatusCode)
243 }
244
245 err = json.NewDecoder(response.Body).Decode(result)
246 if err != nil {
247 return response.StatusCode, fmt.Errorf("decode answer: %w", err)
248 }
249
250 return response.StatusCode, nil
251 }
252
253 // Login runs the device code login. It writes the link and the code for the
254 // user to out, waits until the user approves the code, and writes the tokens to
255 // the token file.
256 func (a *ChatGPTAuth) Login(ctx context.Context, out io.Writer) error {
257 a.mutex.Lock()
258 defer a.mutex.Unlock()
259
260 var code ChatGPTDeviceCode
261
262 err := a.postJSON(ctx, "/api/accounts/deviceauth/usercode", map[string]string{
263 "client_id": chatgptClientID,
264 }, &code)
265 if err != nil {
266 return fmt.Errorf("request device code (device code login must be allowed in the ChatGPT security settings): %w", err)
267 }
268
269 userCode := cmp.Or(code.UserCode, code.UserCodeAlt)
270 if code.DeviceAuthID == "" || userCode == "" {
271 return errors.New("device code response has no device ID or user code")
272 }
273
274 _, err = fmt.Fprintf(out, "Open %s/codex/device on any device and enter this code:\n\n %s\n\nWaiting for the approval...\n", a.issuer, userCode)
275 if err != nil {
276 return fmt.Errorf("write device code: %w", err)
277 }
278
279 grant, err := a.poll(ctx, code.DeviceAuthID, userCode, chatgptPollInterval(code.Interval))
280 if err != nil {
281 return err
282 }
283
284 tokens, err := a.exchange(ctx, grant)
285 if err != nil {
286 return err
287 }
288
289 err = a.write(tokens)
290 if err != nil {
291 return err
292 }
293
294 _, err = fmt.Fprintln(out, "Logged in.")
295 if err != nil {
296 return fmt.Errorf("write login result: %w", err)
297 }
298
299 return nil
300 }
301
302 // poll asks for the grant of the device code until the user approves it or the
303 // login times out.
304 func (a *ChatGPTAuth) poll(ctx context.Context, deviceID, userCode string, interval time.Duration) (ChatGPTDeviceGrant, error) {
305 ctx, cancel := context.WithTimeout(ctx, chatgptLoginTimeout)
306 defer cancel()
307
308 body, err := json.Marshal(map[string]string{
309 "device_auth_id": deviceID,
310 "user_code": userCode,
311 })
312 if err != nil {
313 return ChatGPTDeviceGrant{}, fmt.Errorf("encode poll request: %w", err)
314 }
315
316 for {
317 var grant ChatGPTDeviceGrant
318
319 status, err := a.post(ctx, "/api/accounts/deviceauth/token", "application/json", body, &grant)
320 if err == nil && (grant.AuthorizationCode == "" || grant.CodeVerifier == "") {
321 err = errors.New("device grant has no authorization code or code verifier")
322 }
323
324 if err == nil {
325 return grant, nil
326 }
327
328 if status != http.StatusForbidden && status != http.StatusNotFound {
329 return ChatGPTDeviceGrant{}, fmt.Errorf("poll device code: %w", err)
330 }
331
332 timer := time.NewTimer(interval)
333 select {
334 case <-ctx.Done():
335 timer.Stop()
336
337 return ChatGPTDeviceGrant{}, fmt.Errorf("wait for approval: %w", ctx.Err())
338 case <-timer.C:
339 }
340 }
341 }
342
343 // exchange trades the grant of the device code for tokens.
344 func (a *ChatGPTAuth) exchange(ctx context.Context, grant ChatGPTDeviceGrant) (ChatGPTTokenFile, error) {
345 form := url.Values{
346 "grant_type": {"authorization_code"},
347 "code": {grant.AuthorizationCode},
348 "redirect_uri": {a.issuer + "/deviceauth/callback"},
349 "client_id": {chatgptClientID},
350 "code_verifier": {grant.CodeVerifier},
351 }
352
353 var response ChatGPTTokenResponse
354
355 _, err := a.post(ctx, "/oauth/token", "application/x-www-form-urlencoded", []byte(form.Encode()), &response)
356 if err != nil {
357 return ChatGPTTokenFile{}, fmt.Errorf("exchange code for tokens: %w", err)
358 }
359
360 if response.AccessToken == "" || response.RefreshToken == "" || response.IDToken == "" {
361 return ChatGPTTokenFile{}, errors.New("token response has no access, refresh, or ID token")
362 }
363
364 tokens := ChatGPTTokenFile{
365 AccessToken: response.AccessToken,
366 RefreshToken: response.RefreshToken,
367 IDToken: response.IDToken,
368 }
369
370 tokens.AccountID = cmp.Or(chatgptAccountID(tokens.AccessToken), chatgptAccountID(tokens.IDToken))
371 if tokens.AccountID == "" {
372 return ChatGPTTokenFile{}, errors.New("tokens have no ChatGPT account ID")
373 }
374
375 return tokens, nil
376 }
377
378 // chatgptTokenExpiry returns the expiry of a JWT from its exp claim.
379 func chatgptTokenExpiry(token string) (time.Time, bool) {
380 var claims struct {
381 Exp *float64 `json:"exp"`
382 }
383
384 if !chatgptDecodeClaims(token, &claims) || claims.Exp == nil {
385 return time.Time{}, false
386 }
387
388 return time.Unix(int64(*claims.Exp), 0), true
389 }
390
391 // chatgptAccountID returns the ChatGPT account ID of a JWT, or "" when it has
392 // none.
393 func chatgptAccountID(token string) string {
394 var claims map[string]json.RawMessage
395
396 if !chatgptDecodeClaims(token, &claims) {
397 return ""
398 }
399
400 var auth struct {
401 AccountID string `json:"chatgpt_account_id"`
402 }
403
404 err := json.Unmarshal(claims[chatgptAuthClaim], &auth)
405 if err != nil {
406 return ""
407 }
408
409 return auth.AccountID
410 }
411
412 // chatgptPollInterval returns the poll interval of a device code, given in
413 // seconds as a number or a string.
414 func chatgptPollInterval(raw json.RawMessage) time.Duration {
415 seconds, err := strconv.ParseFloat(strings.Trim(string(raw), `"`), 64)
416 if err != nil || seconds < 0 {
417 return chatgptDefaultPollInterval
418 }
419
420 return time.Duration(seconds * float64(time.Second))
421 }
422
423 // chatgptDecodeClaims decodes the payload of a JWT into claims, without a check
424 // of the signature. The token comes from the login service over HTTPS, and the
425 // client reads only the expiry and the account ID from it.
426 func chatgptDecodeClaims(token string, claims any) bool {
427 parts := strings.Split(token, ".")
428 if len(parts) != 3 {
429 return false
430 }
431
432 payload, err := base64.RawURLEncoding.DecodeString(strings.TrimRight(parts[1], "="))
433 if err != nil {
434 return false
435 }
436
437 return json.Unmarshal(payload, claims) == nil
438 }
439
440 // chatgptLogin runs "onechat login": the device code login into the token file
441 // of the data directory. It holds the lock of the token file, so it does not
442 // run while the daemon runs.
443 func chatgptLogin(ctx context.Context, out io.Writer) (err error) {
444 dir, err := dataDir()
445 if err != nil {
446 return err
447 }
448
449 tokens, err := lockTokens(dir)
450 if err != nil {
451 return err
452 }
453
454 defer func() {
455 err = errors.Join(err, tokens.Close())
456 }()
457
458 return newChatGPTAuth(filepath.Join(dir, chatgptTokenFileName), chatgptIssuer).Login(ctx, out)
459 }