openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
250 lines (249 loc) • 9.6 kB
JavaScript
import { L as resolvePositiveTimerTimeoutMs, j as resolveExpiresAtMsFromDurationOrEpoch, m as asSafeIntegerInRange, t as MAX_DATE_TIMESTAMP_MS } from "./number-coercion-D6u-4YD8.mjs";
import { d as sleepWithAbort } from "./src-BPmQBLJp.mjs";
import { n as createOAuthRefreshResponseError, t as createOAuthRefreshError } from "./oauth-refresh-outcome-DGKa-Dzy.mjs";
import { _ as readResponseTextLimited, h as readProviderJsonResponse } from "./provider-http-errors-Dtgw3x-5.mjs";
import { r as fetchWithSsrFGuard } from "./fetch-guard-BLMw2n18.mjs";
import { c as toFormUrlEncoded, s as generatePkceVerifierChallenge } from "./provider-openai-chatgpt-auth-Lx-WyDpB.mjs";
import "./provider-oauth-runtime-C_hG37Q1.mjs";
import { r as ensureGlobalUndiciEnvProxyDispatcher } from "./undici-global-dispatcher-CdeU188Q.mjs";
import "./ssrf-runtime-B6q6NM4E.mjs";
import "./number-runtime-W4chuk8B.mjs";
import "./runtime-env-D-Pa5lD6.mjs";
import "./provider-http-LcawLneq.mjs";
import "./provider-auth-D_oAZ3fr.mjs";
import { randomBytes, randomUUID } from "node:crypto";
//#region extensions/minimax/oauth.ts
const MINIMAX_OAUTH_CONFIG = {
cn: {
baseUrl: "https://api.minimaxi.com",
oauthBaseUrl: "https://account.minimaxi.com",
clientId: "78257093-7e40-4613-99e0-527b14b39113"
},
global: {
baseUrl: "https://api.minimax.io",
oauthBaseUrl: "https://account.minimax.io",
clientId: "78257093-7e40-4613-99e0-527b14b39113"
}
};
const MINIMAX_OAUTH_SCOPE = "group_id profile model.completion";
const MINIMAX_OAUTH_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:user_code";
const MINIMAX_RELATIVE_EXPIRY_SECONDS_THRESHOLD = 1e9;
const MINIMAX_ABSOLUTE_EXPIRY_MS_THRESHOLD = 0xe8d4a51000;
const MINIMAX_OAUTH_ERROR_BODY_LIMIT_BYTES = 8192;
const MINIMAX_OAUTH_FETCH_TIMEOUT_MS = 3e4;
function getOAuthEndpoints(e) {
const t = MINIMAX_OAUTH_CONFIG[e];
return {
codeEndpoint: `${t.oauthBaseUrl}/oauth2/device/code`,
tokenEndpoint: `${t.oauthBaseUrl}/oauth2/token`,
clientId: t.clientId,
baseUrl: t.baseUrl,
hostname: new URL(t.oauthBaseUrl).hostname
};
}
async function withMiniMaxOAuthResponse(e, t, n, r, i) {
const { response: a, release: o } = await fetchWithSsrFGuard({
url: t === "code" ? e.codeEndpoint : e.tokenEndpoint,
init: {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
Accept: "application/json",
...t === "code" ? { "x-request-id": randomUUID() } : {}
},
body: toFormUrlEncoded(n)
},
...i?.signal ? { signal: i.signal } : {},
beforeRequest: i?.assertCurrent,
timeoutMs: MINIMAX_OAUTH_FETCH_TIMEOUT_MS,
policy: { allowedHostnames: [e.hostname] },
auditContext: `minimax.oauth.${t}`
});
try {
return await r(a);
} finally {
await o();
}
}
async function parseMiniMaxOAuthTokenResponse(e, t) {
const n = await readResponseTextLimited(e, MINIMAX_OAUTH_ERROR_BODY_LIMIT_BYTES);
let r;
if (n) try {
r = JSON.parse(n);
} catch {
r = void 0;
}
if (t !== void 0 && (!e.ok || r?.error !== void 0 || r?.status === "error" || r?.base_resp?.status_code !== void 0 && r.base_resp.status_code !== 0)) throw createOAuthRefreshResponseError("MiniMax OAuth refresh", e.status, r);
if (!e.ok) return {
status: "error",
message: (r?.base_resp?.status_msg ?? n) || "MiniMax OAuth failed to parse response."
};
if (!r) return {
status: "error",
message: "MiniMax OAuth failed to parse response."
};
if (r.status === "error") return {
status: "error",
message: r.base_resp?.status_msg || "An error occurred. Please try again later"
};
if (r.status !== "success") return {
status: "pending",
message: "current user code is not authorized"
};
const i = r.refresh_token === void 0 ? t : r.refresh_token;
if (typeof r.access_token !== "string" || !r.access_token.trim() || typeof i !== "string" || !i.trim() || !r.expired_in) return {
status: "error",
message: "MiniMax OAuth returned incomplete token payload."
};
const a = resolveExpiresAtMsFromDurationOrEpoch(r.expired_in, {
nowMs: Date.now(),
relativeSecondsThreshold: MINIMAX_RELATIVE_EXPIRY_SECONDS_THRESHOLD,
absoluteMillisecondsThreshold: MINIMAX_ABSOLUTE_EXPIRY_MS_THRESHOLD
});
if (a === void 0) return {
status: "error",
message: "MiniMax OAuth returned invalid token expiry."
};
return {
status: "success",
token: {
access: r.access_token,
refresh: i,
expires: a,
resourceUrl: r.resource_url,
notification_message: r.notification_message
}
};
}
function resolveMiniMaxRegionFromBaseUrl(e) {
let t;
try {
t = new URL(e ?? "").hostname.toLowerCase();
} catch {
return;
}
if (t === "api.minimax.cn") return "cn";
return ["global", "cn"].find((e) => new URL(MINIMAX_OAUTH_CONFIG[e].baseUrl).hostname === t);
}
const MINIMAX_SIGN_IN_AGAIN = "Run `openclaw models auth login --provider minimax-portal` to sign in again.";
/**
* Refresh a MiniMax Portal OAuth credential at the token endpoint its login
* recorded. The refresh token is only sent back to that regional endpoint:
* credentials without a recorded endpoint (saved before refresh existed) and
* credentials whose configured base URL now names the other region are refused
* before any request, since either could send the token across regions.
*/
async function refreshMiniMaxPortalOAuthCredential(e, t) {
const n = ["global", "cn"].find((t) => getOAuthEndpoints(t).tokenEndpoint === e.tokenEndpoint);
if (!n) throw new Error(`MiniMax OAuth credential does not record the account region it was issued for. ${MINIMAX_SIGN_IN_AGAIN}`);
const r = resolveMiniMaxRegionFromBaseUrl(t);
if (r && r !== n) throw new Error(`MiniMax OAuth credential was issued for the ${n === "cn" ? "CN" : "Global"} region, but models.providers.minimax-portal.baseUrl now points to ${MINIMAX_OAUTH_CONFIG[r].baseUrl}. ${MINIMAX_SIGN_IN_AGAIN}`);
if (!e.refresh) throw new Error(`MiniMax OAuth credential has no refresh token. ${MINIMAX_SIGN_IN_AGAIN}`);
ensureGlobalUndiciEnvProxyDispatcher();
const i = getOAuthEndpoints(n);
const a = await withMiniMaxOAuthResponse(i, "refresh", {
grant_type: "refresh_token",
client_id: i.clientId,
refresh_token: e.refresh
}, (t) => parseMiniMaxOAuthTokenResponse(t, e.refresh));
if (a.status !== "success") throw createOAuthRefreshError("MiniMax OAuth refresh returned invalid credentials. Sign in again.", {
version: 1,
phase: "after-token-response",
outcome: "unknown"
});
return {
...e,
access: a.token.access,
refresh: a.token.refresh,
expires: a.token.expires
};
}
async function loginMiniMaxPortalOAuth(e) {
ensureGlobalUndiciEnvProxyDispatcher();
const t = e.region ?? "global";
const assertCurrent = () => {
e.signal?.throwIfAborted();
e.assertCurrent?.();
};
const { verifier: n, challenge: r } = generatePkceVerifierChallenge();
const i = randomBytes(16).toString("base64url");
const a = getOAuthEndpoints(t);
const o = await withMiniMaxOAuthResponse(a, "code", {
response_type: "code",
client_id: a.clientId,
scope: MINIMAX_OAUTH_SCOPE,
code_challenge: r,
code_challenge_method: "S256",
state: i
}, async (e) => {
if (!e.ok) {
const t = await readResponseTextLimited(e, MINIMAX_OAUTH_ERROR_BODY_LIMIT_BYTES);
throw new Error(`MiniMax OAuth authorization failed: ${t || e.statusText}`);
}
const t = await readProviderJsonResponse(e, "minimax.oauth-code");
if (!t.user_code || !t.verification_uri) throw new Error(t.error ?? "MiniMax OAuth authorization returned an incomplete payload (missing user_code or verification_uri).");
if (t.state !== i) throw new Error("MiniMax OAuth state mismatch: possible CSRF attack or session corruption.");
const n = asSafeIntegerInRange(t.expired_in, {
min: 1,
max: MAX_DATE_TIMESTAMP_MS
});
if (n === void 0) throw new Error("MiniMax OAuth authorization returned invalid expired_in.");
return {
...t,
expired_in: n
};
}, {
signal: e.signal,
assertCurrent
});
assertCurrent();
const s = o.verification_uri;
const c = [
`Open ${s} to approve access.`,
`If prompted, enter the code ${o.user_code}.`,
`Interval: ${o.interval ?? "default (2000ms)"}, Expires at: ${new Date(o.expired_in).toISOString()}`
];
try {
await e.openUrl(s);
} catch {}
assertCurrent();
if (e.deviceCode) await e.deviceCode({
title: "MiniMax OAuth",
code: o.user_code,
expiresInMinutes: Math.ceil((o.expired_in - Date.now()) / 6e4),
message: "Enter this one-time code to approve access."
});
else await e.note(c.join("\n"), "MiniMax OAuth");
assertCurrent();
let l = resolvePositiveTimerTimeoutMs(o.interval, 2e3);
const u = o.expired_in;
while (Date.now() < u) {
e.progress.update("Waiting for MiniMax OAuth approval…");
const t = await withMiniMaxOAuthResponse(a, "token", {
grant_type: MINIMAX_OAUTH_GRANT_TYPE,
client_id: a.clientId,
user_code: o.user_code,
code_verifier: n
}, parseMiniMaxOAuthTokenResponse, {
signal: e.signal,
assertCurrent
});
assertCurrent();
if (t.status === "success") return {
...t.token,
tokenEndpoint: a.tokenEndpoint
};
if (t.status === "error") throw new Error(t.message);
const r = Math.max(0, u - Date.now());
if (r <= 0) break;
e.signal?.throwIfAborted();
await sleepWithAbort(Math.min(l, r), e.signal).catch(() => {
throw e.signal?.reason instanceof Error ? e.signal.reason : /* @__PURE__ */ new Error("MiniMax login cancelled");
});
assertCurrent();
l = Math.max(l, 2e3);
}
throw new Error("MiniMax OAuth timed out before authorization completed.");
}
//#endregion
export { refreshMiniMaxPortalOAuthCredential as n, loginMiniMaxPortalOAuth as t };