provider, gui: a login token beside sub2api's /v1/usage is told the panel's account query, not sent to the key's
What changed: - balance.go: the guard that never sends a balance token to new-api's /api/usage/token (c9e47f043) now covers sub2api's /v1/usage too, and says to set <site>/api/v1/user/profile (Balance field $data.balance) or remove the token, as the new-api branch says its /api/user/self. - gui: the editor's token warning (balanceFix) and the refusal wording (balanceError) each name sub2api's /v1/usage beside the token; two new strings in zh, zh-TW, ja and de. Run: - TestSub2APIKeyUsageWithLoginToken (new): a JWT beside /v1/usage is never sent there and the panel's account query is named; the key alone still asks. On upstream/main2c18c697it fails asked=true with the panel's raw 401 (the token went out as Authorization). - TestKeyUsageWithAccessToken, TestBalanceKeyAsBearer and the balance tests unchanged; go test -tags nogui -p 2 -count=1 ./internal/provider ok (71.9s). i18n-keys.test.cjs 3/3. - gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows on internal/provider and internal/gui; go build darwin, GOOS=linux -tags nogui, GOOS=windows. Generated-by: GLM-5.3-Flash (ZCode) Review (yetone, #2217): read line by line and kept, with one change in the GUI. The editor's warning for a token beside /v1/usage offered both /api/user/self and /api/v1/user/profile, but /v1/usage is sub2api's, so only the panel's profile is offered now, and a saved "$remaining" (the key query's field) gives way to $data.balance as the button sets the URL. balance-fix.test.cjs gets a test for it (chromium and webkit, 440 wide): it is red on the patch's app.js ("only sub2api's account query is offered") and on main's. Run at the reviewed head, on origin/main2a99e7a42, and again on91b9065a5for vet, gui, provider, tui, gateway, agent and the tests named here: - TestSub2APIKeyUsageWithLoginToken is red with main's balance.go (ok true, the panel's 401 "invalid API key", asked true) and green with the patch. - node --test balance-fix.test.cjs i18n-keys.test.cjs: 103 pass, 0 fail (chromium + webkit; the file's matrix is en, zh, ja, de at 900 and 440; zh-TW strings are checked by i18n-keys only). - gofmt -l; go vet darwin, GOOS=linux -tags nogui, GOOS=windows ./...; go build for the three; go test -tags nogui -count=1 -p 4 ./... at a machine load of 100-150: 50 packages ok; internal/agent and internal/gateway ran past the 10m default under that load and pass with -timeout 40m (674s, 798s); internal/gui's TestSetAnswersWhileDevinAndProvidersHang failed once (a state took 10.4s; open as #1375) and the package passes rerun. Not tried: a real sub2api panel.
This commit is contained in:
@@ -12612,12 +12612,13 @@ function balanceFieldOf(raw) {
|
||||
// knows the fix (see balance.go); "" for any other.
|
||||
function balanceError(err) {
|
||||
if (/takes the API key, not the access token/.test(err)) return t("The Balance URL …/api/usage/token takes the API key, not the access token — set it to …/api/user/self in the provider's settings");
|
||||
if (/takes the API key, not the login token/.test(err)) return t("The Balance URL …/v1/usage takes the API key, not the login token — set it to …/api/v1/user/profile in the provider's settings");
|
||||
if (/New-Api-User/i.test(err)) return t("Add the header New-Api-User = your user ID (shown in the site's personal settings) to the provider's Headers");
|
||||
return "";
|
||||
}
|
||||
|
||||
// An account token is unused without a Balance URL and can't authenticate
|
||||
// /api/usage/token, which takes API keys only. Other URLs may belong to
|
||||
// /api/usage/token or sub2api's /v1/usage, which take API keys only. Other URLs may belong to
|
||||
// another relay and are left alone; both new-api and sub2api issue JWTs.
|
||||
function balanceFix(p) {
|
||||
const box = el("div", "bal-fix");
|
||||
@@ -12632,20 +12633,21 @@ function balanceFix(p) {
|
||||
try { path = new URL(u).pathname.replace(/\/+$/, ""); } catch {}
|
||||
let why = "";
|
||||
if (path === "/api/usage/token") why = t("…/api/usage/token takes the API key, not this token: for the account's balance, new-api uses /api/user/self; sub2api uses /api/v1/user/profile.");
|
||||
else if (path === "/v1/usage") why = t("…/v1/usage takes the API key, not this token: for the account's balance, a sub2api panel uses /api/v1/user/profile.");
|
||||
else if (!u) why = t("The token needs a Balance URL: a new-api relay uses /api/user/self; a sub2api panel uses /api/v1/user/profile to read the account's balance.");
|
||||
if (why) {
|
||||
box.classList.add("warn");
|
||||
box.append(el("span", "", why));
|
||||
const site = origin(u) || origin(draft.chat || draft.anthropic || draft.responses || "");
|
||||
if (!site) return;
|
||||
for (const path of ["/api/user/self", "/api/v1/user/profile"]) {
|
||||
const to = site + path;
|
||||
// sub2api's /v1/usage has one account query beside it: its panel's
|
||||
for (const to of (path === "/v1/usage" ? ["/api/v1/user/profile"] : ["/api/user/self", "/api/v1/user/profile"]).map((q) => site + q)) {
|
||||
const use = el("button", "text action", t("Use {url}", { url: to }));
|
||||
use.onclick = () => {
|
||||
draft.balanceURL = to;
|
||||
// An unrelated expression belongs to the user, so changing the
|
||||
// endpoint must not overwrite it.
|
||||
if (!(draft.balancePath || "").trim() || /total_(available|granted|used)|unlimited_quota/.test(draft.balancePath)) draft.balancePath = balanceFieldOf(to);
|
||||
if (!(draft.balancePath || "").trim() || /total_(available|granted|used)|unlimited_quota|^\s*\$?remaining\s*$/.test(draft.balancePath)) draft.balancePath = balanceFieldOf(to);
|
||||
const ed = box.closest(".editor");
|
||||
const bal = ed?.querySelector(".bal-url");
|
||||
const field = ed?.querySelector(".bal-path");
|
||||
|
||||
@@ -2683,6 +2683,8 @@ const I18N = {
|
||||
"optional · the account's system access token": "可选 · 账户的系统访问令牌",
|
||||
"What the Balance URL is asked with in place of the key, when it wants the account's own token: a new-api relay's System Access Token, or a sub2api panel's login token (a JWT, sent as a Bearer); it is used for nothing else.": "余额接口需要账户自己的令牌时,用它代替 Key 去请求:new-api 中转站填「系统访问令牌」,sub2api 面板填登录令牌(JWT,会以 Bearer 发送);不作他用。",
|
||||
"…/api/usage/token takes the API key, not this token: for the account's balance, new-api uses /api/user/self; sub2api uses /api/v1/user/profile.": "…/api/usage/token 只认 API Key,不认这个令牌:查账户余额时,new-api 使用 /api/user/self,sub2api 使用 /api/v1/user/profile。",
|
||||
"…/v1/usage takes the API key, not this token: for the account's balance, a sub2api panel uses /api/v1/user/profile.": "…/v1/usage 只认 API Key,不认这个令牌:查账户余额时,sub2api 面板使用 /api/v1/user/profile。",
|
||||
"The Balance URL …/v1/usage takes the API key, not the login token — set it to …/api/v1/user/profile in the provider's settings": "余额查询地址 …/v1/usage 只认 API Key,不认登录令牌,请在供应商设置里改为 …/api/v1/user/profile",
|
||||
"The token needs a Balance URL: a new-api relay uses /api/user/self; a sub2api panel uses /api/v1/user/profile to read the account's balance.": "令牌还需要一个余额查询地址:new-api 中转站用 /api/user/self 凭令牌查账户余额;sub2api 面板用 /api/v1/user/profile。",
|
||||
"Use {url}": "改用 {url}",
|
||||
"A new-api relay also wants the header New-Api-User = your user ID (shown in the site's personal settings): add it under Headers.": "new-api 中转站还需请求头 New-Api-User = 你的用户 ID(见站点个人设置),请在「请求头」中添加。",
|
||||
@@ -6216,6 +6218,8 @@ const I18N = {
|
||||
"optional · the account's system access token": "可選 · 帳戶的系統存取權杖",
|
||||
"What the Balance URL is asked with in place of the key, when it wants the account's own token: a new-api relay's System Access Token, or a sub2api panel's login token (a JWT, sent as a Bearer); it is used for nothing else.": "餘額介面需要帳戶自己的令牌時,用它代替 Key 去請求:new-api 中轉站填「系統存取權杖」,sub2api 面板填登入令牌(JWT,會以 Bearer 傳送);不作他用。",
|
||||
"…/api/usage/token takes the API key, not this token: for the account's balance, new-api uses /api/user/self; sub2api uses /api/v1/user/profile.": "…/api/usage/token 只認 API Key,不認這個令牌:查帳戶餘額時,new-api 使用 /api/user/self,sub2api 使用 /api/v1/user/profile。",
|
||||
"…/v1/usage takes the API key, not this token: for the account's balance, a sub2api panel uses /api/v1/user/profile.": "…/v1/usage 只認 API Key,不認這個令牌:查帳戶餘額時,sub2api 面板使用 /api/v1/user/profile。",
|
||||
"The Balance URL …/v1/usage takes the API key, not the login token — set it to …/api/v1/user/profile in the provider's settings": "餘額查詢位址 …/v1/usage 只認 API Key,不認登入令牌,請在供應商設定裡改為 …/api/v1/user/profile",
|
||||
"The token needs a Balance URL: a new-api relay uses /api/user/self; a sub2api panel uses /api/v1/user/profile to read the account's balance.": "令牌還需要一個餘額查詢位址:new-api 中轉站用 /api/user/self 憑令牌查帳戶餘額;sub2api 面板用 /api/v1/user/profile。",
|
||||
"Use {url}": "改用 {url}",
|
||||
"A new-api relay also wants the header New-Api-User = your user ID (shown in the site's personal settings): add it under Headers.": "new-api 中轉站還需請求頭 New-Api-User = 你的使用者 ID(見站點個人設定),請在「請求頭」中新增。",
|
||||
@@ -9756,6 +9760,8 @@ const I18N = {
|
||||
"optional · the account's system access token": "任意 · アカウントのシステムアクセストークン",
|
||||
"What the Balance URL is asked with in place of the key, when it wants the account's own token: a new-api relay's System Access Token, or a sub2api panel's login token (a JWT, sent as a Bearer); it is used for nothing else.": "残高 URL がアカウント自身のトークンを求める場合に、キーの代わりに使うものです。new-api 中継サイトでは System Access Token、sub2api パネルではログイントークン(JWT、Bearer として送信)を入力します。それ以外には使いません。",
|
||||
"…/api/usage/token takes the API key, not this token: for the account's balance, new-api uses /api/user/self; sub2api uses /api/v1/user/profile.": "…/api/usage/token が受け付けるのは API キーで、このトークンではありません。アカウント残高の取得には new-api は /api/user/self、sub2api は /api/v1/user/profile を使います。",
|
||||
"…/v1/usage takes the API key, not this token: for the account's balance, a sub2api panel uses /api/v1/user/profile.": "…/v1/usage が受け付けるのは API キーで、このトークンではありません。アカウント残高の取得には sub2api パネルでは /api/v1/user/profile を使います。",
|
||||
"The Balance URL …/v1/usage takes the API key, not the login token — set it to …/api/v1/user/profile in the provider's settings": "残高 URL …/v1/usage が受け付けるのは API キーで、ログイントークンではありません — プロバイダの設定で …/api/v1/user/profile に変更してください",
|
||||
"The token needs a Balance URL: a new-api relay uses /api/user/self; a sub2api panel uses /api/v1/user/profile to read the account's balance.": "トークンには残高 URL が必要です。new-api 中継サイトでは /api/user/self、sub2api パネルでは /api/v1/user/profile でトークンによりアカウント残高を取得します。",
|
||||
"Use {url}": "{url} を使う",
|
||||
"A new-api relay also wants the header New-Api-User = your user ID (shown in the site's personal settings): add it under Headers.": "new-api 中継サイトではヘッダー New-Api-User = あなたのユーザー ID(サイトの個人設定に表示)も必要です。「ヘッダー」に追加してください。",
|
||||
@@ -13302,6 +13308,8 @@ const I18N = {
|
||||
"optional · the account's system access token": "optional · das System-Zugriffstoken des Kontos",
|
||||
"What the Balance URL is asked with in place of the key, when it wants the account's own token: a new-api relay's System Access Token, or a sub2api panel's login token (a JWT, sent as a Bearer); it is used for nothing else.": "Damit wird die Guthaben-URL statt mit dem Schlüssel abgefragt, wenn sie das eigene Token des Kontos verlangt: das System Access Token eines new-api-Relays oder das Login-Token eines sub2api-Panels (ein JWT, als Bearer gesendet); es wird für nichts anderes verwendet.",
|
||||
"…/api/usage/token takes the API key, not this token: for the account's balance, new-api uses /api/user/self; sub2api uses /api/v1/user/profile.": "…/api/usage/token erwartet den API-Schlüssel, nicht dieses Token: Für das Kontoguthaben verwendet new-api /api/user/self und sub2api /api/v1/user/profile.",
|
||||
"…/v1/usage takes the API key, not this token: for the account's balance, a sub2api panel uses /api/v1/user/profile.": "…/v1/usage erwartet den API-Schlüssel, nicht dieses Token: Für das Kontoguthaben verwendet ein sub2api-Panel /api/v1/user/profile.",
|
||||
"The Balance URL …/v1/usage takes the API key, not the login token — set it to …/api/v1/user/profile in the provider's settings": "Die Guthaben-URL …/v1/usage erwartet den API-Schlüssel, nicht das Login-Token – stellen Sie sie in den Anbietereinstellungen auf …/api/v1/user/profile",
|
||||
"The token needs a Balance URL: a new-api relay uses /api/user/self; a sub2api panel uses /api/v1/user/profile to read the account's balance.": "Das Token braucht eine Guthaben-URL: Ein new-api-Relay fragt das Kontoguthaben mit dem Token unter /api/user/self ab, ein sub2api-Panel unter /api/v1/user/profile.",
|
||||
"Use {url}": "{url} verwenden",
|
||||
"A new-api relay also wants the header New-Api-User = your user ID (shown in the site's personal settings): add it under Headers.": "Ein new-api-Relay verlangt zusätzlich den Header New-Api-User = Ihre Benutzer-ID (in den persönlichen Einstellungen der Website zu sehen): Fügen Sie ihn unter „Header“ hinzu.",
|
||||
|
||||
@@ -180,6 +180,41 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
// sub2api's /v1/usage takes the key alone too (#2217): a login token
|
||||
// beside it is said, with the panel's profile the one way offered, and
|
||||
// a saved "$remaining" gives way to its field
|
||||
test(engine + ": a login token on sub2api's /v1/usage is moved to /api/v1/user/profile", async (t) => {
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||||
const context = await browser.newContext({ viewport: { width: 440, height: 760 }, reducedMotion: "reduce" });
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(5000);
|
||||
const errors = [], posted = [];
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
await page.route("**/*", server(posted, { provider: { ...relay, balanceURL: "https://relay.example.com/v1/usage", balancePath: "$remaining" } }));
|
||||
t.after(() => browser.close());
|
||||
|
||||
await page.goto("http://magpie.test/?view=providers");
|
||||
await page.locator(".row.provider", { hasText: "Relay" }).click();
|
||||
const fix = page.locator(".editor .bal-fix");
|
||||
await fix.waitFor();
|
||||
assert(await fix.evaluate((e) => e.classList.contains("warn")), "the saved token beside /v1/usage is a warning");
|
||||
assert.match(await fix.textContent(), /…\/v1\/usage takes the API key, not this token/);
|
||||
assert.equal(await fix.getByRole("button").count(), 1, "only sub2api's account query is offered");
|
||||
await fix.getByRole("button", { name: "Use https://relay.example.com/api/v1/user/profile", exact: true }).click();
|
||||
assert.equal(await page.locator(".editor .bal-url").inputValue(), "https://relay.example.com/api/v1/user/profile");
|
||||
assert.equal(await page.locator(".editor .bal-path").inputValue(), "$data.balance", "the key query's field gives way");
|
||||
assert.equal(await fix.textContent(), "");
|
||||
|
||||
const said = await page.evaluate(() => quotaError("the Balance URL https://relay.example.com/v1/usage takes the API key, not the login token: set it to https://relay.example.com/api/v1/user/profile (Balance field $data.balance) for the account's balance, or remove the token for the key's own"));
|
||||
assert.equal(said, "The Balance URL …/v1/usage takes the API key, not the login token — set it to …/api/v1/user/profile in the provider's settings");
|
||||
const missing = await page.evaluate(() => [
|
||||
"…/v1/usage takes the API key, not this token: for the account's balance, a sub2api panel uses /api/v1/user/profile.",
|
||||
"The Balance URL …/v1/usage takes the API key, not the login token — set it to …/api/v1/user/profile in the provider's settings",
|
||||
].filter((k) => !I18N.zh[k] || !I18N["zh-TW"][k] || !I18N.ja[k] || !I18N.de[k]));
|
||||
assert.deepEqual(missing, [], "every new string has its translations");
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
for (const lang of ["en", "zh", "ja", "de"]) {
|
||||
for (const width of [900, 440]) {
|
||||
test(`${engine}: Sub2API balance shortcut saves the profile endpoint (${lang}, ${width}px)`, async (t) => {
|
||||
|
||||
@@ -206,7 +206,25 @@ func errKeyUsageWithToken(raw string) error {
|
||||
if u, err := url.Parse(strings.TrimSpace(raw)); err == nil && u.Host != "" {
|
||||
self = u.Scheme + "://" + u.Host + newAPIUserSelf
|
||||
}
|
||||
return fmt.Errorf("the Balance URL %s takes the API key, not the access token: set it to %s (Balance field %s) for the account's balance, or remove the token for the key's own", raw, self, newAPIQuotaPath)
|
||||
return errKeyQueryWithToken(raw, self, newAPIQuotaPath, "access token")
|
||||
}
|
||||
|
||||
// errSub2APIKeyUsageWithToken is a login token beside sub2api's query for a
|
||||
// key, which takes the key alone as new-api's does: the panel's query for
|
||||
// the account is named in its place.
|
||||
func errSub2APIKeyUsageWithToken(raw string) error {
|
||||
profile := sub2APIProfile
|
||||
if u, err := url.Parse(strings.TrimSpace(raw)); err == nil && u.Host != "" {
|
||||
profile = u.Scheme + "://" + u.Host + sub2APIProfile
|
||||
}
|
||||
return errKeyQueryWithToken(raw, profile, "$data.balance", "login token")
|
||||
}
|
||||
|
||||
// errKeyQueryWithToken is a balance token beside a panel's query for a key
|
||||
// (new-api's /api/usage/token, sub2api's /v1/usage), which never takes it:
|
||||
// what to name in its place is said.
|
||||
func errKeyQueryWithToken(raw, accountURL, accountField, token string) error {
|
||||
return fmt.Errorf("the Balance URL %s takes the API key, not the %s: set it to %s (Balance field %s) for the account's balance, or remove the token for the key's own", raw, token, accountURL, accountField)
|
||||
}
|
||||
|
||||
// balanceRefusal is what a reply of {"success":false,"message":…} says, a
|
||||
@@ -1132,8 +1150,13 @@ func balanceRead(ctx context.Context, p Provider) (amount string, parts []Balanc
|
||||
if !ok || p.Account != nil || p.Key == "" {
|
||||
return "", nil, nil, false, nil
|
||||
}
|
||||
if src.token != "" && p.BalanceURL != "" && balanceURLPath(p.BalanceURL) == newAPIKeyUsage {
|
||||
return "", nil, nil, true, errKeyUsageWithToken(p.BalanceURL)
|
||||
if src.token != "" && p.BalanceURL != "" {
|
||||
switch balanceURLPath(p.BalanceURL) {
|
||||
case newAPIKeyUsage:
|
||||
return "", nil, nil, true, errKeyUsageWithToken(p.BalanceURL)
|
||||
case sub2APIKeyUsage:
|
||||
return "", nil, nil, true, errSub2APIKeyUsageWithToken(p.BalanceURL)
|
||||
}
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, withBalanceKey(src.url, p.Key, true), nil)
|
||||
if err != nil {
|
||||
|
||||
@@ -358,6 +358,34 @@ func TestKeyUsageWithAccessToken(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// A login token beside sub2api's /v1/usage, which takes only the key, is
|
||||
// never sent there either: the panel's query for the account is named in
|
||||
// its place, as new-api's is above.
|
||||
func TestSub2APIKeyUsageWithLoginToken(t *testing.T) {
|
||||
asked := false
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
asked = true
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
w.Write([]byte(`{"error":"invalid API key"}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
p := Provider{ID: "panel", Chat: srv.URL, Key: "sk-two",
|
||||
BalanceToken: "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJzIn0.sig",
|
||||
BalanceURL: srv.URL + "/v1/usage"}
|
||||
_, ok, err := Balance(context.Background(), p)
|
||||
if !ok || err == nil || asked {
|
||||
t.Fatalf("ok %v, err %v, asked %v", ok, err, asked)
|
||||
}
|
||||
if want := srv.URL + "/api/v1/user/profile (Balance field $data.balance)"; !strings.Contains(err.Error(), want) || !strings.Contains(err.Error(), "takes the API key, not the login token") {
|
||||
t.Fatalf("err = %v", err)
|
||||
}
|
||||
// the key alone still asks it
|
||||
p.BalanceToken = ""
|
||||
if _, _, err := Balance(context.Background(), p); !asked || err == nil {
|
||||
t.Fatalf("without the token: asked %v, err %v", asked, err)
|
||||
}
|
||||
}
|
||||
|
||||
// new-api's /api/user/self with its field left out reads the quota as
|
||||
// new-api counts it, $1 to 500000.
|
||||
func TestUserSelfDefaultField(t *testing.T) {
|
||||
|
||||
Reference in New Issue
Block a user