UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

163 lines (162 loc) • 6.1 kB
import { O as positiveSecondsToSafeMilliseconds, R as resolveTimerTimeoutMs, b as nonNegativeSecondsToSafeMilliseconds } from "./number-coercion-D6u-4YD8.mjs"; import { d as sleepWithAbort } from "./src-BPmQBLJp.mjs"; import { h as readProviderJsonResponse } from "./provider-http-errors-Dtgw3x-5.mjs"; import { r as fetchWithSsrFGuard } from "./fetch-guard-BLMw2n18.mjs"; import "./ssrf-runtime-B6q6NM4E.mjs"; import "./retry-runtime-DOUvdfOa.mjs"; import "./number-runtime-W4chuk8B.mjs"; import "./provider-http-LcawLneq.mjs"; import { r as normalizeGithubCopilotDomain, t as PUBLIC_GITHUB_COPILOT_DOMAIN } from "./domain-CmrCAfb-.mjs"; //#region extensions/github-copilot/login.ts const CLIENT_ID = "Iv1.b507a08c87ecfe98"; const GITHUB_DEVICE_FLOW_REQUEST_TIMEOUT_MS = 3e4; const GITHUB_DEVICE_FLOW_DEFAULT_INTERVAL_MS = 5e3; const GITHUB_DEVICE_FLOW_SLOW_DOWN_INCREMENT_MS = 5e3; const deviceCodeUrl = (e) => `https://${e}/login/device/code`; const accessTokenUrl = (e) => `https://${e}/login/oauth/access_token`; const deviceVerificationUrl = (e) => `https://${e}/login/device`; const githubAuthSsrfPolicy = (e) => ({ hostnameAllowlist: [e] }); function parseJsonResponse(e) { if (!e || typeof e !== "object") throw new Error("Unexpected response from GitHub"); return e; } function parseDeviceCodeResponse(e, t) { const n = positiveSecondsToSafeMilliseconds(e.expires_in); const r = e.interval === void 0 ? GITHUB_DEVICE_FLOW_DEFAULT_INTERVAL_MS : nonNegativeSecondsToSafeMilliseconds(e.interval); const i = n === void 0 ? void 0 : t + n; if (typeof e.device_code !== "string" || !e.device_code || typeof e.user_code !== "string" || !e.user_code || typeof e.verification_uri !== "string" || !e.verification_uri || n === void 0 || i === void 0 || r === void 0) throw new Error("GitHub device code response missing fields"); return { deviceCode: e.device_code, userCode: e.user_code, verificationUri: e.verification_uri, expiresInMs: n, deadlineMs: i, intervalMs: r }; } async function sleepGitHubDevicePollDelay(e, t, n) { const r = Math.max(1, Math.floor(e)); const i = Math.min(performance.now() + r, t); while (performance.now() < i) { const e = Math.max(1, i - performance.now()); const t = resolveTimerTimeoutMs(e, 1); await sleepWithAbort(Math.min(t, e), n).catch(() => { throw n?.reason instanceof Error ? n.reason : /* @__PURE__ */ new Error("GitHub login cancelled"); }); } } function normalizeGitHubDeviceVerificationUrl(e, t) { const n = URL.parse(e); if (!n) throw new Error("GitHub device flow returned an invalid verification URL"); if (n.protocol !== "https:" || n.hostname !== t || n.pathname !== "/login/device" || n.username || n.password) throw new Error("GitHub device flow returned an unexpected verification URL"); return deviceVerificationUrl(t); } function normalizeGitHubDeviceUserCode(e) { const t = e.trim(); if (!t || t.length > 64) throw new Error("GitHub device flow returned an invalid user code"); return t; } async function runGitHubCopilotDeviceFlow(e, t = PUBLIC_GITHUB_COPILOT_DOMAIN) { const n = normalizeGithubCopilotDomain(t); const assertCurrent = () => { e.signal?.throwIfAborted(); e.assertCurrent?.(); }; const postGitHubDeviceFlowForm = async (e) => { const { response: t, release: r } = await fetchWithSsrFGuard({ url: e.url, init: { method: "POST", headers: { Accept: "application/json", "Content-Type": "application/x-www-form-urlencoded" }, body: e.body }, ...e.signal ? { signal: e.signal } : {}, beforeRequest: assertCurrent, requireHttps: true, policy: githubAuthSsrfPolicy(n), auditContext: "github-copilot-device-flow", timeoutMs: GITHUB_DEVICE_FLOW_REQUEST_TIMEOUT_MS }); try { if (!t.ok) { await t.body?.cancel().catch(() => void 0); throw new Error(`${e.failureLabel}: HTTP ${t.status}`); } return parseJsonResponse(await readProviderJsonResponse(t, "github-copilot.device-flow")); } finally { await r(); } }; assertCurrent(); const requestDeviceCode = async () => { const { signal: t } = e; const r = new URLSearchParams({ client_id: CLIENT_ID, scope: "read:user" }); const i = await postGitHubDeviceFlowForm({ url: deviceCodeUrl(n), body: r, failureLabel: "GitHub device code failed", ...t ? { signal: t } : {} }); assertCurrent(); return parseDeviceCodeResponse(i, performance.now()); }; const r = await requestDeviceCode(); const i = normalizeGitHubDeviceVerificationUrl(r.verificationUri, n); const a = normalizeGitHubDeviceUserCode(r.userCode); assertCurrent(); await e.showCode({ verificationUrl: i, userCode: a, expiresInMs: r.expiresInMs }); assertCurrent(); try { await e.openUrl?.(i); } catch {} assertCurrent(); const { deviceCode: o, deadlineMs: s } = r; let c = Math.max(1e3, r.intervalMs); const { signal: l } = e; const u = new URLSearchParams({ client_id: CLIENT_ID, device_code: o, grant_type: "urn:ietf:params:oauth:grant-type:device_code" }); while (performance.now() < s) { await sleepGitHubDevicePollDelay(c, s, l); assertCurrent(); if (performance.now() >= s) break; const e = await postGitHubDeviceFlowForm({ url: accessTokenUrl(n), body: u, failureLabel: "GitHub device token failed", ...l ? { signal: l } : {} }); assertCurrent(); if ("access_token" in e) { if (typeof e.access_token === "string") return { status: "authorized", accessToken: e.access_token }; throw new Error("GitHub device flow returned an invalid access token"); } const t = e.error; if (t === "authorization_pending") continue; if (t === "slow_down") { c = Math.max(Math.min(Number.MAX_SAFE_INTEGER, c + GITHUB_DEVICE_FLOW_SLOW_DOWN_INCREMENT_MS), positiveSecondsToSafeMilliseconds(e.interval) ?? 0); continue; } if (t === "expired_token") return { status: "expired" }; if (t === "access_denied") return { status: "access_denied" }; throw new Error(`GitHub device flow error: ${t}`); } return { status: "expired" }; } //#endregion export { runGitHubCopilotDeviceFlow as t };