|
| 1 | +import consola from "consola" |
| 2 | + |
| 3 | +import { ENV } from "~/config/env" |
| 4 | +import { _github } from "~/services/api-instance" |
| 5 | + |
| 6 | +interface DeviceCodeResponse { |
| 7 | + device_code: string |
| 8 | + user_code: string |
| 9 | + verification_uri: string |
| 10 | + expires_in: number |
| 11 | + interval: number |
| 12 | +} |
| 13 | + |
| 14 | +interface AccessTokenResponse { |
| 15 | + access_token: string |
| 16 | + token_type: string |
| 17 | + scope: string |
| 18 | +} |
| 19 | + |
| 20 | +export async function getGitHubToken() { |
| 21 | + const response = await _github<DeviceCodeResponse>("/login/device/code", { |
| 22 | + method: "POST", |
| 23 | + body: { |
| 24 | + client_id: ENV.GITHUB_CLIENT_ID, |
| 25 | + scope: ENV.GITHUB_OAUTH_SCOPES, |
| 26 | + }, |
| 27 | + }) |
| 28 | + |
| 29 | + consola.info( |
| 30 | + `Please enter the code "${response.user_code}" in ${response.verification_uri}`, |
| 31 | + ) |
| 32 | + |
| 33 | + while (true) { |
| 34 | + const pollResponse = await _github<AccessTokenResponse>( |
| 35 | + "/login/oauth/access_token", |
| 36 | + { |
| 37 | + method: "POST", |
| 38 | + body: { |
| 39 | + client_id: ENV.GITHUB_CLIENT_ID, |
| 40 | + device_code: response.device_code, |
| 41 | + grant_type: "urn:ietf:params:oauth:grant-type:device_code", |
| 42 | + }, |
| 43 | + }, |
| 44 | + ) |
| 45 | + |
| 46 | + if (pollResponse.access_token) { |
| 47 | + consola.info(`Got token ${pollResponse.access_token.replace(/./g, "*")}`) |
| 48 | + return pollResponse |
| 49 | + } else { |
| 50 | + // Interval is in seconds, we need to multiply by 1000 to get milliseconds |
| 51 | + // I'm also adding another second, just to be safe |
| 52 | + await new Promise((resolve) => |
| 53 | + setTimeout(resolve, (response.interval + 1) * 1000), |
| 54 | + ) |
| 55 | + } |
| 56 | + } |
| 57 | +} |
0 commit comments