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 {
66 clock func() time.Time
69 // tokenFile is the content of the token file.
70 type tokenFile struct {
71 AccessToken string `json:"access_token"`
72 RefreshToken string `json:"refresh_token"`
73 IDToken string `json:"id_token"`
74 AccountID string `json:"account_id"`
77 // tokenResponse is the answer of the token endpoint.
78 type tokenResponse struct {
79 AccessToken string `json:"access_token"`
80 RefreshToken string `json:"refresh_token"`
81 IDToken string `json:"id_token"`
84 // deviceCode is the answer of the user code endpoint. The interval is a number
85 // or a string of seconds.
86 type deviceCode struct {
87 DeviceAuthID string `json:"device_auth_id"`
88 UserCode string `json:"user_code"`
89 UserCodeAlt string `json:"usercode"`
90 Interval json.RawMessage `json:"interval"`
93 // deviceGrant is the answer of the device token endpoint after the user
95 type deviceGrant struct {
96 AuthorizationCode string `json:"authorization_code"`
97 CodeVerifier string `json:"code_verifier"`
100 // login runs "onechat login": the device code login into the token file of the
102 func login(ctx context.Context, out io.Writer) error {
103 dir, err := dataDir()
108 return newChatGPTAuth(filepath.Join(dir, tokenFileName), authIssuer).Login(ctx, out)
111 // newChatGPTAuth returns the authorizer for the token file at path, with the
112 // login service at issuer.
113 func newChatGPTAuth(path, issuer string) *chatgptAuth {
117 http: &http.Client{},
122 // Login runs the device code login. It writes the link and the code for the
123 // user to out, waits until the user approves the code, and writes the tokens
124 // to the token file.
125 func (a *chatgptAuth) Login(ctx context.Context, out io.Writer) error {
127 defer a.mutex.Unlock()
130 err := a.postJSON(ctx, "/api/accounts/deviceauth/usercode", map[string]string{
131 "client_id": codexClientID,
134 return fmt.Errorf("request device code (device code login must be allowed in the ChatGPT security settings): %w", err)
137 userCode := cmp.Or(code.UserCode, code.UserCodeAlt)
138 if code.DeviceAuthID == "" || userCode == "" {
139 return errors.New("device code response has no device ID or user code")
142 _, 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)
147 grant, err := a.poll(ctx, code.DeviceAuthID, userCode, pollInterval(code.Interval))
152 tokens, err := a.exchange(ctx, grant)
157 err = a.write(tokens)
162 _, err = fmt.Fprintln(out, "Logged in.")
167 // postJSON posts body as JSON to the path of the login service and decodes the
168 // answer into result.
169 func (a *chatgptAuth) postJSON(ctx context.Context, path string, body, result any) error {
170 data, err := json.Marshal(body)
172 return fmt.Errorf("encode request: %w", err)
175 _, err = a.post(ctx, path, "application/json", data, result)
180 // post posts body to the path of the login service and decodes a 200 answer
181 // into result. It returns the HTTP status, or 0 when no answer came. The error
182 // holds the status, but not the body, which can hold a token.
183 func (a *chatgptAuth) post(ctx context.Context, path, contentType string, body []byte, result any) (status int, err error) {
184 request, err := http.NewRequestWithContext(ctx, http.MethodPost, a.issuer+path, bytes.NewReader(body))
186 return 0, fmt.Errorf("create request: %w", err)
189 request.Header.Set("Content-Type", contentType)
190 response, err := a.http.Do(request)
192 return 0, fmt.Errorf("send request: %w", err)
196 err = errors.Join(err, response.Body.Close())
199 if response.StatusCode != http.StatusOK {
200 return response.StatusCode, fmt.Errorf("HTTP %d", response.StatusCode)
203 err = json.NewDecoder(response.Body).Decode(result)
205 return response.StatusCode, fmt.Errorf("decode answer: %w", err)
208 return response.StatusCode, nil
211 // poll asks for the grant of the device code until the user approves it or the
213 func (a *chatgptAuth) poll(ctx context.Context, deviceID, userCode string, interval time.Duration) (deviceGrant, error) {
214 ctx, cancel := context.WithTimeout(ctx, loginTimeout)
217 body, err := json.Marshal(map[string]string{
218 "device_auth_id": deviceID,
219 "user_code": userCode,
222 return deviceGrant{}, fmt.Errorf("encode poll request: %w", err)
226 var grant deviceGrant
227 status, err := a.post(ctx, "/api/accounts/deviceauth/token", "application/json", body, &grant)
228 if err == nil && (grant.AuthorizationCode == "" || grant.CodeVerifier == "") {
229 err = errors.New("device grant has no authorization code or code verifier")
236 if status != http.StatusForbidden && status != http.StatusNotFound {
237 return deviceGrant{}, fmt.Errorf("poll device code: %w", err)
240 timer := time.NewTimer(interval)
244 return deviceGrant{}, fmt.Errorf("wait for approval: %w", ctx.Err())
250 // exchange trades the grant of the device code for tokens.
251 func (a *chatgptAuth) exchange(ctx context.Context, grant deviceGrant) (tokenFile, error) {
253 "grant_type": {"authorization_code"},
254 "code": {grant.AuthorizationCode},
255 "redirect_uri": {a.issuer + "/deviceauth/callback"},
256 "client_id": {codexClientID},
257 "code_verifier": {grant.CodeVerifier},
260 var response tokenResponse
261 _, err := a.post(ctx, "/oauth/token", "application/x-www-form-urlencoded", []byte(form.Encode()), &response)
263 return tokenFile{}, fmt.Errorf("exchange code for tokens: %w", err)
266 if response.AccessToken == "" || response.RefreshToken == "" || response.IDToken == "" {
267 return tokenFile{}, errors.New("token response has no access, refresh, or ID token")
271 AccessToken: response.AccessToken,
272 RefreshToken: response.RefreshToken,
273 IDToken: response.IDToken,
276 tokens.AccountID = cmp.Or(accountID(tokens.AccessToken), accountID(tokens.IDToken))
277 if tokens.AccountID == "" {
278 return tokenFile{}, errors.New("tokens have no ChatGPT account ID")
284 // write replaces the token file atomically. The file has mode 0600.
285 func (a *chatgptAuth) write(tokens tokenFile) error {
286 data, err := json.Marshal(tokens)
288 return fmt.Errorf("encode tokens: %w", err)
291 err = writeFileAtomic(a.path, append(data, '\n'))
293 return fmt.Errorf("write token file: %w", err)
299 // Authorize sets the access token and the account ID, after a refresh when the
300 // token expires within refreshMargin.
301 func (a *chatgptAuth) Authorize(ctx context.Context, header http.Header) error {
303 defer a.mutex.Unlock()
305 tokens, err := a.read()
310 expiry, found := tokenExpiry(tokens.AccessToken)
311 if !found || !a.clock().Before(expiry.Add(-refreshMargin)) {
312 tokens, err = a.refresh(ctx, tokens)
318 header.Set("Authorization", "Bearer "+tokens.AccessToken)
319 header.Set("ChatGPT-Account-Id", tokens.AccountID)
324 // read reads the token file.
325 func (a *chatgptAuth) read() (tokenFile, error) {
326 data, err := os.ReadFile(a.path)
327 if errors.Is(err, os.ErrNotExist) {
328 return tokenFile{}, errLoginNeeded
332 return tokenFile{}, fmt.Errorf("read token file: %w", err)
336 err = json.Unmarshal(data, &tokens)
337 if err == nil && (tokens.AccessToken == "" || tokens.RefreshToken == "" || tokens.AccountID == "") {
338 err = errors.New("a token or the account ID is missing")
342 return tokenFile{}, fmt.Errorf("token file: %w: %w", err, errLoginNeeded)
348 // refresh gets new tokens with the refresh token and replaces the token file.
349 // It keeps the old refresh token and ID token when the answer has none.
350 func (a *chatgptAuth) refresh(ctx context.Context, tokens tokenFile) (tokenFile, error) {
351 var response tokenResponse
352 err := a.postJSON(ctx, "/oauth/token", map[string]string{
353 "client_id": codexClientID,
354 "grant_type": "refresh_token",
355 "refresh_token": tokens.RefreshToken,
356 "scope": "openid profile email",
358 if err == nil && response.AccessToken == "" {
359 err = errors.New("refresh response has no access token")
363 return tokenFile{}, fmt.Errorf("refresh tokens: %w: %w", err, errLoginNeeded)
366 tokens.AccessToken = response.AccessToken
367 tokens.RefreshToken = cmp.Or(response.RefreshToken, tokens.RefreshToken)
368 tokens.IDToken = cmp.Or(response.IDToken, tokens.IDToken)
369 tokens.AccountID = cmp.Or(accountID(tokens.AccessToken), accountID(tokens.IDToken), tokens.AccountID)
371 err = a.write(tokens)
373 return tokenFile{}, err
379 // pollInterval returns the poll interval of a device code, given in seconds as
380 // a number or a string.
381 func pollInterval(raw json.RawMessage) time.Duration {
382 seconds, err := strconv.ParseFloat(strings.Trim(string(raw), `"`), 64)
383 if err != nil || seconds < 0 {
384 return defaultPollInterval
387 return time.Duration(seconds * float64(time.Second))
390 // accountID returns the ChatGPT account ID of a JWT, or "" when it has none.
391 func accountID(token string) string {
392 var claims map[string]json.RawMessage
393 if !decodeClaims(token, &claims) {
398 AccountID string `json:"chatgpt_account_id"`
401 err := json.Unmarshal(claims[authClaim], &auth)
406 return auth.AccountID
409 // decodeClaims decodes the payload of a JWT into claims, without a check of
410 // the signature. The token comes from the login service over HTTPS, and the
411 // client reads only the expiry and the account ID from it.
412 func decodeClaims(token string, claims any) bool {
413 parts := strings.Split(token, ".")
418 payload, err := base64.RawURLEncoding.DecodeString(strings.TrimRight(parts[1], "="))
423 return json.Unmarshal(payload, claims) == nil
426 // tokenExpiry returns the expiry of a JWT from its exp claim.
427 func tokenExpiry(token string) (time.Time, bool) {
429 Exp *float64 `json:"exp"`
432 if !decodeClaims(token, &claims) || claims.Exp == nil {
433 return time.Time{}, false
436 return time.Unix(int64(*claims.Exp), 0), true