UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

263 lines (262 loc) • 9.65 kB
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs"; import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs"; import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import { _ as readResponseTextLimited, h as readProviderJsonResponse } from "./provider-http-errors-Dtgw3x-5.mjs"; import { r as fetchWithSsrFGuard } from "./fetch-guard-BLMw2n18.mjs"; import { s as generatePkceVerifierChallenge } from "./provider-openai-chatgpt-auth-Lx-WyDpB.mjs"; import "./string-coerce-runtime-BwAZZDf5.mjs"; import "./ssrf-runtime-B6q6NM4E.mjs"; import "./error-runtime-BM740gJj.mjs"; import { n as buildApiKeyCredential } from "./provider-auth-helpers-ByDXB7Po.mjs"; import { c as startProviderOAuthLoopbackCallbackServer, n as generateHexOAuthState } from "./provider-auth-runtime-DYG2Fn1g.mjs"; import "./provider-http-LcawLneq.mjs"; import "./provider-auth-D_oAZ3fr.mjs"; import { n as applyOpenrouterConfig, t as OPENROUTER_DEFAULT_MODEL_REF } from "./onboard-Cb_MAG1R.mjs"; //#region extensions/openrouter/oauth.ts const PROVIDER_ID = "openrouter"; const OPENROUTER_OAUTH_METHOD_ID = "oauth"; const OPENROUTER_OAUTH_CHOICE_ID = "openrouter-oauth"; const OPENROUTER_OAUTH_AUTHORIZE_URL = "https://openrouter.ai/auth"; const OPENROUTER_OAUTH_TOKEN_URL = "https://openrouter.ai/api/v1/auth/keys"; const OPENROUTER_OAUTH_REDIRECT_URI = `http://localhost:3000/openrouter-oauth/callback`; const OPENROUTER_OAUTH_CODE_CHALLENGE_METHOD = "S256"; const OPENROUTER_OAUTH_TIMEOUT_MS = 3e5; const OPENROUTER_OAUTH_FETCH_TIMEOUT_MS = 3e4; const OPENROUTER_OAUTH_ERROR_BODY_LIMIT_BYTES = 8192; const OPENROUTER_OAUTH_PROFILE_ID = "openrouter:default"; function extractOpenRouterError(e) { if (typeof e === "string") return e.trim() || void 0; if (!isRecord(e)) return; const t = normalizeOptionalString(e.message) ?? normalizeOptionalString(e.error_description); if (t) return t; const n = e.error; if (typeof n === "string") return n.trim() || void 0; if (isRecord(n)) return normalizeOptionalString(n.message) ?? normalizeOptionalString(n.code); } async function readResponseBody(e) { if (e.ok) return await readProviderJsonResponse(e, "OpenRouter OAuth key exchange"); const t = await readResponseTextLimited(e, OPENROUTER_OAUTH_ERROR_BODY_LIMIT_BYTES).catch(() => ""); if (!t.trim()) return null; try { return JSON.parse(t); } catch { return t; } } function parseOpenRouterKeyResponse(e) { if (!isRecord(e)) throw new Error("OpenRouter OAuth key exchange returned an unexpected response."); const t = normalizeOptionalString(e.key); if (!t) throw new Error("OpenRouter OAuth key exchange returned no API key."); const n = normalizeOptionalString(e.user_id) ?? normalizeOptionalString(e.userId); return { key: t, ...n ? { userId: n } : {} }; } function requireOpenRouterOAuthState(e, t) { if (!e) throw new Error("Missing OpenRouter OAuth state. Paste the full redirect URL."); if (e !== t) throw new Error("OpenRouter OAuth state mismatch. Please retry login."); return e; } function parseOpenRouterOAuthCallbackInput(e, t) { const n = e.trim(); if (!n) throw new Error("No input provided."); const parseParams = (e) => { const n = requireOpenRouterOAuthState(normalizeOptionalString(e.get("state")), t); const r = normalizeOptionalString(e.get("error")); if (r) { const t = normalizeOptionalString(e.get("error_description")); throw new Error(`OpenRouter OAuth error: ${t ? `${r}: ${t}` : r}`); } const i = normalizeOptionalString(e.get("code")); if (!i) throw new Error("Missing 'code' parameter in redirect URL."); return { code: i, state: n }; }; try { return parseParams(new URL(n).searchParams); } catch (e) { if (e instanceof TypeError) { if (n.includes("code=") || n.includes("error=")) return parseParams(new URLSearchParams(n)); throw new Error("Paste the full OpenRouter redirect URL, not just the code.", { cause: e }); } throw e; } } async function promptForOpenRouterRedirect(e, t) { return parseOpenRouterOAuthCallbackInput(await e.prompter.text({ message: "Paste the OpenRouter redirect URL", placeholder: `${OPENROUTER_OAUTH_REDIRECT_URI}?state=...&code=...`, validate: (e) => { try { parseOpenRouterOAuthCallbackInput(e, t); return; } catch (e) { return formatErrorMessage(e); } } }), t).code; } async function loginOpenRouterOAuth(e) { const t = e.prompter.progress("Starting OpenRouter OAuth..."); try { const n = generatePkceVerifierChallenge(); const r = generateHexOAuthState(); const buildAuthorizationUrl = (e) => { const t = new URL(e); t.searchParams.set("state", r); const i = new URL(OPENROUTER_OAUTH_AUTHORIZE_URL); i.searchParams.set("callback_url", t.toString()); i.searchParams.set("code_challenge", n.challenge); i.searchParams.set("code_challenge_method", OPENROUTER_OAUTH_CODE_CHALLENGE_METHOD); return i.toString(); }; const i = await (async () => { if (e.oauth.authorize) return (await e.oauth.authorize({ state: r, timeoutMs: OPENROUTER_OAUTH_TIMEOUT_MS, buildAuthorizationUrl })).code; const n = buildAuthorizationUrl(OPENROUTER_OAUTH_REDIRECT_URI); await e.prompter.note(e.isRemote ? [ "Open this URL in your LOCAL browser.", "After signing in, paste the redirect URL back here.", "", `Redirect URI: ${OPENROUTER_OAUTH_REDIRECT_URI}` ].join("\n") : [ "Browser will open for OpenRouter authentication.", "If the callback does not auto-complete, paste the redirect URL.", "", `Redirect URI: ${OPENROUTER_OAUTH_REDIRECT_URI}` ].join("\n"), "OpenRouter OAuth"); if (e.isRemote) { e.runtime.log(`\nOpen this URL in your LOCAL browser:\n\n${n}\n`); await e.openUrl(n); await e.prompter.note(`Open this URL in your LOCAL browser:\n\n${n}`, "OpenRouter OAuth"); return await promptForOpenRouterRedirect(e, r); } let i; let a; try { try { i = await startProviderOAuthLoopbackCallbackServer({ redirectUrl: OPENROUTER_OAUTH_REDIRECT_URI, expectedState: r, timeoutMs: OPENROUTER_OAUTH_TIMEOUT_MS, ...e.signal ? { signal: e.signal } : {} }); t.update(`Waiting for OpenRouter OAuth callback on ${OPENROUTER_OAUTH_REDIRECT_URI}...`); } catch (n) { if (e.signal?.aborted) throw n; t.update("OAuth callback not detected; waiting for redirect URL..."); } try { await e.openUrl(n); e.runtime.log(`Open: ${n}`); } catch { e.runtime.log(`Open manually: ${n}`); } if (!i) return await promptForOpenRouterRedirect(e, r); try { try { a = await i.waitForCallback(); } finally { const e = i; i = void 0; await e.close(); } } catch (n) { if (e.signal?.aborted) throw n; t.update("OAuth callback not detected; waiting for redirect URL..."); return await promptForOpenRouterRedirect(e, r); } } finally { await i?.close(); } if (a.type === "oauth_error") { const e = a.errorDescription ? `${a.error}: ${a.errorDescription}` : a.error; throw new Error(`OpenRouter OAuth error: ${e}`); } return a.code; })(); t.update("Exchanging OpenRouter OAuth code..."); e.signal?.throwIfAborted(); e.assertCurrent?.(); const a = e.signal; const { response: o, release: s } = await fetchWithSsrFGuard({ url: OPENROUTER_OAUTH_TOKEN_URL, init: { method: "POST", headers: { "Content-Type": "application/json", Accept: "application/json" }, body: JSON.stringify({ code: i, code_verifier: n.verifier, code_challenge_method: OPENROUTER_OAUTH_CODE_CHALLENGE_METHOD }), signal: a ? AbortSignal.any([a, AbortSignal.timeout(OPENROUTER_OAUTH_FETCH_TIMEOUT_MS)]) : AbortSignal.timeout(OPENROUTER_OAUTH_FETCH_TIMEOUT_MS) }, beforeRequest: () => e.assertCurrent?.(), mode: "trusted_env_proxy", auditContext: "openrouter.oauth" }); let c; try { const e = await readResponseBody(o); if (!o.ok) { const t = extractOpenRouterError(e); throw new Error(`OpenRouter OAuth key exchange failed (${o.status})${t ? `: ${t}` : ""}`); } c = parseOpenRouterKeyResponse(e); } finally { await s(); } t.stop("OpenRouter credential received"); const l = { authFlow: "oauth-pkce", ...c.userId ? { userId: c.userId } : {} }; const u = { ...buildApiKeyCredential(PROVIDER_ID, c.key, l), displayName: c.userId ? `OpenRouter ${c.userId}` : "OpenRouter OAuth" }; return { profiles: [{ profileId: OPENROUTER_OAUTH_PROFILE_ID, credential: u }], configPatch: applyOpenrouterConfig(e.config), defaultModel: OPENROUTER_DEFAULT_MODEL_REF, notes: ["OpenRouter OAuth issued an OpenRouter API key for the default OpenRouter auth profile.", "Re-run OpenRouter OAuth to rotate that key or use the API-key setup path for a key you manage manually."] }; } catch (e) { t.stop("OpenRouter OAuth failed"); throw new Error(`OpenRouter OAuth failed: ${formatErrorMessage(e)}`, { cause: e }); } } function createOpenRouterOAuthAuthMethod() { return { id: OPENROUTER_OAUTH_METHOD_ID, label: "OpenRouter OAuth", hint: "Browser sign-in", kind: "oauth", wizard: { choiceId: OPENROUTER_OAUTH_CHOICE_ID, choiceLabel: "OpenRouter OAuth", choiceHint: "Browser sign-in", groupId: PROVIDER_ID, groupLabel: "OpenRouter", groupHint: "OAuth or API key", methodId: OPENROUTER_OAUTH_METHOD_ID, onboardingScopes: ["text-inference", "music-generation"], onboardingFeatured: true }, run: loginOpenRouterOAuth }; } //#endregion export { createOpenRouterOAuthAuthMethod as t };