-
Notifications
You must be signed in to change notification settings - Fork 132
/
Copy pathcopilot.go
182 lines (154 loc) · 5.2 KB
/
copilot.go
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
package main
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"runtime"
"strings"
"time"
)
const (
copilotChatAuthURL = "https://api.github.com/copilot_internal/v2/token"
copilotEditorVersion = "vscode/1.95.3"
copilotUserAgent = "curl/7.81.0" // Necessay to bypass the user-agent check
)
// Authentication response from GitHub Copilot's token endpoint.
type CopilotAccessToken struct {
Token string `json:"token"`
ExpiresAt int64 `json:"expires_at"`
Endpoints struct {
API string `json:"api"` // Can change in Github Enterprise instances
OriginTracker string `json:"origin-tracker"`
Proxy string `json:"proxy"`
Telemetry string `json:"telemetry"`
} `json:"endpoints"`
ErrorDetails *struct {
URL string `json:"url,omitempty"`
Message string `json:"message,omitempty"`
Title string `json:"title,omitempty"`
NotificationID string `json:"notification_id,omitempty"`
} `json:"error_details,omitempty"`
}
type copilotHTTPClient struct {
client *http.Client
AccessToken *CopilotAccessToken
}
func newCopilotHTTPClient() *copilotHTTPClient {
return &copilotHTTPClient{
client: &http.Client{},
}
}
func (c *copilotHTTPClient) Do(req *http.Request) (*http.Response, error) {
req.Header.Set("Accept", "application/json")
req.Header.Set("Editor-Version", copilotEditorVersion)
req.Header.Set("User-Agent", copilotUserAgent)
isTokenExpired := c.AccessToken != nil && c.AccessToken.ExpiresAt < time.Now().Unix()
if c.AccessToken == nil || isTokenExpired {
accessToken, err := getCopilotAccessToken(c.client)
if err != nil {
return nil, fmt.Errorf("failed to get access token: %w", err)
}
c.AccessToken = &accessToken
}
if c.AccessToken != nil {
req.Header.Set("Authorization", "Bearer "+c.AccessToken.Token)
}
httpResp, err := c.client.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to make request: %w", err)
}
return httpResp, nil
}
func getCopilotRefreshToken() (string, error) {
configPath := filepath.Join(os.Getenv("HOME"), ".config/github-copilot")
if runtime.GOOS == "windows" {
configPath = filepath.Join(os.Getenv("LOCALAPPDATA"), "github-copilot")
}
// Check both possible config file locations
configFiles := []string{
filepath.Join(configPath, "hosts.json"),
filepath.Join(configPath, "apps.json"),
}
// Try to get token from config files
for _, path := range configFiles {
token, err := extractCopilotTokenFromFile(path)
if err == nil && token != "" {
return token, nil
}
}
return "", fmt.Errorf("no token found in %s", strings.Join(configFiles, ", "))
}
func extractCopilotTokenFromFile(path string) (string, error) {
bytes, err := os.ReadFile(path)
if err != nil {
return "", fmt.Errorf("failed to read Copilot configuration file at %s: %w", path, err)
}
var config map[string]json.RawMessage
if err := json.Unmarshal(bytes, &config); err != nil {
return "", fmt.Errorf("failed to parse Copilot configuration file at %s: %w", path, err)
}
for key, value := range config {
if key == "github.com" || strings.HasPrefix(key, "github.com:") {
var tokenData map[string]string
if err := json.Unmarshal(value, &tokenData); err != nil {
continue
}
if token, exists := tokenData["oauth_token"]; exists {
return token, nil
}
}
}
return "", fmt.Errorf("no token found in %s", path)
}
func getCopilotAccessToken(client *http.Client) (CopilotAccessToken, error) {
cache, err := NewExpiringCache[CopilotAccessToken]()
if err == nil {
var token CopilotAccessToken
err = cache.Read("copilot", func(r io.Reader) error {
return json.NewDecoder(r).Decode(&token)
})
if err == nil && token.ExpiresAt > time.Now().Unix() {
return token, nil
}
}
refreshToken, err := getCopilotRefreshToken()
if err != nil {
return CopilotAccessToken{}, fmt.Errorf("failed to get refresh token: %w", err)
}
tokenReq, err := http.NewRequestWithContext(context.TODO(), http.MethodGet, copilotChatAuthURL, nil)
if err != nil {
return CopilotAccessToken{}, fmt.Errorf("failed to create token request: %w", err)
}
tokenReq.Header.Set("Authorization", "token "+refreshToken)
tokenReq.Header.Set("Accept", "application/json")
tokenReq.Header.Set("Editor-Version", copilotEditorVersion)
tokenReq.Header.Set("User-Agent", copilotUserAgent)
tokenResp, err := client.Do(tokenReq)
if err != nil {
return CopilotAccessToken{}, fmt.Errorf("failed to get access token: %w", err)
}
defer func() {
if closeErr := tokenResp.Body.Close(); closeErr != nil && err == nil {
err = fmt.Errorf("error closing response body: %w", closeErr)
}
}()
var tokenResponse CopilotAccessToken
if err := json.NewDecoder(tokenResp.Body).Decode(&tokenResponse); err != nil {
return CopilotAccessToken{}, fmt.Errorf("failed to decode token response: %w", err)
}
if tokenResponse.ErrorDetails != nil {
return CopilotAccessToken{}, fmt.Errorf("token error: %s", tokenResponse.ErrorDetails.Message)
}
if cache != nil {
if err := cache.Write("copilot", tokenResponse.ExpiresAt, func(w io.Writer) error {
return json.NewEncoder(w).Encode(tokenResponse)
}); err != nil {
return CopilotAccessToken{}, fmt.Errorf("failed to cache token: %w", err)
}
}
return tokenResponse, nil
}