| 260 | instructions: `Enter code: ${deviceData.user_code}`, |
| 261 | method: "auto" as const, |
| 262 | async callback() { |
| 263 | while (true) { |
| 264 | const response = await fetch(urls.ACCESS_TOKEN_URL, { |
| 265 | method: "POST", |
| 266 | headers: { |
| 267 | Accept: "application/json", |
| 268 | "Content-Type": "application/json", |
| 269 | "User-Agent": `opencode/${InstallationVersion}`, |
| 270 | }, |
| 271 | body: JSON.stringify({ |
| 272 | client_id: CLIENT_ID, |
| 273 | device_code: deviceData.device_code, |
| 274 | grant_type: "urn:ietf:params:oauth:grant-type:device_code", |
| 275 | }), |
| 276 | }) |
| 277 | |
| 278 | if (!response.ok) return { type: "failed" as const } |
| 279 | |
| 280 | const data = (await response.json()) as { |
| 281 | access_token?: string |
| 282 | error?: string |
| 283 | interval?: number |
| 284 | } |
| 285 | |
| 286 | if (data.access_token) { |
| 287 | const result: { |
| 288 | type: "success" |
| 289 | refresh: string |
| 290 | access: string |
| 291 | expires: number |
| 292 | provider?: string |
| 293 | enterpriseUrl?: string |
| 294 | } = { |
| 295 | type: "success", |
| 296 | refresh: data.access_token, |
| 297 | access: data.access_token, |
| 298 | expires: 0, |
| 299 | } |
| 300 | |
| 301 | if (deploymentType === "enterprise") { |
| 302 | result.enterpriseUrl = domain |
| 303 | } |
| 304 | |
| 305 | return result |
| 306 | } |
| 307 | |
| 308 | if (data.error === "authorization_pending") { |
| 309 | await sleep(deviceData.interval * 1000 + OAUTH_POLLING_SAFETY_MARGIN_MS) |
| 310 | continue |
| 311 | } |
| 312 | |
| 313 | if (data.error === "slow_down") { |
| 314 | // Based on the RFC spec, we must add 5 seconds to our current polling interval. |
| 315 | // (See https://www.rfc-editor.org/rfc/rfc8628#section-3.5) |
| 316 | let newInterval = (deviceData.interval + 5) * 1000 |
| 317 | |
| 318 | // GitHub OAuth API may return the new interval in seconds in the response. |
| 319 | // We should try to use that if provided with safety margin. |