23 // authIssuer is the OpenAI login service.
24 authIssuer = "https://auth.openai.com"
26 // codexClientID is the OAuth client ID of the Codex CLI. The ChatGPT
27 // backend takes the tokens of this client only.
28 codexClientID = "app_EMoamEEZ73f0CkXaXp7hrann"
30 // authClaim is the JWT claim that holds the ChatGPT account ID.
31 authClaim = "https://api.openai.com/auth"
33 // refreshMargin is how long before its expiry an access token is
35 refreshMargin = 60 * time.Second
37 // loginTimeout is how long a device code login waits for the user.
38 loginTimeout = 15 * time.Minute
40 // tokenFileName is the name of the token file in the data directory.
41 tokenFileName = "auth.json"
43 // defaultPollInterval is the poll interval of a device code login when
44 // the login service gives none.
45 defaultPollInterval = 5 * time.Second
48 // errLoginNeeded tells that no valid token is available, so the user must run
50 var errLoginNeeded = errors.New(`login needed: run "onechat login"`)
52 // chatgptAuth authorizes model calls to the ChatGPT backend with the tokens in
53 // the token file. The tokens belong to OneChat only. The Codex CLI rotates the
54 // refresh token on each refresh, so two programs with one token file log each
57 // Before each call it reads the expiry from the access token. Within
58 // refreshMargin of the expiry it gets new tokens with the refresh token and
59 // replaces the file atomically. A mutex lets one refresh run at a time, and a
60 // call that waits for it uses the new tokens.
61 type chatgptAuth struct {
68 // tokenFile is the content of the token file.
69 type tokenFile struct {
70 AccessToken string `json:"access_token"`
71 RefreshToken string `json:"refresh_token"`
72 IDToken string `json:"id_token"`
73 AccountID string `json:"account_id"`
76 // tokenResponse is the answer of the token endpoint.
77 type tokenResponse struct {
78 AccessToken string `json:"access_token"`
79 RefreshToken string `json:"refresh_token"`
80 IDToken string `json:"id_token"`
83 // deviceCode is the answer of the user code endpoint. The interval is a number
84 // or a string of seconds.
85 type deviceCode struct {
86 DeviceAuthID string `json:"device_auth_id"`
87 UserCode string `json:"user_code"`
88 UserCodeAlt string `json:"usercode"`
89 Interval json.RawMessage `json:"interval"`
92 // deviceGrant is the answer of the device token endpoint after the user
94 type deviceGrant struct {
95 AuthorizationCode string `json:"authorization_code"`
96 CodeVerifier string `json:"code_verifier"`
99 // login runs "onechat login": the device code login into the token file of the
100 // data directory. It holds the lock of the token file, so it does not run while
102 func login(ctx context.Context, out io.Writer) (err error) {
103 dir, err := dataDir()
108 tokens, err := lockTokens(dir)
114 err = errors.Join(err, tokens.Close())
117 return newChatGPTAuth(filepath.Join(dir, tokenFileName), authIssuer).Login(ctx, out)
120 // newChatGPTAuth returns the authorizer for the token file at path, with the
121 // login service at issuer.
122 func newChatGPTAuth(path, issuer string) *chatgptAuth {
126 http: &http.Client{},
130 // Login runs the device code login. It writes the link and the code for the
131 // user to out, waits until the user approves the code, and writes the tokens
132 // to the token file.
133 func (a *chatgptAuth) Login(ctx context.Context, out io.Writer) error {
135 defer a.mutex.Unlock()
138 err := a.postJSON(ctx, "/api/accounts/deviceauth/usercode", map[string]string{
139 "client_id": codexClientID,
142 return fmt.Errorf("request device code (device code login must be allowed in the ChatGPT security settings): %w", err)
145 userCode := cmp.Or(code.UserCode, code.UserCodeAlt)
146 if code.DeviceAuthID == "" || userCode == "" {
147 return errors.New("device code response has no device ID or user code")
150 _, 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)
155 grant, err := a.poll(ctx, code.DeviceAuthID, userCode, pollInterval(code.Interval))
160 tokens, err := a.exchange(ctx, grant)
165 err = a.write(tokens)
170 _, err = fmt.Fprintln(out, "Logged in.")
175 // postJSON posts body as JSON to the path of the login service and decodes the
176 // answer into result.
177 func (a *chatgptAuth) postJSON(ctx context.Context, path string, body, result any) error {
178 data, err := json.Marshal(body)
180 return fmt.Errorf("encode request: %w", err)
183 _, err = a.post(ctx, path, "application/json", data, result)
188 // post posts body to the path of the login service and decodes a 200 answer
189 // into result. It returns the HTTP status, or 0 when no answer came. The error
190 // holds the status, but not the body, which can hold a token.
191 func (a *chatgptAuth) post(ctx context.Context, path, contentType string, body []byte, result any) (status int, err error) {
192 request, err := http.NewRequestWithContext(ctx, http.MethodPost, a.issuer+path, bytes.NewReader(body))
194 return 0, fmt.Errorf("create request: %w", err)
197 request.Header.Set("Content-Type", contentType)
198 response, err := a.http.Do(request)
200 return 0, fmt.Errorf("send request: %w", err)
204 err = errors.Join(err, response.Body.Close())
207 if response.StatusCode != http.StatusOK {
208 return response.StatusCode, fmt.Errorf("HTTP %d", response.StatusCode)
211 err = json.NewDecoder(response.Body).Decode(result)
213 return response.StatusCode, fmt.Errorf("decode answer: %w", err)
216 return response.StatusCode, nil
219 // poll asks for the grant of the device code until the user approves it or the
221 func (a *chatgptAuth) poll(ctx context.Context, deviceID, userCode string, interval time.Duration) (deviceGrant, error) {
222 ctx, cancel := context.WithTimeout(ctx, loginTimeout)
225 body, err := json.Marshal(map[string]string{
226 "device_auth_id": deviceID,
227 "user_code": userCode,
230 return deviceGrant{}, fmt.Errorf("encode poll request: %w", err)
234 var grant deviceGrant
235 status, err := a.post(ctx, "/api/accounts/deviceauth/token", "application/json", body, &grant)
236 if err == nil && (grant.AuthorizationCode == "" || grant.CodeVerifier == "") {
237 err = errors.New("device grant has no authorization code or code verifier")
244 if status != http.StatusForbidden && status != http.StatusNotFound {
245 return deviceGrant{}, fmt.Errorf("poll device code: %w", err)
248 timer := time.NewTimer(interval)
252 return deviceGrant{}, fmt.Errorf("wait for approval: %w", ctx.Err())
258 // exchange trades the grant of the device code for tokens.
259 func (a *chatgptAuth) exchange(ctx context.Context, grant deviceGrant) (tokenFile, error) {
261 "grant_type": {"authorization_code"},
262 "code": {grant.AuthorizationCode},
263 "redirect_uri": {a.issuer + "/deviceauth/callback"},
264 "client_id": {codexClientID},
265 "code_verifier": {grant.CodeVerifier},
268 var response tokenResponse
269 _, err := a.post(ctx, "/oauth/token", "application/x-www-form-urlencoded", []byte(form.Encode()), &response)
271 return tokenFile{}, fmt.Errorf("exchange code for tokens: %w", err)
274 if response.AccessToken == "" || response.RefreshToken == "" || response.IDToken == "" {
275 return tokenFile{}, errors.New("token response has no access, refresh, or ID token")
279 AccessToken: response.AccessToken,
280 RefreshToken: response.RefreshToken,
281 IDToken: response.IDToken,
284 tokens.AccountID = cmp.Or(accountID(tokens.AccessToken), accountID(tokens.IDToken))
285 if tokens.AccountID == "" {
286 return tokenFile{}, errors.New("tokens have no ChatGPT account ID")
292 // write replaces the token file atomically. The file has mode 0600.
293 func (a *chatgptAuth) write(tokens tokenFile) error {
294 data, err := json.Marshal(tokens)
296 return fmt.Errorf("encode tokens: %w", err)
299 err = writeFileAtomic(a.path, append(data, '\n'))
301 return fmt.Errorf("write token file: %w", err)
307 // Authorize sets the access token and the account ID, after a refresh when the
308 // token expires within refreshMargin.
309 func (a *chatgptAuth) Authorize(ctx context.Context, header http.Header) error {
311 defer a.mutex.Unlock()
313 tokens, err := a.read()
318 expiry, found := tokenExpiry(tokens.AccessToken)
319 if !found || !time.Now().Before(expiry.Add(-refreshMargin)) {
320 tokens, err = a.refresh(ctx, tokens)
326 header.Set("Authorization", "Bearer "+tokens.AccessToken)
327 header.Set("ChatGPT-Account-Id", tokens.AccountID)
332 // read reads the token file.
333 func (a *chatgptAuth) read() (tokenFile, error) {
334 data, err := os.ReadFile(a.path)
335 if errors.Is(err, os.ErrNotExist) {
336 return tokenFile{}, errLoginNeeded
340 return tokenFile{}, fmt.Errorf("read token file: %w", err)
344 err = json.Unmarshal(data, &tokens)
345 if err == nil && (tokens.AccessToken == "" || tokens.RefreshToken == "" || tokens.AccountID == "") {
346 err = errors.New("a token or the account ID is missing")
350 return tokenFile{}, fmt.Errorf("token file: %w: %w", err, errLoginNeeded)
356 // refresh gets new tokens with the refresh token and replaces the token file.
357 // It keeps the old refresh token and ID token when the answer has none.
358 func (a *chatgptAuth) refresh(ctx context.Context, tokens tokenFile) (tokenFile, error) {
359 var response tokenResponse
360 err := a.postJSON(ctx, "/oauth/token", map[string]string{
361 "client_id": codexClientID,
362 "grant_type": "refresh_token",
363 "refresh_token": tokens.RefreshToken,
364 "scope": "openid profile email",
366 if err == nil && response.AccessToken == "" {
367 err = errors.New("refresh response has no access token")
371 return tokenFile{}, fmt.Errorf("refresh tokens: %w: %w", err, errLoginNeeded)
374 tokens.AccessToken = response.AccessToken
375 tokens.RefreshToken = cmp.Or(response.RefreshToken, tokens.RefreshToken)
376 tokens.IDToken = cmp.Or(response.IDToken, tokens.IDToken)
377 tokens.AccountID = cmp.Or(accountID(tokens.AccessToken), accountID(tokens.IDToken), tokens.AccountID)
379 err = a.write(tokens)
381 return tokenFile{}, err
387 // pollInterval returns the poll interval of a device code, given in seconds as
388 // a number or a string.
389 func pollInterval(raw json.RawMessage) time.Duration {
390 seconds, err := strconv.ParseFloat(strings.Trim(string(raw), `"`), 64)
391 if err != nil || seconds < 0 {
392 return defaultPollInterval
395 return time.Duration(seconds * float64(time.Second))
398 // accountID returns the ChatGPT account ID of a JWT, or "" when it has none.
399 func accountID(token string) string {
400 var claims map[string]json.RawMessage
401 if !decodeClaims(token, &claims) {
406 AccountID string `json:"chatgpt_account_id"`
409 err := json.Unmarshal(claims[authClaim], &auth)
414 return auth.AccountID
417 // decodeClaims decodes the payload of a JWT into claims, without a check of
418 // the signature. The token comes from the login service over HTTPS, and the
419 // client reads only the expiry and the account ID from it.
420 func decodeClaims(token string, claims any) bool {
421 parts := strings.Split(token, ".")
426 payload, err := base64.RawURLEncoding.DecodeString(strings.TrimRight(parts[1], "="))
431 return json.Unmarshal(payload, claims) == nil
434 // tokenExpiry returns the expiry of a JWT from its exp claim.
435 func tokenExpiry(token string) (time.Time, bool) {
437 Exp *float64 `json:"exp"`
440 if !decodeClaims(token, &claims) || claims.Exp == nil {
441 return time.Time{}, false
444 return time.Unix(int64(*claims.Exp), 0), true