-
Notifications
You must be signed in to change notification settings - Fork 346
Expand file tree
/
Copy pathauth.go
More file actions
97 lines (82 loc) · 2.25 KB
/
auth.go
File metadata and controls
97 lines (82 loc) · 2.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package codexauth
import (
"encoding/base64"
"encoding/json"
"errors"
"os"
"path/filepath"
"strings"
)
const authFileName = "auth.json"
// Auth represents the persisted local Codex CLI authentication state.
type Auth struct {
OpenAIAPIKey string `json:"OPENAI_API_KEY"`
AuthMode string `json:"auth_mode"`
Tokens struct {
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
IDToken string `json:"id_token"`
AccountID string `json:"account_id"`
} `json:"tokens"`
}
// Claims contains the subset of JWT claims used by docker-agent.
type Claims struct {
ChatGPTAccountID string `json:"chatgpt_account_id"`
}
// DefaultPath returns the default location of the local Codex auth file.
func DefaultPath() string {
home, err := os.UserHomeDir()
if err != nil {
return ""
}
return filepath.Join(home, ".codex", authFileName)
}
// Load reads the local Codex auth file from the default location.
func Load() (*Auth, error) {
path := DefaultPath()
if path == "" {
return nil, errors.New("unable to resolve Codex auth path")
}
data, err := os.ReadFile(path)
if err != nil {
return nil, err
}
var auth Auth
if err := json.Unmarshal(data, &auth); err != nil {
return nil, err
}
return &auth, nil
}
// HasChatGPTAuth reports whether the auth file contains a ChatGPT-backed login.
func (a *Auth) HasChatGPTAuth() bool {
return strings.EqualFold(a.AuthMode, "chatgpt") && a.Tokens.AccessToken != ""
}
// AccountID returns the ChatGPT account ID from the auth file or token claims.
func (a *Auth) AccountID() string {
if a.Tokens.AccountID != "" {
return a.Tokens.AccountID
}
for _, token := range []string{a.Tokens.IDToken, a.Tokens.AccessToken} {
if claims, err := parseClaims(token); err == nil && claims.ChatGPTAccountID != "" {
return claims.ChatGPTAccountID
}
}
return ""
}
func parseClaims(jwt string) (*Claims, error) {
parts := strings.Split(jwt, ".")
if len(parts) < 2 {
return nil, errors.New("invalid JWT format")
}
payload, err := base64.RawURLEncoding.DecodeString(parts[1])
if err != nil {
return nil, err
}
var raw struct {
Auth Claims `json:"https://api.openai.com/auth"`
}
if err := json.Unmarshal(payload, &raw); err != nil {
return nil, err
}
return &raw.Auth, nil
}