|
| 1 | +using System.Text.Json; |
| 2 | +using System.Text.Json.Serialization; |
| 3 | +using System.Text.Json.Serialization.Metadata; |
| 4 | + |
| 5 | +namespace WinHarness.Providers; |
| 6 | + |
| 7 | +/// <summary> |
| 8 | +/// GitHub Copilot OAuth device-code flow and short-lived bearer exchange. |
| 9 | +/// Endpoints, client id, and required headers verified against pi's shipping |
| 10 | +/// implementation (ADR-0005). All endpoint knowledge lives here so vendor |
| 11 | +/// drift is a single-file fix. |
| 12 | +/// </summary> |
| 13 | +public sealed class GitHubCopilotOAuthFlow : IOAuthTokenRefresher |
| 14 | +{ |
| 15 | + // VS Code Copilot Chat client id, stored base64-obfuscated per ADR-0005. |
| 16 | + private static readonly string ClientId = |
| 17 | + System.Text.Encoding.UTF8.GetString(Convert.FromBase64String("SXYxLmI1MDdhMDhjODdlY2ZlOTg=")); |
| 18 | + |
| 19 | + private static readonly Dictionary<string, string> CopilotHeaders = new(StringComparer.Ordinal) |
| 20 | + { |
| 21 | + ["User-Agent"] = "GitHubCopilotChat/0.35.0", |
| 22 | + ["Editor-Version"] = "vscode/1.107.0", |
| 23 | + ["Editor-Plugin-Version"] = "copilot-chat/0.35.0", |
| 24 | + ["Copilot-Integration-Id"] = "vscode-chat", |
| 25 | + }; |
| 26 | + |
| 27 | + /// <summary>Fallback base URL when the bearer carries no proxy endpoint.</summary> |
| 28 | + public const string DefaultBaseUrl = "https://api.individual.githubcopilot.com"; |
| 29 | + |
| 30 | + private readonly HttpClient _http; |
| 31 | + private readonly string _domain; |
| 32 | + |
| 33 | + /// <summary>Creates the flow against github.com or an enterprise domain.</summary> |
| 34 | + public GitHubCopilotOAuthFlow(HttpClient http, string domain = "github.com") |
| 35 | + { |
| 36 | + _http = http; |
| 37 | + _domain = domain; |
| 38 | + } |
| 39 | + |
| 40 | + /// <inheritdoc /> |
| 41 | + public string OAuthProviderId => "copilot"; |
| 42 | + |
| 43 | + /// <summary> |
| 44 | + /// Starts the device flow: returns the user code and verification URI to |
| 45 | + /// display, plus polling parameters. |
| 46 | + /// </summary> |
| 47 | + public async ValueTask<CopilotDeviceCode> StartDeviceFlowAsync(CancellationToken cancellationToken) |
| 48 | + { |
| 49 | + using HttpRequestMessage request = new(HttpMethod.Post, $"https://{_domain}/login/device/code"); |
| 50 | + request.Headers.TryAddWithoutValidation("Accept", "application/json"); |
| 51 | + request.Headers.TryAddWithoutValidation("User-Agent", CopilotHeaders["User-Agent"]); |
| 52 | + request.Content = new FormUrlEncodedContent(new Dictionary<string, string> |
| 53 | + { |
| 54 | + ["client_id"] = ClientId, |
| 55 | + ["scope"] = "read:user", |
| 56 | + }); |
| 57 | + |
| 58 | + CopilotDeviceCode device = await SendAsync( |
| 59 | + request, |
| 60 | + CopilotJsonContext.Default.CopilotDeviceCode, |
| 61 | + cancellationToken).ConfigureAwait(false); |
| 62 | + if (string.IsNullOrEmpty(device.DeviceCode) || string.IsNullOrEmpty(device.UserCode) || |
| 63 | + !Uri.TryCreate(device.VerificationUri, UriKind.Absolute, out Uri? uri) || |
| 64 | + (uri.Scheme != Uri.UriSchemeHttps && uri.Scheme != Uri.UriSchemeHttp)) |
| 65 | + { |
| 66 | + throw new InvalidOperationException("Invalid device code response from GitHub."); |
| 67 | + } |
| 68 | + |
| 69 | + return device; |
| 70 | + } |
| 71 | + |
| 72 | + /// <summary> |
| 73 | + /// Polls the access-token endpoint until the user authorizes (RFC 8628: |
| 74 | + /// default 5s interval, +5s on slow_down, deadline from expires_in). |
| 75 | + /// Returns the long-lived GitHub token (the "refresh" credential). |
| 76 | + /// </summary> |
| 77 | + public async ValueTask<string> PollForGitHubTokenAsync(CopilotDeviceCode device, CancellationToken cancellationToken) |
| 78 | + { |
| 79 | + TimeSpan interval = TimeSpan.FromSeconds(Math.Max(1, device.Interval ?? 5)); |
| 80 | + DateTimeOffset deadline = DateTimeOffset.UtcNow.AddSeconds(device.ExpiresIn); |
| 81 | + |
| 82 | + while (DateTimeOffset.UtcNow < deadline) |
| 83 | + { |
| 84 | + cancellationToken.ThrowIfCancellationRequested(); |
| 85 | + |
| 86 | + using HttpRequestMessage request = new(HttpMethod.Post, $"https://{_domain}/login/oauth/access_token"); |
| 87 | + request.Headers.TryAddWithoutValidation("Accept", "application/json"); |
| 88 | + request.Headers.TryAddWithoutValidation("User-Agent", CopilotHeaders["User-Agent"]); |
| 89 | + request.Content = new FormUrlEncodedContent(new Dictionary<string, string> |
| 90 | + { |
| 91 | + ["client_id"] = ClientId, |
| 92 | + ["device_code"] = device.DeviceCode, |
| 93 | + ["grant_type"] = "urn:ietf:params:oauth:grant-type:device_code", |
| 94 | + }); |
| 95 | + |
| 96 | + CopilotAccessTokenResponse response = await SendAsync( |
| 97 | + request, |
| 98 | + CopilotJsonContext.Default.CopilotAccessTokenResponse, |
| 99 | + cancellationToken).ConfigureAwait(false); |
| 100 | + |
| 101 | + if (!string.IsNullOrEmpty(response.AccessToken)) |
| 102 | + { |
| 103 | + return response.AccessToken; |
| 104 | + } |
| 105 | + |
| 106 | + switch (response.Error) |
| 107 | + { |
| 108 | + case "authorization_pending": |
| 109 | + break; |
| 110 | + case "slow_down": |
| 111 | + interval += TimeSpan.FromSeconds(5); |
| 112 | + break; |
| 113 | + default: |
| 114 | + throw new InvalidOperationException( |
| 115 | + $"Device flow failed: {response.Error}{(string.IsNullOrEmpty(response.ErrorDescription) ? "" : $": {response.ErrorDescription}")}"); |
| 116 | + } |
| 117 | + |
| 118 | + await Task.Delay(interval, cancellationToken).ConfigureAwait(false); |
| 119 | + } |
| 120 | + |
| 121 | + throw new InvalidOperationException("Device flow timed out before the code was authorized."); |
| 122 | + } |
| 123 | + |
| 124 | + /// <inheritdoc /> |
| 125 | + public async ValueTask<OAuthTokenSet> RefreshAsync(OAuthTokenSet current, CancellationToken cancellationToken) |
| 126 | + { |
| 127 | + if (string.IsNullOrEmpty(current.RefreshToken)) |
| 128 | + { |
| 129 | + throw new InvalidOperationException("No GitHub token stored; run 'winharness login --provider copilot' again."); |
| 130 | + } |
| 131 | + |
| 132 | + return await ExchangeForBearerAsync(current.RefreshToken, cancellationToken).ConfigureAwait(false); |
| 133 | + } |
| 134 | + |
| 135 | + /// <summary> |
| 136 | + /// Exchanges the long-lived GitHub token for a short-lived Copilot bearer. |
| 137 | + /// The bearer embeds a proxy endpoint that becomes the chat base URL. |
| 138 | + /// </summary> |
| 139 | + public async ValueTask<OAuthTokenSet> ExchangeForBearerAsync(string githubToken, CancellationToken cancellationToken) |
| 140 | + { |
| 141 | + using HttpRequestMessage request = new(HttpMethod.Get, $"https://api.{_domain}/copilot_internal/v2/token"); |
| 142 | + request.Headers.TryAddWithoutValidation("Accept", "application/json"); |
| 143 | + request.Headers.TryAddWithoutValidation("Authorization", $"Bearer {githubToken}"); |
| 144 | + foreach ((string name, string value) in CopilotHeaders) |
| 145 | + { |
| 146 | + request.Headers.TryAddWithoutValidation(name, value); |
| 147 | + } |
| 148 | + |
| 149 | + CopilotBearerResponse bearer = await SendAsync( |
| 150 | + request, |
| 151 | + CopilotJsonContext.Default.CopilotBearerResponse, |
| 152 | + cancellationToken).ConfigureAwait(false); |
| 153 | + if (string.IsNullOrEmpty(bearer.Token) || bearer.ExpiresAt is null) |
| 154 | + { |
| 155 | + throw new InvalidOperationException("Invalid Copilot token response."); |
| 156 | + } |
| 157 | + |
| 158 | + return new OAuthTokenSet( |
| 159 | + AccessToken: bearer.Token, |
| 160 | + RefreshToken: githubToken, |
| 161 | + ExpiresAt: DateTimeOffset.FromUnixTimeSeconds(bearer.ExpiresAt.Value), |
| 162 | + Scopes: "read:user", |
| 163 | + BaseUrl: ExtractBaseUrl(bearer.Token)); |
| 164 | + } |
| 165 | + |
| 166 | + /// <summary> |
| 167 | + /// Extracts the API base URL from the bearer's embedded proxy endpoint |
| 168 | + /// (format: "tid=...;exp=...;proxy-ep=proxy.individual.githubcopilot.com;..."). |
| 169 | + /// </summary> |
| 170 | + public static string ExtractBaseUrl(string bearerToken) |
| 171 | + { |
| 172 | + foreach (string part in bearerToken.Split(';')) |
| 173 | + { |
| 174 | + if (part.StartsWith("proxy-ep=", StringComparison.Ordinal)) |
| 175 | + { |
| 176 | + string host = part["proxy-ep=".Length..]; |
| 177 | + if (host.StartsWith("proxy.", StringComparison.Ordinal)) |
| 178 | + { |
| 179 | + host = "api." + host["proxy.".Length..]; |
| 180 | + } |
| 181 | + |
| 182 | + return $"https://{host}"; |
| 183 | + } |
| 184 | + } |
| 185 | + |
| 186 | + return DefaultBaseUrl; |
| 187 | + } |
| 188 | + |
| 189 | + private async ValueTask<T> SendAsync<T>( |
| 190 | + HttpRequestMessage request, |
| 191 | + JsonTypeInfo<T> typeInfo, |
| 192 | + CancellationToken cancellationToken) |
| 193 | + { |
| 194 | + using HttpResponseMessage response = await _http.SendAsync(request, cancellationToken).ConfigureAwait(false); |
| 195 | + string body = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); |
| 196 | + if (!response.IsSuccessStatusCode) |
| 197 | + { |
| 198 | + throw new InvalidOperationException($"{(int)response.StatusCode} {response.ReasonPhrase}: {body}"); |
| 199 | + } |
| 200 | + |
| 201 | + return JsonSerializer.Deserialize(body, typeInfo) |
| 202 | + ?? throw new InvalidOperationException("Empty response from GitHub."); |
| 203 | + } |
| 204 | +} |
0 commit comments