1package auth
2
3import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "fmt"
8 "io"
9 "net/http"
10 "net/url"
11 "strings"
12 "time"
13)
14
15const githubCopilotClientID = "Iv1.b507a08c87ecfe98"
16
17// GitHubCopilotDeviceAuthorization is GitHub's OAuth 2 device-code
18// response used for Copilot subscription login.
19type GitHubCopilotDeviceAuthorization struct {
20 DeviceCode string `json:"device_code"`
21 UserCode string `json:"user_code"`
22 VerificationURI string `json:"verification_uri"`
23 ExpiresIn int `json:"expires_in"`
24 Interval int `json:"interval"`
25}
26
27// RequestGitHubCopilotDeviceAuthorization starts GitHub Copilot's
28// device-code login. The resulting GitHub access token is later traded
29// for short-lived Copilot inference tokens by the provider client.
30func RequestGitHubCopilotDeviceAuthorization(ctx context.Context) (GitHubCopilotDeviceAuthorization, error) {
31 form := url.Values{}
32 form.Set("client_id", githubCopilotClientID)
33 form.Set("scope", "read:user")
34 req, err := http.NewRequestWithContext(ctx, "POST", "https://github.com/login/device/code", bytes.NewBufferString(form.Encode()))
35 if err != nil {
36 return GitHubCopilotDeviceAuthorization{}, err
37 }
38 req.Header.Set("content-type", "application/x-www-form-urlencoded")
39 req.Header.Set("accept", "application/json")
40 req.Header.Set("user-agent", "GitHubCopilotChat/0.35.0")
41
42 resp, err := (&http.Client{Timeout: 30 * time.Second}).Do(req)
43 if err != nil {
44 return GitHubCopilotDeviceAuthorization{}, fmt.Errorf("github copilot device authorization: %w", err)
45 }
46 defer resp.Body.Close()
47 body, _ := io.ReadAll(resp.Body)
48 if resp.StatusCode < 200 || resp.StatusCode >= 300 {
49 return GitHubCopilotDeviceAuthorization{}, fmt.Errorf("github copilot device authorization http %d: %s", resp.StatusCode, strings.TrimSpace(string(body)))
50 }
51 var out GitHubCopilotDeviceAuthorization
52 if err := json.Unmarshal(body, &out); err != nil {
53 return out, fmt.Errorf("parse github copilot device authorization: %w", err)
54 }
55 if out.Interval <= 0 {
56 out.Interval = 5
57 }
58 return out, nil
59}
60
61// PollGitHubCopilotDeviceToken polls until GitHub's browser/device-code
62// login completes and returns the GitHub access token.
63func PollGitHubCopilotDeviceToken(ctx context.Context, auth GitHubCopilotDeviceAuthorization) (*OAuthToken, error) {
64 interval := time.Duration(auth.Interval) * time.Second
65 if interval <= 0 {
66 interval = 5 * time.Second
67 }
68 deadline := time.Now().Add(time.Duration(auth.ExpiresIn) * time.Second)
69 for {
70 if auth.ExpiresIn > 0 && time.Now().After(deadline) {
71 return nil, fmt.Errorf("github copilot device login expired")
72 }
73 tok, retry, err := pollGitHubCopilotDeviceTokenOnce(ctx, auth.DeviceCode, interval)
74 if err != nil {
75 return nil, err
76 }
77 if tok != nil {
78 return tok, nil
79 }
80 select {
81 case <-ctx.Done():
82 return nil, ctx.Err()
83 case <-time.After(retry):
84 }
85 }
86}
87
88func pollGitHubCopilotDeviceTokenOnce(ctx context.Context, deviceCode string, interval time.Duration) (*OAuthToken, time.Duration, error) {
89 form := url.Values{}
90 form.Set("client_id", githubCopilotClientID)
91 form.Set("device_code", deviceCode)
92 form.Set("grant_type", "urn:ietf:params:oauth:grant-type:device_code")
93 req, err := http.NewRequestWithContext(ctx, "POST", "https://github.com/login/oauth/access_token", bytes.NewBufferString(form.Encode()))
94 if err != nil {
95 return nil, 0, err
96 }
97 req.Header.Set("content-type", "application/x-www-form-urlencoded")
98 req.Header.Set("accept", "application/json")
99 req.Header.Set("user-agent", "GitHubCopilotChat/0.35.0")
100 resp, err := (&http.Client{Timeout: 30 * time.Second}).Do(req)
101 if err != nil {
102 return nil, 0, fmt.Errorf("github copilot token poll: %w", err)
103 }
104 defer resp.Body.Close()
105 body, _ := io.ReadAll(resp.Body)
106 var raw struct {
107 AccessToken string `json:"access_token"`
108 TokenType string `json:"token_type"`
109 Scope string `json:"scope"`
110 Error string `json:"error"`
111 ErrorDescription string `json:"error_description"`
112 }
113 _ = json.Unmarshal(body, &raw)
114 if resp.StatusCode == http.StatusOK && raw.AccessToken != "" {
115 return &OAuthToken{
116 AccessToken: raw.AccessToken,
117 TokenType: raw.TokenType,
118 Scope: raw.Scope,
119 ClientID: githubCopilotClientID,
120 }, 0, nil
121 }
122 if raw.Error == "authorization_pending" || resp.StatusCode == http.StatusBadRequest {
123 return nil, interval, nil
124 }
125 if raw.Error == "slow_down" {
126 return nil, interval + 5*time.Second, nil
127 }
128 if raw.Error != "" {
129 return nil, 0, fmt.Errorf("github copilot token poll: %s: %s", raw.Error, raw.ErrorDescription)
130 }
131 return nil, 0, fmt.Errorf("github copilot token poll http %d: %s", resp.StatusCode, strings.TrimSpace(string(body)))
132}