23 // chatgptIssuer is the OpenAI login service.
24 chatgptIssuer = "https://auth.openai.com"
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"
30 // chatgptAuthClaim is the JWT claim that holds the ChatGPT account ID.
31 chatgptAuthClaim = "https://api.openai.com/auth"
33 // chatgptRefreshMargin is how long before its expiry an access token is
35 chatgptRefreshMargin = 60 * time.Second
37 // chatgptLoginTimeout is how long a device code login waits for the
39 chatgptLoginTimeout = 15 * time.Minute
41 // chatgptTokenFileName is the name of the token file in the data
43 chatgptTokenFileName = "auth.json"
45 // chatgptDefaultPollInterval is the poll interval of a device code
46 // login when the login service gives none.
47 chatgptDefaultPollInterval = 5 * time.Second
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"`)
54 // chatgptLogin runs "onechat login": the device code login into the token file
55 // of the data directory. It holds the lock of the token file, so it does not
56 // run while the daemon runs.
57 func chatgptLogin(ctx context.Context, out io.Writer) (err error) {
63 tokens, err := lockTokens(dir)
69 err = errors.Join(err, tokens.Close())
72 return newChatGPTAuth(filepath.Join(dir, chatgptTokenFileName), chatgptIssuer).Login(ctx, out)
75 // newChatGPTAuth returns the authorizer for the token file at path, with the
76 // login service at issuer.
77 func newChatGPTAuth(path, issuer string) *ChatGPTAuth {
85 // ChatGPTAuth authorizes model calls to the ChatGPT backend with the tokens in
86 // the token file. The tokens belong to OneChat only. The Codex CLI rotates the
87 // refresh token on each refresh, so two programs with one token file log each
90 // Before each call it reads the expiry from the access token. Within
91 // chatgptRefreshMargin of the expiry it gets new tokens with the refresh token
92 // and replaces the file atomically. A mutex lets one refresh run at a time, and
93 // a call that waits for it uses the new tokens.
94 type ChatGPTAuth struct {
101 // Authorize sets the access token and the account ID, after a refresh when the
102 // token expires within chatgptRefreshMargin.
103 func (a *ChatGPTAuth) Authorize(ctx context.Context, header http.Header) error {
105 defer a.mutex.Unlock()
107 tokens, err := a.read()
112 expiry, found := chatgptTokenExpiry(tokens.AccessToken)
113 if !found || !time.Now().Before(expiry.Add(-chatgptRefreshMargin)) {
114 tokens, err = a.refresh(ctx, tokens)
120 header.Set("Authorization", "Bearer "+tokens.AccessToken)
121 header.Set("ChatGPT-Account-Id", tokens.AccountID)
126 // Login runs the device code login. It writes the link and the code for the
127 // user to out, waits until the user approves the code, and writes the tokens
128 // to the token file.
129 func (a *ChatGPTAuth) Login(ctx context.Context, out io.Writer) error {
131 defer a.mutex.Unlock()
133 var code ChatGPTDeviceCode
134 err := a.postJSON(ctx, "/api/accounts/deviceauth/usercode", map[string]string{
135 "client_id": chatgptClientID,
138 return fmt.Errorf("request device code (device code login must be allowed in the ChatGPT security settings): %w", err)
141 userCode := cmp.Or(code.UserCode, code.UserCodeAlt)
142 if code.DeviceAuthID == "" || userCode == "" {
143 return errors.New("device code response has no device ID or user code")
146 _, 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)
151 grant, err := a.poll(ctx, code.DeviceAuthID, userCode, chatgptPollInterval(code.Interval))
156 tokens, err := a.exchange(ctx, grant)
161 err = a.write(tokens)
166 _, err = fmt.Fprintln(out, "Logged in.")
171 // read reads the token file.
172 func (a *ChatGPTAuth) read() (ChatGPTTokenFile, error) {
173 data, err := os.ReadFile(a.path)
174 if errors.Is(err, os.ErrNotExist) {
175 return ChatGPTTokenFile{}, errChatGPTLoginNeeded
179 return ChatGPTTokenFile{}, fmt.Errorf("read token file: %w", err)
182 var tokens ChatGPTTokenFile
183 err = json.Unmarshal(data, &tokens)
184 if err == nil && (tokens.AccessToken == "" || tokens.RefreshToken == "" || tokens.AccountID == "") {
185 err = errors.New("a token or the account ID is missing")
189 return ChatGPTTokenFile{}, fmt.Errorf("token file: %w: %w", err, errChatGPTLoginNeeded)
195 // refresh gets new tokens with the refresh token and replaces the token file.
196 // It keeps the old refresh token and ID token when the answer has none.
197 func (a *ChatGPTAuth) refresh(ctx context.Context, tokens ChatGPTTokenFile) (ChatGPTTokenFile, error) {
198 var response ChatGPTTokenResponse
199 err := a.postJSON(ctx, "/oauth/token", map[string]string{
200 "client_id": chatgptClientID,
201 "grant_type": "refresh_token",
202 "refresh_token": tokens.RefreshToken,
203 "scope": "openid profile email",
205 if err == nil && response.AccessToken == "" {
206 err = errors.New("refresh response has no access token")
210 return ChatGPTTokenFile{}, fmt.Errorf("refresh tokens: %w: %w", err, errChatGPTLoginNeeded)
213 tokens.AccessToken = response.AccessToken
214 tokens.RefreshToken = cmp.Or(response.RefreshToken, tokens.RefreshToken)
215 tokens.IDToken = cmp.Or(response.IDToken, tokens.IDToken)
216 tokens.AccountID = cmp.Or(chatgptAccountID(tokens.AccessToken), chatgptAccountID(tokens.IDToken), tokens.AccountID)
218 err = a.write(tokens)
220 return ChatGPTTokenFile{}, err
226 // postJSON posts body as JSON to the path of the login service and decodes the
227 // answer into result.
228 func (a *ChatGPTAuth) postJSON(ctx context.Context, path string, body, result any) error {
229 data, err := json.Marshal(body)
231 return fmt.Errorf("encode request: %w", err)
234 _, err = a.post(ctx, path, "application/json", data, result)
239 // poll asks for the grant of the device code until the user approves it or the
241 func (a *ChatGPTAuth) poll(ctx context.Context, deviceID, userCode string, interval time.Duration) (ChatGPTDeviceGrant, error) {
242 ctx, cancel := context.WithTimeout(ctx, chatgptLoginTimeout)
245 body, err := json.Marshal(map[string]string{
246 "device_auth_id": deviceID,
247 "user_code": userCode,
250 return ChatGPTDeviceGrant{}, fmt.Errorf("encode poll request: %w", err)
254 var grant ChatGPTDeviceGrant
255 status, err := a.post(ctx, "/api/accounts/deviceauth/token", "application/json", body, &grant)
256 if err == nil && (grant.AuthorizationCode == "" || grant.CodeVerifier == "") {
257 err = errors.New("device grant has no authorization code or code verifier")
264 if status != http.StatusForbidden && status != http.StatusNotFound {
265 return ChatGPTDeviceGrant{}, fmt.Errorf("poll device code: %w", err)
268 timer := time.NewTimer(interval)
272 return ChatGPTDeviceGrant{}, fmt.Errorf("wait for approval: %w", ctx.Err())
278 // exchange trades the grant of the device code for tokens.
279 func (a *ChatGPTAuth) exchange(ctx context.Context, grant ChatGPTDeviceGrant) (ChatGPTTokenFile, error) {
281 "grant_type": {"authorization_code"},
282 "code": {grant.AuthorizationCode},
283 "redirect_uri": {a.issuer + "/deviceauth/callback"},
284 "client_id": {chatgptClientID},
285 "code_verifier": {grant.CodeVerifier},
288 var response ChatGPTTokenResponse
289 _, err := a.post(ctx, "/oauth/token", "application/x-www-form-urlencoded", []byte(form.Encode()), &response)
291 return ChatGPTTokenFile{}, fmt.Errorf("exchange code for tokens: %w", err)
294 if response.AccessToken == "" || response.RefreshToken == "" || response.IDToken == "" {
295 return ChatGPTTokenFile{}, errors.New("token response has no access, refresh, or ID token")
298 tokens := ChatGPTTokenFile{
299 AccessToken: response.AccessToken,
300 RefreshToken: response.RefreshToken,
301 IDToken: response.IDToken,
304 tokens.AccountID = cmp.Or(chatgptAccountID(tokens.AccessToken), chatgptAccountID(tokens.IDToken))
305 if tokens.AccountID == "" {
306 return ChatGPTTokenFile{}, errors.New("tokens have no ChatGPT account ID")
312 // write replaces the token file atomically. The file has mode 0600.
313 func (a *ChatGPTAuth) write(tokens ChatGPTTokenFile) error {
314 data, err := json.Marshal(tokens)
316 return fmt.Errorf("encode tokens: %w", err)
319 err = writeFileAtomic(a.path, append(data, '\n'))
321 return fmt.Errorf("write token file: %w", err)
327 // post posts body to the path of the login service and decodes a 200 answer
328 // into result. It returns the HTTP status, or 0 when no answer came. The error
329 // holds the status, but not the body, which can hold a token.
330 func (a *ChatGPTAuth) post(ctx context.Context, path, contentType string, body []byte, result any) (status int, err error) {
331 request, err := http.NewRequestWithContext(ctx, http.MethodPost, a.issuer+path, bytes.NewReader(body))
333 return 0, fmt.Errorf("create request: %w", err)
336 request.Header.Set("Content-Type", contentType)
337 response, err := a.http.Do(request)
339 return 0, fmt.Errorf("send request: %w", err)
343 err = errors.Join(err, response.Body.Close())
346 if response.StatusCode != http.StatusOK {
347 return response.StatusCode, fmt.Errorf("HTTP %d", response.StatusCode)
350 err = json.NewDecoder(response.Body).Decode(result)
352 return response.StatusCode, fmt.Errorf("decode answer: %w", err)
355 return response.StatusCode, nil
358 // ChatGPTDeviceCode is the answer of the user code endpoint. The interval is a
359 // number or a string of seconds.
360 type ChatGPTDeviceCode struct {
361 DeviceAuthID string `json:"device_auth_id"`
362 UserCode string `json:"user_code"`
363 UserCodeAlt string `json:"usercode"`
364 Interval json.RawMessage `json:"interval"`
367 // ChatGPTTokenFile is the content of the token file.
368 type ChatGPTTokenFile struct {
369 AccessToken string `json:"access_token"`
370 RefreshToken string `json:"refresh_token"`
371 IDToken string `json:"id_token"`
372 AccountID string `json:"account_id"`
375 // ChatGPTTokenResponse is the answer of the token endpoint.
376 type ChatGPTTokenResponse struct {
377 AccessToken string `json:"access_token"`
378 RefreshToken string `json:"refresh_token"`
379 IDToken string `json:"id_token"`
382 // ChatGPTDeviceGrant is the answer of the device token endpoint after the user
383 // approves the code.
384 type ChatGPTDeviceGrant struct {
385 AuthorizationCode string `json:"authorization_code"`
386 CodeVerifier string `json:"code_verifier"`
389 // chatgptTokenExpiry returns the expiry of a JWT from its exp claim.
390 func chatgptTokenExpiry(token string) (time.Time, bool) {
392 Exp *float64 `json:"exp"`
395 if !chatgptDecodeClaims(token, &claims) || claims.Exp == nil {
396 return time.Time{}, false
399 return time.Unix(int64(*claims.Exp), 0), true
402 // chatgptPollInterval returns the poll interval of a device code, given in
403 // seconds as a number or a string.
404 func chatgptPollInterval(raw json.RawMessage) time.Duration {
405 seconds, err := strconv.ParseFloat(strings.Trim(string(raw), `"`), 64)
406 if err != nil || seconds < 0 {
407 return chatgptDefaultPollInterval
410 return time.Duration(seconds * float64(time.Second))
413 // chatgptAccountID returns the ChatGPT account ID of a JWT, or "" when it has
415 func chatgptAccountID(token string) string {
416 var claims map[string]json.RawMessage
417 if !chatgptDecodeClaims(token, &claims) {
422 AccountID string `json:"chatgpt_account_id"`
425 err := json.Unmarshal(claims[chatgptAuthClaim], &auth)
430 return auth.AccountID
433 // chatgptDecodeClaims decodes the payload of a JWT into claims, without a check
434 // of the signature. The token comes from the login service over HTTPS, and the
435 // client reads only the expiry and the account ID from it.
436 func chatgptDecodeClaims(token string, claims any) bool {
437 parts := strings.Split(token, ".")
442 payload, err := base64.RawURLEncoding.DecodeString(strings.TrimRight(parts[1], "="))
447 return json.Unmarshal(payload, claims) == nil