openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
245 lines (244 loc) • 10.1 kB
JavaScript
import { l as normalizeOptionalString } from "../../string-coerce-CCIiB4H7.mjs";
import { M as resolveExpiresAtMsFromDurationSeconds, O as positiveSecondsToSafeMilliseconds } from "../../number-coercion-D6u-4YD8.mjs";
import { n as asNullableObjectRecord } from "../../record-coerce-CVPuDqcc.mjs";
import { a as extractErrorCode, r as collectErrorGraphCandidates } from "../../error-coercion-hDrHOSGy.mjs";
import { d as sleepWithAbort } from "../../src-BPmQBLJp.mjs";
import { _ as readResponseTextLimited } from "../../provider-http-errors-Dtgw3x-5.mjs";
import { c as shouldUseEnvHttpProxyForUrl } from "../../proxy-env-CZP0dXDG.mjs";
import { o as withTrustedEnvProxyGuardedFetchMode } from "../../fetch-guard-BLMw2n18.mjs";
import { r as resolveOpenAICodexAccessTokenExpiry } from "../../provider-openai-chatgpt-auth-Lx-WyDpB.mjs";
import "../../string-coerce-runtime-BwAZZDf5.mjs";
import { t as classifyTransientNetworkErrorCode } from "../../retry-runtime-DOUvdfOa.mjs";
import "../../number-runtime-W4chuk8B.mjs";
import "../../error-runtime-BM740gJj.mjs";
import "../../fetch-runtime-Dz-KqFMb.mjs";
import "../../provider-http-LcawLneq.mjs";
import "../../provider-auth-D_oAZ3fr.mjs";
import { n as withOpenAIOAuthResponse, t as createOpenAIAuthorizationCodeForm } from "../../openai-oauth-http.runtime-BpkH-j-4.mjs";
//#region extensions/openai/openai-chatgpt-device-code.ts
const OPENAI_AUTH_BASE_URL = "https://auth.openai.com";
const OPENAI_CODEX_CLIENT_ID = "app_EMoamEEZ73f0CkXaXp7hrann";
const OPENAI_CODEX_DEVICE_CODE_TIMEOUT_MS = 9e5;
const OPENAI_CODEX_DEVICE_REQUEST_TIMEOUT_MS = 3e4;
const OPENAI_CODEX_DEVICE_CODE_DEFAULT_INTERVAL_MS = 5e3;
const OPENAI_CODEX_DEVICE_CODE_MIN_INTERVAL_MS = 1e3;
const OPENAI_CODEX_DEVICE_CALLBACK_URL = `${OPENAI_AUTH_BASE_URL}/deviceauth/callback`;
const OPENAI_CODEX_DEVICE_ERROR_BODY_LIMIT_BYTES = 8192;
const OPENAI_CODEX_DEVICE_JSON_BODY_LIMIT_BYTES = 262144;
function resolveOpenAICodexDeviceCodeHeaders(e) {
const t = process.env.OPENCLAW_VERSION?.trim();
return {
"Content-Type": e,
originator: "openclaw",
...t ? { version: t } : {},
"User-Agent": t ? `openclaw/${t}` : "openclaw"
};
}
function parseJsonObject(e) {
try {
return asNullableObjectRecord(JSON.parse(e));
} catch {
return null;
}
}
function sanitizeDeviceCodeErrorText(e) {
const t = String.fromCharCode(27);
const n = new RegExp(`${t}\\[[\\u0020-\\u003f]*[\\u0040-\\u007e]`, "g");
const r = new RegExp(`${t}\\]8;;.*?${t}\\\\|${t}\\]8;;${t}\\\\`, "g");
const i = new RegExp(`[${String.fromCharCode(0)}-${String.fromCharCode(31)}${String.fromCharCode(127)}${String.fromCharCode(128)}-${String.fromCharCode(159)}]`, "g");
return e.replace(r, "").replace(n, "").replace(i, " ").replace(/\s+/g, " ").trim();
}
function resolveNextDeviceCodePollDelayMs(e, t) {
const n = Math.max(0, t - performance.now());
return Math.min(Math.max(e, OPENAI_CODEX_DEVICE_CODE_MIN_INTERVAL_MS), n);
}
function resolveDeviceCodePollRequestTimeoutMs(e) {
return Math.min(OPENAI_CODEX_DEVICE_REQUEST_TIMEOUT_MS, Math.max(0, e - performance.now()));
}
function isDeviceCodeOperationTimeoutError(e) {
return e instanceof Error && (e.name === "TimeoutError" || e.name === "AbortError");
}
function rethrowIfDeviceCodeCallerAborted(e, t) {
if (e?.aborted) throw e.reason instanceof Error ? e.reason : t;
}
function formatDeviceCodeError(e) {
const t = parseJsonObject(e.bodyText);
const n = normalizeOptionalString(t?.error);
const r = normalizeOptionalString(t?.error_description);
const i = n ? sanitizeDeviceCodeErrorText(n) : void 0;
const a = r ? sanitizeDeviceCodeErrorText(r) : void 0;
if (i && a) return `${e.prefix}: ${i} (${a})`;
if (i) return `${e.prefix}: ${i}`;
const o = sanitizeDeviceCodeErrorText(e.bodyText);
return o ? `${e.prefix}: HTTP ${e.status} ${o}` : `${e.prefix}: HTTP ${e.status}`;
}
async function runOpenAICodexDeviceRequest(e) {
const t = {
url: e.url,
fetchImpl: e.fetchFn,
init: e.init,
timeoutMs: e.timeoutMs,
...e.signal ? { signal: e.signal } : {},
beforeRequest: e.assertCurrent,
requireHttps: true,
auditContext: "openai-chatgpt-device-code"
};
return await withOpenAIOAuthResponse(shouldUseEnvHttpProxyForUrl(e.url) ? withTrustedEnvProxyGuardedFetchMode(t) : t, async (t) => ({
ok: t.ok,
status: t.status,
bodyText: await readResponseTextLimited(t, t.ok ? OPENAI_CODEX_DEVICE_JSON_BODY_LIMIT_BYTES : OPENAI_CODEX_DEVICE_ERROR_BODY_LIMIT_BYTES, { chunkTimeoutMs: e.timeoutMs })
}));
}
async function fetchOpenAICodexDeviceCode(e) {
try {
return await runOpenAICodexDeviceRequest({
...e,
timeoutMs: OPENAI_CODEX_DEVICE_REQUEST_TIMEOUT_MS
});
} catch (t) {
rethrowIfDeviceCodeCallerAborted(e.signal, t);
if (isDeviceCodeOperationTimeoutError(t)) throw new Error(`OpenAI device code ${e.timeoutOperation} timed out after ${OPENAI_CODEX_DEVICE_REQUEST_TIMEOUT_MS}ms`, { cause: t });
throw t;
}
}
async function loginOpenAICodexDeviceCode(e) {
const t = e.fetchFn ?? fetch;
e.onProgress?.("Requesting device code…");
const requestOpenAICodexDeviceCode = async () => {
const { signal: n, assertCurrent: r } = e;
n?.throwIfAborted();
const i = await fetchOpenAICodexDeviceCode({
fetchFn: t,
url: `${OPENAI_AUTH_BASE_URL}/api/accounts/deviceauth/usercode`,
init: {
method: "POST",
headers: resolveOpenAICodexDeviceCodeHeaders("application/json"),
body: JSON.stringify({ client_id: OPENAI_CODEX_CLIENT_ID })
},
timeoutOperation: "user code request",
...n ? { signal: n } : {},
assertCurrent: r
});
if (!i.ok) {
if (i.status === 404) throw new Error("OpenAI Codex device code login is not enabled for this server. Use ChatGPT OAuth instead.");
throw new Error(formatDeviceCodeError({
prefix: "OpenAI device code request failed",
status: i.status,
bodyText: i.bodyText
}));
}
const a = parseJsonObject(i.bodyText);
const o = normalizeOptionalString(a?.device_auth_id);
const s = normalizeOptionalString(a?.user_code) ?? normalizeOptionalString(a?.usercode);
if (!o || !s) throw new Error("OpenAI device code response was missing the device code or user code.");
return {
deviceAuthId: o,
userCode: s,
verificationUrl: `${OPENAI_AUTH_BASE_URL}/codex/device`,
intervalMs: positiveSecondsToSafeMilliseconds(a?.interval) ?? OPENAI_CODEX_DEVICE_CODE_DEFAULT_INTERVAL_MS
};
};
const n = await requestOpenAICodexDeviceCode();
await e.onVerification({
verificationUrl: n.verificationUrl,
userCode: n.userCode,
expiresInMs: OPENAI_CODEX_DEVICE_CODE_TIMEOUT_MS
});
e.onProgress?.("Waiting for device authorization…");
const pollOpenAICodexDeviceCode = async () => {
const { deviceAuthId: r, userCode: i, intervalMs: a } = n;
const { signal: o, assertCurrent: s } = e;
const c = performance.now() + OPENAI_CODEX_DEVICE_CODE_TIMEOUT_MS;
while (performance.now() < c) {
o?.throwIfAborted();
const e = resolveDeviceCodePollRequestTimeoutMs(c);
if (e <= 0) break;
let n;
try {
n = await runOpenAICodexDeviceRequest({
fetchFn: t,
url: `${OPENAI_AUTH_BASE_URL}/api/accounts/deviceauth/token`,
init: {
method: "POST",
headers: resolveOpenAICodexDeviceCodeHeaders("application/json"),
body: JSON.stringify({
device_auth_id: r,
user_code: i
})
},
timeoutMs: e,
...o ? { signal: o } : {},
assertCurrent: s
});
} catch (e) {
rethrowIfDeviceCodeCallerAborted(o, e);
if (isDeviceCodeOperationTimeoutError(e)) continue;
if (!collectErrorGraphCandidates(e, (e) => [e.cause]).some((e) => classifyTransientNetworkErrorCode(extractErrorCode(e)) !== void 0)) throw e;
}
if (n?.ok) {
const e = parseJsonObject(n.bodyText);
const t = normalizeOptionalString(e?.authorization_code);
const r = normalizeOptionalString(e?.code_verifier);
if (!t || !r) throw new Error("OpenAI device authorization response was missing the exchange code.");
return {
authorizationCode: t,
codeVerifier: r
};
}
if (n && n.status !== 403 && n.status !== 404) throw new Error(formatDeviceCodeError({
prefix: "OpenAI device authorization failed",
status: n.status,
bodyText: n.bodyText
}));
await waitForDeviceCodePoll(resolveNextDeviceCodePollDelayMs(a, c), o);
}
throw new Error("OpenAI device authorization timed out after 15 minutes.");
};
const r = await pollOpenAICodexDeviceCode();
e.onProgress?.("Exchanging device code…");
const exchangeOpenAICodexDeviceCode = async () => {
const { authorizationCode: n, codeVerifier: i } = r;
const { signal: a, assertCurrent: o } = e;
a?.throwIfAborted();
const s = await fetchOpenAICodexDeviceCode({
fetchFn: t,
url: `${OPENAI_AUTH_BASE_URL}/oauth/token`,
init: {
method: "POST",
headers: resolveOpenAICodexDeviceCodeHeaders("application/x-www-form-urlencoded"),
body: createOpenAIAuthorizationCodeForm({
code: n,
redirectUri: OPENAI_CODEX_DEVICE_CALLBACK_URL,
clientId: OPENAI_CODEX_CLIENT_ID,
verifier: i
})
},
timeoutOperation: "token exchange",
...a ? { signal: a } : {},
assertCurrent: o
});
if (!s.ok) throw new Error(formatDeviceCodeError({
prefix: "OpenAI device token exchange failed",
status: s.status,
bodyText: s.bodyText
}));
const c = parseJsonObject(s.bodyText);
const l = normalizeOptionalString(c?.access_token);
const u = normalizeOptionalString(c?.refresh_token);
if (!l || !u) throw new Error("OpenAI token exchange succeeded but did not return OAuth tokens.");
return {
access: l,
refresh: u,
expires: resolveExpiresAtMsFromDurationSeconds(c?.expires_in) ?? resolveOpenAICodexAccessTokenExpiry(l) ?? Date.now()
};
};
return await exchangeOpenAICodexDeviceCode();
}
function waitForDeviceCodePoll(e, t) {
t?.throwIfAborted();
return sleepWithAbort(Math.max(1, e), t).catch(() => {
throw t?.reason instanceof Error ? t.reason : /* @__PURE__ */ new Error("Device login cancelled");
});
}
//#endregion
export { loginOpenAICodexDeviceCode };