1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
| const WHAM_USAGE_URL = "https://chatgpt.com/backend-api/wham/usage";
function text(msg, status = 400) { return new Response(msg, { status }); }
function json(data, status = 200) { return new Response(JSON.stringify(data, null, 2), { status, headers: { "content-type": "application/json; charset=utf-8" }, }); }
function parseIntSafe(value, fallback) { const n = Number.parseInt(String(value ?? ""), 10); return Number.isFinite(n) && n > 0 ? n : fallback; }
function getAccountId(item) { for (const key of ["chatgpt_account_id", "chatgptAccountId", "account_id", "accountId"]) { const value = item?.[key]; if (typeof value === "string" && value.trim()) return value.trim(); } let token = item?.id_token; if (typeof token === "string") { try { token = JSON.parse(token); } catch { token = null; } } if (token && typeof token === "object") { for (const key of ["chatgpt_account_id", "chatgptAccountId", "account_id", "accountId"]) { const value = token?.[key]; if (typeof value === "string" && value.trim()) return value.trim(); } } return ""; }
function mgmtHeaders(env, includeJson = false) { const headers = { Authorization: `Bearer ${env.MANAGEMENT_KEY}`, Accept: "application/json, text/plain, */*", }; if (includeJson) headers["Content-Type"] = "application/json"; return headers; }
async function fetchJSON(url, init) { const resp = await fetch(url, init); const bodyText = await resp.text(); let body = null; if (bodyText) { try { body = JSON.parse(bodyText); } catch { body = bodyText; } } return { ok: resp.ok, status: resp.status, body }; }
function normalizeAuthFiles(body) { if (Array.isArray(body)) return body; if (body && typeof body === "object" && Array.isArray(body.files)) return body.files; return []; }
async function scanAndDelete401(env) { if (!env.MANAGEMENT_KEY || !env.MANAGEMENT_KEY.trim()) { return { ok: false, error: "MANAGEMENT_KEY is empty" }; }
const upstream = new URL(env.UPSTREAM_BASE_URL); const typeFilter = (env.WARDEN_TARGET_TYPE || "codex").trim().toLowerCase(); const providerFilter = (env.WARDEN_PROVIDER || "").trim().toLowerCase(); const maxScan = parseIntSafe(env.WARDEN_MAX_SCAN, 500);
const listRes = await fetchJSON(`${upstream.origin}/v0/management/auth-files`, { method: "GET", headers: mgmtHeaders(env, false), }); if (!listRes.ok) { return { ok: false, error: "failed to fetch auth-files", status: listRes.status, details: listRes.body, }; }
const files = normalizeAuthFiles(listRes.body); const candidates = files .filter((item) => { const typ = String(item?.type || "").trim().toLowerCase(); const provider = String(item?.provider || "").trim().toLowerCase(); if (typeFilter && typ !== typeFilter) return false; if (providerFilter && provider !== providerFilter) return false; return true; }) .slice(0, maxScan);
const invalid401 = []; for (const item of candidates) { const name = String(item?.name || "").trim(); const authIndex = String(item?.auth_index || "").trim(); if (!name) continue;
if (item?.unavailable === true) { invalid401.push({ name, reason: "unavailable=true" }); continue; }
const accountId = getAccountId(item); if (!authIndex || !accountId) continue;
const payload = { auth_index: authIndex, request: { method: "GET", url: WHAM_USAGE_URL, headers: { Authorization: "Bearer $TOKEN$", "Content-Type": "application/json", "User-Agent": "codex_cli_rs/0.76.0 (Cloudflare Worker)", "Chatgpt-Account-Id": accountId, }, }, };
const probe = await fetchJSON(`${upstream.origin}/v0/management/api-call`, { method: "POST", headers: mgmtHeaders(env, true), body: JSON.stringify(payload), });
if (!probe.ok || typeof probe.body !== "object" || probe.body === null) continue; if (probe.body.status_code === 401) { invalid401.push({ name, reason: "status_code=401" }); } }
const deleted = []; const failed = []; for (const item of invalid401) { const del = await fetchJSON( `${upstream.origin}/v0/management/auth-files?name=${encodeURIComponent(item.name)}`, { method: "DELETE", headers: mgmtHeaders(env, false) } ); const success = del.ok && del.body && typeof del.body === "object" && del.body.status === "ok"; if (success) { deleted.push(item.name); } else { failed.push({ name: item.name, status: del.status, details: del.body, }); } }
return { ok: true, scanned: candidates.length, detected_401: invalid401.length, deleted_401: deleted.length, deleted_names: deleted, delete_failed: failed, filters: { type: typeFilter || null, provider: providerFilter || null, max_scan: maxScan, }, }; }
function isWardenAuthorized(request, env) { const required = (env.WARDEN_TOKEN || "").trim(); if (!required) return true;
const fromHeader = request.headers.get("x-warden-token") || ""; if (fromHeader === required) return true;
const auth = request.headers.get("authorization") || ""; return auth === `Bearer ${required}`; }
export default { async fetch(request, env) { const base = (env.UPSTREAM_BASE_URL || "").trim(); if (!base) return text("UPSTREAM_BASE_URL not configured", 500);
let upstream; try { upstream = new URL(base); } catch { return text("Invalid UPSTREAM_BASE_URL", 500); }
const incoming = new URL(request.url);
if (incoming.pathname === "/warden/maintain-401") { if (!isWardenAuthorized(request, env)) return text("Unauthorized", 401); if (request.method !== "POST" && request.method !== "GET") { return text("Method Not Allowed", 405); } const result = await scanAndDelete401(env); return json(result, result.ok ? 200 : 500); }
const edgeToken = (env.EDGE_BEARER_TOKEN || "").trim(); if (edgeToken) { const auth = request.headers.get("authorization") || ""; if (auth !== `Bearer ${edgeToken}`) return text("Unauthorized", 401); }
if (incoming.pathname === "/") { return Response.redirect(new URL("/management.html#/login", incoming.origin).toString(), 302); }
const target = new URL(incoming.pathname + incoming.search, upstream.origin); const headers = new Headers(request.headers);
headers.set("x-forwarded-host", incoming.host); headers.set("x-forwarded-proto", incoming.protocol.replace(":", "")); headers.set("x-forwarded-for", request.headers.get("cf-connecting-ip") || "");
headers.delete("cf-connecting-ip"); headers.delete("cf-ipcountry"); headers.delete("cf-ray"); headers.delete("cf-visitor");
const proxied = new Request(target.toString(), { method: request.method, headers, body: request.body, redirect: "manual", });
return fetch(proxied); },
async scheduled(_event, env, ctx) { const base = (env.UPSTREAM_BASE_URL || "").trim(); if (!base) return;
let upstream; try { upstream = new URL(base); } catch { return; }
const enableKeepalive = String(env.ENABLE_KEEPALIVE || "true").toLowerCase() === "true"; const keepalivePath = String(env.KEEPALIVE_PATH || "/").trim() || "/"; const enableCronWarden = String(env.ENABLE_CRON_WARDEN || "false").toLowerCase() === "true";
if (enableKeepalive) { const keepaliveURL = new URL(keepalivePath, upstream.origin).toString(); ctx.waitUntil( fetch(keepaliveURL, { method: "GET" }).catch(() => null) ); }
if (enableCronWarden) { ctx.waitUntil(scanAndDelete401(env).catch(() => null)); } }, };
|