diff --git a/README.md b/README.md index 5807618..3d485b2 100644 --- a/README.md +++ b/README.md @@ -4,13 +4,13 @@ [![CI](https://github.com/margrop/coding-plan-dashboard/actions/workflows/test.yml/badge.svg)](./.github/workflows/test.yml) A single-page dashboard that aggregates the coding-plan quotas of multiple AI providers -(Codex, MiniMax, Volcengine AgentPlan / CodingPlan, Kimi Code, LongCat, Qianwen AI and -Google AI Gemini 3.5 Flash) into one self-hosted UI. Each provider supports multiple +(Codex, MiniMax, Volcengine AgentPlan / CodingPlan, Kimi Code, LongCat, Qianwen AI, + Zhipu AI CodingPlan and Google AI Gemini Models) into one self-hosted UI. Each provider supports multiple accounts with independent labels. 一个部署在局域网中的 Coding Plan 配额看板,支持 Codex、MiniMax、火山方舟 CodingPlan / -AgentPlan、Kimi Code、LongCat、千问 AI 和 Google AI (Gemini 3.5 Flash)。支持同一平台 -多账号,每个账号可添加备注。 +AgentPlan、Kimi Code、LongCat、千问 AI、智谱 AI CodingPlan 和 Google AI Gemini Models。支持同一平台 +多账号,每个账号可添加备注。Google AI 显示 Gemini Models 的 5 小时和周额度。 ## Features / 功能 @@ -22,15 +22,23 @@ AgentPlan、Kimi Code、LongCat、千问 AI 和 Google AI (Gemini 3.5 Flash)。 JSON 文件,容器重启后自动恢复。 - First paint shows the cached snapshot then silently refreshes to the latest data; successful refreshes do not pop up any dialog. +- Five built-in visual themes (Aurora, Ocean, Forest, Sunset and Paper), each with + Light / Dark modes. The selected theme and mode are saved in browser local storage; + the appearance controls are available after unlocking the page. - Multi-account support: each imported curl is stored as a separate account with its own ID, label, edit, delete (with double confirm), and reorder controls. +- Existing Kimi accounts can update request verification headers from a fresh + `GetSubscriptionStats` curl without replacing the saved URL, body, or account. +- Existing Kimi accounts can save a complete `RefreshToken` directly; every quota + refresh then exchanges the stored token before calling `GetSubscriptionStats`, and + persists rotated access / refresh tokens plus response cookies when provided. - Per-account Volcengine AK/SK configuration (no curl required); uses HMAC-SHA256 V4 signing against `GetCodingPlanUsage` / `GetAgentPlanAFPUsage`. - Codex supports both the official `/usage` + `/rate-limit-reset-credits` endpoints and a NewAPI replacement (`/api/channel/{channelId}/codex/usage[/reset-credits]`). The server merges them into a single Codex card and skips the official requests when a NewAPI variant is configured. -- All progress bars show one-decimal usage percentage; each card shows a live +- All progress bars show two-decimal usage percentage; each card shows a live countdown to the next reset in the top-right corner. - Self-contained single-file browser UI (`index.html`) with a custom SVG logo and no external favicon dependency. @@ -51,7 +59,8 @@ AGENTS.md Coding-agent instructions for this repository ### Requirements - Linux host / NAS with Docker Engine and Docker Compose v2. -- The host must be able to reach Codex, MiniMax and Volcengine APIs. +- The host must be able to reach the APIs for the providers you import, including + Zhipu AI at `www.bigmodel.cn`. - If you import a Codex curl with `--proxy`, the proxy must be reachable from the Docker host. - Default listen port is `8080`; change `PORT` in `docker-compose.yml` if occupied. @@ -140,7 +149,28 @@ auto-classifies by URL: - `www.kimi.com/.../GetSubscriptionStats` → Kimi Code - `longcat.chat/api/pay/quota/metering/token-packs/summary` → LongCat - `cs-data.qianwenai.com/.../data/api.json` (contains `tokenplan`) → Qianwen AI TokenPlan -- `fetchAvailableModels` (Gemini 3.5 Flash) → Google AI (Antigravity) +- `www.bigmodel.cn/api/monitor/usage/quota/limit` → Zhipu AI CodingPlan +- `retrieveUserQuotaSummary` (Gemini Models 5 小时 / 周额度) → Google AI (Antigravity) + +For Zhipu AI CodingPlan, the two `TOKENS_LIMIT` entries are distinguished by their +window metadata and displayed separately as 5-hour Token and weekly quota; their +`nextResetTime` values drive the countdown. `TIME_LIMIT` is displayed as MCP monthly +quota. Paste the complete browser-copied curl; the existing restricted parser handles +its authorization headers and cookies without spawning a shell. + +To repair an expired Kimi verification request, unlock the page, click **更新验证头** +on the existing Kimi card, then paste a fresh browser-copied `GetSubscriptionStats` +curl. The server validates the same Kimi endpoint and merges only its request headers; +the saved account ID, URL, request body, and cached result remain unchanged until refresh. + +To enable automatic Kimi token renewal, unlock the page, click **设置 RefreshToken** +or **更新 RefreshToken** on the Kimi card, then paste the complete RefreshToken JWT +directly. The server stores only the token and required request headers, and never +returns those fields from `/api/requests`. Device, session, and traffic headers are +derived from JWT claims when no previous Kimi request headers exist. Each refresh +exchanges the token first, updates the saved `Authorization` header, synchronizes +Kimi device headers, and merges any `Set-Cookie` response into the subscription request. +The legacy full RefreshToken cURL API remains accepted for existing configurations. Codex official and NewAPI endpoints can coexist; the server merges them into one card. `curl -sS`, `--proxy` and `--insecure` flags are translated into Python HTTPS @@ -154,8 +184,8 @@ and shows "接口未返回" instead of fabricating usage. - The server does not shell out; imported curl is parsed and re-issued via Python `urllib`-style HTTPS requests. - The host allowlist defaults to `chatgpt.com`, `www.minimaxi.com`, - `console.volcengine.com`, `www.kimi.com`, `longcat.chat`, - `cs-data.qianwenai.com`; additional NewAPI hosts can be enabled via the + `console.volcengine.com`, `www.kimi.com`, `auth.kimi.com`, `longcat.chat`, + `cs-data.qianwenai.com`, and `www.bigmodel.cn`; additional NewAPI hosts can be enabled via the `NEWAPI_HOSTS` (comma-separated) environment variable and are accepted only for the Codex `/usage` and `/usage/reset-credits` paths. - Google AI uses OAuth client pairs loaded from the `GOOGLE_AI_CLIENTS` @@ -169,8 +199,10 @@ and shows "接口未返回" instead of fabricating usage. `codexUsage` request, and likewise for `codexNewApiCredits` → `codexCredits`. This avoids repeated `401` noise when the official token is stale. - Raw curl (Token / Cookie / Digest) is stored in `requests.json` in plaintext, and - Volcengine AK/SK is stored in `credentials.json` in plaintext. Never commit real - credentials; the README and tests use redacted samples only. + Volcengine AK/SK is stored in `credentials.json` in plaintext. Kimi RefreshToken + input is reduced to its token and required headers in `requests.json`; it is not + returned by the API. Never commit real credentials; the README and tests use + redacted samples only. - Restrict `8080` to a trusted LAN and rotate credentials immediately on leak. ## Tests diff --git a/index.html b/index.html index 22d9afc..32485c2 100644 --- a/index.html +++ b/index.html @@ -5,11 +5,15 @@ Coding Plan 配额中心 + + - +
Local quota console

Coding Plan 配额中心

统一查看各平台 Coding Plan 的限额、使用量、重置信息和数据更新时间。支持同一平台多账号。

-
+
-
+

数据采集

导入原始 curl:系统会根据接口 URL 自动识别平台类型。每个 curl 保存为独立账号,可添加备注区分。请求会保存到服务器 JSON 文件,页面每次打开或点击刷新时由服务器重新执行。注意:原始 curl 可能包含 Token/Cookie,会以明文保存在服务器。

@@ -48,7 +82,7 @@

数据采集

导入原始 curl:系统会根据接口 U

-
+

新增火山方舟账号

无需抓包,直接填写 AccessKey ID / Secret Access Key 创建 CodingPlan 或 AgentPlan 账号。同一火山账号可分别创建 CodingPlan 和 AgentPlan 两个独立条目,并分别填写备注区分。需要在火山引擎控制台创建具备 ark:ListCodingPlan/ark:GetCodingPlanUsage(CodingPlan)以及 ark:GetAgentPlanAFPUsage(AgentPlan)权限的 RAM 凭据。

@@ -58,11 +92,11 @@

新增火山方舟账号

无需抓包,直接填写 Acc

-
+

更新已有火山方舟账号的 AK/SK

在对应 CodingPlan / AgentPlan 卡片上点击「设置 AK/SK」即可为该账号配置 OpenAPI 凭据。配置后该账号将通过 OpenAPI 签名鉴权获取用量,无需 curl 中的 Cookie。

-
-

新增 Google AI 账号

填写 Antigravity / Gemini CLI 的 OAuth refresh token 创建 Google AI 账号,显示 Gemini 3.5 Flash 的用量和重置时间。refresh token 可在 ~/.gemini/antigravity-cli/antigravity-oauth-token(字段 token.refresh_token)或 ~/.gemini/oauth_creds.json 中找到。代理默认使用服务器环境变量 GOOGLE_AI_PROXY,可在此覆盖;不填则直接对外网请求。

+
+

新增 Google AI 账号

填写 Antigravity / Gemini CLI 的 OAuth refresh token 创建 Google AI 账号,显示 Gemini Models 的 5 小时和周额度。refresh token 可在 ~/.gemini/antigravity-cli/antigravity-oauth-token(字段 token.refresh_token)或 ~/.gemini/oauth_creds.json 中找到。代理默认使用服务器环境变量 GOOGLE_AI_PROXY,可在此覆盖;不填则直接对外网请求。

@@ -84,9 +118,26 @@

新增 Google AI 账号

填写 Antigravity / Gemini CLI kimi:{name:'Kimi',sub:'Code 订阅',logo:'KM',className:'kimi'}, longcat:{name:'LongCat',sub:'Token Pack',logo:'LC',className:'longcat'}, qianwen:{name:'千问AI',sub:'Token Plan',logo:'QW',className:'qianwen'}, - googleAi:{name:'Google AI',sub:'Gemini 3.5 Flash',logo:'G',className:'google'} + zhipuCoding:{name:'智谱AI',sub:'CodingPlan',logo:'GLM',className:'zhipu'}, + googleAi:{name:'Google AI',sub:'Gemini Models',logo:'G',className:'google'} }; -const DISPLAY_TYPE={codexUsage:'codex',codexCredits:'codex',codexNewApi:'codex',codexNewApiCredits:'codex',minimax:'minimax',volcCoding:'volcCoding',volcAgent:'volcAgent',kimi:'kimi',longcat:'longcat',qianwen:'qianwen',googleAi:'googleAi'}; +const APPEARANCE_THEMES={aurora:'极光',ocean:'海湾',forest:'森林',sunset:'暮色',paper:'纸张'}; +const APPEARANCE_MODES={dark:'暗黑',light:'普通'}; +function applyAppearance(theme,mode,persist=true){ + const nextTheme=Object.prototype.hasOwnProperty.call(APPEARANCE_THEMES,theme)?theme:'aurora'; + const nextMode=Object.prototype.hasOwnProperty.call(APPEARANCE_MODES,mode)?mode:'dark'; + document.documentElement.dataset.theme=nextTheme; + document.documentElement.dataset.mode=nextMode; + const themeSelect=document.querySelector('#themeSelect'); + const modeSelect=document.querySelector('#modeSelect'); + if(themeSelect)themeSelect.value=nextTheme; + if(modeSelect)modeSelect.value=nextMode; + if(persist){localStorage.setItem('coding-plan-theme',nextTheme);localStorage.setItem('coding-plan-mode',nextMode)} +} +function loadAppearance(){ + applyAppearance(localStorage.getItem('coding-plan-theme')||document.documentElement.dataset.theme,localStorage.getItem('coding-plan-mode')||document.documentElement.dataset.mode,false); +} +const DISPLAY_TYPE={codexUsage:'codex',codexCredits:'codex',codexNewApi:'codex',codexNewApiCredits:'codex',minimax:'minimax',volcCoding:'volcCoding',volcAgent:'volcAgent',kimi:'kimi',longcat:'longcat',qianwen:'qianwen',zhipuCoding:'zhipuCoding',googleAi:'googleAi'}; const state={}; const refreshErrors={}; let requestDefinitions={}; @@ -94,7 +145,7 @@

新增 Google AI 账号

填写 Antigravity / Gemini CLI let accountOrder=[]; const $=s=>document.querySelector(s); const now=()=>new Date().toISOString(); -const fmtDate=value=>value?new Date(value).toLocaleString('zh-CN',{hour12:false}):'未提供'; +const fmtDate=value=>{if(value===null||value===undefined||value==='')return'未提供';const numeric=Number(value),date=Number.isFinite(numeric)?new Date(numeric):new Date(value);return Number.isNaN(date.getTime())?'未提供':date.toLocaleString('zh-CN',{hour12:false})}; const num=value=>Number.isFinite(Number(value))?Number(value):0; function firstNumber(value,keys){for(const key of keys){const candidate=value?.[key];if(typeof candidate==='number'&&Number.isFinite(candidate))return candidate;if(typeof candidate==='string'&&candidate.trim()!==''&&Number.isFinite(Number(candidate)))return Number(candidate)}return null} function firstValue(value,keys){for(const key of keys)if(value&&value[key]!==undefined&&value[key]!==null)return value[key];return null} @@ -105,11 +156,12 @@

新增 Google AI 账号

填写 Antigravity / Gemini CLI function normalizeCodexUsage(payload){const unwrapped=unwrap(payload),value=unwrapped.usage&&typeof unwrapped.usage==='object'?{...unwrapped,...unwrapped.usage}:unwrapped,rateLimit=value.rate_limit&&typeof value.rate_limit==='object'?value.rate_limit:{};const toWindow=(window,fallbackName)=>{if(!window||typeof window!=='object')return{name:fallbackName,available:false,usedPercent:0,remainingPercent:100,resetAt:null};const seconds=firstNumber(window,['limit_window_seconds'])??0,name=seconds===18000?'5h':seconds>=604800?'weekly':fallbackName,usedPercent=Math.max(0,Math.min(100,percent(window.used_percent))),resetAt=firstNumber(window,['reset_at']);return{name,available:true,usedPercent,remainingPercent:Math.max(0,100-usedPercent),resetAt:resetAt?resetAt*1000:null}};return{windows:[toWindow(rateLimit.primary_window,'weekly'),toWindow(rateLimit.secondary_window,'5h')],resetCards:firstNumber(value.rate_limit_reset_credits,['available_count']),planType:value.plan_type||null,updatedAt:now()}} function normalizeCodexNewApi(payload){const value=unwrap(payload),usage=normalizeCodexUsage(value.usage&&typeof value.usage==='object'?value.usage:value),result={usage,updatedAt:now()};if(Array.isArray(value.credits)&&value.credits.length)result.credits=normalizeCodexCredits(value);return result} function normalizeMiniMax(payload){const value=unwrap(payload),windows=normalizeWindows(value),remaining=firstNumber(value,['remains_percent','remaining_percent','remain_percent','remainingPercent']),windowRemaining=windows[0]?.interval?.remainingPercent,normalizedRemaining=windowRemaining===undefined?(remaining===null?0:Math.max(0,Math.min(100,remaining))):windowRemaining;return{limit:100,used:100-normalizedRemaining,remaining:normalizedRemaining,unit:'%',windows,updatedAt:now()}} -function normalizeKimi(payload){const value=unwrap(payload),ratioToPercent=ratio=>Number.isFinite(Number(ratio))?Math.max(0,Math.min(100,Number(ratio)*100)):0,periods=[];if(value.ratelimitCode5h&&typeof value.ratelimitCode5h==='object')periods.push({name:'5h',usedPercent:ratioToPercent(value.ratelimitCode5h.ratio),remainingPercent:Math.max(0,100-ratioToPercent(value.ratelimitCode5h.ratio)),resetAt:value.ratelimitCode5h.resetTime||null});if(value.ratelimitCode7d&&typeof value.ratelimitCode7d==='object')periods.push({name:'7d',usedPercent:ratioToPercent(value.ratelimitCode7d.ratio),remainingPercent:Math.max(0,100-ratioToPercent(value.ratelimitCode7d.ratio)),resetAt:value.ratelimitCode7d.resetTime||null});if(value.subscriptionBalance&&typeof value.subscriptionBalance==='object'){const used=ratioToPercent(value.subscriptionBalance.kimiCodeUsedRatio??value.subscriptionBalance.amountUsedRatio);periods.push({name:'订阅',usedPercent:used,remainingPercent:Math.max(0,100-used),resetAt:value.subscriptionBalance.expireTime||null})}const used=periods.length?Math.max(...periods.map(period=>period.usedPercent)):0;return{limit:100,used,remaining:Math.max(0,100-used),unit:'%',periods,updatedAt:now()}} +function normalizeKimi(payload){const value=unwrap(payload),ratioToPercent=ratio=>Number.isFinite(Number(ratio))?Math.max(0,Math.min(100,Number(ratio)*100)):0,periods=[];if(value.ratelimitCode5h&&typeof value.ratelimitCode5h==='object')periods.push({name:'5h',usedPercent:ratioToPercent(value.ratelimitCode5h.ratio),remainingPercent:Math.max(0,100-ratioToPercent(value.ratelimitCode5h.ratio)),resetAt:value.ratelimitCode5h.resetTime||null});if(value.ratelimitCode7d&&typeof value.ratelimitCode7d==='object')periods.push({name:'7d',usedPercent:ratioToPercent(value.ratelimitCode7d.ratio),remainingPercent:Math.max(0,100-ratioToPercent(value.ratelimitCode7d.ratio)),resetAt:value.ratelimitCode7d.resetTime||null});if(value.subscriptionBalance&&typeof value.subscriptionBalance==='object'){const used=ratioToPercent(value.subscriptionBalance.amountUsedRatio??value.subscriptionBalance.kimiCodeUsedRatio);periods.push({name:'订阅',usedPercent:used,remainingPercent:Math.max(0,100-used),resetAt:value.subscriptionBalance.expireTime||null})}const used=periods.length?Math.max(...periods.map(period=>period.usedPercent)):0;return{limit:100,used,remaining:Math.max(0,100-used),unit:'%',periods,updatedAt:now()}} function normalizeQianwen(payload){const r2p=ratio=>Number.isFinite(Number(ratio))?Math.max(0,Math.min(100,Number(ratio)*100)):0,root=unwrap(payload);let value=root;for(const key of ['DataV2','data','data','data']){if(value&&typeof value[key]==='object')value=value[key]}const periods=[];if(value.per5HourPercentage!==undefined)periods.push({name:'5h',usedPercent:r2p(value.per5HourPercentage),remainingPercent:Math.max(0,100-r2p(value.per5HourPercentage)),resetAt:firstNumber(value,['per5HourResetTime'])});if(value.per1WeekPercentage!==undefined)periods.push({name:'1w',usedPercent:r2p(value.per1WeekPercentage),remainingPercent:Math.max(0,100-r2p(value.per1WeekPercentage)),resetAt:firstNumber(value,['per1WeekResetTime'])});const used=periods.length?Math.max(...periods.map(period=>period.usedPercent)):0;return{limit:100,used,remaining:Math.max(0,100-used),unit:'%',periods,updatedAt:now()}} function normalizeLongCat(payload){const value=unwrap(payload),periods=[],addLot=(lot,fallbackName)=>{if(!lot||typeof lot!=='object')return;const ratio=firstNumber(lot,['consumedRatio'])??0,usedPercent=Math.max(0,Math.min(100,ratio*100));let name=fallbackName;if(lot.source==='FREE_PACK')name='免费额度';else if(typeof lot.source==='string'&&lot.source.startsWith('PACK_'))name='付费额度';periods.push({name,usedPercent,remainingPercent:Math.max(0,100-usedPercent),expireTime:lot.expireTime||null})};addLot(value.currentLot,'当前额度');if(Array.isArray(value.otherLots))value.otherLots.forEach(lot=>addLot(lot,'其他额度'));const used=periods.length?Math.max(...periods.map(period=>period.usedPercent)):0;return{limit:100,used,remaining:Math.max(0,100-used),unit:'%',periods,updatedAt:now()}} function normalizeVolcengine(payload){const value=payload?.Result&&typeof payload.Result==='object'?payload.Result:unwrap(payload);const afpPeriods=[['5h',value.AFPFiveHour],['weekly',value.AFPWeekly],['monthly',value.AFPMonthly]].filter(([,item])=>item&&typeof item==='object').map(([name,item])=>{const quota=firstNumber(item,['Quota'])??0,used=firstNumber(item,['Used'])??0,usedPercent=quota?used/quota*100:0,resetTime=firstNumber(item,['ResetTime']);return{name,quota,used,usedPercent,remainingPercent:quota?Math.max(0,100-usedPercent):100,resetAt:resetTime&&resetTime>0?resetTime:null}});const periods=afpPeriods.length?afpPeriods:Array.isArray(value.QuotaUsage)?value.QuotaUsage.map(item=>({name:String(item.Level||'').toLowerCase(),usedPercent:percent(item.Percent),remainingPercent:Math.max(0,100-percent(item.Percent)),resetAt:firstNumber(item,['ResetTimestamp'])>0?firstNumber(item,['ResetTimestamp'])*1000:null})):[];const details=Array.isArray(value.Details)?value.Details.map(item=>({time:item.Time||null,objectName:item.ObjectName||'',usage:firstNumber(item,['Usage'])??0,unit:item.Unit||'',billingType:item.BillingType||''})):[];if(periods.length){const usedPercent=Math.max(...periods.map(period=>period.usedPercent));return{limit:100,used:usedPercent,remaining:Math.max(0,100-usedPercent),unit:'%',periods,details}}const limit=firstNumber(value,['total','total_count','quota','limit','plan_quota','totalQuota']);const used=firstNumber(value,['used','used_count','usage','consumed','usedQuota']);const remaining=firstNumber(value,['remaining','remain','remaining_count','left','leftQuota']);const resolvedLimit=limit??((used??0)+(remaining??0));const resolvedUsed=used??Math.max(0,resolvedLimit-(remaining??0));return{limit:resolvedLimit,used:resolvedUsed,remaining:Math.max(0,resolvedLimit-resolvedUsed),unit:'次',periods,details}} -function normalizeGoogleAi(payload){const value=unwrap(payload),models=(value&&typeof value.models==='object')?value.models:{};let found=null;for(const[key,m]of Object.entries(models)){if(!m||typeof m!=='object')continue;const name=m.displayName||key;if(String(name).includes('Gemini 3.5 Flash')){found=m;break}}if(!found)return{limit:100,used:0,remaining:100,unit:'%',periods:[],updatedAt:now()};const qi=found.quotaInfo||found.quota||{},remaining=Number.isFinite(Number(qi.remainingFraction))?Math.max(0,Math.min(1,Number(qi.remainingFraction))):1,usedPercent=Math.max(0,Math.min(100,(1-remaining)*100));return{limit:100,used:usedPercent,remaining:Math.max(0,100-usedPercent),unit:'%',periods:[{name:'Gemini 3.5 Flash',usedPercent,remainingPercent:Math.max(0,100-usedPercent),resetAt:qi.resetTime||null}],updatedAt:now()}} +function normalizeGoogleAi(payload){const value=unwrap(payload),groups=Array.isArray(value.groups)?value.groups:[],group=groups.find(item=>String(item?.displayName||'').toLowerCase()==='gemini models')||groups.find(item=>String(item?.displayName||'').toLowerCase().includes('gemini'));if(!group||!Array.isArray(group.buckets))return{limit:100,used:0,remaining:100,unit:'%',periods:[],updatedAt:now()};const labels={ '5h':'5h',weekly:'weekly' },periods=group.buckets.filter(bucket=>bucket&&labels[bucket.window]&&Number.isFinite(Number(bucket.remainingFraction))).map(bucket=>{const remaining=Math.max(0,Math.min(1,Number(bucket.remainingFraction))),usedPercent=Math.max(0,Math.min(100,(1-remaining)*100));return{name:labels[bucket.window],usedPercent,remainingPercent:Math.max(0,100-usedPercent),resetAt:bucket.resetTime||bucket.reset_at||null}}).sort((left,right)=>({'5h':0,weekly:1}[left.name]??9)-({'5h':0,weekly:1}[right.name]??9)),used=periods.length?Math.max(...periods.map(period=>period.usedPercent)):0;return{limit:100,used,remaining:Math.max(0,100-used),unit:'%',periods,updatedAt:now()}} +function normalizeZhipu(payload){const value=unwrap(payload),limits=Array.isArray(value.limits)?value.limits:[],parsePercentage=item=>{const rawPercentage=typeof item.percentage==='string'?item.percentage.replace('%',''):item.percentage,percentage=Number(rawPercentage);return Number.isFinite(percentage)?Math.max(0,Math.min(100,percentage)):null},resetAt=item=>firstValue(item,['nextResetTime','next_reset_time','resetTime','reset_time']),tokenLimits=limits.map((item,index)=>item&&typeof item==='object'&&['TOKENS_LIMIT','CREDIT_LIMIT'].includes(item.type)?{item,index,usedPercent:parsePercentage(item),resetAt:resetAt(item)}:null).filter(entry=>entry&&entry.usedPercent!==null).sort((left,right)=>{const windowRank=item=>{const unit=Number(item.item.unit),number=Number(item.item.number);if(unit===3&&number===5)return 0;if(unit===6&&(number===1||number===7))return 1;return 2},rankDifference=windowRank(left)-windowRank(right);if(rankDifference)return rankDifference;const leftReset=Number(left.resetAt),rightReset=Number(right.resetAt);if(Number.isFinite(leftReset)&&Number.isFinite(rightReset)&&leftReset!==rightReset)return leftReset-rightReset;return left.index-right.index}),periods=tokenLimits.map((entry,index)=>{const unit=Number(entry.item.unit),number=Number(entry.item.number),name=unit===3&&number===5?'5h':unit===6&&(number===1||number===7)?'weekly':index===0?'5h':'weekly';return{name,usedPercent:entry.usedPercent,remainingPercent:Math.max(0,100-entry.usedPercent),resetAt:entry.resetAt??null}}),timeLimit=limits.find(item=>item&&typeof item==='object'&&item.type==='TIME_LIMIT'),timeUsedPercent=timeLimit?parsePercentage(timeLimit):null;if(timeUsedPercent!==null)periods.push({name:'time',usedPercent:timeUsedPercent,remainingPercent:Math.max(0,100-timeUsedPercent),resetAt:resetAt(timeLimit)??null});const order={'5h':0,weekly:1,time:2};periods.sort((left,right)=>order[left.name]-order[right.name]);const used=periods.length?Math.max(...periods.map(period=>period.usedPercent)):0;return{limit:100,used,remaining:Math.max(0,100-used),unit:'%',periods,updatedAt:now()}} function parseForAccount(source,payload){ if(source==='codexNewApi'){const r=normalizeCodexNewApi(payload);return{windows:r.usage?.windows||[],resetCards:r.usage?.resetCards??r.credits?.availableCount??null,nextExpiresAt:r.credits?.nextExpiresAt||null,updatedAt:now()}} if(source==='codexUsage'){const r=normalizeCodexUsage(payload);return{windows:r.windows||[],resetCards:r.resetCards??null,nextExpiresAt:null,updatedAt:now()}} @@ -118,6 +170,7 @@

新增 Google AI 账号

填写 Antigravity / Gemini CLI if(source==='minimax')return normalizeMiniMax(payload); if(source==='kimi')return normalizeKimi(payload); if(source==='qianwen')return normalizeQianwen(payload); + if(source==='zhipuCoding')return normalizeZhipu(payload); if(source==='longcat')return normalizeLongCat(payload); return normalizeVolcengine(payload); } @@ -125,18 +178,23 @@

新增 Google AI 账号

填写 Antigravity / Gemini CLI async function save(){saveLocal();try{await fetch('/api/snapshot',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(state)})}catch{}} async function load(){try{const response=await fetch('/api/snapshot');if(response.ok){const data=await response.json();if(data&&typeof data==='object')for(const[k,v]of Object.entries(data))if(k.startsWith('acc_'))state[k]=v;return}}catch{}try{const saved=JSON.parse(localStorage.getItem('coding-plan-quota-snapshot')||'{}');for(const[k,v]of Object.entries(saved))if(k.startsWith('acc_'))state[k]=v}catch{}} function pct(item){if(!item)return 0;const values=[];(item.periods||[]).forEach(period=>{if(Number.isFinite(Number(period.usedPercent)))values.push(Number(period.usedPercent))});(item.windows||[]).forEach(window=>{if(Number.isFinite(Number(window.usedPercent)))values.push(Number(window.usedPercent))});if(Number.isFinite(Number(item.usedPercent)))values.push(Number(item.usedPercent));if(values.length)return Math.max(...values);if(Number.isFinite(Number(item.used))&&Number.isFinite(Number(item.limit))&&item.limit>0)return item.used/item.limit*100;return 0} -function status(item){if(!item)return['未加载','warn'];const p=pct(item),displayPercent=Math.round(p*10)/10;if(displayPercent>=100)return['无法使用','bad'];if(displayPercent>=90)return['接近上限','warn'];return['已同步','ok']} +function periodRank(name){const key=String(name||'').toLowerCase();if(['5h','session','当前窗口','今日用量'].includes(key))return 1;if(['weekly','7d','1w','周额度','本周用量'].includes(key))return 2;if(['monthly','月额度','本月用量'].includes(key))return 3;if(['订阅','订阅额度','免费额度','付费额度','当前额度','其他额度'].includes(key))return 4;return 0} +function quotaCandidates(item){if(!item)return[];const candidates=[];for(const period of item.periods||[]){const used=Number(period.usedPercent);if(Number.isFinite(used)&&period.available!==false)candidates.push({rank:periodRank(period.name),used:Math.max(0,Math.min(100,used)),resetAt:period.resetAt||period.expireTime||null})}for(const window of item.windows||[]){if(window.available===false)continue;const interval=window.interval;if(interval&&Number.isFinite(Number(interval.usedPercent)))candidates.push({rank:1,used:Math.max(0,Math.min(100,Number(interval.usedPercent))),resetAt:interval.resetAt||null});const weekly=window.weekly;if(weekly&&Number.isFinite(Number(weekly.usedPercent)))candidates.push({rank:2,used:Math.max(0,Math.min(100,Number(weekly.usedPercent))),resetAt:weekly.resetAt||null});if(Number.isFinite(Number(window.usedPercent)))candidates.push({rank:periodRank(window.name),used:Math.max(0,Math.min(100,Number(window.usedPercent))),resetAt:window.resetAt||null})}return candidates} +function longestPeriodPct(item){const candidates=quotaCandidates(item);if(!candidates.length)return null;const rank=Math.max(...candidates.map(candidate=>candidate.rank));const selected=candidates.filter(candidate=>candidate.rank===rank);return Math.max(...selected.map(candidate=>candidate.used))} +function status(item){if(!item)return['未加载','warn'];if(item.limit===0)return['已过期','bad'];const p=pct(item),displayPercent=Math.round(p*10)/10;if(displayPercent>=100)return['无法使用','bad'];if(displayPercent>=90)return['接近上限','warn'];return['已同步','ok']} function windowLabel(window){const duration=(window.interval.resetAt&&window.interval.startAt)?window.interval.resetAt-window.interval.startAt:0;if(duration>=4*3600000&&duration<=6*3600000)return'5h';return''} function waitText(resetAt){if(resetAt===null||resetAt===undefined||resetAt==='')return'暂无重置时间';const n=Number(resetAt);const ts=Number.isFinite(n)?n:Date.parse(resetAt);if(!Number.isFinite(ts))return'暂无重置时间';const seconds=Math.max(0,Math.floor((ts-Date.now())/1000));if(!seconds)return'已重置';const days=Math.floor(seconds/86400),hours=Math.floor(seconds%86400/3600),minutes=Math.floor(seconds%3600/60),rest=seconds%60;return`${days?days+'天 ':''}${hours?hours+'小时 ':''}${minutes?minutes+'分 ':''}${rest}秒`} -function progressPeriod(label,used,resetAt,remaining){const value=Math.max(0,Math.min(100,Number(used)||0));return`

${value.toFixed(1)}%重置等待 ${waitText(resetAt)}
${label}已使用剩余 ${Number(remaining??Math.max(0,100-value)).toFixed(1)}%
`} -function updateWaits(){document.querySelectorAll('[data-reset-at]').forEach(element=>{element.textContent=`重置等待 ${waitText(element.dataset.resetAt)}`})} +function resetText(resetAt){const wait=waitText(resetAt);if(wait==='暂无重置时间')return wait;const numeric=Number(resetAt),timestamp=Number.isFinite(numeric)?numeric:Date.parse(resetAt),remainingSeconds=Number.isFinite(timestamp)?Math.max(0,Math.floor((timestamp-Date.now())/1000)):0;return`${remainingSeconds>=86400?`下次重置 ${fmtDate(resetAt)}
`:''}剩余时间 ${wait}`} +function progressPeriod(label,used,resetAt,remaining){const value=Math.max(0,Math.min(100,Number(used)||0));return`
${value.toFixed(2)}%${resetText(resetAt)}
${label}已使用剩余 ${Number(remaining??Math.max(0,100-value)).toFixed(2)}%
`} +function updateWaits(){document.querySelectorAll('[data-reset-at]').forEach(element=>{element.innerHTML=resetText(element.dataset.resetAt)})} function codexAccountRows(data){if(!data)return'';let html='';if(data.resetCards!==null&&data.resetCards!==undefined){const expires=data.nextExpiresAt?`最近到期 ${fmtDate(data.nextExpiresAt)}`:'暂无到期时间';html+=`
${data.resetCards}可用重置卡 · ${expires}
重置卡数量
`}html+=(data.windows||[]).map(window=>window.available?progressPeriod(window.name==='5h'?'5小时':'周额度',window.usedPercent,window.resetAt,window.remainingPercent):`
-接口未返回
${window.name==='5h'?'5小时':'周额度'}已使用暂无数据
`).join('');return html} function miniMaxRows(item){const windows=(item.windows||[]).filter(window=>windowLabel(window)==='5h');const selected=windows.length?windows:(item.windows||[]).slice(0,1);return selected.map(window=>progressPeriod(`${window.modelName} · 5h`,window.interval.usedPercent,window.interval.resetAt,window.interval.remainingPercent)).join('')} function volcPeriodRows(item){const labels={session:'当前窗口','5h':'5小时',weekly:'周额度',monthly:'月额度','7d':'7天额度','1w':'周额度',订阅:'订阅额度'};return(item.periods||[]).map(period=>progressPeriod(labels[period.name]||period.name,period.usedPercent,period.resetAt,period.remainingPercent)).join('')} -function longcatRows(item){return(item.periods||[]).map(period=>{const value=Math.max(0,Math.min(100,Number(period.usedPercent)||0));return`
${value.toFixed(1)}%${period.expireTime?fmtDate(period.expireTime):'暂无到期时间'}
${period.name}已使用剩余 ${Number(period.remainingPercent??Math.max(0,100-value)).toFixed(1)}%
`}).join('')} +function zhipuPeriodRows(item){const labels={'5h':'5小时 Token',weekly:'周额度',time:'MCP月额度'};return(item.periods||[]).map(period=>progressPeriod(labels[period.name]||period.name,period.usedPercent,period.resetAt,period.remainingPercent)).join('')} +function longcatRows(item){return(item.periods||[]).map(period=>{const value=Math.max(0,Math.min(100,Number(period.usedPercent)||0));return`
${value.toFixed(2)}%${period.expireTime?fmtDate(period.expireTime):'暂无到期时间'}
${period.name}已使用剩余 ${Number(period.remainingPercent??Math.max(0,100-value)).toFixed(2)}%
`}).join('')} function agentPeriods(item){const details=item.details||[],current=new Date(),dayStart=new Date(current.getFullYear(),current.getMonth(),current.getDate()).getTime(),weekStart=dayStart-((current.getDay()+6)%7)*86400000,monthStart=new Date(current.getFullYear(),current.getMonth(),1).getTime(),dayReset=new Date(current.getFullYear(),current.getMonth(),current.getDate()+1).getTime(),weekReset=new Date(current.getFullYear(),current.getMonth(),current.getDate()+8-current.getDay()).getTime(),monthReset=new Date(current.getFullYear(),current.getMonth()+1,1).getTime(),sums=[['今日用量',dayStart,dayReset],['本周用量',weekStart,weekReset],['本月用量',monthStart,monthReset]].map(([label,start,resetAt])=>({label,resetAt,usage:details.reduce((sum,detail)=>sum+(detail.time>=start?num(detail.usage):0),0)})),max=Math.max(...sums.map(period=>period.usage),0);return sums.map(period=>progressPeriod(`${period.label}(相对用量)`,max?period.usage/max*100:0,period.resetAt,max?Math.max(0,100-period.usage/max*100):100)).join('')} -function accountRows(source,data){if(!data)return'';const dt=DISPLAY_TYPE[source]||source;if(dt==='codex')return codexAccountRows(data);if(source==='minimax'&&data?.windows?.length)return miniMaxRows(data);if(source==='longcat'&&data?.periods?.length)return longcatRows(data);if((source==='volcCoding'||source==='kimi'||source==='qianwen')&&data?.periods?.length)return volcPeriodRows(data);if(source==='volcAgent'&&data?.periods?.length)return volcPeriodRows(data);if(source==='volcAgent'&&data?.details?.length)return agentPeriods(data);if(source==='googleAi'&&data?.periods?.length)return volcPeriodRows(data);return''} -function renderRefreshAlert(){const errors=Object.entries(refreshErrors);const alert=$('#refreshAlert');if(!errors.length){alert.classList.add('hidden');alert.textContent='';return}alert.classList.remove('hidden');alert.innerHTML=`刷新异常:${errors.map(([id,error])=>{const acc=requestDefinitions[id];const name=acc?`${SOURCES[acc.source]?.name||acc.source}${acc.label?' · '+acc.label:''}`:id;return`${name} 返回 HTTP ${error.status??'未知'}`}).join(';')}。已保留上次缓存数据。`} +function accountRows(source,data){if(!data)return'';const dt=DISPLAY_TYPE[source]||source;if(dt==='codex')return codexAccountRows(data);if(source==='minimax'&&data?.windows?.length)return miniMaxRows(data);if(source==='longcat'&&data?.periods?.length)return longcatRows(data);if(source==='zhipuCoding'&&data?.periods?.length)return zhipuPeriodRows(data);if((source==='volcCoding'||source==='kimi'||source==='qianwen')&&data?.periods?.length)return volcPeriodRows(data);if(source==='volcAgent'&&data?.periods?.length)return volcPeriodRows(data);if(source==='volcAgent'&&data?.details?.length)return agentPeriods(data);if(source==='googleAi'&&data?.periods?.length)return volcPeriodRows(data);return''} +function renderRefreshAlert(){const errors=Object.entries(refreshErrors);const alert=$('#refreshAlert');if(!errors.length){alert.classList.add('hidden');alert.textContent='';return}alert.classList.remove('hidden');alert.innerHTML=`刷新异常:${errors.map(([id,error])=>{const acc=requestDefinitions[id];const name=acc?`${SOURCES[acc.source]?.name||acc.source}${acc.label?' · '+acc.label:''}`:id;const detail=error.error&&error.error!==`HTTP ${error.status}`?`(${escapeHtml(error.error)})`:'';return`${name} 返回 HTTP ${error.status??'未知'}${detail}`}).join(';')}。已保留上次缓存数据。`} function escapeHtml(s){return String(s).replace(/&/g,'&').replace(//g,'>').replace(/"/g,'"')} function mergeCodexNewApiCredits(){ const creditsId=Object.entries(requestDefinitions).find(([,a])=>a.source==='codexNewApiCredits')?.[0]; @@ -151,27 +209,31 @@

新增 Google AI 账号

填写 Antigravity / Gemini CLI mergeCodexNewApiCredits(); const accounts=getOrderedAccounts().filter(([,acc])=>acc.source!=='codexNewApiCredits'); const items=accounts.map(([id])=>state[id]).filter(Boolean); - const total=items.reduce((sum,item)=>sum+num(item.limit),0),used=items.reduce((sum,item)=>sum+num(item.used),0); - const summary=[['账号数',`${accounts.length}`,'已保存'],['总限额',total?total.toLocaleString():'-','合计'],['已使用',used?used.toLocaleString():'-','合计'],['最近更新',items.length?fmtDate(items.map(x=>x.updatedAt).filter(Boolean).sort().at(-1)):'-','本机时间']]; + const total=items.reduce((sum,item)=>sum+num(item.limit),0),currentUsed=items.reduce((sum,item)=>sum+pct(item),0),longestUsed=items.reduce((sum,item)=>sum+(longestPeriodPct(item)??0),0),longestCount=items.filter(item=>longestPeriodPct(item)!==null).length; + const summary=[['账号数 / 总限额',`${accounts.length} / ${total?total.toLocaleString():'-'}`,'已保存账号 / 合计限额'],['当前已使用',`${currentUsed.toFixed(2)}%`,'各账号最大用量相加'],['总已使用',`${longestCount?longestUsed.toFixed(2):'-'}%`,'各账号最长周期用量相加'],['最近更新',items.length?fmtDate(items.map(x=>x.updatedAt).filter(Boolean).sort().at(-1)):'-','本机时间']]; $('#summary').innerHTML=summary.map(([a,b,c])=>`

${b}${c}
`).join(''); renderRefreshAlert(); $('#cards').innerHTML=accounts.map(([id,acc])=>{ const source=SOURCES[acc.source]||{name:acc.source,sub:'',logo:'?',className:''}; const item=state[id],error=refreshErrors[id]; const [label,kind]=error?[`异常 HTTP ${error.status??'未知'}`,'bad']:status(item); - const staleClass=error?' stale':''; - const staleNote=error?`
本次刷新失败,继续显示上次缓存数据(HTTP ${error.status??'未知'})。
`:''; + const expired=item&&item.limit===0; + const staleClass=error||expired?' stale':''; + const staleNote=error?`
本次刷新失败,继续显示上次缓存数据(HTTP ${error.status??'未知'})。
`:expired?`
订阅已过期或已被回收,可用额度为 0。
`:''; const labelDisplay=acc.label?``:''; const periods=accountRows(acc.source,item); const volcCredsBtn=(acc.source==='volcCoding'||acc.source==='volcAgent')?``:''; const googleCredsBtn=(acc.source==='googleAi')?``:''; + const kimiVerificationBtn=(acc.source==='kimi')?``:''; + const kimiRefreshBtn=(acc.source==='kimi')?``:''; + const minimaxVerificationBtn=(acc.source==='minimax')?``:''; const reorderHtml=`
`; - const actionsHtml=`
${volcCredsBtn}${googleCredsBtn}
${reorderHtml}`; + const actionsHtml=`
${reorderHtml}${volcCredsBtn}${googleCredsBtn}${kimiVerificationBtn}${kimiRefreshBtn}${minimaxVerificationBtn}
`; if(periods){ return `

${source.name}

${source.sub}

${labelDisplay}
${label}
${actionsHtml}
${periods}
${staleNote}
${item?fmtDate(item.updatedAt):'-'}数据更新时间
` } const rows=`
${item?num(item.limit).toLocaleString():'-'}订阅限额
${item?num(item.used).toLocaleString():'-'}已使用
`; - return `

${source.name}

${source.sub}

${labelDisplay}
${label}
${actionsHtml}
${item?num(item.remaining).toLocaleString():'-'}${item?.unit||'剩余'}
已使用 ${item?num(item.used).toLocaleString():'-'} / ${item?num(item.limit).toLocaleString():'-'}${item?pct(item).toFixed(1):'-'}%
${rows}
${item?fmtDate(item.updatedAt):'-'}数据更新时间
${staleNote}
` + return `

${source.name}

${source.sub}

${labelDisplay}
${label}
${actionsHtml}
${item?num(item.remaining).toLocaleString():'-'}${item?.unit||'剩余'}
已使用 ${item?num(item.used).toLocaleString():'-'} / ${item?num(item.limit).toLocaleString():'-'}${item?pct(item).toFixed(2):'-'}%
${rows}
${item?fmtDate(item.updatedAt):'-'}数据更新时间
${staleNote}
` }).join(''); updateWaits(); } @@ -185,16 +247,22 @@

新增 Google AI 账号

填写 Antigravity / Gemini CLI function editLabel(id){if(locked)return;const acc=requestDefinitions[id];if(!acc)return;const cards=document.querySelectorAll('#cards .card');for(const card of cards){const btn=card.querySelector('.card-actions button');if(btn&&btn.getAttribute('onclick')&&btn.getAttribute('onclick').includes(id)){const brandDiv=card.querySelector('.brand > div:last-child');if(brandDiv){const currentLabel=acc.label||'';brandDiv.insertAdjacentHTML('beforeend',`

`);brandDiv.querySelector('.label-edit input')?.focus()}break}}} async function deleteAccount(id){if(locked)return;const acc=requestDefinitions[id];if(!acc)return;const name=`${SOURCES[acc.source]?.name||acc.source}${acc.label?' · '+acc.label:''}`;if(!confirm(`确认删除账号「${name}」?\n\n删除后不可恢复,该账号的 curl 和缓存数据将被清除。`))return;try{const response=await fetch('/api/requests',{method:'DELETE',headers:{'Content-Type':'application/json'},body:JSON.stringify({id})});if(!response.ok)throw new Error(await response.text());delete requestDefinitions[id];delete state[id];delete refreshErrors[id];render()}catch(error){alert(`删除失败:${error.message}`)}} async function importCurrent(){alert('JSON 导入功能在多账号模式下暂不可用,请使用 curl 导入并刷新')} -function editCreds(id){if(locked)return;const acc=requestDefinitions[id];if(!acc)return;const card=[...document.querySelectorAll('#cards .card')].find(c=>{const b=c.querySelector('.card-actions button');return b&&b.getAttribute('onclick')&&b.getAttribute('onclick').includes(id)});if(!card)return;let box=card.querySelector('.creds-edit');if(box){box.remove();return}box=document.createElement('div');box.className='creds-edit';box.innerHTML=`
`;card.querySelector('.period-list')?.after(box);box.querySelector('input')?.focus()} +function editCreds(id){if(locked)return;const acc=requestDefinitions[id];if(!acc)return;const card=[...document.querySelectorAll('#cards .card')].find(c=>{const b=c.querySelector('.card-actions button');return b&&b.getAttribute('onclick')&&b.getAttribute('onclick').includes(id)});if(!card)return;let box=card.querySelector('.creds-edit');if(box){box.remove();return}box=document.createElement('div');box.className='creds-edit';box.innerHTML=`
`;(card.querySelector('.period-list')||card.querySelector('.card-actions'))?.after(box);box.querySelector('input')?.focus()} async function saveCreds(id,ak,sk){if(locked)return;try{const acc=requestDefinitions[id];if(!acc)return;const body={id,ak,sk,label:acc.label||'',curl:acc.curl,updatedAt:now()};const response=await fetch('/api/requests',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)});if(!response.ok)throw new Error(await response.text());requestDefinitions[id]={...acc,ak,hasCreds:true};render();await refreshFromServer()}catch(error){alert(`保存凭据失败:${error.message}`)}} async function clearCreds(id){if(locked)return;try{const acc=requestDefinitions[id];if(!acc)return;const body={id,ak:'',sk:'',label:acc.label||'',curl:acc.curl,updatedAt:now()};const response=await fetch('/api/requests',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)});if(!response.ok)throw new Error(await response.text());delete requestDefinitions[id].ak;delete requestDefinitions[id].hasCreds;render()}catch(error){alert(`清除凭据失败:${error.message}`)}} -function editGoogleCreds(id){if(locked)return;const acc=requestDefinitions[id];if(!acc)return;const card=[...document.querySelectorAll('#cards .card')].find(c=>{const b=c.querySelector('.card-actions button');return b&&b.getAttribute('onclick')&&b.getAttribute('onclick').includes(id)});if(!card)return;let box=card.querySelector('.creds-edit');if(box){box.remove();return}box=document.createElement('div');box.className='creds-edit';box.innerHTML=`
`;card.querySelector('.period-list')?.after(box);box.querySelector('input')?.focus()} -async function saveGoogleCreds(id,refreshToken,proxy){if(locked)return;try{const acc=requestDefinitions[id];if(!acc)return;const body={id,label:acc.label||'',curl:acc.curl,updatedAt:now()};if(refreshToken)body.refreshToken=refreshToken;if(proxy)body.proxy=proxy;const response=await fetch('/api/requests',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)});if(!response.ok)throw new Error(await response.text());requestDefinitions[id]={...acc,hasCreds:true,proxy:proxy||acc.proxy};render();await refreshFromServer()}catch(error){alert(`保存 Token 失败:${error.message}`)}} +function editGoogleCreds(id){if(locked)return;const acc=requestDefinitions[id];if(!acc)return;const card=[...document.querySelectorAll('#cards .card')].find(c=>{const b=c.querySelector('.card-actions button');return b&&b.getAttribute('onclick')&&b.getAttribute('onclick').includes(id)});if(!card)return;let box=card.querySelector('.creds-edit');if(box){box.remove();return}box=document.createElement('div');box.className='creds-edit';box.innerHTML=`
`;(card.querySelector('.period-list')||card.querySelector('.card-actions'))?.after(box);box.querySelector('input')?.focus()} +async function saveGoogleCreds(id,refreshToken,proxy){if(locked)return;try{const acc=requestDefinitions[id];if(!acc)return;const body={id,label:acc.label||'',curl:acc.curl,updatedAt:now()};if(refreshToken)body.refreshToken=refreshToken;if(proxy)body.proxy=proxy;const response=await fetch('/api/requests',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)});if(!response.ok)throw new Error(await response.text());requestDefinitions[id]={...acc,hasCreds:true};render();await refreshFromServer()}catch(error){alert(`保存 Token 失败:${error.message}`)}} +function editKimiVerification(id){if(locked)return;const acc=requestDefinitions[id];if(!acc||acc.source!=='kimi')return;const card=[...document.querySelectorAll('#cards .card')].find(c=>{const b=c.querySelector('.card-actions button');return b&&b.getAttribute('onclick')&&b.getAttribute('onclick').includes(id)});if(!card)return;let box=card.querySelector('.creds-edit');if(box){box.remove();return}box=document.createElement('div');box.className='creds-edit';box.innerHTML=`
在已登录的 Kimi 页面中,对 GetSubscriptionStats 请求选择“复制为 cURL”,粘贴完整请求。服务器只更新请求头,原 URL、请求体和账号不会改变。
`;(card.querySelector('.period-list')||card.querySelector('.card-actions'))?.after(box);box.querySelector('textarea')?.focus()} +async function saveKimiVerification(id,verificationCurl){if(locked)return;if(!verificationCurl.trim()){alert('请粘贴新的 Kimi GetSubscriptionStats cURL');return}try{const response=await fetch('/api/requests',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({id,kimiVerificationCurl:verificationCurl})});if(!response.ok)throw new Error(await response.text());await loadRequests();render();await refreshFromServer()}catch(error){alert(`更新 Kimi 验证头失败:${error.message}`)}} +function editKimiRefresh(id){if(locked)return;const acc=requestDefinitions[id];if(!acc||acc.source!=='kimi')return;const card=[...document.querySelectorAll('#cards .card')].find(c=>{const b=c.querySelector('.card-actions button');return b&&b.getAttribute('onclick')&&b.getAttribute('onclick').includes(id)});if(!card)return;let box=card.querySelector('.creds-edit');if(box){box.remove();return}box=document.createElement('div');box.className='creds-edit';box.innerHTML=`
直接粘贴完整的 Kimi RefreshToken(JWT),不需要复制 cURL。服务器只保存 token 和必要请求头,保存后不会回显 token。
`;(card.querySelector('.period-list')||card.querySelector('.card-actions'))?.after(box);box.querySelector('input')?.focus()} +async function saveKimiRefresh(id,refreshToken){if(locked)return;if(!refreshToken.trim()){alert('请粘贴 Kimi RefreshToken');return}try{const response=await fetch('/api/requests',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({id,kimiRefreshToken:refreshToken})});if(!response.ok)throw new Error(await response.text());await loadRequests();render();await refreshFromServer()}catch(error){alert(`更新 Kimi RefreshToken 失败:${error.message}`)}} +function editMinimaxVerification(id){if(locked)return;const acc=requestDefinitions[id];if(!acc||acc.source!=='minimax')return;const card=[...document.querySelectorAll('#cards .card')].find(c=>{const b=c.querySelector('.card-actions button');return b&&b.getAttribute('onclick')&&b.getAttribute('onclick').includes(id)});if(!card)return;let box=card.querySelector('.creds-edit');if(box){box.remove();return}box=document.createElement('div');box.className='creds-edit';box.innerHTML=`
在已登录的 MiniMax 平台页面中,对 token_plan/remains_percent 请求选择“复制为 cURL”,粘贴完整请求。服务器只更新请求头(含 Cookie 中的 _token),原 URL、请求体和账号不会改变。
`;(card.querySelector('.period-list')||card.querySelector('.card-actions'))?.after(box);box.querySelector('textarea')?.focus()} +async function saveMinimaxVerification(id,verificationCurl){if(locked)return;if(!verificationCurl.trim()){alert('请粘贴新的 MiniMax token_plan cURL');return}try{const response=await fetch('/api/requests',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({id,minimaxVerificationCurl:verificationCurl})});if(!response.ok)throw new Error(await response.text());await loadRequests();render();await refreshFromServer()}catch(error){alert(`更新 MiniMax 验证头失败:${error.message}`)}} function toggleLock(){locked=!locked;const btn=$('#lockToggle');if(locked){btn.textContent='🔒';btn.classList.remove('unlocked');btn.title='已锁定,点击解锁编辑';document.body.classList.add('locked')}else{btn.textContent='🔓';btn.classList.add('unlocked');btn.title='已解锁,可编辑备注/删除/排序';document.body.classList.remove('locked')}render()} function getOrderedAccounts(){const seen=new Set();const ordered=[];for(const id of accountOrder){if(requestDefinitions[id]&&!seen.has(id)){ordered.push([id,requestDefinitions[id]]);seen.add(id)}}for(const[id,acc] of Object.entries(requestDefinitions)){if(!seen.has(id)){ordered.push([id,acc]);seen.add(id)}}return ordered} function moveAccount(id,dir){if(locked)return;const ordered=getOrderedAccounts();const idx=ordered.findIndex(([aid])=>aid===id);if(idx<0)return;const target=idx+dir;if(target<0||target>=ordered.length)return;const tmp=ordered[idx];ordered[idx]=ordered[target];ordered[target]=tmp;accountOrder=ordered.map(([aid])=>aid);saveOrder();render()} async function saveOrder(){try{await fetch('/api/order',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({order:accountOrder})})}catch{}} -$('#refreshAll').onclick=()=>refreshFromServer();$('#lockToggle').onclick=toggleLock;$('#saveCurl').onclick=saveCurl;$('#importPayload').onclick=importCurrent;$('#fetchCurrent').onclick=()=>refreshFromServer();$('#clearData').onclick=async()=>{if(locked){alert('请先解锁编辑(点击右上角 🔒 图标)');return}if(!confirm('确认清除所有本地缓存数据?\n\n服务器保存的账号配置和最后一次成功的查询结果不会被清除。'))return;localStorage.removeItem('coding-plan-quota-snapshot');Object.keys(state).forEach(key=>delete state[key]);await save();render()};$('#addVolcAccount').onclick=addVolcAccount;$('#addGoogleAccount').onclick=addGoogleAccount;setInterval(updateWaits,1000);(async()=>{document.body.classList.add('locked');await load();render();await loadRequests();await loadCachedResults();render();await refreshFromServer();render()})(); +loadAppearance();$('#themeSelect').onchange=event=>applyAppearance(event.target.value,$('#modeSelect').value);$('#modeSelect').onchange=event=>applyAppearance($('#themeSelect').value,event.target.value);$('#refreshAll').onclick=()=>refreshFromServer();$('#lockToggle').onclick=toggleLock;$('#saveCurl').onclick=saveCurl;$('#importPayload').onclick=importCurrent;$('#fetchCurrent').onclick=()=>refreshFromServer();$('#clearData').onclick=async()=>{if(locked){alert('请先解锁编辑(点击右上角 🔒 图标)');return}if(!confirm('确认清除所有本地缓存数据?\n\n服务器保存的账号配置和最后一次成功的查询结果不会被清除。'))return;localStorage.removeItem('coding-plan-quota-snapshot');Object.keys(state).forEach(key=>delete state[key]);await save();render()};$('#addVolcAccount').onclick=addVolcAccount;$('#addGoogleAccount').onclick=addGoogleAccount;setInterval(updateWaits,1000);(async()=>{document.body.classList.add('locked');await load();render();await loadRequests();await loadCachedResults();render();await refreshFromServer();render()})(); diff --git a/parser.js b/parser.js index 3f46f24..45a8287 100644 --- a/parser.js +++ b/parser.js @@ -119,7 +119,7 @@ function normalizeKimi(payload) { periods.push({ name: '7d', usedPercent: ratioToPercent(value.ratelimitCode7d.ratio), remainingPercent: Math.max(0, 100 - ratioToPercent(value.ratelimitCode7d.ratio)), resetAt: value.ratelimitCode7d.resetTime || null }); } if (value.subscriptionBalance && typeof value.subscriptionBalance === 'object') { - const used = ratioToPercent(value.subscriptionBalance.kimiCodeUsedRatio ?? value.subscriptionBalance.amountUsedRatio); + const used = ratioToPercent(value.subscriptionBalance.amountUsedRatio ?? value.subscriptionBalance.kimiCodeUsedRatio); periods.push({ name: '订阅', usedPercent: used, remainingPercent: Math.max(0, 100 - used), resetAt: value.subscriptionBalance.expireTime || null }); } const used = periods.length ? Math.max(...periods.map(period => period.usedPercent)) : 0; @@ -144,6 +144,52 @@ function normalizeQianwen(payload) { return { limit: 100, used, remaining: Math.max(0, 100 - used), unit: '%', periods, updatedAt: Date.now() }; } +function normalizeZhipu(payload) { + const value = unwrap(payload); + const limits = Array.isArray(value.limits) ? value.limits : []; + const parsePercentage = item => { + const rawPercentage = typeof item.percentage === 'string' ? item.percentage.replace('%', '') : item.percentage; + const percentage = Number(rawPercentage); + return Number.isFinite(percentage) ? Math.max(0, Math.min(100, percentage)) : null; + }; + const resetAt = item => firstValue(item, ['nextResetTime', 'next_reset_time', 'resetTime', 'reset_time']); + const tokenLimits = limits + .map((item, index) => item && typeof item === 'object' && ['TOKENS_LIMIT', 'CREDIT_LIMIT'].includes(item.type) + ? { item, index, usedPercent: parsePercentage(item), resetAt: resetAt(item) } + : null) + .filter(entry => entry && entry.usedPercent !== null) + .sort((left, right) => { + const windowRank = item => { + const unit = Number(item.item.unit); + const number = Number(item.item.number); + if (unit === 3 && number === 5) return 0; + if (unit === 6 && (number === 1 || number === 7)) return 1; + return 2; + }; + const rankDifference = windowRank(left) - windowRank(right); + if (rankDifference) return rankDifference; + const leftReset = Number(left.resetAt); + const rightReset = Number(right.resetAt); + if (Number.isFinite(leftReset) && Number.isFinite(rightReset) && leftReset !== rightReset) return leftReset - rightReset; + return left.index - right.index; + }); + const periods = tokenLimits.map((entry, index) => { + const unit = Number(entry.item.unit); + const number = Number(entry.item.number); + const name = unit === 3 && number === 5 ? '5h' : unit === 6 && (number === 1 || number === 7) ? 'weekly' : index === 0 ? '5h' : 'weekly'; + return { name, usedPercent: entry.usedPercent, remainingPercent: Math.max(0, 100 - entry.usedPercent), resetAt: entry.resetAt ?? null }; + }); + const timeLimit = limits.find(item => item && typeof item === 'object' && item.type === 'TIME_LIMIT'); + const timeUsedPercent = timeLimit ? parsePercentage(timeLimit) : null; + if (timeUsedPercent !== null) { + periods.push({ name: 'time', usedPercent: timeUsedPercent, remainingPercent: Math.max(0, 100 - timeUsedPercent), resetAt: resetAt(timeLimit) ?? null }); + } + const order = { '5h': 0, weekly: 1, time: 2 }; + periods.sort((left, right) => order[left.name] - order[right.name]); + const used = periods.length ? Math.max(...periods.map(period => period.usedPercent)) : 0; + return { limit: 100, used, remaining: Math.max(0, 100 - used), unit: '%', periods, updatedAt: Date.now() }; +} + function normalizeLongCat(payload) { const value = unwrap(payload); const periods = []; @@ -214,25 +260,21 @@ function normalizeVolcengine(payload) { function normalizeGoogleAi(payload) { const value = unwrap(payload); - const models = (value && typeof value.models === 'object') ? value.models : {}; - let found = null; - for (const [key, m] of Object.entries(models)) { - if (!m || typeof m !== 'object') continue; - const name = m.displayName || key; - if (String(name).includes('Gemini 3.5 Flash')) { found = m; break; } - } - if (!found) return { limit: 100, used: 0, remaining: 100, unit: '%', periods: [], updatedAt: Date.now() }; - const qi = found.quotaInfo || found.quota || {}; - const remaining = Number.isFinite(Number(qi.remainingFraction)) ? Math.max(0, Math.min(1, Number(qi.remainingFraction))) : 1; - const usedPercent = Math.max(0, Math.min(100, (1 - remaining) * 100)); - return { - limit: 100, - used: usedPercent, - remaining: Math.max(0, 100 - usedPercent), - unit: '%', - periods: [{ name: 'Gemini 3.5 Flash', usedPercent, remainingPercent: Math.max(0, 100 - usedPercent), resetAt: qi.resetTime || null }], - updatedAt: Date.now() - }; + const groups = Array.isArray(value.groups) ? value.groups : []; + const group = groups.find(item => String(item?.displayName || '').toLowerCase() === 'gemini models') + || groups.find(item => String(item?.displayName || '').toLowerCase().includes('gemini')); + if (!group || !Array.isArray(group.buckets)) return { limit: 100, used: 0, remaining: 100, unit: '%', periods: [], updatedAt: Date.now() }; + const labels = { '5h': '5h', weekly: 'weekly' }; + const periods = group.buckets + .filter(bucket => bucket && labels[bucket.window] && Number.isFinite(Number(bucket.remainingFraction))) + .map(bucket => { + const remaining = Math.max(0, Math.min(1, Number(bucket.remainingFraction))); + const usedPercent = Math.max(0, Math.min(100, (1 - remaining) * 100)); + return { name: labels[bucket.window], usedPercent, remainingPercent: Math.max(0, 100 - usedPercent), resetAt: bucket.resetTime || bucket.reset_at || null }; + }) + .sort((left, right) => ({ '5h': 0, weekly: 1 }[left.name] ?? 9) - ({ '5h': 0, weekly: 1 }[right.name] ?? 9)); + const used = periods.length ? Math.max(...periods.map(period => period.usedPercent)) : 0; + return { limit: 100, used, remaining: Math.max(0, 100 - used), unit: '%', periods, updatedAt: Date.now() }; } -module.exports = { normalizeCodex, normalizeCodexCredits, normalizeCodexNewApi, normalizeCodexUsage, normalizeMiniMax, normalizeKimi, normalizeQianwen, normalizeLongCat, normalizeVolcengine, normalizeGoogleAi }; +module.exports = { normalizeCodex, normalizeCodexCredits, normalizeCodexNewApi, normalizeCodexUsage, normalizeMiniMax, normalizeKimi, normalizeQianwen, normalizeZhipu, normalizeLongCat, normalizeVolcengine, normalizeGoogleAi }; diff --git a/server.py b/server.py index 8886f10..2707415 100644 --- a/server.py +++ b/server.py @@ -5,6 +5,7 @@ import re import shlex import uuid +import base64 from datetime import datetime, timezone from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path @@ -114,10 +115,15 @@ def execute_volcengine_openapi(credentials, action): GOOGLE_OAUTH_URL = "https://oauth2.googleapis.com/token" GOOGLE_UA = "antigravity-tools/1.1.5" GOOGLE_BASES = [ - "https://cloudcode-pa.googleapis.com", "https://daily-cloudcode-pa.googleapis.com", + "https://cloudcode-pa.googleapis.com", "https://daily-cloudcode-pa.sandbox.googleapis.com", ] +GOOGLE_QUOTA_ENDPOINTS = [ + "retrieveUserQuotaSummary", + "retrieveUserQuota", + "loadCodeAssist", +] def _load_google_clients(): """Resolve Google AI OAuth client pairs. @@ -195,23 +201,28 @@ def execute_google_ai(credentials): return 1, "", f"oauth refresh failed: {last_error}" body = b"{}" last_error = None - for base in GOOGLE_BASES: - request = Request( - f"{base}/v1internal:fetchAvailableModels", - data=body, - method="POST", - headers={"Authorization": f"Bearer {access_token}", "Content-Type": "application/json", "User-Agent": GOOGLE_UA}, - ) - try: - opener = _google_opener(proxy) - context = opener.open(request, timeout=35) if opener else urlopen(request, timeout=35) - with context as response: - return response.status, response.read().decode("utf-8", errors="replace"), "" - except HTTPError as error: - last_error = f"HTTP {error.code} {error.reason} @ {base}" - except URLError as error: - last_error = f"{error.reason} @ {base}" - return 1, "", f"fetchAvailableModels failed: {last_error}" + + for endpoint in GOOGLE_QUOTA_ENDPOINTS: + for base in GOOGLE_BASES: + request = Request( + f"{base}/v1internal:{endpoint}", + data=body, + method="POST", + headers={"Authorization": f"Bearer {access_token}", "Content-Type": "application/json", "User-Agent": GOOGLE_UA}, + ) + try: + opener = _google_opener(proxy) + context = opener.open(request, timeout=35) if opener else urlopen(request, timeout=35) + with context as response: + response_body = response.read().decode("utf-8", errors="replace") + if "remainingFraction" in response_body or "remaining_fraction" in response_body: + return response.status, response_body, "" + last_error = f"HTTP {response.status} no quota data @ {base}/{endpoint}" + except HTTPError as error: + last_error = f"HTTP {error.code} {error.reason} @ {base}/{endpoint}" + except URLError as error: + last_error = f"{error.reason} @ {base}/{endpoint}" + return 1, "", f"quota endpoints failed: {last_error}" def mask_secret(secret): @@ -254,13 +265,77 @@ def should_skip_source(source, accounts): return skip_usage or skip_credits +def find_matching_newapi_account(curl, requests): + """Find an existing NewAPI account for the same Codex endpoint.""" + url, _ = parse_curl(curl) + parsed = urlparse(url) + source = infer_source(curl) + for account_id, definition in requests.items(): + if definition.get("source") != source: + continue + try: + existing_url, _ = parse_curl(definition.get("curl", "")) + except ValueError: + continue + existing = urlparse(existing_url) + if existing.hostname == parsed.hostname and existing.port == parsed.port and existing.path == parsed.path: + return account_id + return None + + +def provider_response_ok(source, code, body): + """Treat HTTP 200 business-error responses as failed provider calls.""" + if not is_success_status(code): + return False + if source not in {NEWAPI_CODEX_USAGE_PATH, NEWAPI_CODEX_CREDITS_PATH, "qianwen", "zhipuCoding", "minimax"}: + return True + try: + payload = json.loads(body) + except (TypeError, ValueError): + return False + if source == "qianwen": + data = payload.get("data") + return isinstance(data, dict) and data.get("success") is not False and not data.get("errorCode") and not data.get("errorMsg") + if source == "zhipuCoding": + data = payload.get("data") + return isinstance(data, dict) and isinstance(data.get("limits"), list) + if source == "minimax": + base_resp = payload.get("base_resp") + if isinstance(base_resp, dict): + return base_resp.get("status_code") == 0 + return True + return payload.get("success") is not False and "Unauthorized" not in str(payload.get("message", "")) + + +def provider_response_error(source, body): + if source not in {"qianwen", "zhipuCoding", "minimax"}: + return "" + try: + payload = json.loads(body) + except (TypeError, ValueError): + return "" + if source == "zhipuCoding": + return str(payload.get("message") or payload.get("msg") or payload.get("error") or "").strip() + if source == "minimax": + base_resp = payload.get("base_resp") + if isinstance(base_resp, dict): + return str(base_resp.get("status_msg") or "").strip() + return "" + data = payload.get("data") + if not isinstance(data, dict): + return "" + return str(data.get("errorMsg") or data.get("errorCode") or "").strip() + + ALLOWED_HOSTS = { "chatgpt.com", "www.minimaxi.com", "console.volcengine.com", "www.kimi.com", + "auth.kimi.com", "longcat.chat", "cs-data.qianwenai.com", + "www.bigmodel.cn", } # NewAPI gateway hosts allowed to serve /api/channel/{id}/codex/{usage,usage/reset-credits}. # Configurable via NEWAPI_HOSTS env var (comma-separated hostnames). Defaults to the @@ -310,6 +385,16 @@ def parse_curl(command): args.append(token) index += 1 continue + if token == "--url": + if index + 1 >= len(tokens): + raise ValueError("missing value for --url") + urls.append(tokens[index + 1]) + index += 2 + continue + if token.startswith("--url="): + urls.append(token[6:]) + index += 1 + continue if token in ALLOWED_OPTIONS_WITH_VALUE: if index + 1 >= len(tokens): raise ValueError(f"missing value for {token}") @@ -353,6 +438,8 @@ def infer_source(command): return "longcat" if parsed.hostname == "cs-data.qianwenai.com" and path.endswith("/data/api.json") and "tokenplan" in parsed.query: return "qianwen" + if parsed.hostname == "www.bigmodel.cn" and path.rstrip("/") == "/api/monitor/usage/quota/limit": + return "zhipuCoding" if parsed.hostname == "www.minimaxi.com": return "minimax" if parsed.hostname == "console.volcengine.com" and path.endswith("GetCodingPlanUsage"): @@ -362,6 +449,399 @@ def infer_source(command): raise ValueError("unable to infer source from URL") +KIMI_VERIFICATION_HEADERS = {"authorization", "cookie", "x-traffic-id"} +KIMI_IGNORED_HEADERS = {"connection", "content-length", "host"} +KIMI_REFRESH_URL = "https://auth.kimi.com/api/account.gateway.v1.AuthService/RefreshToken" +KIMI_REFRESH_IGNORED_HEADERS = KIMI_IGNORED_HEADERS | {"content-type"} +KIMI_DYNAMIC_HEADERS = { + "origin", + "referer", + "r-timezone", + "user-agent", + "x-language", + "x-msh-device-id", + "x-msh-platform", + "x-msh-session-id", + "x-msh-version", + "x-traffic-id", +} +KIMI_DEFAULT_REFRESH_HEADERS = { + "accept": "*/*", + "accept-language": "zh-CN,zh;q=0.9", + "connect-protocol-version": "1", + "origin": "https://www.kimi.com", + "r-timezone": "Asia/Hong_Kong", + "referer": "https://www.kimi.com/", + "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/151.0.0.0 Safari/537.36", + "x-msh-platform": "web", + "x-msh-version": "2.0.0", +} + + +def _normalize_curl_header_name(raw): + return raw.split(":", 1)[0].strip().rstrip(";").strip().lower() + + +def _curl_header_entries(args): + entries = [] + index = 1 + while index < len(args) - 1: + token = args[index] + if token in {"-H", "--header"}: + raw = args[index + 1] + name = _normalize_curl_header_name(raw) + if name: + entries.append((name, raw)) + index += 2 + continue + if token in {"-b", "--cookie"}: + entries.append(("cookie", f"Cookie: {args[index + 1]}")) + index += 2 + continue + if token in {"-A", "--user-agent"}: + entries.append(("user-agent", f"User-Agent: {args[index + 1]}")) + index += 2 + continue + if token in ALLOWED_OPTIONS_WITH_VALUE: + index += 2 + continue + index += 1 + return entries + + +def _curl_header_value(raw): + _, separator, value = raw.partition(":") + return value.lstrip() if separator else "" + + +def _decode_jwt_payload(token): + parts = str(token).split(".") + if len(parts) != 3: + return {} + try: + encoded = parts[1] + "=" * ((4 - len(parts[1]) % 4) % 4) + payload = json.loads(base64.urlsafe_b64decode(encoded).decode("utf-8")) + except (ValueError, UnicodeDecodeError, json.JSONDecodeError): + return {} + return payload if isinstance(payload, dict) else {} + + +def kimi_refresh_headers_for_token(token, existing_headers=None): + """Complete direct-token configuration without requiring a copied cURL.""" + headers = dict(KIMI_DEFAULT_REFRESH_HEADERS) + if isinstance(existing_headers, dict): + headers.update({str(name).lower(): str(value) for name, value in existing_headers.items()}) + payload = _decode_jwt_payload(token) + claims = { + "x-msh-device-id": payload.get("device_id"), + "x-msh-session-id": payload.get("ssid"), + "x-traffic-id": payload.get("sub"), + } + headers.update({name: str(value) for name, value in claims.items() if value not in (None, "")}) + return headers + + +def parse_kimi_refresh_curl(refresh_curl): + """Extract the Kimi refresh token and safe request headers from a cURL.""" + refresh_url, refresh_args = parse_curl(refresh_curl) + endpoint = urlparse(refresh_url) + expected = urlparse(KIMI_REFRESH_URL) + if (endpoint.scheme, endpoint.hostname, endpoint.port, endpoint.path) != ( + expected.scheme, + expected.hostname, + expected.port, + expected.path, + ): + raise ValueError("Kimi RefreshToken cURL must target the RefreshToken endpoint") + + request, proxy = build_http_request(refresh_args) + if proxy: + raise ValueError("Kimi RefreshToken cURL must not contain a proxy") + if request.method != "POST" or request.data is None: + raise ValueError("Kimi RefreshToken cURL must contain a POST JSON body") + try: + payload = json.loads(request.data.decode("utf-8")) + except (UnicodeDecodeError, json.JSONDecodeError) as error: + raise ValueError("Kimi RefreshToken body must be valid JSON") from error + if not isinstance(payload, dict) or not str(payload.get("refresh_token", "")).strip(): + raise ValueError("Kimi RefreshToken body must contain refresh_token") + + headers = {} + for name, raw in _curl_header_entries(refresh_args): + if name not in KIMI_REFRESH_IGNORED_HEADERS: + headers[name] = _curl_header_value(raw) + return str(payload["refresh_token"]).strip(), headers + + +def _replace_curl_headers(existing_curl, updates): + """Replace selected headers in an existing parsed cURL without changing its body.""" + existing_url, existing_args = parse_curl(existing_curl) + merged = [existing_args[0]] + replaced = set() + index = 1 + while index < len(existing_args) - 1: + token = existing_args[index] + if token in {"-H", "--header"}: + raw = existing_args[index + 1] + name = _normalize_curl_header_name(raw) + if name in updates: + if name not in replaced: + merged.extend(["-H", f"{name}: {updates[name]}"]) + replaced.add(name) + else: + merged.extend([token, raw]) + index += 2 + continue + if token in {"-b", "--cookie"}: + if "cookie" in updates: + if "cookie" not in replaced: + merged.extend(["-H", f"Cookie: {updates['cookie']}"]) + replaced.add("cookie") + else: + merged.extend([token, existing_args[index + 1]]) + index += 2 + continue + if token in {"-A", "--user-agent"}: + if "user-agent" in updates: + if "user-agent" not in replaced: + merged.extend(["-H", f"User-Agent: {updates['user-agent']}"]) + replaced.add("user-agent") + else: + merged.extend([token, existing_args[index + 1]]) + index += 2 + continue + if token in ALLOWED_OPTIONS_WITH_VALUE: + merged.extend([token, existing_args[index + 1]]) + index += 2 + continue + merged.append(token) + index += 1 + for name, value in updates.items(): + if name not in replaced: + merged.extend(["-H", f"{name}: {value}"]) + merged.append(existing_url) + return " ".join(shlex.quote(arg) for arg in merged) + + +def _extract_json_value(payload, keys): + if isinstance(payload, dict): + for key, value in payload.items(): + if str(key).lower() in keys and isinstance(value, str) and value.strip(): + return value.strip() + for value in payload.values(): + found = _extract_json_value(value, keys) + if found: + return found + elif isinstance(payload, list): + for value in payload: + found = _extract_json_value(value, keys) + if found: + return found + return "" + + +def _response_error_message(body): + try: + payload = json.loads(body) + except (TypeError, ValueError): + return "" + if not isinstance(payload, dict): + return "" + details = payload.get("details") + if isinstance(details, list): + for detail in details: + if not isinstance(detail, dict): + continue + debug = detail.get("debug") + if isinstance(debug, dict): + reason = debug.get("reason") + if isinstance(reason, str) and reason.strip(): + return reason.strip()[:160] + value = detail.get("value") + if isinstance(value, str) and value.strip(): + return value.strip()[:160] + for key in ("message", "error_description", "error", "msg", "code"): + value = payload.get(key) + if isinstance(value, (str, int, float)) and str(value).strip(): + return str(value).strip()[:160] + return "" + + +def _set_cookie_pairs(headers): + pairs = {} + for value in headers or []: + pair = str(value).split(";", 1)[0].strip() + name, separator, cookie_value = pair.partition("=") + if separator and name.strip(): + pairs[name.strip()] = cookie_value.strip() + return pairs + + +def _merge_cookie_header(existing_cookie, set_cookie_headers): + cookies = {} + for part in str(existing_cookie or "").split(";"): + name, separator, value = part.strip().partition("=") + if separator and name: + cookies[name] = value + for name, value in _set_cookie_pairs(set_cookie_headers).items(): + if value: + cookies[name] = value + else: + cookies.pop(name, None) + return "; ".join(f"{name}={value}" for name, value in cookies.items()) + + +def _kimi_subscription_headers(curl): + _, args = parse_curl(curl) + return {name: _curl_header_value(raw) for name, raw in _curl_header_entries(args)} + + +def refresh_kimi_access_token(definition): + """Refresh Kimi credentials and return an updated subscription cURL definition.""" + refresh_token = str(definition.get("kimiRefreshToken", "")).strip() + if not refresh_token: + return 0, {}, "missing Kimi RefreshToken configuration" + configured_headers = definition.get("kimiRefreshHeaders", {}) + headers = { + str(name).lower(): str(value) + for name, value in configured_headers.items() + if isinstance(name, str) and name.lower() not in KIMI_REFRESH_IGNORED_HEADERS + } if isinstance(configured_headers, dict) else {} + headers["content-type"] = "application/json" + body = json.dumps({"refresh_token": refresh_token}, ensure_ascii=False, separators=(",", ":")).encode("utf-8") + request = Request(KIMI_REFRESH_URL, data=body, headers=headers, method="POST") + try: + with urlopen(request, timeout=35) as response: + response_body = response.read().decode("utf-8", errors="replace") + response_headers = response.headers.get_all("Set-Cookie", []) + status = response.status + except HTTPError as error: + response_body = error.read().decode("utf-8", errors="replace") + response_headers = error.headers.get_all("Set-Cookie", []) if error.headers else [] + return error.code, {}, f"Kimi RefreshToken HTTP {error.code}: {_response_error_message(response_body) or error.reason}" + except URLError as error: + return 1, {}, f"Kimi RefreshToken request failed: {error.reason}" + + if status != 200: + return status, {}, f"Kimi RefreshToken HTTP {status}: {_response_error_message(response_body) or 'request failed'}" + try: + payload = json.loads(response_body) + except json.JSONDecodeError: + return status, {}, "Kimi RefreshToken returned invalid JSON" + access_token = _extract_json_value(payload, {"access_token", "accesstoken", "token"}) + if not access_token: + return status, {}, "Kimi RefreshToken response did not contain an access token" + new_refresh_token = _extract_json_value(payload, {"refresh_token", "refreshtoken"}) + updated = dict(definition) + updated["kimiRefreshToken"] = new_refresh_token or refresh_token + subscription_headers = _kimi_subscription_headers(definition.get("curl", "")) + updates = {"authorization": f"Bearer {access_token}"} + updates.update({name: value for name, value in headers.items() if name in KIMI_DYNAMIC_HEADERS}) + cookie = _merge_cookie_header(subscription_headers.get("cookie", ""), response_headers) + if cookie: + updates["cookie"] = cookie + updated["curl"] = _replace_curl_headers(definition.get("curl", ""), updates) + return status, updated, "" + + +def merge_verification_curl(existing_curl, verification_curl, ignored_headers, required_prefixes, source_name): + """Merge verification headers from a new cURL into an existing one. + + Args: + existing_curl: The original cURL command to update. + verification_curl: The new cURL command containing fresh headers. + ignored_headers: Set of header names to skip (e.g. connection, content-length). + required_prefixes: Tuple of header name prefixes that must be present (e.g. ("authorization", "cookie", "x-msh-")). + source_name: Human-readable source name for error messages. + """ + existing_url, existing_args = parse_curl(existing_curl) + verification_url, verification_args = parse_curl(verification_curl) + if infer_source(existing_curl) != infer_source(verification_curl): + raise ValueError(f"both requests must target the same {source_name} endpoint") + existing_endpoint = urlparse(existing_url) + verification_endpoint = urlparse(verification_url) + if (existing_endpoint.scheme, existing_endpoint.hostname, existing_endpoint.port, existing_endpoint.path) != ( + verification_endpoint.scheme, + verification_endpoint.hostname, + verification_endpoint.port, + verification_endpoint.path, + ): + raise ValueError(f"new {source_name} request must target the existing endpoint") + updates = { + name: raw + for name, raw in _curl_header_entries(verification_args) + if name not in ignored_headers + } + if not updates or not any(name.startswith(required_prefixes) for name in updates): + raise ValueError(f"new {source_name} request is missing verification headers") + merged = [existing_args[0]] + replaced = set() + index = 1 + while index < len(existing_args) - 1: + token = existing_args[index] + if token in {"-H", "--header"}: + raw = existing_args[index + 1] + name = _normalize_curl_header_name(raw) + if name in updates: + if name not in replaced: + merged.extend(["-H", updates[name]]) + replaced.add(name) + else: + merged.extend([token, raw]) + index += 2 + continue + if token in {"-b", "--cookie"}: + if "cookie" in updates: + if "cookie" not in replaced: + merged.extend(["-H", updates["cookie"]]) + replaced.add("cookie") + else: + merged.extend([token, existing_args[index + 1]]) + index += 2 + continue + if token in {"-A", "--user-agent"}: + if "user-agent" in updates: + if "user-agent" not in replaced: + merged.extend(["-H", updates["user-agent"]]) + replaced.add("user-agent") + else: + merged.extend([token, existing_args[index + 1]]) + index += 2 + continue + if token in ALLOWED_OPTIONS_WITH_VALUE: + merged.extend([token, existing_args[index + 1]]) + index += 2 + continue + merged.append(token) + index += 1 + for name, raw in _curl_header_entries(verification_args): + if name in updates and name not in replaced: + merged.extend(["-H", raw]) + replaced.add(name) + merged.append(existing_args[-1]) + return " ".join(shlex.quote(arg) for arg in merged) + + +def merge_kimi_verification_curl(existing_curl, verification_curl): + return merge_verification_curl( + existing_curl, + verification_curl, + KIMI_IGNORED_HEADERS, + ("authorization", "cookie", "x-msh-"), + "Kimi", + ) + + +def merge_minimax_verification_curl(existing_curl, verification_curl): + return merge_verification_curl( + existing_curl, + verification_curl, + {"connection", "content-length", "host"}, + ("cookie", "authorization", "x-"), + "MiniMax", + ) + + def load_requests(path): value = load_snapshot(path) if not isinstance(value, dict): @@ -470,6 +950,12 @@ def do_GET(self): masked = {} for aid, acc in accounts.items(): item = dict(acc) + item.pop("proxy", None) + kimi_refresh_configured = bool(item.get("kimiRefreshToken")) + item.pop("kimiRefreshToken", None) + item.pop("kimiRefreshHeaders", None) + if acc.get("source") == "kimi": + item["hasKimiRefreshToken"] = kimi_refresh_configured if "sk" in item: item["sk"] = mask_secret(item["sk"]) item["hasCreds"] = True @@ -532,10 +1018,78 @@ def do_POST(self): explicit_source = str(payload.get("source", "")).strip() requests = load_requests(self.requests_path) existing = requests.get(account_id, {}) if account_id else {} + if "kimiRefreshToken" in payload: + if not account_id: + raise ValueError("id is required for Kimi RefreshToken updates") + if existing.get("source") != "kimi": + raise ValueError("account is not a Kimi account") + refresh_token_value = str(payload.get("kimiRefreshToken", "")).strip() + if not refresh_token_value: + raise ValueError("kimiRefreshToken is required") + updated = dict(existing) + updated["kimiRefreshToken"] = refresh_token_value + updated["kimiRefreshHeaders"] = kimi_refresh_headers_for_token( + refresh_token_value, + existing.get("kimiRefreshHeaders", {}), + ) + updated["updatedAt"] = now_iso() + requests[account_id] = updated + save_requests(self.requests_path, requests) + self.send_json({"ok": True, "id": account_id, "source": "kimi", "updatedAt": updated["updatedAt"]}) + return + if "kimiRefreshCurl" in payload: + if not account_id: + raise ValueError("id is required for Kimi RefreshToken updates") + if existing.get("source") != "kimi": + raise ValueError("account is not a Kimi account") + refresh_curl = str(payload.get("kimiRefreshCurl", "")).strip() + if not refresh_curl: + raise ValueError("kimiRefreshCurl is required") + refresh_token_value, refresh_headers = parse_kimi_refresh_curl(refresh_curl) + updated = dict(existing) + updated["kimiRefreshToken"] = refresh_token_value + updated["kimiRefreshHeaders"] = refresh_headers + updated["updatedAt"] = now_iso() + requests[account_id] = updated + save_requests(self.requests_path, requests) + self.send_json({"ok": True, "id": account_id, "source": "kimi", "updatedAt": updated["updatedAt"]}) + return + if "kimiVerificationCurl" in payload: + if not account_id: + raise ValueError("id is required for Kimi verification updates") + if existing.get("source") != "kimi": + raise ValueError("account is not a Kimi account") + verification_curl = str(payload.get("kimiVerificationCurl", "")).strip() + if not verification_curl: + raise ValueError("kimiVerificationCurl is required") + updated = dict(existing) + updated["curl"] = merge_kimi_verification_curl(existing.get("curl", ""), verification_curl) + updated["updatedAt"] = now_iso() + requests[account_id] = updated + save_requests(self.requests_path, requests) + self.send_json({"ok": True, "id": account_id, "source": "kimi", "updatedAt": updated["updatedAt"]}) + return + if "minimaxVerificationCurl" in payload: + if not account_id: + raise ValueError("id is required for MiniMax verification updates") + if existing.get("source") != "minimax": + raise ValueError("account is not a MiniMax account") + verification_curl = str(payload.get("minimaxVerificationCurl", "")).strip() + if not verification_curl: + raise ValueError("minimaxVerificationCurl is required") + updated = dict(existing) + updated["curl"] = merge_minimax_verification_curl(existing.get("curl", ""), verification_curl) + updated["updatedAt"] = now_iso() + requests[account_id] = updated + save_requests(self.requests_path, requests) + self.send_json({"ok": True, "id": account_id, "source": "minimax", "updatedAt": updated["updatedAt"]}) + return if not curl and existing: curl = existing.get("curl", "") if curl: source = infer_source(curl) + if not account_id and source in {NEWAPI_CODEX_USAGE_PATH, NEWAPI_CODEX_CREDITS_PATH}: + account_id = find_matching_newapi_account(curl, requests) or "" elif explicit_source in CREDENTIAL_SOURCES and not existing: source = explicit_source if source in VOLC_ACTIONS and not (ak and sk_input): @@ -556,6 +1110,9 @@ def do_POST(self): if source == "googleAi": definition["refreshToken"] = refresh_token or existing.get("refreshToken", "") definition["proxy"] = proxy_input or existing.get("proxy", "") + if source == "kimi" and existing.get("source") == "kimi": + definition["kimiRefreshToken"] = existing.get("kimiRefreshToken", "") + definition["kimiRefreshHeaders"] = existing.get("kimiRefreshHeaders", {}) requests[account_id] = definition save_requests(self.requests_path, requests) self.send_json({"ok": True, "id": account_id, "source": source}) @@ -584,6 +1141,7 @@ def do_POST(self): cached_results = load_results(self.results_path) credentials = load_credentials(self.credentials_path) accounts = load_requests(self.requests_path) + requests_changed = False for account_id, definition in accounts.items(): source = definition.get("source", "") if should_skip_source(source, accounts): @@ -603,15 +1161,32 @@ def do_POST(self): code, stdout, stderr = execute_google_ai({"refreshToken": refresh_token, "proxy": proxy}) else: code, stdout, stderr = execute_curl(definition.get("curl", "")) + elif source == "kimi" and definition.get("kimiRefreshToken"): + code, refreshed_definition, stderr = refresh_kimi_access_token(definition) + if refreshed_definition: + accounts[account_id] = refreshed_definition + requests_changed = True + definition = refreshed_definition + code, stdout, curl_error = execute_curl(definition.get("curl", "")) + stderr = curl_error + else: + stdout = "" + if code == 200: + code = 502 else: code, stdout, stderr = execute_curl(definition.get("curl", "")) - updated_at = now_iso() if is_success_status(code) else None - result = {"ok": is_success_status(code), "status": code, "body": stdout, "error": stderr, "updatedAt": updated_at} + provider_ok = provider_response_ok(source, code, stdout) + if not provider_ok and is_success_status(code): + stderr = stderr or provider_response_error(source, stdout) or "provider returned an unsuccessful business response" + updated_at = now_iso() if provider_ok else None + result = {"ok": provider_ok, "status": code, "body": stdout, "error": stderr, "updatedAt": updated_at} results[account_id] = result - if is_success_status(code): + if provider_ok: cached_results[account_id] = result except (ValueError, OSError, TimeoutError) as error: results[account_id] = {"ok": False, "status": None, "body": "", "error": str(error)} + if requests_changed: + save_requests(self.requests_path, accounts) save_results(self.results_path, cached_results) self.send_json(results) except (ValueError, UnicodeDecodeError, json.JSONDecodeError) as error: diff --git a/tests/parser.test.js b/tests/parser.test.js index 4b4c6a4..2dc0844 100644 --- a/tests/parser.test.js +++ b/tests/parser.test.js @@ -9,7 +9,8 @@ const { normalizeKimi, normalizeLongCat, normalizeQianwen, - normalizeVolcengine + normalizeVolcengine, + normalizeZhipu } = require('../parser.js'); test('normalizes Codex reset credit count', () => { @@ -165,13 +166,13 @@ test('normalizes Kimi Code subscription usage periods', () => { const result = normalizeKimi({ ratelimitCode5h: { ratio: 0.0002, enabled: true, resetTime: '2026-07-17T09:44:50.542928506Z' }, ratelimitCode7d: { ratio: 0.0001, enabled: true, resetTime: '2026-07-24T04:44:49.542928506Z' }, - subscriptionBalance: { amountUsedRatio: 0.0001, kimiCodeUsedRatio: 0.0001, expireTime: '2026-08-17T04:44:51Z' } + subscriptionBalance: { amountUsedRatio: 0.0933, kimiCodeUsedRatio: 0.0795, expireTime: '2026-08-17T04:44:51Z' } }); assert.deepEqual(result.periods.map(period => period.name), ['5h', '7d', '订阅']); assert.ok(Math.abs(result.periods[0].usedPercent - 0.02) < 0.000001); assert.equal(result.periods[0].resetAt, '2026-07-17T09:44:50.542928506Z'); assert.ok(Math.abs(result.periods[1].usedPercent - 0.01) < 0.000001); - assert.ok(Math.abs(result.periods[2].usedPercent - 0.01) < 0.000001); + assert.ok(Math.abs(result.periods[2].usedPercent - 9.33) < 0.000001); assert.equal(result.periods[2].resetAt, '2026-08-17T04:44:51Z'); }); @@ -250,32 +251,74 @@ test('normalizes Qianwen AI TokenPlan usage periods', () => { assert.equal(result.unit, '%'); }); -test('normalizes Google AI Gemini 3.5 Flash quota usage', () => { +test('normalizes Zhipu CodingPlan token and time limits', () => { + const result = normalizeZhipu({ + data: { + limits: [ + { type: 'TIME_LIMIT', percentage: '8.2%' }, + { type: 'TOKENS_LIMIT', unit: 6, number: 1, percentage: 45, nextResetTime: 1787607163997 }, + { type: 'TOKENS_LIMIT', unit: 3, number: 5, percentage: 12.5, nextResetTime: 1787176502893 }, + { type: 'UNKNOWN_LIMIT', percentage: 99 } + ] + } + }); + assert.deepEqual(result.periods.map(period => period.name), ['5h', 'weekly', 'time']); + assert.equal(result.periods[0].usedPercent, 12.5); + assert.equal(result.periods[0].remainingPercent, 87.5); + assert.equal(result.periods[0].resetAt, 1787176502893); + assert.equal(result.periods[1].usedPercent, 45); + assert.equal(result.periods[1].resetAt, 1787607163997); + assert.equal(result.periods[2].usedPercent, 8.2); + assert.equal(result.used, 45); + assert.equal(result.remaining, 55); + assert.equal(result.limit, 100); + assert.equal(result.unit, '%'); +}); + +test('orders Zhipu token windows by reset time when window metadata is absent', () => { + const result = normalizeZhipu({ + data: { + limits: [ + { type: 'TOKENS_LIMIT', percentage: 41, nextResetTime: 1787607163997 }, + { type: 'TOKENS_LIMIT', percentage: 9, nextResetTime: 1787176502893 } + ] + } + }); + assert.deepEqual(result.periods.map(period => period.name), ['5h', 'weekly']); + assert.equal(result.periods[0].usedPercent, 9); + assert.equal(result.periods[1].usedPercent, 41); +}); + +test('normalizes an empty Zhipu CodingPlan response', () => { + const result = normalizeZhipu({ data: { limits: [] } }); + assert.deepEqual(result.periods, []); + assert.equal(result.used, 0); + assert.equal(result.remaining, 100); +}); + +test('normalizes Google AI Gemini Models five-hour and weekly quota usage', () => { const { normalizeGoogleAi } = require('../parser.js'); const result = normalizeGoogleAi({ - models: { - 'gemini-3-flash-agent': { - displayName: 'Gemini 3.5 Flash (High)', - quotaInfo: { remainingFraction: 0.55, resetTime: '2026-07-22T06:06:29Z' } - }, - 'other-model': { - displayName: 'Gemini 3.1 Pro', - quotaInfo: { remainingFraction: 0.1, resetTime: '2026-07-22T06:06:29Z' } - } - } + groups: [{ + displayName: 'Gemini Models', + buckets: [ + { bucketId: 'gemini-weekly', window: 'weekly', remainingFraction: 0.99498266 }, + { bucketId: 'gemini-5h', window: '5h', remainingFraction: 1 } + ] + }] }); - assert.equal(result.periods.length, 1); - assert.equal(result.periods[0].name, 'Gemini 3.5 Flash'); - assert.ok(Math.abs(result.periods[0].usedPercent - 45) < 0.000001); - assert.equal(result.periods[0].resetAt, '2026-07-22T06:06:29Z'); - assert.ok(Math.abs(result.used - 45) < 0.000001); + assert.equal(result.periods.length, 2); + assert.deepEqual(result.periods.map(period => period.name), ['5h', 'weekly']); + assert.equal(result.periods[0].usedPercent, 0); + assert.ok(Math.abs(result.periods[1].usedPercent - 0.501734) < 0.000001); + assert.ok(Math.abs(result.used - 0.501734) < 0.000001); assert.equal(result.limit, 100); assert.equal(result.unit, '%'); }); -test('normalizes Google AI with no matching model returns empty periods', () => { +test('normalizes Google AI without Gemini Models group as empty periods', () => { const { normalizeGoogleAi } = require('../parser.js'); - const result = normalizeGoogleAi({ models: { 'x': { displayName: 'Other', quotaInfo: { remainingFraction: 1 } } } }); + const result = normalizeGoogleAi({ groups: [{ displayName: 'Claude and GPT models', buckets: [] }] }); assert.equal(result.periods.length, 0); assert.equal(result.used, 0); }); diff --git a/tests/test_server.py b/tests/test_server.py index 420e67a..a719b22 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -1,3 +1,4 @@ +import base64 import json import tempfile import unittest @@ -13,8 +14,13 @@ load_results, load_order, load_snapshot, + kimi_refresh_headers_for_token, + merge_kimi_verification_curl, + merge_minimax_verification_curl, mask_secret, + parse_kimi_refresh_curl, parse_curl, + refresh_kimi_access_token, save_credentials, save_order, save_requests, @@ -70,6 +76,275 @@ def test_load_requests_migrates_old_format(self): self.assertEqual(loaded, loaded2) class CurlImportTest(unittest.TestCase): + def test_parses_kimi_refresh_curl_without_retaining_raw_command(self): + refresh_curl = "curl --url 'https://auth.kimi.com/api/account.gateway.v1.AuthService/RefreshToken' -H 'content-type: application/json' -H 'x-msh-device-id: REDACTED_DEVICE' --data-raw '{\"refresh_token\":\"REDACTED_REFRESH\"}'" + + token, headers = parse_kimi_refresh_curl(refresh_curl) + + self.assertEqual(token, "REDACTED_REFRESH") + self.assertEqual(headers["x-msh-device-id"], "REDACTED_DEVICE") + self.assertNotIn("content-type", headers) + + def test_rejects_non_refresh_kimi_endpoint(self): + with self.assertRaisesRegex(ValueError, "RefreshToken endpoint"): + parse_kimi_refresh_curl("curl 'https://www.kimi.com/not-refresh' --data-raw '{}'") + + def test_saves_kimi_refresh_config_but_masks_it_from_requests_api(self): + from io import BytesIO + from server import DashboardHandler + + existing = "curl 'https://www.kimi.com/apiv2/kimi.gateway.membership.v2.MembershipService/GetSubscriptionStats' -H 'authorization: Bearer REDACTED_ACCESS' --data-raw '{}'" + refresh_curl = "curl --url 'https://auth.kimi.com/api/account.gateway.v1.AuthService/RefreshToken' -H 'x-msh-device-id: REDACTED_DEVICE' --data-raw '{\"refresh_token\":\"REDACTED_REFRESH\"}'" + with tempfile.TemporaryDirectory() as tmp: + req_path = Path(tmp) / "requests.json" + save_requests(req_path, {"acc_k": {"source": "kimi", "label": "Kimi", "curl": existing}}) + DashboardHandler.requests_path = req_path + body = json.dumps({"id": "acc_k", "kimiRefreshCurl": refresh_curl}).encode() + handler = DashboardHandler.__new__(DashboardHandler) + handler.path = "/api/requests" + handler.headers = {"Content-Length": str(len(body))} + handler.rfile = BytesIO(body) + handler.send_json = lambda payload: setattr(handler, "captured", payload) + + DashboardHandler.do_POST(handler) + + stored = load_requests(req_path)["acc_k"] + self.assertEqual(stored["kimiRefreshToken"], "REDACTED_REFRESH") + self.assertNotIn("refresh_curl", stored) + + output_handler = DashboardHandler.__new__(DashboardHandler) + output_handler.path = "/api/requests" + output_handler.send_json = lambda payload: setattr(output_handler, "output", payload) + DashboardHandler.do_GET(output_handler) + account = output_handler.output["acc_k"] + self.assertTrue(account["hasKimiRefreshToken"]) + self.assertNotIn("kimiRefreshToken", account) + self.assertNotIn("kimiRefreshHeaders", account) + + def test_saves_kimi_refresh_token_directly_and_derives_headers(self): + from io import BytesIO + from server import DashboardHandler + + def encoded(value): + return base64.urlsafe_b64encode(json.dumps(value).encode()).rstrip(b"=").decode() + + token = ".".join([ + encoded({"alg": "HS512"}), + encoded({"device_id": "REDACTED_DEVICE", "ssid": "REDACTED_SESSION", "sub": "REDACTED_TRAFFIC"}), + "REDACTED_SIGNATURE", + ]) + existing = "curl 'https://www.kimi.com/apiv2/kimi.gateway.membership.v2.MembershipService/GetSubscriptionStats' -H 'authorization: Bearer REDACTED_ACCESS' --data-raw '{}'" + with tempfile.TemporaryDirectory() as tmp: + req_path = Path(tmp) / "requests.json" + save_requests(req_path, {"acc_k": {"source": "kimi", "label": "Kimi", "curl": existing}}) + DashboardHandler.requests_path = req_path + body = json.dumps({"id": "acc_k", "kimiRefreshToken": token}).encode() + handler = DashboardHandler.__new__(DashboardHandler) + handler.path = "/api/requests" + handler.headers = {"Content-Length": str(len(body))} + handler.rfile = BytesIO(body) + handler.send_json = lambda payload: setattr(handler, "captured", payload) + + DashboardHandler.do_POST(handler) + + stored = load_requests(req_path)["acc_k"] + self.assertEqual(stored["kimiRefreshToken"], token) + headers = stored["kimiRefreshHeaders"] + self.assertEqual(headers["x-msh-device-id"], "REDACTED_DEVICE") + self.assertEqual(headers["x-msh-session-id"], "REDACTED_SESSION") + self.assertEqual(headers["x-traffic-id"], "REDACTED_TRAFFIC") + self.assertEqual(headers["x-msh-platform"], "web") + self.assertNotIn("kimiRefreshCurl", stored) + + def test_refreshes_kimi_access_token_and_rotates_saved_credentials(self): + import server + from unittest.mock import patch + + class FakeHeaders: + def get_all(self, name, default=None): + return ["kimi-auth=REDACTED_COOKIE; Path=/"] if name.lower() == "set-cookie" else default + + class FakeResponse: + status = 200 + headers = FakeHeaders() + + def read(self): + return b'{"access_token":"REDACTED_ACCESS_NEW","refresh_token":"REDACTED_REFRESH_NEW"}' + + def __enter__(self): + return self + + def __exit__(self, *_args): + return None + + existing = "curl 'https://www.kimi.com/apiv2/kimi.gateway.membership.v2.MembershipService/GetSubscriptionStats' -H 'authorization: Bearer REDACTED_ACCESS_OLD' -H 'cookie: other=REDACTED_OTHER; kimi-auth=REDACTED_OLD_COOKIE' -H 'x-msh-device-id: REDACTED_DEVICE_OLD' --data-raw '{}'" + definition = { + "source": "kimi", + "curl": existing, + "kimiRefreshToken": "REDACTED_REFRESH_OLD", + "kimiRefreshHeaders": { + "x-msh-device-id": "REDACTED_DEVICE_NEW", + "x-msh-session-id": "REDACTED_SESSION", + }, + } + + with patch.object(server, "urlopen", return_value=FakeResponse()) as mocked_urlopen: + status, updated, error = refresh_kimi_access_token(definition) + + self.assertEqual(status, 200) + self.assertEqual(error, "") + self.assertEqual(updated["kimiRefreshToken"], "REDACTED_REFRESH_NEW") + url, args = parse_curl(updated["curl"]) + request, _ = build_http_request(args) + self.assertEqual(url, "https://www.kimi.com/apiv2/kimi.gateway.membership.v2.MembershipService/GetSubscriptionStats") + self.assertEqual(request.get_header("Authorization"), "Bearer REDACTED_ACCESS_NEW") + self.assertEqual(request.get_header("X-msh-device-id"), "REDACTED_DEVICE_NEW") + self.assertIn("kimi-auth=REDACTED_COOKIE", request.get_header("Cookie")) + self.assertIn("other=REDACTED_OTHER", request.get_header("Cookie")) + mocked_request = mocked_urlopen.call_args.args[0] + self.assertEqual(json.loads(mocked_request.data.decode())["refresh_token"], "REDACTED_REFRESH_OLD") + self.assertEqual(mocked_request.get_header("X-msh-device-id"), "REDACTED_DEVICE_NEW") + + def test_reports_nested_kimi_refresh_error_reason(self): + import server + from unittest.mock import patch + + class FakeHeaders: + def get_all(self, _name, default=None): + return default + + class FakeResponse: + status = 401 + headers = FakeHeaders() + + def read(self): + return b'{"code":"unauthenticated","details":[{"debug":{"reason":"REASON_INVALID_AUTH_TOKEN"}}]}' + + def __enter__(self): + return self + + def __exit__(self, *_args): + return None + + definition = { + "source": "kimi", + "curl": "curl 'https://www.kimi.com/apiv2/kimi.gateway.membership.v2.MembershipService/GetSubscriptionStats' --data-raw '{}'", + "kimiRefreshToken": "REDACTED_REFRESH", + "kimiRefreshHeaders": {}, + } + with patch.object(server, "urlopen", return_value=FakeResponse()): + status, updated, error = refresh_kimi_access_token(definition) + + self.assertEqual(status, 401) + self.assertEqual(updated, {}) + self.assertIn("REASON_INVALID_AUTH_TOKEN", error) + + def test_refresh_endpoint_uses_new_kimi_credentials_before_quota_request(self): + from io import BytesIO + from server import DashboardHandler + from unittest.mock import patch + + existing = "curl 'https://www.kimi.com/apiv2/kimi.gateway.membership.v2.MembershipService/GetSubscriptionStats' -H 'authorization: Bearer REDACTED_ACCESS_OLD' --data-raw '{}'" + refreshed = dict( + source="kimi", + label="Kimi", + curl=existing.replace("REDACTED_ACCESS_OLD", "REDACTED_ACCESS_NEW"), + kimiRefreshToken="REDACTED_REFRESH_NEW", + kimiRefreshHeaders={"x-msh-device-id": "REDACTED_DEVICE"}, + ) + with tempfile.TemporaryDirectory() as tmp: + DashboardHandler.requests_path = Path(tmp) / "requests.json" + DashboardHandler.results_path = Path(tmp) / "results.json" + DashboardHandler.credentials_path = Path(tmp) / "credentials.json" + save_requests(DashboardHandler.requests_path, { + "acc_k": { + "source": "kimi", + "label": "Kimi", + "curl": existing, + "kimiRefreshToken": "REDACTED_REFRESH_OLD", + "kimiRefreshHeaders": {"x-msh-device-id": "REDACTED_DEVICE"}, + } + }) + body = b"{}" + handler = DashboardHandler.__new__(DashboardHandler) + handler.path = "/api/refresh" + handler.headers = {"Content-Length": str(len(body))} + handler.rfile = BytesIO(body) + handler.send_json = lambda payload: setattr(handler, "captured", payload) + + with patch("server.refresh_kimi_access_token", return_value=(200, refreshed, "")) as refresh_mock, patch( + "server.execute_curl", return_value=(200, '{"subscriptionBalance":{}}', "") + ) as curl_mock: + DashboardHandler.do_POST(handler) + + self.assertTrue(handler.captured["acc_k"]["ok"]) + refresh_mock.assert_called_once() + curl_mock.assert_called_once_with(refreshed["curl"]) + self.assertEqual(load_requests(DashboardHandler.requests_path)["acc_k"]["kimiRefreshToken"], "REDACTED_REFRESH_NEW") + + def test_merges_kimi_verification_headers_and_preserves_request_body(self): + existing = "curl 'https://www.kimi.com/apiv2/kimi.gateway.membership.v2.MembershipService/GetSubscriptionStats' -H 'accept: application/json' -H 'authorization: Bearer REDACTED_OLD' -H 'x-msh-device-id: REDACTED_DEVICE_OLD' --data-raw '{\"scope\":\"subscription\"}'" + verification = "curl 'https://www.kimi.com/apiv2/kimi.gateway.membership.v2.MembershipService/GetSubscriptionStats' -H 'authorization: Bearer REDACTED_NEW' -H 'x-msh-device-id: REDACTED_DEVICE_NEW' -H 'x-msh-shield-data: REDACTED_SHIELD'" + + merged = merge_kimi_verification_curl(existing, verification) + url, args = parse_curl(merged) + request, _ = build_http_request(args) + + self.assertEqual(url, "https://www.kimi.com/apiv2/kimi.gateway.membership.v2.MembershipService/GetSubscriptionStats") + self.assertEqual(request.data, b'{"scope":"subscription"}') + self.assertEqual(request.get_header("Authorization"), "Bearer REDACTED_NEW") + self.assertEqual(request.get_header("X-msh-device-id"), "REDACTED_DEVICE_NEW") + self.assertEqual(request.get_header("X-msh-shield-data"), "REDACTED_SHIELD") + self.assertNotIn("REDACTED_OLD", merged) + + def test_updates_existing_kimi_verification_headers(self): + from io import BytesIO + from server import DashboardHandler + + existing = "curl 'https://www.kimi.com/apiv2/kimi.gateway.membership.v2.MembershipService/GetSubscriptionStats' -H 'authorization: Bearer REDACTED_OLD' --data-raw '{}'" + verification = "curl 'https://www.kimi.com/apiv2/kimi.gateway.membership.v2.MembershipService/GetSubscriptionStats' -H 'authorization: Bearer REDACTED_NEW' -H 'x-msh-shield-data: REDACTED_SHIELD'" + with tempfile.TemporaryDirectory() as tmp: + req_path = Path(tmp) / "requests.json" + save_requests(req_path, {"acc_k": {"source": "kimi", "label": "Kimi", "curl": existing}}) + DashboardHandler.requests_path = req_path + body = json.dumps({"id": "acc_k", "kimiVerificationCurl": verification}).encode() + handler = DashboardHandler.__new__(DashboardHandler) + handler.path = "/api/requests" + handler.headers = {"Content-Length": str(len(body))} + handler.rfile = BytesIO(body) + handler.send_json = lambda payload: setattr(handler, "captured", payload) + handler.send_error = lambda code, message=None: setattr(handler, "error", (code, message)) + + DashboardHandler.do_POST(handler) + + self.assertEqual(handler.captured["source"], "kimi") + updated = load_requests(req_path)["acc_k"]["curl"] + self.assertIn("REDACTED_NEW", updated) + self.assertIn("REDACTED_SHIELD", updated) + self.assertNotIn("REDACTED_OLD", updated) + + def test_merges_minimax_verification_curl_and_preserves_request_body(self): + existing = "curl 'https://www.minimaxi.com/backend/account/token_plan/remains_percent' -H 'accept: application/json' -b 'session=abc; _token=OLD_TOKEN' --data-raw '{}'" + verification = "curl 'https://www.minimaxi.com/backend/account/token_plan/remains_percent' -H 'accept: application/json' -b 'session=abc; _token=NEW_TOKEN; minimax_group_id_v2=123' -H 'x-custom: value'" + + merged = merge_minimax_verification_curl(existing, verification) + url, args = parse_curl(merged) + request, _ = build_http_request(args) + + self.assertEqual(url, "https://www.minimaxi.com/backend/account/token_plan/remains_percent") + self.assertEqual(request.data, b'{}') + self.assertEqual(request.get_header("Cookie"), "session=abc; _token=NEW_TOKEN; minimax_group_id_v2=123") + self.assertEqual(request.get_header("X-custom"), "value") + self.assertNotIn("OLD_TOKEN", merged) + + def test_minimax_business_error_is_not_provider_success(self): + from server import provider_response_ok, provider_response_error + body = '{"base_resp":{"status_code":1016,"status_msg":"invalid api key"}}' + self.assertFalse(provider_response_ok("minimax", 200, body)) + self.assertEqual(provider_response_error("minimax", body), "invalid api key") + self.assertTrue(provider_response_ok("minimax", 200, '{"base_resp":{"status_code":0,"status_msg":"success"}}')) + self.assertTrue(provider_response_ok("minimax", 200, '{"model_remains":[]}')) + def test_only_http_200_is_a_successful_provider_result(self): self.assertTrue(is_success_status(200)) self.assertFalse(is_success_status(0)) @@ -108,6 +383,46 @@ def test_infers_source_from_endpoint(self): self.assertEqual(infer_source("curl https://console.volcengine.com/api/top/ark/cn-beijing/2024-01-01/GetCodingPlanUsage?"), "volcCoding") self.assertEqual(infer_source("curl https://console.volcengine.com/api/top/ark/cn-beijing/2024-01-01/GetAgentPlanUsageDetails?"), "volcAgent") self.assertEqual(infer_source("curl https://console.volcengine.com/api/top/ark/cn-beijing/2024-01-01/GetAgentPlanAFPUsage?"), "volcAgent") + self.assertEqual(infer_source("curl https://www.bigmodel.cn/api/monitor/usage/quota/limit"), "zhipuCoding") + self.assertEqual(infer_source("curl https://www.bigmodel.cn/api/monitor/usage/quota/limit/"), "zhipuCoding") + + def test_parses_curl_url_option(self): + command = "curl --url 'https://www.kimi.com/apiv2/kimi.gateway.membership.v2.MembershipService/GetSubscriptionStats' -H 'x-msh-shield-data: REDACTED_SHIELD'" + url, args = parse_curl(command) + self.assertEqual(url, "https://www.kimi.com/apiv2/kimi.gateway.membership.v2.MembershipService/GetSubscriptionStats") + request, _ = build_http_request(args) + self.assertEqual(request.get_header("X-msh-shield-data"), "REDACTED_SHIELD") + + def test_newapi_import_reuses_matching_endpoint_account(self): + from server import find_matching_newapi_account + curl = "curl 'http://newapi.example.lan:3000/api/channel/26/codex/usage'" + requests = { + "acc_old": { + "source": "codexNewApi", + "curl": curl, + } + } + import unittest.mock + import server + with unittest.mock.patch.object(server, "NEWAPI_HOSTS", {"newapi.example.lan"}): + self.assertEqual(find_matching_newapi_account(curl, requests), "acc_old") + + def test_newapi_unauthorized_http_200_is_not_provider_success(self): + from server import provider_response_ok + self.assertFalse(provider_response_ok("codexNewApi", 200, '{"success":false,"message":"Unauthorized"}')) + self.assertTrue(provider_response_ok("codexNewApi", 200, '{"success":true,"data":{}}')) + + def test_qianwen_login_error_http_200_is_not_provider_success(self): + from server import provider_response_error, provider_response_ok + body = '{"code":"200","data":{"success":false,"errorCode":"BailianGateway.Login.NotLogined","errorMsg":"BailianGateway.Login.NotLogined"}}' + self.assertFalse(provider_response_ok("qianwen", 200, body)) + self.assertEqual(provider_response_error("qianwen", body), "BailianGateway.Login.NotLogined") + self.assertTrue(provider_response_ok("qianwen", 200, '{"data":{"success":true,"errorCode":"","errorMsg":""}}')) + + def test_zhipu_business_response_requires_limits_array(self): + from server import provider_response_ok + self.assertTrue(provider_response_ok("zhipuCoding", 200, '{"data":{"limits":[]}}')) + self.assertFalse(provider_response_ok("zhipuCoding", 200, '{"data":{"message":"unauthorized"}}')) def test_parses_allowed_curl_without_shell(self): command = "curl 'https://www.minimaxi.com/backend/account/token_plan/remains_percent' -H 'accept: application/json' --data-raw '{}'" @@ -377,6 +692,35 @@ def test_edit_label_on_google_ai_account_preserves_token(self): self.assertEqual(result["refreshToken"], "RT_OLD") self.assertEqual(result["proxy"], "http://p:1") + def test_google_ai_proxy_is_not_returned_to_frontend(self): + from server import DashboardHandler + + with tempfile.TemporaryDirectory() as tmp: + req_path = Path(tmp) / "requests.json" + save_requests(req_path, { + "acc_g": { + "source": "googleAi", + "label": "google", + "curl": "", + "refreshToken": "RT_SECRET", + "proxy": "http://real-private-proxy:1091", + } + }) + DashboardHandler.requests_path = req_path + + handler = DashboardHandler.__new__(DashboardHandler) + handler.path = "/api/requests" + captured = {} + handler.send_json = lambda payload: captured.update({"payload": payload}) + + DashboardHandler.do_GET(handler) + + self.assertNotIn("proxy", captured["payload"]["acc_g"]) + self.assertEqual( + load_requests(req_path)["acc_g"]["proxy"], + "http://real-private-proxy:1091", + ) + if __name__ == "__main__": unittest.main()