openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
179 lines (178 loc) • 6.87 kB
JavaScript
import { i as normalizeBoundedOptionalString, l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs";
import { a as asOptionalRecord, l as isRecord } from "./record-coerce-CVPuDqcc.mjs";
import { s as redactSensitiveText } from "./redact-Mj7pppxC.mjs";
import { n as createOAuthRefreshResponseError } from "./oauth-refresh-outcome-DGKa-Dzy.mjs";
import { i as readResponseWithLimit } from "./http-response-body-B-i_0116.mjs";
import { c as throwIfOAuthLoginAborted, o as resolveOAuthTokenExpiresAt, s as resolveOAuthTokenLifetimeMs } from "./provider-oauth-runtime-C_hG37Q1.mjs";
import "./string-coerce-runtime-BwAZZDf5.mjs";
import "./security-runtime-C-zE_Zy_.mjs";
import "./response-limit-runtime-DkiFHsEX.mjs";
import { n as withOpenAIOAuthResponse, t as createOpenAIAuthorizationCodeForm } from "./openai-oauth-http.runtime.js";
//#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
export { refreshOpenAIAccessToken as n, exchangeOpenAIAuthorizationCode as t };