openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
324 lines (323 loc) • 12.5 kB
JavaScript
import { n as withOpenAIOAuthResponse, t as createOpenAIAuthorizationCodeForm } from "./openai-oauth-http.runtime-CBVTbRsf.mjs";
import { asOptionalRecord, isRecord, normalizeBoundedOptionalString, normalizeOptionalString } from "openclaw/plugin-sdk/string-coerce-runtime";
import { createOAuthLoginCancelledError, createOAuthRefreshError, createOAuthRefreshResponseError, generatePKCE, oauthErrorHtml, oauthSuccessHtml, parseOAuthAuthorizationInput, resolveOAuthTokenExpiresAt, resolveOAuthTokenLifetimeMs, resolveOpenAICodexAuthIdentity, throwIfOAuthLoginAborted, withOAuthLoginAbort } from "openclaw/plugin-sdk/provider-oauth-runtime";
import { readResponseWithLimit } from "openclaw/plugin-sdk/response-limit-runtime";
import { createLazyRuntimeModule } from "openclaw/plugin-sdk/lazy-runtime";
import { redactSensitiveText } from "openclaw/plugin-sdk/security-runtime";
//#region extensions/openai/openai-chatgpt-oauth-authorization.runtime.ts
const CLIENT_ID$1 = "app_EMoamEEZ73f0CkXaXp7hrann";
const AUTHORIZE_URL = "https://auth.openai.com/oauth/authorize";
const CALLBACK_PORT = 1455;
const CALLBACK_PATH = "/auth/callback";
const DEFAULT_CALLBACK_HOST = "localhost";
const LOOPBACK_CALLBACK_HOSTS = /* @__PURE__ */ new Set([
"localhost",
"127.0.0.1",
"::1"
]);
const SCOPE = "openid profile email offline_access";
function resolveOpenAICallbackHost(e = process.env) {
const t = e.OPENCLAW_OAUTH_CALLBACK_HOST?.trim() || DEFAULT_CALLBACK_HOST;
if (!LOOPBACK_CALLBACK_HOSTS.has(t)) throw new Error("OpenAI Codex OAuth callback host must be localhost, 127.0.0.1, or ::1");
return t;
}
function resolveOpenAIRedirectUri(e) {
const t = new URL(`http://${e === "::1" ? "[::1]" : e}:${CALLBACK_PORT}`);
t.pathname = CALLBACK_PATH;
return t.toString();
}
async function createOpenAIAuthorizationFlow(e, t) {
if (typeof process === "undefined" || !process.versions?.node && !process.versions?.bun) throw new Error("OpenAI Codex OAuth is only available in Node.js environments");
const [{ verifier: n, challenge: r }, { randomBytes: i }] = await Promise.all([generatePKCE(), import("node:crypto")]);
const a = i(16).toString("hex");
const o = new URL(AUTHORIZE_URL);
o.searchParams.set("response_type", "code");
o.searchParams.set("client_id", CLIENT_ID$1);
o.searchParams.set("redirect_uri", t);
o.searchParams.set("scope", SCOPE);
o.searchParams.set("code_challenge", r);
o.searchParams.set("code_challenge_method", "S256");
o.searchParams.set("state", a);
o.searchParams.set("id_token_add_organizations", "true");
o.searchParams.set("codex_cli_simplified_flow", "true");
o.searchParams.set("originator", e);
return {
verifier: n,
redirectUri: t,
state: a,
url: o.toString()
};
}
//#endregion
//#region extensions/openai/openai-chatgpt-oauth-token.runtime.ts
const CLIENT_ID = "app_EMoamEEZ73f0CkXaXp7hrann";
const TOKEN_URL = "https://auth.openai.com/oauth/token";
const OAUTH_TOKEN_SSRF_POLICY = {
allowRfc2544BenchmarkRange: true,
allowIpv6UniqueLocalRange: true,
hostnameAllowlist: ["auth.openai.com"]
};
const TOKEN_REQUEST_TIMEOUT_MS = 3e4;
const OAUTH_TOKEN_RESPONSE_BODY_LIMIT_BYTES = 1048576;
const OAUTH_TOKEN_ERROR_SUMMARY_MAX_CHARS = 500;
const TOKEN_FAILURE_REASON_BY_CODE = {
invalid_grant: "invalid_grant",
invalid_refresh_token: "invalid_refresh_token",
refresh_token_expired: "expired",
refresh_token_invalidated: "token_invalidated",
refresh_token_reused: "refresh_token_reused"
};
const TOKEN_FAILURE_CODES = new Set(Object.keys(TOKEN_FAILURE_REASON_BY_CODE));
function normalizeTokenErrorSummary(e) {
const t = normalizeBoundedOptionalString(e, OAUTH_TOKEN_ERROR_SUMMARY_MAX_CHARS * 4)?.replace(/\s+/gu, " ").trim();
return t ? normalizeBoundedOptionalString(redactSensitiveText(t, { mode: "tools" }), OAUTH_TOKEN_ERROR_SUMMARY_MAX_CHARS) : void 0;
}
function normalizeTokenErrorFact(e, t) {
const n = normalizeOptionalString(e)?.toLowerCase();
return n && t.has(n) ? n : void 0;
}
function buildTokenResponseFailure(e) {
let t;
try {
t = asOptionalRecord(JSON.parse(e.text));
} catch {}
const n = asOptionalRecord(t?.error);
const r = normalizeTokenErrorFact(n?.code ?? (typeof t?.error === "string" ? t.error : t?.code), TOKEN_FAILURE_CODES);
const i = normalizeOptionalString(n?.type ?? t?.type)?.toLowerCase();
const a = i === "invalid_grant" || i === "invalid_request_error" ? i : void 0;
const o = r ? TOKEN_FAILURE_REASON_BY_CODE[r] : void 0;
const s = normalizeTokenErrorSummary(n?.message ?? t?.error_description ?? t?.message) ?? `OpenAI Codex token ${e.operation} failed (HTTP ${e.response.status}).`;
return {
type: "failed",
operation: e.operation,
summary: s,
status: e.response.status,
...e.operation === "refresh" ? { oauthRefreshOutcome: createOAuthRefreshResponseError("OpenAI token refresh", e.response.status, t).oauthRefreshOutcome } : {},
...r ? { code: r } : {},
...a ? { errorType: a } : {},
...o ? { reason: o } : {}
};
}
function formatMissingTokenResponseFields(e, t) {
const n = [];
if (!normalizeOptionalString(e.access_token)) n.push("access_token");
if (!(e.refresh_token === void 0 ? t : normalizeOptionalString(e.refresh_token))) n.push("refresh_token");
if (resolveOAuthTokenLifetimeMs(e.expires_in) === void 0) n.push("expires_in");
return n.join(", ");
}
function formatTokenRequestError(e, t, n, r) {
if (r?.aborted) return "Login cancelled";
if (t instanceof Error && (t.name === "AbortError" || t.name === "TimeoutError")) return `OpenAI Codex token ${e} timed out after ${n}ms`;
const i = normalizeTokenErrorSummary(t instanceof Error ? t.message : String(t));
return normalizeTokenErrorSummary(`OpenAI Codex token ${e} error${i ? `: ${i}` : ""}`) ?? `OpenAI Codex token ${e} error`;
}
async function requestOpenAIToken(e, t, n = {}, r) {
const i = n.timeoutMs ?? TOKEN_REQUEST_TIMEOUT_MS;
try {
throwIfOAuthLoginAborted(n.signal);
const { response: a, text: o } = await withOpenAIOAuthResponse({
url: TOKEN_URL,
mode: "trusted_env_proxy",
policy: OAUTH_TOKEN_SSRF_POLICY,
init: {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: e
},
timeoutMs: i,
signal: n.signal,
beforeRequest: n.assertCurrent,
auditContext: "openai-chatgpt-oauth-token"
}, async (e) => {
const t = await readResponseWithLimit(e, OAUTH_TOKEN_RESPONSE_BODY_LIMIT_BYTES, { onOverflow: ({ size: e, maxBytes: t }) => /* @__PURE__ */ new Error(`OpenAI Codex OAuth token response body too large: ${e} bytes (limit: ${t} bytes)`) });
return {
response: e,
text: new TextDecoder("utf-8", { fatal: true }).decode(t)
};
});
const s = readOpenAITokenResponse(a, o, t, r);
return s.type === "failed" && t === "refresh" ? {
...s,
oauthRefreshOutcome: s.oauthRefreshOutcome ?? {
version: 1,
phase: "after-token-response",
outcome: "unknown",
status: a.status
}
} : s;
} catch (e) {
return {
type: "failed",
operation: t,
...t === "refresh" ? { oauthRefreshOutcome: {
version: 1,
phase: "token-response",
outcome: "unknown"
} } : {},
...n.signal?.aborted ? { cancelled: true } : {},
summary: formatTokenRequestError(t, e, i, n.signal)
};
}
}
function readOpenAITokenResponse(e, t, n, r) {
if (!e.ok) return buildTokenResponseFailure({
response: e,
operation: n,
text: t
});
let i;
try {
i = JSON.parse(t);
} catch {
return {
type: "failed",
operation: n,
summary: `OpenAI Codex token ${n} failed: response is not valid JSON`
};
}
if (!isRecord(i)) return {
type: "failed",
operation: n,
summary: `OpenAI Codex token ${n} failed: expected JSON object response`
};
if (i.error !== void 0) return buildTokenResponseFailure({
response: e,
operation: n,
text: t
});
const a = resolveOAuthTokenExpiresAt(i.expires_in);
const o = normalizeOptionalString(i.access_token);
const s = i.refresh_token === void 0 ? r : normalizeOptionalString(i.refresh_token);
if (!o || !s || a === void 0) return {
type: "failed",
operation: n,
summary: `OpenAI Codex token ${n} response missing fields: ${formatMissingTokenResponseFields(i, r)}`
};
return {
type: "success",
access: o,
refresh: s,
expires: a
};
}
async function exchangeOpenAIAuthorizationCode(e, t, n, r = {}) {
return await requestOpenAIToken(createOpenAIAuthorizationCodeForm({
clientId: CLIENT_ID,
code: e,
verifier: t,
redirectUri: n
}), "exchange", r);
}
async function refreshOpenAIAccessToken(e, t = {}) {
return await requestOpenAIToken(new URLSearchParams({
grant_type: "refresh_token",
refresh_token: e,
client_id: CLIENT_ID
}), "refresh", t, e);
}
//#endregion
//#region extensions/openai/openai-chatgpt-oauth-flow.runtime.ts
const CALLBACK_HOST = resolveOpenAICallbackHost();
const REDIRECT_URI = resolveOpenAIRedirectUri(CALLBACK_HOST);
const loadOAuthCallbackServer = createLazyRuntimeModule(() => import("openclaw/plugin-sdk/provider-auth-runtime").then(({ startProviderOAuthLoopbackCallbackServer: e }) => e));
function parseAuthorizationCode(e, t) {
const n = parseOAuthAuthorizationInput(e);
if (n.state && n.state !== t) throw new Error("State mismatch");
return n.code;
}
async function promptForAuthorizationCode(e, t) {
return parseAuthorizationCode(await e({ message: "Paste the authorization code (or full redirect URL):" }), t);
}
function resolveOpenAICredentials(e) {
if (e.type !== "success") {
if (e.cancelled) throw createOAuthLoginCancelledError();
const t = [
e.status ? `HTTP ${e.status}` : void 0,
e.code ? `code=${e.code}` : void 0,
e.errorType ? `type=${e.errorType}` : void 0
].filter((e) => Boolean(e));
const n = t.length > 0 ? `OpenAI Codex token ${e.operation} failed (${t.join("; ")}).` : void 0;
throw Object.assign(new Error([e.summary, n].filter(Boolean).join("\n\n")), {
...e.oauthRefreshOutcome ? { oauthRefreshOutcome: e.oauthRefreshOutcome } : {},
oauthRefreshFailure: {
summary: e.summary,
...e.errorType ? { errorType: e.errorType } : {},
...e.reason ? { reason: e.reason } : {},
...e.status ? { status: e.status } : {}
}
});
}
const t = resolveOpenAICodexAuthIdentity({ access: e.access }).accountId;
if (!t) throw createOAuthRefreshError("Failed to extract accountId from token. Sign in again.", {
version: 1,
phase: "after-token-response",
outcome: "unknown"
});
return {
access: e.access,
refresh: e.refresh,
expires: e.expires,
accountId: t
};
}
async function loginOpenAICodex(e) {
e.assertCurrent?.();
throwIfOAuthLoginAborted(e.signal);
const { verifier: t, redirectUri: n, state: r, url: i } = await createOpenAIAuthorizationFlow(e.originator ?? "openclaw", REDIRECT_URI);
const a = await loadOAuthCallbackServer();
e.assertCurrent?.();
throwIfOAuthLoginAborted(e.signal);
let o;
try {
o = await a({
redirectUrl: REDIRECT_URI,
expectedState: r,
bindOnlyHostname: CALLBACK_HOST,
signal: e.signal,
renderSuccess: () => ({
body: oauthSuccessHtml("OpenAI authentication completed. You can close this window."),
contentType: "text/html; charset=utf-8"
}),
renderError: (e) => ({
body: oauthErrorHtml(e),
contentType: "text/html; charset=utf-8"
})
});
} catch {
e.assertCurrent?.();
throwIfOAuthLoginAborted(e.signal);
}
const waitForLogin = (t) => withOAuthLoginAbort(t, e.signal);
let s;
try {
e.assertCurrent?.();
throwIfOAuthLoginAborted(e.signal);
await waitForLogin(Promise.resolve(e.onAuth({
url: i,
instructions: "A browser window should open. Complete login to finish."
})));
throwIfOAuthLoginAborted(e.signal);
const a = o?.waitForCallback().then((e) => {
if (e.type === "oauth_error") throw new Error("OpenAI authorization was not completed.");
return e.code;
});
a?.catch(() => void 0);
const c = e.onManualCodeInput().then((e) => parseAuthorizationCode(e, r), (e) => {
throw e instanceof Error ? e : new Error(String(e));
});
s = await waitForLogin(a ? Promise.race([a, c]) : c);
if (!s) s = await waitForLogin(promptForAuthorizationCode(e.onPrompt, r));
if (!s) throw new Error("Missing authorization code");
return resolveOpenAICredentials(await exchangeOpenAIAuthorizationCode(s, t, n, {
signal: e.signal,
assertCurrent: e.assertCurrent
}));
} finally {
await o?.close();
}
}
async function refreshOpenAICodexToken(e) {
return resolveOpenAICredentials(await refreshOpenAIAccessToken(e));
}
//#endregion
export { refreshOpenAICodexToken as n, loginOpenAICodex as t };