UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

907 lines (906 loc) • 36.2 kB
import { a as TOKEN_SHARING_ISSUER, c as TOKEN_SHARING_RESOURCE, i as TOKEN_SHARING_CLIENT_ID, l as TOKEN_SHARING_SCOPE, n as IDENTITY_AUTH_FLOW, o as TOKEN_SHARING_LEGACY_SCOPE, r as TOKEN_SHARING_AUTH_FLOW, s as TOKEN_SHARING_REDIRECT_URI, u as isSIWCAuthFlow } from "./provider-metadata-h9vYLGeZ.mjs"; import { n as withOpenAIOAuthResponse, t as createOpenAIAuthorizationCodeForm } from "./openai-oauth-http.runtime-CBVTbRsf.mjs"; import { t as OPENAI_DEFAULT_MODEL } from "./openai-provider-DOlwxx6u.mjs"; import { asOptionalRecord, isRecord, normalizeOptionalString } from "openclaw/plugin-sdk/string-coerce-runtime"; import { createOAuthRefreshError, createOAuthRefreshResponseError, generateOAuthState, generatePKCE, oauthErrorHtml, oauthSuccessHtml, resolveOAuthTokenExpiresAt, withOAuthLoginAbort } from "openclaw/plugin-sdk/provider-oauth-runtime"; import { createHash } from "node:crypto"; import { readResponseWithLimit } from "openclaw/plugin-sdk/response-limit-runtime"; import { buildOauthProviderAuthResult } from "openclaw/plugin-sdk/provider-auth-result"; import { startProviderOAuthLoopbackCallbackServer } from "openclaw/plugin-sdk/provider-auth-runtime"; //#region node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/buffer_utils.js const encoder = new TextEncoder(); const decoder = new TextDecoder(); const strictDecoder = new TextDecoder("utf-8", { fatal: !0 }); function concat(...e) { const t = e.reduce((e, { length: t }) => e + t, 0), n = new Uint8Array(t); let r = 0; for (const t of e) n.set(t, r), r += t.length; return n; } const NON_ASCII = /[^\x00-\x7f]/; function encode(e) { if (typeof e == "string" && e.length >= 128) { if (NON_ASCII.test(e)) throw new TypeError("non-ASCII string encountered in encode()"); return encoder.encode(e); } const t = new Uint8Array(e.length); for (let n = 0; n < e.length; n++) { const r = e.charCodeAt(n); if (r > 127) throw new TypeError("non-ASCII string encountered in encode()"); t[n] = r; } return t; } function decodeBase64(e, t = !1) { if (Uint8Array.fromBase64) return Uint8Array.fromBase64(e, { alphabet: t ? "base64url" : "base64" }); if (t) { if (e.includes("+") || e.includes("/")) throw new TypeError("Invalid base64url"); e = e.replace(/-/g, "+").replace(/_/g, "/"); } const n = atob(e), r = new Uint8Array(n.length); for (let e = 0; e < n.length; e++) r[e] = n.charCodeAt(e); return r; } //#endregion //#region node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/util/errors.js var JOSEError = class extends Error { static code = "ERR_JOSE_GENERIC"; code = "ERR_JOSE_GENERIC"; constructor(e, t) { super(e, t), this.name = this.constructor.name, Error.captureStackTrace?.(this, this.constructor); } }; var JWTClaimValidationFailed = class extends JOSEError { static code = "ERR_JWT_CLAIM_VALIDATION_FAILED"; code = "ERR_JWT_CLAIM_VALIDATION_FAILED"; claim; reason; payload; constructor(e, t, n = "unspecified", r = "unspecified") { super(e, { cause: { claim: n, reason: r, payload: t } }), this.claim = n, this.reason = r, this.payload = t; } }; var JWTExpired = class extends JOSEError { static code = "ERR_JWT_EXPIRED"; code = "ERR_JWT_EXPIRED"; claim; reason; payload; constructor(e, t, n = "unspecified", r = "unspecified") { super(e, { cause: { claim: n, reason: r, payload: t } }), this.claim = n, this.reason = r, this.payload = t; } }; var JOSEAlgNotAllowed = class extends JOSEError { static code = "ERR_JOSE_ALG_NOT_ALLOWED"; code = "ERR_JOSE_ALG_NOT_ALLOWED"; }; var JOSENotSupported = class extends JOSEError { static code = "ERR_JOSE_NOT_SUPPORTED"; code = "ERR_JOSE_NOT_SUPPORTED"; }; var JWSInvalid = class extends JOSEError { static code = "ERR_JWS_INVALID"; code = "ERR_JWS_INVALID"; }; var JWTInvalid = class extends JOSEError { static code = "ERR_JWT_INVALID"; code = "ERR_JWT_INVALID"; }; var JWKSInvalid = class extends JOSEError { static code = "ERR_JWKS_INVALID"; code = "ERR_JWKS_INVALID"; }; var JWKSNoMatchingKey = class extends JOSEError { static code = "ERR_JWKS_NO_MATCHING_KEY"; code = "ERR_JWKS_NO_MATCHING_KEY"; constructor(e = "no applicable key found in the JSON Web Key Set", t) { super(e, t); } }; var JWKSMultipleMatchingKeys = class extends JOSEError { [Symbol.asyncIterator] = async function* () {}; static code = "ERR_JWKS_MULTIPLE_MATCHING_KEYS"; code = "ERR_JWKS_MULTIPLE_MATCHING_KEYS"; constructor(e = "multiple matching keys found in the JSON Web Key Set", t) { super(e, t); } }; var JWSSignatureVerificationFailed = class extends JOSEError { static code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED"; code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED"; constructor(e = "signature verification failed", t) { super(e, t); } }; //#endregion //#region node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/util/base64url.js const invalid = "The input to be decoded is not correctly encoded."; function decode(e) { try { return decodeBase64(typeof e == "string" ? e : decoder.decode(e), !0); } catch (e) { throw new TypeError(invalid, { cause: e }); } } //#endregion //#region node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/validate.js function isObject(e) { if (typeof e != "object" || e === null || Object.prototype.toString.call(e) !== "[object Object]") return !1; const t = Object.getPrototypeOf(e); return t === null || Object.getPrototypeOf(t) === null; } function isJwkSet(e) { return isObject(e) && Array.isArray(e.keys) && Array.from(e.keys).every(isObject); } function isDisjoint(...e) { const t = /* @__PURE__ */ new Set(); for (const n of e) if (n) for (const e of Object.keys(n)) { if (t.has(e)) return !1; t.add(e); } return !0; } function decodeBase64url(e, t, n) { try { return decode(e); } catch { throw new n(`Failed to base64url decode the ${t}`); } } function encodeBase64url(e, t, n) { try { return encode(e); } catch { throw new n(`The ${t} is not a valid base64url string`); } } function parseJoseHeader(e, t, n) { let r; try { r = JSON.parse(strictDecoder.decode(decode(e))); } catch { throw new t(n); } if (!isObject(r)) throw new t(n); return r; } const JWS_RECOGNIZED = { __proto__: null, b64: !0 }; function validateAlgorithms(e, t) { if (t !== void 0 && (!Array.isArray(t) || t.some((e) => typeof e != "string"))) throw new TypeError(`"${e}" option must be an array of strings`); return t === void 0 ? void 0 : new Set(t); } function validateCrit(e, t, n, r, i) { if (i.crit !== void 0 && r?.crit === void 0) throw new e("\"crit\" (Critical) Header Parameter MUST be integrity protected"); if (!r || r.crit === void 0) return []; if (!Array.isArray(r.crit) || r.crit.length === 0 || r.crit.some((e) => typeof e != "string" || e.length === 0)) throw new e("\"crit\" (Critical) Header Parameter MUST be an array of non-empty strings when present"); const a = n === void 0 ? t : { __proto__: null, ...n, ...t }; for (const t of r.crit) { if (!(t in a)) throw new JOSENotSupported(`Extension Header Parameter "${t}" is not recognized`); if (!Object.hasOwn(i, t) || i[t] === void 0) throw new e(`Extension Header Parameter "${t}" is missing`); if (a[t] && (!Object.hasOwn(r, t) || r[t] === void 0)) throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`); } return r.crit; } function validateB64(e, t) { if (t.includes("b64")) { const t = e.b64; if (typeof t != "boolean") throw new JWSInvalid("The \"b64\" (base64url-encode payload) Header Parameter must be a boolean"); return t; } return !0; } //#endregion //#region node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/key.js const tag = (e) => e[Symbol.toStringTag]; const jwkMatchesOp = (e, t, n) => { const { alg: r } = e; if (t.use !== void 0) { const e = n === "sign" || n === "verify" ? "sig" : "enc"; if (t.use !== e) throw new TypeError(`Invalid key for this operation, its "use" must be "${e}" when present`); } if (t.alg !== void 0 && t.alg !== r) throw new TypeError(`Invalid key for this operation, its "alg" must be "${r}" when present`); if (Array.isArray(t.key_ops)) { const r = n === "encrypt" || n === "decrypt" ? e.ops?.[n === "encrypt" ? 0 : 1] : n; if (r && !t.key_ops.includes(r)) throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${r}" when present`); } }; async function prepareKey(e, t, n) { const { alg: r, secret: i } = e, a = n === "decrypt" || n === "sign"; if (i && t instanceof Uint8Array) return t; let o, s; if (isObject(t)) { if (o = normalizeJwk(t), typeof o.kty != "string") throw invalidKeyType(r, t, i); if (!(i ? o.kty === "oct" && typeof o.k == "string" : o.kty !== "oct" && (a ? o.kty === "AKP" && typeof o.priv == "string" || typeof o.d == "string" : o.d === void 0 && o.priv === void 0))) throw new TypeError(i ? "JSON Web Key for symmetric algorithms must have JWK \"kty\" (Key Type) equal to \"oct\" and the JWK \"k\" (Key Value) present" : `JSON Web Key for this operation must be a ${a ? "private" : "public"} JWK`); if (jwkMatchesOp(e, o, n), o.kty === "oct") return decode(o.k); if (!Object.isFrozen(t)) { const { key_ops: e } = t; Array.isArray(e) && Object.freeze(e), Object.freeze(t); } } else { if (!isKeyLike(t)) throw invalidKeyType(r, t, i); const e = i ? "secret" : a ? "private" : "public"; if (t.type !== e && (i || [ "secret", "public", "private" ].includes(t.type))) throw new TypeError(`${tag(t)} instances must be of type "${e}" for the ${r} algorithm`); if (isCryptoKey(t)) return t; if (s = t, s.type === "secret") return s.export(); } cache ||= /* @__PURE__ */ new WeakMap(); const c = t; let l = cache.get(c); if (l?.[r]) return l[r]; if (l || cache.set(c, l = {}), s && typeof s.toCryptoKey == "function") { const t = s.type === "public", n = nist[s.asymmetricKeyDetails?.namedCurve], i = e.resolve?.({ crv: n, asymmetricKeyType: s.asymmetricKeyType }) ?? e.subtle; return l[r] = s.toCryptoKey(i, t, e.usages[t ? 0 : 1]); } return o ??= s.export({ format: "jwk" }), o.alg = r, l[r] = await jwkToKey(e, o); } let cache; const nist = { __proto__: null, prime256v1: "P-256", secp384r1: "P-384", secp521r1: "P-521" }; const isCryptoKey = (e) => { if (e?.[Symbol.toStringTag] === "CryptoKey") return !0; try { return e instanceof CryptoKey; } catch { return !1; } }; const isKeyObject = (e) => e?.[Symbol.toStringTag] === "KeyObject"; const isKeyLike = (e) => isCryptoKey(e) || isKeyObject(e); function message(e, t, ...n) { if (n.length > 2) { const t = n.pop(); e += `one of type ${n.join(", ")}, or ${t}.`; } else n.length === 2 ? e += `one of type ${n[0]} or ${n[1]}.` : e += `of type ${n[0]}.`; return t == null ? e += ` Received ${t}` : typeof t == "function" && t.name ? e += ` Received function ${t.name}` : typeof t == "object" && t != null && t.constructor?.name && (e += ` Received an instance of ${t.constructor.name}`), e; } function invalidKeyType(e, t, n) { const r = [ "CryptoKey", "KeyObject", "JSON Web Key" ]; return n && r.push("Uint8Array"), new TypeError(message(`Key for the ${e} algorithm must be `, t, ...r)); } const unusable = (e, t = "algorithm.name") => /* @__PURE__ */ new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`); function checkUsage(e, t) { if (t && !e.usages.includes(t)) throw new TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`); } function checkModulusLength(e, t) { const { modulusLength: n } = t.algorithm; if (typeof n != "number" || n < 2048) throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`); } function checkCryptoKey(e, t, n) { const r = e.algorithm; if (r.name !== t.name) throw unusable(t.name); if (t.hash && r.hash?.name !== t.hash) throw unusable(t.hash, "algorithm.hash"); if (t.namedCurve && r.namedCurve !== t.namedCurve) throw unusable(t.namedCurve, "algorithm.namedCurve"); if (t.length !== void 0 && r.length !== t.length) throw unusable(t.length, "algorithm.length"); checkUsage(e, n); } function snapshotJwk(e) { return { __proto__: null, ...e }; } function normalizeJwk(e) { const t = snapshotJwk(e); if (t.ext !== void 0 && typeof t.ext != "boolean") throw new TypeError("\"ext\" (Extractable) Parameter must be a boolean"); if (t.key_ops !== void 0) { const e = t.key_ops, n = Array.isArray(e) ? [...e] : void 0; if (!n || n.some((e) => typeof e != "string") || new Set(n).size !== n.length) throw new TypeError("\"key_ops\" (Key Operations) Parameter must be an array of unique strings"); t.key_ops = n; } return t; } async function jwkToKey(e, t, n) { if (!e.kty.includes(t.kty)) throw new JOSENotSupported("Invalid or unsupported JWK \"alg\" (Algorithm) Parameter value"); const r = e.resolve?.({ kty: t.kty, crv: t.crv }) ?? e.subtle, i = !!(t.d || t.priv), a = { ...t, ext: n ?? t.ext }; return a.kty !== "AKP" && delete a.alg, delete a.use, crypto.subtle.importKey("jwk", a, r, a.ext ?? !i, t.key_ops ?? e.usages[i ? 1 : 0]); } async function rawKey(e, t, n, r = !1) { return e instanceof Uint8Array && (e = await crypto.subtle.importKey("raw", e, t, r, [n])), checkCryptoKey(e, t, n), e; } //#endregion //#region node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/key_descriptor.js function table(e) { const t = { __proto__: null }; for (const n in e) t[n] = { ...e[n], alg: n }; return t; } //#endregion //#region node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/jws_algorithms.js const sig = [["verify"], ["sign"]]; function hmac(e) { const t = { name: "HMAC", hash: `SHA-${e}` }; return { kty: ["oct"], secret: !0, subtle: t, signing: t, usages: sig }; } function rsa(e, t) { const n = { name: t ? "RSA-PSS" : "RSASSA-PKCS1-v1_5", hash: `SHA-${e}` }; return { kty: ["RSA"], subtle: n, signing: t ? { ...n, saltLength: t } : n, usages: sig, minRsaBits: 2048 }; } function ecdsa(e, t) { return { kty: ["EC"], crv: e, subtle: { name: "ECDSA", namedCurve: e }, signing: { name: "ECDSA", hash: `SHA-${t}` }, usages: sig }; } function eddsa() { const e = { name: "Ed25519" }; return { kty: ["OKP"], crv: "Ed25519", subtle: e, signing: e, usages: sig }; } function mldsa(e) { const t = { name: `ML-DSA-${e}` }; return { kty: ["AKP"], subtle: t, signing: t, usages: sig }; } const JWS = table({ HS256: hmac(256), HS384: hmac(384), HS512: hmac(512), RS256: rsa(256), RS384: rsa(384), RS512: rsa(512), PS256: rsa(256, 32), PS384: rsa(384, 48), PS512: rsa(512, 64), ES256: ecdsa("P-256", 256), ES384: ecdsa("P-384", 384), ES512: ecdsa("P-521", 512), EdDSA: eddsa(), Ed25519: eddsa(), "ML-DSA-44": mldsa(44), "ML-DSA-65": mldsa(65), "ML-DSA-87": mldsa(87) }); function jwsAlgorithm(e) { const t = typeof e == "string" ? JWS[e] : void 0; if (!t) throw new JOSENotSupported(`alg ${e} is not supported either by JOSE or your javascript runtime`); return t; } //#endregion //#region node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/jws_verify.js function prepareVerify(e) { return [e && validateAlgorithms("algorithms", e.algorithms), e?.crit]; } function parseProtectedHeader(e) { return e === void 0 ? {} : parseJoseHeader(e, JWSInvalid, "JWS Protected Header is invalid"); } function encodeCompactUnencodedPayload(e) { try { return encode(e); } catch { throw new JWSInvalid("JWS Compact Serialization payload must use only ASCII characters"); } } async function verifySignature(e, t, n, r, i) { const { protected: a, header: o, payload: s } = e, c = i ?? parseProtectedHeader(a); if (!isDisjoint(c, o)) throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint"); const l = { ...c, ...o }, u = validateB64(c, validateCrit(JWSInvalid, JWS_RECOGNIZED, t[1], c, l)), { alg: d } = l; if (typeof d != "string" || !d) throw new JWSInvalid("JWS \"alg\" (Algorithm) Header Parameter missing or invalid"); if (t[0] && !t[0].has(d)) throw new JOSEAlgNotAllowed("\"alg\" (Algorithm) Header Parameter value not allowed"); if (u) { if (typeof s != "string") throw new JWSInvalid("JWS Payload must be a string"); } else if (typeof s != "string" && !(s instanceof Uint8Array)) throw new JWSInvalid("JWS Payload must be a string or an Uint8Array instance"); const f = u || typeof s != "string" ? s : r(s); let p = !1; typeof n == "function" && (n = await n(c, e), p = !0); const m = jwsAlgorithm(d), h = concat(a !== void 0 ? encode(a) : /* @__PURE__ */ new Uint8Array(), encode("."), typeof f == "string" ? t[2] ??= encodeBase64url(f, "payload", JWSInvalid) : f), g = decodeBase64url(e.signature, "signature", JWSInvalid), _ = await prepareKey(m, n, "verify"), v = await rawKey(_, m.subtle, "verify"); m.minRsaBits && checkModulusLength(m.alg, v); let y = !1; try { y = await crypto.subtle.verify(m.signing, v, g, h); } catch {} if (!y) throw new JWSSignatureVerificationFailed(); const b = { payload: typeof f == "string" ? decodeBase64url(f, "payload", JWSInvalid) : f }; return a !== void 0 && (b.protectedHeader = c), o !== void 0 && (b.unprotectedHeader = o), p ? [{ ...b, key: _ }, u] : [b, u]; } async function verifyCompact(e, t, n) { if (e instanceof Uint8Array && (e = decoder.decode(e)), typeof e != "string") throw new JWSInvalid("Compact JWS must be a string or Uint8Array"); const { 0: r, 1: i, 2: a, length: o } = e.split("."); if (o !== 3) throw new JWSInvalid("Invalid Compact JWS"); return verifySignature({ payload: i, protected: r, signature: a }, t, n, encodeCompactUnencodedPayload); } //#endregion //#region node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/jwt_claims_set.js const epoch = (e) => Math.floor(e.getTime() / 1e3); const multipliers = { s: 1, m: 60, h: 3600, d: 86400, w: 604800, y: 31557600 }; const REGEX = /^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i; const checkFailed = "check_failed"; function invalidDuration() { throw new TypeError("Invalid time period format"); } function secs(e) { typeof e != "string" && invalidDuration(); const t = REGEX.exec(e); (!t || t[4] && t[1]) && invalidDuration(); const n = parseFloat(t[2]), r = Math.round(n * multipliers[t[3][0].toLowerCase()]); return Number.isFinite(r) || invalidDuration(), t[1] === "-" || t[4] === "ago" ? -r : r; } function validateInput(e, t) { if (!Number.isFinite(t)) throw new TypeError(`Invalid ${e} input`); return t; } const normalizeTyp = (e) => { const t = e.toLowerCase(); return e.includes("/") ? t : `application/${t}`; }; const checkAudiencePresence = (e, t) => typeof e == "string" ? t.includes(e) : Array.isArray(e) ? t.some((t) => e.includes(t)) : !1; function validateNumericDate(e, t, n = !1) { const r = e[t]; if (!(r === void 0 && !n)) { if (typeof r != "number") throw new JWTClaimValidationFailed(`"${t}" claim must be a number`, e, t, "invalid"); return r; } } function unexpectedClaim(e, t) { throw new JWTClaimValidationFailed(`unexpected "${t}" claim value`, e, t, checkFailed); } function validateClaimsSet(e, t, n = {}) { let r; try { r = JSON.parse(strictDecoder.decode(t)); } catch {} if (!isObject(r)) throw new JWTInvalid("JWT Claims Set must be a top-level JSON object"); const { typ: i } = n; if (i !== void 0 && (typeof e.typ != "string" || normalizeTyp(e.typ) !== normalizeTyp(i))) throw new JWTClaimValidationFailed("unexpected \"typ\" JWT header value", r, "typ", checkFailed); const { requiredClaims: a = [], issuer: o, subject: s, audience: c, maxTokenAge: l } = n, u = [...a]; l !== void 0 && u.push("iat"), c !== void 0 && u.push("aud"), s !== void 0 && u.push("sub"), o !== void 0 && u.push("iss"); for (const e of new Set(u.reverse())) if (!Object.hasOwn(r, e)) throw new JWTClaimValidationFailed(`missing required "${e}" claim`, r, e, "missing"); o !== void 0 && !(Array.isArray(o) ? o : [o]).includes(r.iss) && unexpectedClaim(r, "iss"), s !== void 0 && r.sub !== s && unexpectedClaim(r, "sub"), c !== void 0 && !checkAudiencePresence(r.aud, typeof c == "string" ? [c] : c) && unexpectedClaim(r, "aud"); const { clockTolerance: d } = n; let f = 0; if (typeof d == "string") f = secs(d); else if (d !== void 0) { if (typeof d != "number") throw new TypeError("Invalid clockTolerance option type"); f = d; } validateInput("clockTolerance option", f); const { currentDate: p } = n, m = validateInput("currentDate option", epoch(p === void 0 ? /* @__PURE__ */ new Date() : p)), h = validateNumericDate(r, "iat", l !== void 0), g = validateNumericDate(r, "nbf"); if (g !== void 0 && g > m + f) throw new JWTClaimValidationFailed("\"nbf\" claim timestamp check failed", r, "nbf", checkFailed); const _ = validateNumericDate(r, "exp"); if (_ !== void 0 && _ <= m - f) throw new JWTExpired("\"exp\" claim timestamp check failed", r, "exp", checkFailed); if (l !== void 0) { const e = m - h, t = validateInput("maxTokenAge option", typeof l == "number" ? l : secs(l)); if (e - f > t) throw new JWTExpired("\"iat\" claim timestamp check failed (too far in the past)", r, "iat", checkFailed); if (e < -f) throw new JWTClaimValidationFailed("\"iat\" claim timestamp check failed (it should be in the past)", r, "iat", checkFailed); } return r; } //#endregion //#region node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/jwt/verify.js async function jwtVerify(e, t, n) { const [r, i] = await verifyCompact(e, prepareVerify(n), t); if (!i) throw new JWTInvalid("JWTs MUST NOT use unencoded payload"); const a = validateClaimsSet(r.protectedHeader, r.payload, n); return { ...r, payload: a }; } //#endregion //#region node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/jwks/local.js function isUsableJWK(e, t, n, r) { const { kty: i, key_ops: a, ext: o, kid: s, alg: c, use: l, crv: u } = e; return (o === void 0 || typeof o == "boolean") && (a === void 0 || Array.isArray(a) && a.every((e, t) => typeof e == "string" && a.indexOf(e) === t) && a.includes("verify")) && t.kty.includes(i) && (r === void 0 || typeof r == "string" && r === s) && (c === void 0 ? i !== "AKP" : n === c) && (l === void 0 || l === "sig") && (!t.crv || u === t.crv); } async function importWithAlgCache(e, t, n) { const r = e.get(t) || e.set(t, {}).get(t), { alg: i } = n; if (r[i] === void 0) { const e = jwkToKey(n, t, !0).then((e) => { if (e.type !== "public") throw new JWKSInvalid("JSON Web Key Set members must be public keys"); return r[i] = e, e; }).catch((t) => { throw r[i] === e && delete r[i], t; }); r[i] = e; } return r[i]; } function createLocalJWKSet(e) { let t; try { t = structuredClone(e); } catch {} if (!isJwkSet(t)) throw new JWKSInvalid("JSON Web Key Set malformed"); const n = t.keys.map((e) => { const t = snapshotJwk(e); return Array.isArray(t.key_ops) && (t.key_ops = [...t.key_ops]), t; }), r = /* @__PURE__ */ new WeakMap(); return Object.defineProperty(async (e, i) => { const { alg: a, kid: o } = { ...e, ...i?.header }, s = typeof a == "string" ? JWS[a] : void 0; if (!s || s.secret) throw new JOSENotSupported("Unsupported \"alg\" value for a JSON Web Key Set"); const c = t.keys.filter((e, t) => isUsableJWK(n[t], s, a, o)), { 0: l, length: u } = c; if (!u) throw new JWKSNoMatchingKey(); if (u !== 1) { const e = new JWKSMultipleMatchingKeys(); throw e[Symbol.asyncIterator] = async function* () { for (const e of c) try { yield await importWithAlgCache(r, e, s); } catch {} }, e; } return importWithAlgCache(r, l, s); }, "jwks", { value: () => structuredClone(t) }); } //#endregion //#region node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/util/decode_jwt.js function decodeJwt(e) { if (typeof e != "string") throw new JWTInvalid("JWTs must use Compact JWS serialization, JWT must be a string"); const { 1: t, length: n } = e.split("."); if (n === 5) throw new JWTInvalid("Only JWTs using Compact JWS serialization can be decoded"); if (n !== 3) throw new JWTInvalid("Invalid JWT"); if (!t) throw new JWTInvalid("JWTs must contain a payload"); let r; try { r = decode(t); } catch { throw new JWTInvalid("Failed to base64url decode the payload"); } let i; try { i = JSON.parse(strictDecoder.decode(r)); } catch { throw new JWTInvalid("Failed to parse the decoded payload as JSON"); } if (!isObject(i)) throw new JWTInvalid("Invalid JWT Claims Set"); return i; } //#endregion //#region extensions/openai/token-sharing-oauth.runtime.ts const TOKEN_ENDPOINT = `${TOKEN_SHARING_ISSUER}/api/accounts/oauth/token`; const MAX_RESPONSE_BYTES = 1048576; const LOGIN_TIMEOUT_MS = 3e5; async function requestJson(e, t, n) { t.signal?.throwIfAborted(); t.assertCurrent?.(); return await withOpenAIOAuthResponse({ url: e, policy: { hostnameAllowlist: ["auth.openai.com"] }, mode: "trusted_env_proxy", requireHttps: true, maxRedirects: 0, capture: false, timeoutMs: 3e4, signal: t.signal, beforeRequest: t.assertCurrent, auditContext: "openai-token-sharing-oauth", ...n ? { init: { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: n } } : {} }, async (e) => { const r = await readResponseWithLimit(e, MAX_RESPONSE_BYTES); t.signal?.throwIfAborted(); t.assertCurrent?.(); let i; try { i = asOptionalRecord(JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(r))); } catch {} if (n?.get("grant_type") === "refresh_token" && (!e.ok || i?.error !== void 0)) { const t = createOAuthRefreshResponseError("ChatGPT token-sharing refresh", e.status, i); if (i?.error === "invalid_grant") t.message = "ChatGPT connection expired or was revoked. Sign in again to reconnect."; throw t; } if (!e.ok) { const t = i?.error === "invalid_grant"; throw Object.assign(/* @__PURE__ */ new Error(t ? "ChatGPT connection expired or was revoked. Sign in again to reconnect." : `ChatGPT authentication request failed (HTTP ${e.status}). Retry sign-in later.`), { oauthRefreshFailure: { status: e.status, ...t ? { reason: "invalid_grant", errorType: "invalid_grant" } : {} } }); } if (!i) throw new Error("ChatGPT authentication returned an invalid response."); return i; }); } async function verifyIdentity(e, t, n, r) { const i = await requestJson(`${TOKEN_SHARING_ISSUER}/.well-known/jwks.json`, n); if (!Array.isArray(i.keys) || !i.keys.every(isRecord)) throw new Error("ChatGPT returned an invalid signing key set. Start sign-in again."); const { payload: a } = await jwtVerify(e, createLocalJWKSet({ keys: i.keys }), { issuer: TOKEN_SHARING_ISSUER, audience: t, algorithms: ["RS256"], requiredClaims: [ "iss", "aud", "sub", "iat", "exp" ] }); if (!a.sub || r !== void 0 && a.nonce !== r || a.azp !== void 0 && a.azp !== t || Array.isArray(a.aud) && a.aud.length > 1 && a.azp !== t) throw new Error("ChatGPT sign-in identity could not be verified. Start sign-in again."); n.assertCurrent?.(); n.signal?.throwIfAborted(); return a; } async function readCredential(e) { const { json: t, previous: n, clientId: r, owner: i } = e; const a = normalizeOptionalString(t.access_token); const o = t.refresh_token === void 0 ? n?.refresh : normalizeOptionalString(t.refresh_token); let s = resolveOAuthTokenExpiresAt(t.expires_in); const c = t.id_token === void 0 ? n?.idToken : normalizeOptionalString(t.id_token); if (!a || !o || s === void 0 || !c || typeof t.token_type !== "string" || t.token_type.toLowerCase() !== "bearer") throw new Error("ChatGPT did not return a complete renewable credential. Start sign-in again."); try { const e = decodeJwt(a).exp; if (typeof e === "number" && Number.isSafeInteger(e) && e > 0 && Number.isSafeInteger(e * 1e3)) s = Math.min(s, e * 1e3); } catch {} const l = t.id_token !== void 0 || !n ? await verifyIdentity(c, r, i, e.nonce) : decodeJwt(c); const u = l.sub; if (!u || n?.idToken && decodeJwt(n.idToken).sub !== u) throw new Error("ChatGPT account changed during refresh. Sign in again to reconnect."); const d = t.scope === void 0 ? n?.grantedScope : typeof t.scope === "string" ? t.scope.trim() : void 0; if ((t.scope !== void 0 || !n) && d === void 0) throw new Error("ChatGPT did not report the granted scopes. Start sign-in again."); const f = new Set(d?.split(/\s+/u)); const p = d === void 0 ? n?.authFlow === TOKEN_SHARING_AUTH_FLOW : f.has("resource.invoke") && ["chatpass.enable.request.direct", "chatgpt.tokens.use.direct"].some((e) => f.has(e)); return { subject: u, credential: { ...n, type: "oauth", provider: "openai", access: a, refresh: o, expires: s, idToken: c, email: normalizeOptionalString(l.email), clientId: r, issuer: TOKEN_SHARING_ISSUER, accountId: createHash("sha256").update(`${TOKEN_SHARING_ISSUER}\0${r}\0${u}`).digest("hex"), tokenEndpoint: TOKEN_ENDPOINT, grantedScope: d, authFlow: p ? TOKEN_SHARING_AUTH_FLOW : IDENTITY_AUTH_FLOW, displayName: p ? "Sign in with ChatGPT" : "Sign in with ChatGPT (identity only)" } }; } /** The auth-profile owner serializes refresh and atomically persists the returned rotation. */ async function refreshTokenSharingCredential(e) { if (!e.accountId || !e.clientId || e.clientId === "dynamic_agent_client" || e.issuer !== "https://auth.openai.com" || e.tokenEndpoint !== TOKEN_ENDPOINT) throw new Error("ChatGPT token-sharing registration is missing. Sign in again to reconnect."); const t = await requestJson(TOKEN_ENDPOINT, {}, new URLSearchParams({ grant_type: "refresh_token", client_id: e.clientId, refresh_token: e.refresh, resource: TOKEN_SHARING_RESOURCE })); try { return (await readCredential({ json: t, clientId: e.clientId, owner: {}, previous: e })).credential; } catch (e) { throw createOAuthRefreshError("ChatGPT refresh identity could not be verified. Sign in again.", { version: 1, phase: "after-token-response", outcome: "unknown" }, { cause: e }); } } /** Local authorization owns the listener, state, verifier, and callback lifetime together. */ async function loginTokenSharing(e) { const t = { ...e, signal: AbortSignal.any([AbortSignal.timeout(LOGIN_TIMEOUT_MS), ...e.signal ? [e.signal] : []]) }; t.assertCurrent?.(); const n = (e.existingProfiles ?? []).filter((e) => e.credential.type === "oauth" && e.credential.provider === "openai" && isSIWCAuthFlow(e.credential.authFlow) && e.credential.issuer === "https://auth.openai.com" && e.credential.tokenEndpoint === TOKEN_ENDPOINT && Boolean(e.credential.clientId) && e.credential.clientId !== "dynamic_agent_client"); const r = n.length ? await e.prompter.select({ message: "Reconnect a ChatGPT account or connect a different account/workspace?", initialValue: n[0].profileId, options: [...n.map(({ profileId: e, credential: t }) => ({ value: e, label: t.displayName ?? t.email ?? e, hint: `Reconnect ${e} using its existing registration` })), { value: TOKEN_SHARING_CLIENT_ID, label: "Connect a different ChatGPT account or workspace" }] }) : TOKEN_SHARING_CLIENT_ID; const i = n.find((e) => e.profileId === r); const a = i?.credential.clientId ?? "dynamic_agent_client"; const o = a === TOKEN_SHARING_CLIENT_ID; const s = (i?.credential.authorizationScope ?? (i ? "openid resource.invoke chatgpt.tokens.use.direct offline_access" : "openid email profile resource.invoke chatgpt.tokens.use.direct offline_access")).split(/\s+/u).map((e) => e === "chatpass.enable.request.direct" ? "chatgpt.tokens.use.direct" : e).join(" "); t.assertCurrent?.(); t.signal.throwIfAborted(); const { verifier: c, challenge: l } = await generatePKCE(); const u = generateOAuthState(); const d = generateOAuthState(); const f = await startProviderOAuthLoopbackCallbackServer({ redirectUrl: TOKEN_SHARING_REDIRECT_URI, expectedState: u, signal: t.signal, bindOnlyHostname: "127.0.0.1", deferResponse: true }); try { const n = f.redirectUrl; const { port: r } = new URL(n); const p = new URL(`${TOKEN_SHARING_ISSUER}/api/accounts/authorize`); p.search = new URLSearchParams({ response_type: "code", client_id: a, redirect_uri: n, resource: TOKEN_SHARING_RESOURCE, scope: s, code_challenge: l, code_challenge_method: "S256", state: u, nonce: d, ...o ? { agent_name_hint: "OpenClaw" } : {} }).toString(); t.assertCurrent?.(); await withOAuthLoginAbort(e.openUrl(p.toString()), t.signal); t.assertCurrent?.(); t.signal.throwIfAborted(); await withOAuthLoginAbort(e.prompter.note([ "Choose whether OpenClaw can use your ChatGPT plan for eligible Responses API requests. Token sharing does not grant access to conversations, Codex history, or connected apps.", ...o ? [] : ["Reconnect with the same ChatGPT user and workspace. To switch either, cancel and choose Connect a different ChatGPT account or workspace."], ...e.isRemote ? [`Open the sign-in link in your browser. Its localhost:${r} callback must reach this OpenClaw process, and the port changes on every sign-in. For an SSH host, forward it before opening the link: ssh -N -L ${r}:127.0.0.1:${r} user@gateway-host`] : [], ...e.prompter.openUrl ? [] : [`Sign-in URL: ${p.toString()}`] ].join("\n\n"), "Sign in with ChatGPT"), t.signal); t.assertCurrent?.(); t.signal.throwIfAborted(); const m = await withOAuthLoginAbort(f.waitForCallback(), t.signal); t.assertCurrent?.(); t.signal.throwIfAborted(); if (m.type === "oauth_error") throw new Error(m.error === "access_denied" ? "ChatGPT authorization was declined. Start sign-in again when ready." : "ChatGPT authorization failed. Start sign-in again."); const h = m.parameters.getAll("client_id"); const g = h[0]; if (h.length > 1 || (o ? !g || !/^oaiapp_[A-Za-z0-9_-]+$/u.test(g) : g !== void 0 && g !== a)) throw new Error("ChatGPT returned an invalid OAuth client ID. Start sign-in again."); const _ = g ?? a; const { credential: v, subject: y } = await readCredential({ json: await requestJson(TOKEN_ENDPOINT, t, createOpenAIAuthorizationCodeForm({ clientId: _, code: m.code, verifier: c, redirectUri: n, resource: TOKEN_SHARING_RESOURCE })), clientId: _, nonce: d, owner: t }); v.authorizationScope = s; if (i) { const e = i.credential; if (!(e.accountId !== void 0 ? e.accountId === v.accountId : Boolean(e.idToken && decodeJwt(e.idToken).sub === y))) throw new Error("ChatGPT account changed. Reconnect with the original account, or choose Connect a different ChatGPT account or workspace."); } const b = v.accountId.slice(0, 24); const x = v.authFlow === TOKEN_SHARING_AUTH_FLOW; await f.complete({ status: 200, contentType: "text/html; charset=utf-8", body: oauthSuccessHtml(x ? "ChatGPT token sharing is connected. You can return to OpenClaw." : "ChatGPT sign-in succeeded. Token sharing is disabled; return to OpenClaw to choose inference access.") }); t.signal.throwIfAborted(); t.assertCurrent?.(); const S = buildOauthProviderAuthResult({ providerId: "openai", profilePrefix: "openai:token-sharing", profileName: b, defaultModel: OPENAI_DEFAULT_MODEL, access: v.access, refresh: v.refresh, expires: v.expires, credentialExtra: v, ...x ? {} : { configPatch: {} }, notes: [x ? "Account connected. Eligible Responses API requests with this account use your ChatGPT plan." : "ChatGPT sign-in succeeded, but token sharing is disabled. Sign in again and enable sharing, or explicitly choose another inference credential."] }); if (i) S.profiles[0].profileId = i.profileId; if (!x) return { profiles: S.profiles, notes: S.notes }; return S; } catch (e) { await f.complete({ status: 400, contentType: "text/html; charset=utf-8", body: oauthErrorHtml("Sign-in did not complete. Return to OpenClaw for details and retry.") }); throw e; } finally { await f.close(); } } //#endregion export { loginTokenSharing, refreshTokenSharingCredential };