/** * GitHub CLI (`gh`) 客户端封装 * * 支持三种认证方式: * 1. gh CLI 默认凭据(gh auth login) * 2. GitHub App — JWT → Installation Token(自动续期) * 3. 个人 OAuth Token(用户绑定 / Device Flow) * * 零外部依赖,使用 Node.js 原生模块。 */ import { spawn } from 'node:child_process'; import { createEndpointOperation } from 'zhin.js/adapter'; import { EndpointDeliveryError } from '@zhin.js/im-contract'; import crypto from 'node:crypto'; import fs from 'node:fs'; // ── GitHub App 认证配置 ────────────────────────────────────────────── export interface AppAuth { appId: string | number; /** PEM 格式私钥内容,或私钥文件路径 */ privateKey: string; } export interface GitHubBotIdentity { login: string; email: string; slug: string; userId: number; } export interface GitHubCommitAuthor { name: string; email: string; date?: string; } export interface GhClientOptions { readonly signal?: AbortSignal; /** GitHub Enterprise 主机名(默认 github.com) */ host?: string; /** 覆盖 gh CLI 默认认证的 Personal Access Token / OAuth Token */ token?: string; /** GitHub App 认证 — 自动管理 Installation Token */ appAuth?: AppAuth; } /** Per-request cancellation is independent of this account's execution lifetime. */ export interface GhRequestLifetime { readonly signal?: AbortSignal } /** An API action and its transport inputs, retained together through authentication and subprocess IO. */ export interface GhApiRequest extends GhRequestLifetime { readonly method: string; readonly path: string; readonly body?: unknown; readonly headers?: Readonly>; } /** One comment publication, shared by issue and PR conversation sends. */ export interface GhCommentRequest extends GhRequestLifetime { readonly repo: string; readonly number: number; readonly body: string; } interface GhCommandRequest extends GhRequestLifetime { readonly args: readonly string[]; readonly stdin?: string; readonly token?: string } export class GhClient { protected apiHost?: string; protected executionSignal?: AbortSignal; protected bindExecutionSignal(signal: AbortSignal): void { this.executionSignal = signal; } /** Aborted when the owning endpoint stops; long-running background work should observe it. */ get lifecycleSignal(): AbortSignal | undefined { return this.executionSignal; } private token?: string; private _appAuth?: AppAuth; private _resolvedKey?: string; private _user: string | null = null; /** Installation Token 缓存: installationId → { token, expiresAt } */ private _installationTokens = new Map(); /** repo(小写) → installationId */ private _repoToInstallation = new Map(); /** 所有 Installation 信息 */ private _allInstallations: Array<{ id: number; account: { login: string; type: string }; target_type: string }> = []; /** 上次 syncInstallations 时间 (ms) */ private _lastSyncTime = 0; constructor(options: GhClientOptions = {}) { this.apiHost = options.host; this.executionSignal = options.signal; this.token = options.token; this._appAuth = options.appAuth; } protected fetchNative(input: string, init?: RequestInit): Promise { this.executionSignal?.throwIfAborted(); init?.signal?.throwIfAborted(); return fetch(input, { ...init, ...(this.executionSignal ? { signal: init?.signal ? AbortSignal.any([this.executionSignal, init.signal]) : this.executionSignal } : {}) }); } /** 创建使用指定 token 的副本(共享 host 配置,不继承 App 认证) */ withToken(token: string): GhClient { return new GhClient({ host: this.apiHost, token, signal: this.executionSignal }); } get authenticatedUser() { return this._user; } // ── 底层执行 ────────────────────────────────────────────────────── private exec({ args, stdin, token, signal = this.executionSignal }: GhCommandRequest): Promise { signal?.throwIfAborted(); const fullArgs = this.apiHost ? [...args, '--hostname', this.apiHost] : args; const env = token ? { ...process.env, GH_TOKEN: token } : undefined; return new Promise((resolve, reject) => { const proc = spawn('gh', fullArgs, { stdio: ['pipe', 'pipe', 'pipe'], env, signal }); let stdout = ''; let stderr = ''; proc.stdout.on('data', (d: Buffer) => (stdout += d.toString())); proc.stderr.on('data', (d: Buffer) => (stderr += d.toString())); proc.on('error', (err: NodeJS.ErrnoException) => { if (err.code === 'ENOENT') reject(new Error('gh CLI 未安装,请先安装: https://cli.github.com/')); else reject(err); }); proc.on('close', (code) => { if (code === 0) resolve(stdout); else reject( Object.assign(new Error(stderr.trim() || `gh exited with code ${code}`), { stdout, stderr, exitCode: code, }), ); }); if (stdin !== undefined) proc.stdin.write(stdin); proc.stdin.end(); }); } // ── API 调用 ────────────────────────────────────────────────────── /** * 确保 App 认证的 Installation Token 有效(自动按 repo 查找对应安装) * @param repo 仓库全名(owner/repo),用于选择正确的 Installation */ private async ensureTokenForRepo(repo?: string, signal?: AbortSignal): Promise { if (!this._appAuth) return this.token; let installId: number | undefined; if (repo) { const key = repo.toLowerCase(); installId = this._repoToInstallation.get(key); if (!installId) { // Owner 级别匹配(安装在整个账号/组织上) const owner = key.split('/')[0]; for (const inst of this._allInstallations) { if (inst.account.login.toLowerCase() === owner) { installId = inst.id; break; } } } // 懒加载重新发现(5 分钟冷却) if (!installId && Date.now() - this._lastSyncTime > 5 * 60_000) { await this.syncInstallations({ signal }); installId = this._repoToInstallation.get(key); if (!installId) { const owner = key.split('/')[0]; for (const inst of this._allInstallations) { if (inst.account.login.toLowerCase() === owner) { installId = inst.id; break; } } } } } // 回退到第一个安装 if (!installId && this._allInstallations.length) { installId = this._allInstallations[0].id; } if (!installId) return this.token; const cached = this._installationTokens.get(installId); if (cached && cached.expiresAt > Date.now() + 60_000) { return cached.token; } await this.refreshInstallationToken(installId, { signal }); return this._installationTokens.get(installId)?.token; } async request({ method, path, body, headers, signal }: GhApiRequest): Promise<{ ok: boolean; status: number; data: T }> { const operationSignal = this.executionSignal && signal ? AbortSignal.any([this.executionSignal, signal]) : this.executionSignal ?? signal; const operation = createEndpointOperation({ signal: operationSignal }); // 从路径自动检测 repo 以选择正确的 Installation Token const repoMatch = path.match(/^\/repos\/([^/?]+\/[^/?]+)/); const token = await operation.prepare(() => this.ensureTokenForRepo(repoMatch?.[1], operationSignal)); const args = ['api', path, '--method', method]; if (body) args.push('--input', '-'); if (headers) { for (const [k, v] of Object.entries(headers)) { args.push('-H', `${k}: ${v}`); } } try { const execute = () => this.exec({ args, stdin: body ? JSON.stringify(body) : undefined, token, signal: operationSignal }); const raw = await operation.run(execute); let data: any; try { data = raw ? JSON.parse(raw) : null; } catch { data = raw; } return { ok: true, status: 200, data }; } catch (err: unknown) { if (err instanceof EndpointDeliveryError) throw err; let data: any; const errObj = err instanceof Error ? err : new Error(String(err)); try { data = (err as any).stdout ? JSON.parse((err as any).stdout) : { message: errObj.message }; } catch { data = { message: (err as any).stderr?.trim() || errObj.message }; } return { ok: false, status: (err as any).exitCode || 0, data }; } } private get(path: string) { return this.request({ method: 'GET', path }); } private post(path: string, body?: any) { return this.request({ method: 'POST', path, body }); } private patch(path: string, body?: any) { return this.request({ method: 'PATCH', path, body }); } private put(path: string, body?: any) { return this.request({ method: 'PUT', path, body }); } private del(path: string, body?: any) { return this.request({ method: 'DELETE', path, body }); } // ── 认证验证 ────────────────────────────────────────────────────── async verifyAuth(): Promise<{ ok: boolean; user: string; message: string }> { // App 认证模式:自动发现所有安装 if (this._appAuth) { try { await this.syncInstallations(); if (!this._allInstallations.length) { return { ok: false, user: '', message: 'GitHub App 没有任何安装,请先在 GitHub 上安装 App' }; } // 用 JWT 查询 App 信息(/app 端点只接受 JWT 认证,不能用 Installation Token) const key = this.resolvePrivateKey(); const jwt = GhClient.createJWT(this._appAuth.appId, key); const baseUrl = this.apiHost ? `https://${this.apiHost}/api/v3` : 'https://api.github.com'; const appRes = await this.fetchNative(`${baseUrl}/app`, { headers: { Authorization: `Bearer ${jwt}`, Accept: 'application/vnd.github+json' }, }); if (appRes.ok) { const appData = (await appRes.json()) as { name: string; slug: string; client_id?: string }; const name = `${appData.slug || appData.name}[bot]`; this._user = name; this._appSlug = appData.slug || null; if (appData.client_id) this._clientId = appData.client_id; await this.resolveBotUserId(); const repos = this._repoToInstallation.size; return { ok: true, user: name, message: `GitHub App: ${name} (${this._allInstallations.length} 安装, ${repos} 仓库)` }; } const errBody = await appRes.text(); return { ok: false, user: '', message: `App Token 验证失败 (${appRes.status}): ${errBody}` }; } catch (e: unknown) { return { ok: false, user: '', message: (e instanceof Error ? e.message : String(e)) || 'App 认证失败' }; } } // Token 模式(用户绑定)或 gh CLI 默认模式 try { if (this.token) { // 直接用 token 查 /user const r = await this.get<{ login: string }>('/user'); if (r.ok) { this._user = r.data.login; return { ok: true, user: r.data.login, message: `token: ${r.data.login}` }; } return { ok: false, user: '', message: 'Token 无效' }; } await this.exec({ args: ['auth', 'status'], token: this.token }); const raw = await this.exec({ args: ['api', '/user', '--jq', '.login'], token: this.token }); const login = raw.trim(); this._user = login; return { ok: true, user: login, message: `gh CLI: ${login}` }; } catch (e: unknown) { return { ok: false, user: '', message: (e instanceof Error ? e.message : String(e)) || 'gh 认证检查失败' }; } } // ── Issue 评论 (聊天核心) ───────────────────────────────────────── // ── REST 便捷方法(gh api 封装,供命令/技能调用) ───────────────────── async getRepo(repo: string) { return this.get(`/repos/${repo}`); } async listIssues(repo: string, state: 'open' | 'closed' | 'all' = 'open') { return this.get(`/repos/${repo}/issues?state=${state}&per_page=30`); } async getIssue(repo: string, number: number) { return this.get(`/repos/${repo}/issues/${number}`); } async listPRs(repo: string, state: 'open' | 'closed' | 'all' = 'open') { return this.get(`/repos/${repo}/pulls?state=${state}&per_page=30`); } async getPR(repo: string, number: number) { return this.get(`/repos/${repo}/pulls/${number}`); } async searchRepos(query: string, perPage = 10) { return this.get<{ total_count: number; items: any[] }>( `/search/repositories?q=${encodeURIComponent(query)}&per_page=${perPage}`, ); } async listCommits( repo: string, sha?: string, _path?: string, perPage = 10, ) { let path = `/repos/${repo}/commits?per_page=${perPage}`; if (sha) path += `&sha=${encodeURIComponent(sha)}`; return this.get(path); } async listBranches(repo: string, perPage = 20) { return this.get(`/repos/${repo}/branches?per_page=${perPage}`); } async listReleases(repo: string, perPage = 10) { return this.get(`/repos/${repo}/releases?per_page=${perPage}`); } async listWorkflowRuns(repo: string, perPage = 10) { return this.get<{ workflow_runs: any[] }>( `/repos/${repo}/actions/runs?per_page=${perPage}`, ); } async closeIssue(repo: string, number: number) { return this.patch(`/repos/${repo}/issues/${number}`, { state: 'closed' }); } async closePR(repo: string, number: number) { return this.patch(`/repos/${repo}/pulls/${number}`, { state: 'closed' }); } async createIssueComment({ repo, number, body, signal }: GhCommentRequest) { return this.request<{ id: number; html_url: string; message?: string }>({ method: 'POST', path: `/repos/${repo}/issues/${number}/comments`, body: { body }, signal, }); } async deleteIssueComment(repo: string, commentId: number) { return this.del(`/repos/${repo}/issues/comments/${commentId}`); } async createPRComment(request: GhCommentRequest) { return this.createIssueComment(request); } async deletePRReviewComment(repo: string, commentId: number) { return this.del(`/repos/${repo}/pulls/comments/${commentId}`); } // ── Contents / Pulls(Bot 写操作)────────────────────────────────── async getFileContent(repo: string, path: string, ref?: string) { let apiPath = `/repos/${repo}/contents/${path.split('/').map(encodeURIComponent).join('/')}`; if (ref) apiPath += `?ref=${encodeURIComponent(ref)}`; return this.get<{ content: string; sha: string; encoding: string }>(apiPath); } async createOrUpdateFile( repo: string, path: string, content: string, message: string, options?: { branch?: string; sha?: string }, ) { const body: Record = { message, content: Buffer.from(content, 'utf-8').toString('base64'), }; if (options?.branch) body.branch = options.branch; if (options?.sha) body.sha = options.sha; const apiPath = `/repos/${repo}/contents/${path.split('/').map(encodeURIComponent).join('/')}`; return this.put<{ commit: { sha: string; html_url?: string }; content: { html_url?: string } }>( apiPath, body, ); } async getRef(repo: string, ref: string) { return this.get<{ ref: string; object: { sha: string; type: string } }>( `/repos/${repo}/git/ref/${encodeURIComponent(ref)}`, ); } async createRef(repo: string, ref: string, sha: string) { return this.post(`/repos/${repo}/git/refs`, { ref, sha }); } async createPullRequest( repo: string, title: string, head: string, base: string, body?: string, ) { return this.post<{ number: number; html_url: string; head: { ref: string } }>( `/repos/${repo}/pulls`, { title, head, base, body: body ?? '' }, ); } getBotLogin(): string | null { if (this._user) return this._user; if (this._appSlug) return `${this._appSlug}[bot]`; return null; } getCommitAuthor(): GitHubCommitAuthor | null { const identity = this.getBotIdentitySync(); if (!identity) return null; return { name: identity.login, email: identity.email, date: new Date().toISOString() }; } getBotIdentitySync(): GitHubBotIdentity | null { const slug = this._appSlug; const login = this.getBotLogin(); if (!slug || !login || this._botUserId == null) return null; return { login, slug, userId: this._botUserId, email: `${this._botUserId}+${login}@users.noreply.github.com`, }; } async getBotIdentity(): Promise { if (!this._appAuth) return null; if (this._botUserId == null) await this.resolveBotUserId(); return this.getBotIdentitySync(); } buildCloneUrl(repo: string, token: string): string { const host = this.apiHost || 'github.com'; return `https://x-access-token:${encodeURIComponent(token)}@${host}/${repo}.git`; } async resolveBotUserId(): Promise { if (this._botUserId != null) return this._botUserId; const slug = this._appSlug; if (!slug) return null; const login = `${slug}[bot]`; const baseUrl = this.apiHost ? `https://${this.apiHost}/api/v3` : 'https://api.github.com'; try { const res = await this.fetchNative(`${baseUrl}/users/${encodeURIComponent(login)}`, { headers: { Accept: 'application/vnd.github+json' }, }); if (!res.ok) return null; const data = (await res.json()) as { id?: number }; if (typeof data.id === 'number') { this._botUserId = data.id; return data.id; } } catch { return null; } return null; } // ── Star ───────────────────────────────────────────────────────── async starRepo(repo: string) { return this.put(`/user/starred/${repo}`); } async unstarRepo(repo: string) { return this.del(`/user/starred/${repo}`); } async isStarred(repo: string): Promise { const r = await this.request({ method: 'GET', path: `/user/starred/${repo}` }); return r.ok; } // ── Fork ───────────────────────────────────────────────────────── async forkRepo(repo: string) { return this.post(`/repos/${repo}/forks`); } // ── GitHub App JWT + Installation Token ────────────────────────── /** 解析私钥:PEM字符串 或 文件路径 */ private resolvePrivateKey(): string { if (this._resolvedKey) return this._resolvedKey; if (!this._appAuth) throw new Error('未配置 App 认证'); let key = this._appAuth.privateKey; if (!key.includes('-----BEGIN')) { // 当作文件路径读取 key = fs.readFileSync(key, 'utf-8'); } this._resolvedKey = key; return key; } /** 生成 GitHub App JWT(有效期 10 分钟) */ static createJWT(appId: string | number, privateKey: string): string { const header = Buffer.from(JSON.stringify({ alg: 'RS256', typ: 'JWT' })).toString('base64url'); const now = Math.floor(Date.now() / 1000); const payload = Buffer.from(JSON.stringify({ iat: now - 60, exp: now + 600, iss: Number(appId), })).toString('base64url'); const signature = crypto .sign('sha256', Buffer.from(`${header}.${payload}`), privateKey) .toString('base64url'); return `${header}.${payload}.${signature}`; } /** 使用 JWT 获取指定 Installation 的 Access Token(有效期 1 小时) */ async refreshInstallationToken(installationId: number, { signal }: GhRequestLifetime = {}): Promise { signal?.throwIfAborted(); if (!this._appAuth) throw new Error('未配置 App 认证'); const key = this.resolvePrivateKey(); const jwt = GhClient.createJWT(this._appAuth.appId, key); const baseUrl = this.apiHost ? `https://${this.apiHost}/api/v3` : 'https://api.github.com'; const res = await this.fetchNative( `${baseUrl}/app/installations/${installationId}/access_tokens`, { method: 'POST', signal, headers: { Authorization: `Bearer ${jwt}`, Accept: 'application/vnd.github+json', }, }, ); if (!res.ok) { const body = await res.text(); throw new Error(`Installation Token 获取失败 (${res.status}): ${body}`); } const data = (await res.json()) as { token: string; expires_at: string }; signal?.throwIfAborted(); this.token = data.token; this._installationTokens.set(installationId, { token: data.token, expiresAt: new Date(data.expires_at).getTime(), }); } /** 发现所有 App 安装及其可访问的仓库 */ async syncInstallations({ signal }: GhRequestLifetime = {}): Promise { signal?.throwIfAborted(); if (!this._appAuth) return; const key = this.resolvePrivateKey(); const jwt = GhClient.createJWT(this._appAuth.appId, key); const baseUrl = this.apiHost ? `https://${this.apiHost}/api/v3` : 'https://api.github.com'; const listRes = await this.fetchNative(`${baseUrl}/app/installations`, { headers: { Authorization: `Bearer ${jwt}`, Accept: 'application/vnd.github+json' }, signal, }); if (!listRes.ok) { const errBody = await listRes.text(); throw new Error(`列出安装失败: ${listRes.status} - ${errBody}`); } const installations = (await listRes.json()) as Array<{ id: number; account: { login: string; type: string }; target_type: string; }>; signal?.throwIfAborted(); this._allInstallations = installations; this._repoToInstallation.clear(); for (const inst of installations) { try { await this.refreshInstallationToken(inst.id, { signal }); const cached = this._installationTokens.get(inst.id); if (!cached) continue; const repoRes = await this.fetchNative(`${baseUrl}/installation/repositories?per_page=100`, { headers: { Authorization: `Bearer ${cached.token}`, Accept: 'application/vnd.github+json' }, signal, }); if (repoRes.ok) { const data = (await repoRes.json()) as { repositories: Array<{ full_name: string }> }; signal?.throwIfAborted(); for (const repo of data.repositories) { this._repoToInstallation.set(repo.full_name.toLowerCase(), inst.id); } } } catch { signal?.throwIfAborted(); this.executionSignal?.throwIfAborted(); // 单个安装失败不影响其他 } } this._lastSyncTime = Date.now(); } /** 当前是否使用 App 认证 */ get isAppAuth(): boolean { return !!this._appAuth; } /** 所有已发现的安装 */ get installations() { return this._allInstallations; } /** App 的 slug(verifyAuth 后可用) */ private _appSlug: string | null = null; get appSlug(): string | null { return this._appSlug; } /** App 的 client_id(verifyAuth 后从 /app 获取,用于 Device Flow) */ private _clientId: string | null = null; /** Bot 机器用户 numeric id(/users/{slug}[bot]) */ private _botUserId: number | null = null; /** 确保 App 认证的 Installation Token 对指定 repo 有效,并返回 token */ async ensureInstallationTokenForRepo(repo: string): Promise { if (!this._appAuth) return this.token; await this.ensureTokenForRepo(repo); return this.token; } get clientId(): string | null { return this._clientId; } // ── 事件轮询 ───────────────────────────────────────────────────── /** * 获取仓库事件(支持 ETag 条件请求) * @returns events 数组 + 新 etag;若 304 未修改则 events 为空 */ async listRepoEvents( repo: string, etag?: string, ): Promise<{ events: any[]; etag: string | null }> { const token = await this.ensureTokenForRepo(repo); const args = ['api', `/repos/${repo}/events?per_page=30`, '--method', 'GET', '--include']; if (etag) args.push('-H', `If-None-Match: ${etag}`); try { const raw = await this.exec({ args, token }); // --include 输出包含 HTTP 头 + 空行 + body const sepIdx = raw.indexOf('\r\n\r\n'); const headerPart = sepIdx >= 0 ? raw.slice(0, sepIdx) : ''; const bodyPart = sepIdx >= 0 ? raw.slice(sepIdx + 4) : raw; const newEtag = headerPart.match(/etag:\s*"?([^"\r\n]+)"?/i)?.[1] || null; let events: any[]; try { events = JSON.parse(bodyPart); } catch { events = []; } return { events: Array.isArray(events) ? events : [], etag: newEtag }; } catch (err: unknown) { // 304 Not Modified — gh 会以非 0 退出码返回 const ghErr = err instanceof Error ? (err as Error & { stderr?: string; exitCode?: number }) : null; if (ghErr?.stderr?.includes('304') || (ghErr as { exitCode?: number } | null)?.exitCode === 1) { return { events: [], etag: etag || null }; } throw err; } } // ── Device Flow OAuth(多用户绑定) ────────────────────────────── /** * 第一步:请求设备码 * GitHub App 不需要 scope 参数(权限由 App 设置决定),OAuth App 可传 scope。 * 注意:Device Flow 端点在 github.com(而非 api.github.com),需确保网络可达。 * @returns device_code, user_code, verification_uri, expires_in, interval */ static async deviceFlowRequestCode(clientId: string, host?: string): Promise<{ device_code: string; user_code: string; verification_uri: string; expires_in: number; interval: number; }> { const baseUrl = host ? `https://${host}` : 'https://github.com'; const url = `${baseUrl}/login/device/code`; let res: Response; try { res = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Accept': 'application/json', }, body: JSON.stringify({ client_id: clientId }), signal: AbortSignal.timeout(15_000), }); } catch (e: unknown) { const errMsg = e instanceof Error ? e.message : String(e); const errCause = e instanceof Error ? (e as any).cause?.code : undefined; throw new Error( `Device Flow 请求失败: 无法连接 ${baseUrl} (${errCause || errMsg})。` + `Device Flow 需要访问 github.com(非 api.github.com),请检查网络/代理设置。`, ); } if (!res.ok) { const body = await res.text().catch(() => ''); const hint = res.status === 400 ? ' (请确认 GitHub App 已启用 Device Flow: Settings → Developer settings → GitHub Apps → General)' : ''; throw new Error(`Device Flow 请求失败: ${res.status}${body ? ' — ' + body : ''}${hint}`); } return res.json(); } /** * 第二步:轮询等待用户授权。 * 可通过 `signal` 取消;单次请求有超时;网络/JSON 等瞬时错误会重试到设备码过期为止。 */ static async deviceFlowPollToken({ clientId, deviceCode, interval = 5, expiresIn = 900, host, signal, requestTimeoutMs = 15_000, }: GhDeviceFlowPollRequest): Promise { const baseUrl = host ? `https://${host}` : 'https://github.com'; const deadline = Date.now() + expiresIn * 1000; let pollInterval = interval * 1000; while (true) { if (signal?.aborted) return { status: 'aborted' }; const remaining = deadline - Date.now(); if (remaining <= 0) return { status: 'expired' }; if (!await abortableDelay(Math.min(pollInterval, remaining), signal)) return { status: 'aborted' }; if (Date.now() >= deadline) return { status: 'expired' }; let data: Record; try { const timeout = AbortSignal.timeout(requestTimeoutMs); const res = await fetch(`${baseUrl}/login/oauth/access_token`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Accept': 'application/json', }, body: JSON.stringify({ client_id: clientId, device_code: deviceCode, grant_type: 'urn:ietf:params:oauth:grant-type:device_code', }), signal: signal ? AbortSignal.any([signal, timeout]) : timeout, }); data = await res.json() as Record; } catch { if (signal?.aborted) return { status: 'aborted' }; // Transient network / timeout / non-JSON response: keep polling until the deadline. continue; } if (!data || typeof data !== 'object') continue; if (typeof data.access_token === 'string' && data.access_token) { return { status: 'authorized', access_token: data.access_token, token_type: typeof data.token_type === 'string' ? data.token_type : 'bearer', scope: typeof data.scope === 'string' ? data.scope : '', }; } if (data.error === 'authorization_pending') continue; if (data.error === 'slow_down') { const next = Number(data.interval); pollInterval = (Number.isFinite(next) && next > 0 ? next : pollInterval / 1000 + 5) * 1000; continue; } if (data.error === 'expired_token') return { status: 'expired' }; if (data.error === 'access_denied') return { status: 'denied' }; if (typeof data.error === 'string') { return { status: 'error', error: typeof data.error_description === 'string' ? data.error_description : data.error }; } // No token and no error (e.g. a 5xx JSON body): treat as transient. } } } export interface GhDeviceFlowPollRequest { readonly clientId: string; readonly deviceCode: string; /** Seconds between polls (GitHub default 5). */ readonly interval?: number; /** Seconds until the device code expires (GitHub default 900). */ readonly expiresIn?: number; readonly host?: string; readonly signal?: AbortSignal; readonly requestTimeoutMs?: number; } export type GhDeviceFlowPollResult = | { readonly status: 'authorized'; readonly access_token: string; readonly token_type: string; readonly scope: string } | { readonly status: 'expired' | 'denied' | 'aborted' } | { readonly status: 'error'; readonly error: string }; /** Resolves true after `ms`, or false as soon as `signal` aborts. */ function abortableDelay(ms: number, signal?: AbortSignal): Promise { return new Promise((resolve) => { if (signal?.aborted) { resolve(false); return; } const onAbort = () => { clearTimeout(timer); resolve(false); }; const timer = setTimeout(() => { signal?.removeEventListener('abort', onAbort); resolve(true); }, ms); signal?.addEventListener('abort', onAbort, { once: true }); }); }