//// Copilot's GitHub credentials, minted session tokens and entitlement access. //// Selection remembers only for model requests; listing uses discovery access. import albedo_clock import albedo_env import albedo_ext_github_copilot/wire import albedo_http/buffered import albedo_model as types import albedo_openai/catalog as model_catalog import albedo_process/memo import albedo_sdk/credentials import albedo_sdk/http import albedo_sdk/key_environment.{type KeyEnvironment} import albedo_sdk/oauth import albedo_sdk/rotation import gleam/dict.{type Dict} import gleam/dynamic.{type Dynamic} import gleam/dynamic/decode import gleam/float import gleam/int import gleam/json import gleam/list import gleam/option.{None, Some} import gleam/result import gleam/string import gleam/uri pub type Credential { OAuth( access: String, account_id: String, login: String, label: String, endpoint: String, ) Key(key: String, public_id: String, label: String, endpoint: String) } pub type Session { Session(token: String, endpoint: String) } pub type Access { Access(account: credentials.Stored(Credential), session: Session) } type Profile { Profile(endpoint: String, bound: Bool, inline: Bool) } pub const default_endpoint = "https://api.githubcopilot.com" const store = "github-copilot" const signed_out = "GitHub Copilot is not signed in; run /login to add a GitHub account, or set GITHUB_TOKEN" fn decoder() -> decode.Decoder(Credential) { use kind <- decode.optional_field("type", "", decode.string) use label <- decode.optional_field("label", "", decode.string) case kind { "oauth" -> { use access <- decode.field("access", decode.string) use account_id <- decode.optional_field("accountId", "", decode.string) use login <- decode.optional_field("login", "", decode.string) use endpoint <- decode.optional_field("endpointsApi", "", decode.string) decode.success(OAuth(access, account_id, login, label, endpoint)) } "key" | "" -> { use key <- decode.field("apiKey", decode.string) use public_id <- decode.optional_field( "_albedo_account_id", "", decode.string, ) use legacy_id <- decode.optional_field("accountId", "", decode.string) let id = case legacy_id { "" -> public_id id -> id } use endpoint <- decode.optional_field("endpointsApi", "", decode.string) decode.success(Key(key, id, label, endpoint)) } _ -> decode.failure(Key("", "", "", ""), "GitHub credential") } } fn profile(home: String, name: String) -> Result(Profile, String) { credentials.profile(home, name, { use endpoint <- decode.optional_field("baseUrl", "", decode.string) use key <- decode.optional_field("apiKey", "", decode.string) use id <- decode.optional_field( "accountId", None, decode.optional(decode.string), ) use ids <- decode.optional_field( "accountIds", None, decode.optional(decode.list(decode.string)), ) decode.success(Profile( model_catalog.root(endpoint), id != None || ids != None, key != "", )) }) } pub fn identity(value: Credential) -> String { case value { OAuth(_, id, _, _, _) if id != "" -> id OAuth(access, _, _, _, _) -> fingerprint(access) Key(_, id, _, _) if id != "" -> id Key(key, _, _, _) -> rotation.key_label(key) } } fn github_token(value: Credential) -> String { case value { OAuth(access, ..) -> access Key(key, ..) -> key } } pub fn label(value: Credential) -> String { case value { OAuth(login: login, ..) if login != "" -> login OAuth(label: label, ..) | Key(label: label, ..) if label != "" -> label _ -> "GitHub Copilot" } } fn candidates( home: String, name: String, keys: KeyEnvironment, ) -> Result(List(credentials.Stored(Credential)), String) { use profile <- result.try(profile(home, name)) use values <- result.try(credentials.candidates( home, store, name, decoder(), keys, )) case profile.inline, profile.bound { True, _ -> Ok(values) False, True -> credentials.bound(home, name, values) False, False -> { // Saved credentials precede environment credentials, even when cooling. let saved = values |> list.filter(fn(value) { !string.starts_with(credentials.public_id(value), "env:") && github_token(credentials.value(value)) != "" }) let selected = list.filter(saved, credentials.selected) let selected = case selected { [] -> saved _ -> selected } let available = list.filter(selected, fn(value) { credentials.until(value, None) <= albedo_clock.system_ms() }) let ordered = case available { [] -> selected _ -> list.append( available, list.filter(selected, fn(value) { credentials.until(value, None) > albedo_clock.system_ms() }), ) } let environment = list.filter(values, fn(value) { string.starts_with(credentials.public_id(value), "env:") }) Ok(list.take(list.append(ordered, environment), 1)) } } } pub fn select( home: String, name: String, session: String, keys: KeyEnvironment, ) -> Result(Access, String) { use values <- result.try(candidates(home, name, keys)) use account <- result.try( credentials.order(store, values, session, identity, None) |> list.first |> result.replace_error(signed_out), ) credentials.remember(store, session, identity(credentials.value(account))) use requested <- result.try(profile(home, name)) access(account, requested.endpoint) } fn access( account: credentials.Stored(Credential), requested: String, ) -> Result(Access, String) { let value = credentials.value(account) use session <- result.try(token(github_token(value))) let own = case value { OAuth(endpoint: endpoint, ..) | Key(endpoint: endpoint, ..) -> endpoint } let endpoint = [requested, own, session.endpoint, default_endpoint] |> list.find(fn(value) { value != "" }) |> result.unwrap(default_endpoint) Ok(Access(account, Session(..session, endpoint: endpoint))) } pub fn discovery( home: String, endpoint: String, keys: KeyEnvironment, ) -> Result(Access, String) { use values <- result.try(candidates(home, "", keys)) use account <- result.try( list.first(values) |> result.replace_error("no GitHub Copilot account"), ) access(account, model_catalog.root(endpoint)) } pub fn expire(access: Access) -> Nil { memo.remove( sessions(), fingerprint(github_token(credentials.value(access.account))), ) } pub fn mark( home: String, name: String, keys: KeyEnvironment, access: Access, limit: types.RateLimit, ) -> Result(rotation.Limited, String) { let lasting = limit.limit == Some(types.Lasting) let until = albedo_clock.system_ms() + case lasting { True -> 900_000 False -> 30_000 } use _ <- result.try(credentials.mark(access.account, until, None)) let used = identity(credentials.value(access.account)) let next = candidates(home, name, keys) |> result.unwrap([]) |> list.find(fn(account) { identity(credentials.value(account)) != used && credentials.until(account, None) <= albedo_clock.system_ms() }) |> result.map(fn(account) { label(credentials.value(account)) }) |> result.unwrap("") Ok(rotation.Limited("", oauth.local_time(until), next, lasting)) } pub fn serves(home: String, endpoint: String) -> Bool { let endpoint = model_catalog.root(endpoint) let host = uri.parse(endpoint) |> result.map(fn(uri) { option.unwrap(uri.host, "") |> string.lowercase }) |> result.unwrap("") endpoint == default_endpoint || host == "api.githubcopilot.com" || string.contains(host, ".githubcopilot.com") || string.contains(host, "copilot-api.") || { endpoint != "" && list.any(credentials.profiles(home).entries, fn(profile) { profile.provider == store && model_catalog.root(profile.endpoint) == endpoint }) } } pub fn headers(token: String, github: Bool) -> List(#(String, String)) { [ #( "authorization", case github { True -> "token " False -> "Bearer " } <> token, ), #("user-agent", wire.identity.user_agent), #("editor-version", wire.identity.editor_version), #("editor-plugin-version", wire.identity.editor_plugin_version), #("copilot-integration-id", wire.identity.integration_id), #("x-github-api-version", case github { True -> "2025-04-01" False -> wire.api_version }), #("accept", "application/json"), ] } /// GitHub's API host for the Copilot token and entitlement lookups, and its /// web host for device sign-in. Both are read from the environment on each /// use so a test can point a running daemon at a local server. fn github_api() -> String { override("COPILOT_GITHUB_API", "https://api.github.com") } fn github_web() -> String { override("COPILOT_GITHUB_WEB", "https://github.com") } fn override(name: String, default: String) -> String { case albedo_env.get(name) { "" -> default value -> model_catalog.root(value) } } /// copilot.vim's public GitHub OAuth app: the device flow GitHub allows for a /// Copilot client, borrowed the way every third-party client borrows one. const client_id = "Iv1.b507a08c87ecfe98" /// GitHub's device sign-in. It is built when a sign-in starts, so the web /// host override is read then. pub fn device_flow() -> oauth.DeviceFlow { oauth.DeviceFlow( server: github_web(), code_path: "/login/device/code", token_path: "/login/oauth/access_token", payload: oauth.Form( code: [#("client_id", client_id), #("scope", "read:user")], token: [ #("client_id", client_id), #("grant_type", "urn:ietf:params:oauth:grant-type:device_code"), ], ), headers: [ #("accept", "application/json"), #("user-agent", wire.identity.editor_version), ], progress: "Waiting for authorization in your browser…", instructions: fn(code, _url) { "Confirm code " <> code <> " in your browser, then authorize GitHub Copilot." }, credential: device_credential, ) } /// A GitHub token is only worth storing if the account can chat: OAuth itself /// succeeds for any GitHub account. A failed entitlement lookup is not a /// denial, so only an explicit `chat_enabled: false` blocks the sign-in. fn device_credential( token: Dict(String, Dynamic), ) -> Result(Dict(String, Dynamic), String) { let access = field(token, "access_token", decode.string, "") let user = copilot_user(access) |> result.unwrap(dict.new()) case field(user, "chat_enabled", decode.bool, True) { False -> Error(entitlement_error(user)) True -> Ok(oauth_credential(access, user)) } } fn entitlement_error(user: Dict(String, Dynamic)) -> String { case field(user, "can_signup_for_limited", decode.bool, False) { True -> "This GitHub account is not signed up for GitHub Copilot. Sign up for Copilot Free at " <> "https://github.com/features/copilot/plans and connect again." False -> "This GitHub account has no GitHub Copilot access; it needs an active Copilot " <> "subscription or a seat from an organization." } } /// The stored credential for a GitHub token and its entitlement record, /// which is empty when the lookup failed. fn oauth_credential( access: String, user: Dict(String, Dynamic), ) -> Dict(String, Dynamic) { let login = field(user, "login", decode.string, "") let #(id, label) = case login { "" -> #(fingerprint(access), "GitHub Copilot") _ -> #(login, login) } let api = field(user, "endpoints", decode.at(["api"], decode.string), "") |> model_catalog.root [ #("type", "oauth"), #("access", access), #("accountId", id), #("login", login), #("label", label), ..case api { "" -> [] _ -> [#("endpointsApi", api)] } ] |> list.map(fn(entry) { #(entry.0, dynamic.string(entry.1)) }) |> dict.from_list } /// The signed-in account's Copilot entitlement record, or an error when it /// could not be fetched or was not a JSON object. fn copilot_user(access: String) -> Result(Dict(String, Dynamic), Nil) { case http.get( github_api() <> "/copilot_internal/user", headers(access, True), buffered.Timeouts(10_000, 5000), ) { Ok(#(200, body)) -> json.parse_bits(body, decode.dict(decode.string, decode.dynamic)) |> result.replace_error(Nil) _ -> Error(Nil) } } fn field( values: Dict(String, Dynamic), name: String, decoder: decode.Decoder(value), default: value, ) -> value { dict.get(values, name) |> result.try(fn(value) { decode.run(value, decoder) |> result.replace_error(Nil) }) |> result.unwrap(default) } /// Minted Copilot session tokens by GitHub token fingerprint. They live in /// memory only, so a restart mints again. fn sessions() -> memo.Memo(Session) { let decoder = { use token <- decode.field(1, decode.string) use endpoint <- decode.field(2, decode.string) decode.success(Session(token, endpoint)) } memo.new("github_copilot/sessions", decoder) } fn token(github: String) -> Result(Session, String) { case github { "" -> Error("This GitHub Copilot account has no GitHub token; run /login") _ -> case memo.get(sessions(), fingerprint(github)) { Ok(value) -> Ok(value) Error(Nil) -> mint(github) } } } fn mint(github: String) -> Result(Session, String) { use #(status, body) <- result.try(http.get( github_api() <> "/copilot_internal/v2/token", headers(github, True), buffered.Timeouts(10_000, 5000), )) case status { 200 -> { use #(token, endpoint, relative, absolute) <- result.try( json.parse_bits(body, { use token <- decode.field("token", decode.string) use endpoint <- decode.optional_field("endpoints", default_endpoint, { use api <- decode.optional_field( "api", default_endpoint, decode.string, ) decode.success(api) }) use relative <- decode.optional_field("refresh_in", 0, number()) use absolute <- decode.optional_field("expires_at", 0, number()) decode.success(#(token, endpoint, relative, absolute)) }) |> result.replace_error( "GitHub returned an incomplete Copilot token response.", ), ) case token { "" -> Error("GitHub returned an incomplete Copilot token response.") _ -> { let now = albedo_clock.system_ms() let expires = case relative { 0 -> case absolute { 0 -> now + 1_440_000 value -> int.max( now, { case value > 100_000_000_000 { True -> value False -> value * 1000 } } - 60_000, ) } seconds -> now + int.max(seconds * 1000 - 60_000, 1000) } let value = Session(token, case model_catalog.root(endpoint) { "" -> default_endpoint endpoint -> endpoint }) memo.put_until(sessions(), fingerprint(github), value, until: expires) Ok(value) } } } 401 -> Error("GitHub rejected this token; run /login to sign in again") 403 | 404 -> { let value = Session(github, default_endpoint) memo.put_until( sessions(), fingerprint(github), value, until: albedo_clock.system_ms() + 300_000, ) Ok(value) } _ -> Error(http.failure("GitHub Copilot token exchange", status, body)) } } fn number() -> decode.Decoder(Int) { decode.one_of(decode.int, [ decode.float |> decode.map(float.round), decode.string |> decode.map(fn(value) { int.parse(value) |> result.unwrap(0) }), decode.success(0), ]) } // Preserve the account IDs and cache keys used by existing Copilot credentials. fn fingerprint(value: String) -> String { case value { "" -> "" _ -> rotation.key_label(value) } }