provider: Baidu Qianfan's ended console sign-in asks for a new one in the editor, and a renewed cookie is kept (yuushabu_buyinn on X, #5860)

yuushabu_buyinn asked for AccessKey + SecretKey in place of the console
cookie, which expires. Baidu has no such route. Its documented OpenAPI has
no read for a Token Plan Personal:
- the Qianfan API catalog (doc/qianfan/s/Smownk4en): 量包
  v2/charge?Action=DescribePackageResources lists token packs by series,
  with no Token Plan;
- Finance's API (doc/Finance/s/ojxecslph): bills, balance, orders,
  vouchers;
- the Token Plan Enterprise's seat APIs (tokenplan?Action=...
  DescribeTeamSeatUsageDetail), which take an API key and are for team
  seats only.
The Token Plan Personal doc (doc/qianfan/s/Dmrabu8b6) shows usage only on
the console's 我的订阅 page. So the cookie stays, and what is mended is
what happens when it ends:

- Before, a session the console refused showed "Signed out of the Baidu
  Cloud console" on the card, while the provider's editor still said
  "Signed in" with only Sign out. Now the kept sign-in is marked ended
  (qianfanSession.Ended, set the first time only, and not when a newer
  paste has replaced the cookie the read used). /api/providers says
  qianfanPlan.ended, and qianfanplan.js draws "Baidu Cloud ended this
  sign-in. Bring a new one:" above the bookmarklet and paste steps. A
  new paste, or a later read the console takes, clears the mark.
- A cookie the console sets in a reply that read the plan (on the
  resource's path) is merged into the kept Cookie header as a browser
  would: replaced in place, added, or taken out when deleted or expired
  (mergeQianfanCookies). A session Baidu renews as it is used then stays
  the one magpie holds. The paste check keeps what its reply set too.

The StepFun sibling (the same "still Signed in" gap, drawn by
renderStepPlan in app.js) is #6808. The Qianfan fix adds no app.js bytes.

Run (mote, at 3b643f397 plus this change; go test, vet, gofmt, qianfan-plan
and i18n-keys again after rebasing on f64c7e54f, all ok):
- gofmt -l, go vet (darwin, GOOS=linux -tags nogui, GOOS=windows) for
  internal/provider and internal/gui: clean.
- go test -count=1 ./internal/provider ./internal/gui: ok.
- node --test qianfan-plan, i18n-keys, i18n-en-no-cjk: 12/12 (chromium +
  webkit, en + zh). stepfun-per-provider and qianwen-plan: all ok.
  old-webkit 4 and 5 are red the same on a clean 3b643f397 copy (#6030,
  #5919).
- Broken by hand: without the ended mark, TestQianfanSessionEnded fails
  "an ended sign-in should be kept, marked ended". Without the merge it
  fails "renewed cookie kept as ...s-1".

Not tried: no real Baidu Cloud account. How long the console's cookie
lasts was not measured (a third-party tool reports a few weeks), and
whether the console sets renewed cookies on this request is not known.
The merge does nothing if it doesn't.
This commit is contained in:
yetone
2026-11-16 10:49:31 +08:00
parent f64c7e54f1
commit 2ad38c8b3e
9 changed files with 247 additions and 34 deletions
File diff suppressed because one or more lines are too long
+1
View File
@@ -3773,6 +3773,7 @@ body:not(.side-nav) #addSheet > .row-head.stuck::before { box-shadow: 0 1px 0 va
.stepplan .state { flex: 1; min-width: 0; font-size: 12px; color: var(--muted); line-height: 1.4; }
.stepplan .steps { margin: 0; padding-left: 18px; display: flex; flex-direction: column; gap: 8px; font-size: 12px; color: var(--muted); line-height: 1.5; }
.stepplan .steps .pair { margin-top: 2px; }
.stepplan .ended { display: block; margin-bottom: 8px; color: var(--fg); }
.stepplan .bookmarklet { display: inline-block; padding: 1px 8px; border: 1px solid var(--line); border-radius: 6px; color: var(--fg); background: var(--pill); text-decoration: none; cursor: grab; white-space: nowrap; }
.editor input[type="text"], .editor input[type="password"], .editor input[type="url"], .editor input[type="number"], .acc .kf input, .acc input.rename-in {
height: 27px; padding: 0 9px; border-radius: 7px;
+4
View File
@@ -3960,6 +3960,7 @@ const I18N = {
"Sign in to the Baidu Cloud console in your browser ↗": "在浏览器中登录百度智能云控制台 ↗",
"Signed in to the Baidu Cloud console": "已登录百度智能云控制台",
"Signed out of the Baidu Cloud console — bring a new sign-in in the provider's settings": "已退出百度智能云控制台 — 在服务商设置中重新带入登录",
"Baidu Cloud ended this sign-in. Bring a new one:": "百度智能云已结束这次登录,请重新带入:",
"This Baidu Cloud account has no Token Plan Personal": "这个百度智能云账号没有 Token Plan 个人版",
"A key tells nothing of the plan's usage. Its month is told only to a sign-in on Baidu Cloud's console: bring yours here once and magpie keeps it, used for nothing else. If magpie can't use what the bookmarklet copied, paste the Cookie header of the console's request from your browser's developer tools.": "密钥不告知套餐用量。套餐本月的用量只告知百度智能云控制台的登录:在这里带入一次,magpie 会保存它,不作他用。如果 magpie 用不了书签复制的内容,请从浏览器开发者工具中复制控制台请求的 Cookie 请求头粘贴到这里。",
"saved · paste a new one to replace it": "已保存 · 粘贴新的即可替换",
@@ -9288,6 +9289,7 @@ const I18N = {
"Sign in to the Baidu Cloud console in your browser ↗": "在瀏覽器中登入百度智慧雲主控台 ↗",
"Signed in to the Baidu Cloud console": "已登入百度智慧雲主控台",
"Signed out of the Baidu Cloud console — bring a new sign-in in the provider's settings": "已登出百度智慧雲主控台 — 在供應商設定中重新帶入登入",
"Baidu Cloud ended this sign-in. Bring a new one:": "百度智慧雲已結束這次登入,請重新帶入:",
"This Baidu Cloud account has no Token Plan Personal": "這個百度智慧雲帳號沒有 Token Plan 個人版",
"A key tells nothing of the plan's usage. Its month is told only to a sign-in on Baidu Cloud's console: bring yours here once and magpie keeps it, used for nothing else. If magpie can't use what the bookmarklet copied, paste the Cookie header of the console's request from your browser's developer tools.": "金鑰不告知方案用量。方案本月的用量只告知百度智慧雲主控台的登入:在這裡帶入一次,magpie 會保存它,不作他用。如果 magpie 用不了書籤複製的內容,請從瀏覽器開發者工具中複製主控台請求的 Cookie 標頭貼到這裡。",
"saved · paste a new one to replace it": "已儲存 · 貼上新的即可替換",
@@ -14624,6 +14626,7 @@ const I18N = {
"Sign in to the Baidu Cloud console in your browser ↗": "ブラウザで Baidu Cloud コンソールにサインイン ↗",
"Signed in to the Baidu Cloud console": "Baidu Cloud コンソールにサインイン済み",
"Signed out of the Baidu Cloud console — bring a new sign-in in the provider's settings": "Baidu Cloud コンソールからサインアウトしました — プロバイダの設定で新しいサインインを渡してください",
"Baidu Cloud ended this sign-in. Bring a new one:": "Baidu Cloud がこのサインインを終了しました。新しいサインインを渡してください:",
"This Baidu Cloud account has no Token Plan Personal": "この Baidu Cloud アカウントには Token Plan 個人版がありません",
"A key tells nothing of the plan's usage. Its month is told only to a sign-in on Baidu Cloud's console: bring yours here once and magpie keeps it, used for nothing else. If magpie can't use what the bookmarklet copied, paste the Cookie header of the console's request from your browser's developer tools.": "キーはプランの使用量を伝えません。今月の使用量は Baidu Cloud コンソールへのサインインにのみ伝えられます。ここで一度渡せば magpie が保存し、ほかの用途には使いません。ブックマークレットのコピーが使えない場合は、ブラウザの開発者ツールからコンソールのリクエストの Cookie ヘッダーを貼り付けてください。",
"saved · paste a new one to replace it": "保存済み · 新しいものを貼り付けると置き換えます",
@@ -19969,6 +19972,7 @@ const I18N = {
"Sign in to the Baidu Cloud console in your browser ↗": "Im Browser bei der Baidu-Cloud-Konsole anmelden ↗",
"Signed in to the Baidu Cloud console": "Bei der Baidu-Cloud-Konsole angemeldet",
"Signed out of the Baidu Cloud console — bring a new sign-in in the provider's settings": "Von der Baidu-Cloud-Konsole abgemeldet — bringen Sie in den Einstellungen des Anbieters eine neue Anmeldung mit",
"Baidu Cloud ended this sign-in. Bring a new one:": "Baidu Cloud hat diese Anmeldung beendet. Bringen Sie eine neue mit:",
"This Baidu Cloud account has no Token Plan Personal": "Dieses Baidu-Cloud-Konto hat keinen Token Plan Personal",
"A key tells nothing of the plan's usage. Its month is told only to a sign-in on Baidu Cloud's console: bring yours here once and magpie keeps it, used for nothing else. If magpie can't use what the bookmarklet copied, paste the Cookie header of the console's request from your browser's developer tools.": "Ein Schlüssel verrät die Nutzung des Plans nicht. Sein Monat wird nur einer Anmeldung in der Baidu-Cloud-Konsole verraten: Bringen Sie Ihre einmal hierher, magpie bewahrt sie auf und nutzt sie für nichts anderes. Kann magpie nicht verwenden, was das Bookmarklet kopiert hat, fügen Sie den Cookie-Header der Konsolenanfrage aus den Entwicklertools Ihres Browsers ein.",
"saved · paste a new one to replace it": "gespeichert · zum Ersetzen ein neues einfügen",
+12 -6
View File
@@ -1,9 +1,15 @@
// Baidu Qianfan's Token Plan Personal: its month is told only to a sign-in
// on Baidu Cloud's console, brought by the bookmarklet and paste StepFun's
// Step Plan uses (renderStepPlan) and kept per provider id
// (qianfan_plan.go). app.js imports this when such a provider's editor
// opens, so it weighs nothing on the core.
window.qianfanPlanField = (p) => field(t("Token Plan usage"), renderStepPlan(p.qianfanPlan, p.id, {
route: "qianfan", bm: "magpie · Qianfan", state: t("Signed in · the Usage page shows the Token Plan"),
open: t("Sign in to the Baidu Cloud console in your browser ↗"), ok: t("Signed in to the Baidu Cloud console"),
}), t("A key tells nothing of the plan's usage. Its month is told only to a sign-in on Baidu Cloud's console: bring yours here once and magpie keeps it, used for nothing else. If magpie can't use what the bookmarklet copied, paste the Cookie header of the console's request from your browser's developer tools."));
// (qianfan_plan.go). A sign-in the console has ended (sp.ended) asks for a
// new one with the same steps, saying why. app.js imports this when such a
// provider's editor opens, so it weighs nothing on the core.
window.qianfanPlanField = (p) => {
const sp = p.qianfanPlan;
const box = renderStepPlan(sp.ended ? { ...sp, signedIn: false } : sp, p.id, {
route: "qianfan", bm: "magpie · Qianfan", state: t("Signed in · the Usage page shows the Token Plan"),
open: t("Sign in to the Baidu Cloud console in your browser ↗"), ok: t("Signed in to the Baidu Cloud console"),
});
if (sp.ended) box.prepend(el("div", "state ended", t("Baidu Cloud ended this sign-in. Bring a new one:")));
return field(t("Token Plan usage"), box, t("A key tells nothing of the plan's usage. Its month is told only to a sign-in on Baidu Cloud's console: bring yours here once and magpie keeps it, used for nothing else. If magpie can't use what the bookmarklet copied, paste the Cookie header of the console's request from your browser's developer tools."));
};
+5 -2
View File
@@ -575,6 +575,9 @@ type stepPlanJSON struct {
SignedIn bool `json:"signedIn"`
URL string `json:"url"`
Bookmarklet string `json:"bookmarklet"`
// Ended: the vendor has ended the kept sign-in, and a new one is asked
// for (Baidu Qianfan's alone tells it)
Ended bool `json:"ended,omitempty"`
}
// qianwenPlanJSON: whether magpie has a sign-in to the Qwen AI platform
@@ -1043,13 +1046,13 @@ func providerInfoWith(p provider.Provider, ls provider.Listing, agents []agentUs
}
}
if site := provider.StepFunSite(p); site != "" {
out.StepPlan = &stepPlanJSON{site, provider.StepFunSignedIn(p.ID), provider.StepFunSignInURL(site), provider.StepFunBookmarklet()}
out.StepPlan = &stepPlanJSON{site, provider.StepFunSignedIn(p.ID), provider.StepFunSignInURL(site), provider.StepFunBookmarklet(), false}
}
if provider.QianwenPlan(p) {
out.QianwenPlan = &qianwenPlanJSON{provider.QianwenSignedIn(p.ID), provider.QianwenAccount(p.ID)}
}
if provider.QianfanPlan(p) {
out.QianfanPlan = &stepPlanJSON{"", provider.QianfanSignedIn(p.ID), provider.QianfanSignInURL, provider.QianfanBookmarklet()}
out.QianfanPlan = &stepPlanJSON{"", provider.QianfanSignedIn(p.ID), provider.QianfanSignInURL, provider.QianfanBookmarklet(), provider.QianfanEnded(p.ID)}
}
out.Key.Set = p.Key != ""
out.Key.Masked = provider.Mask(p.Key)
+13 -3
View File
@@ -38,7 +38,7 @@ func TestQianfanSignInRoutes(t *testing.T) {
mux := http.NewServeMux()
providerRoutes(mux, nil)
plans := func() map[string]struct {
SignedIn bool
SignedIn, Ended bool
URL, Bookmarklet string
} {
t.Helper()
@@ -48,7 +48,7 @@ func TestQianfanSignInRoutes(t *testing.T) {
Providers []struct {
ID string
QianfanPlan *struct {
SignedIn bool
SignedIn, Ended bool
URL, Bookmarklet string
}
}
@@ -57,7 +57,7 @@ func TestQianfanSignInRoutes(t *testing.T) {
t.Fatal(err)
}
out := map[string]struct {
SignedIn bool
SignedIn, Ended bool
URL, Bookmarklet string
}{}
for _, p := range got.Providers {
@@ -72,6 +72,16 @@ func TestQianfanSignInRoutes(t *testing.T) {
!strings.HasPrefix(got["baidu-qianfan"].URL, "https://console.bce.baidu.com/") {
t.Fatalf("before: %+v", got)
}
if got["baidu-qianfan"].Ended {
t.Fatalf("a sign-in the console takes reads as ended: %+v", got)
}
// one the console has ended is told, so the editor asks for a new one
if err := os.WriteFile(auth, []byte(`{"baidu-qianfan":{"cookie":"BDUSS=x","ended":"2026-11-16T00:00:00Z"}}`), 0o600); err != nil {
t.Fatal(err)
}
if got := plans(); !got["baidu-qianfan"].SignedIn || !got["baidu-qianfan"].Ended {
t.Fatalf("ended: %+v", got)
}
for _, id := range []string{"relay", "qianfan-team", "nobody"} {
for _, path := range []string{"session", "signout"} {
w := httptest.NewRecorder()
+19 -4
View File
@@ -3,7 +3,9 @@
// Baidu Cloud's console the way StepFun's does (yuushabu_buyinn on X, #5860):
// the paste posts to /api/qianfan/{id}/session for that provider's id, and a
// signed-in one's Sign out posts /api/qianfan/{id}/signout. A Qianfan
// provider without the plan has no such field. In English and Chinese.
// provider without the plan has no such field. One whose sign-in Baidu
// ended says so and asks for a new one with the same steps. In English and
// Chinese.
const assert = require("node:assert/strict");
const fs = require("node:fs/promises");
const path = require("node:path");
@@ -15,11 +17,11 @@ const qianfan = (id, name, plan) => ({
id, name, icon: "baiducloud-color", preset: "baidu-qianfan", chat: "https://qianfan.baidubce.com/v2/tokenplan/personal", responses: "", anthropic: "", catalog: "",
models: [{ id: "ernie-5.0", name: "ERNIE 5.0", on: true }], agents: [], fallback: [], headers: {},
key: { set: true, masked: "…ab12" }, keyList: [], balanceToken: { takes: false, set: false }, proxy: "",
...(plan ? { qianfanPlan: { site: "", signedIn: plan === "in", url: "https://console.bce.baidu.com/qianfan/resource/token-plan", bookmarklet: "javascript:void 0" } } : {}),
...(plan ? { qianfanPlan: { site: "", signedIn: plan !== "out", ...(plan === "ended" ? { ended: true } : {}), url: "https://console.bce.baidu.com/qianfan/resource/token-plan", bookmarklet: "javascript:void 0" } } : {}),
});
function serve(lang, posts) {
const providers = { providers: [qianfan("qianfan", "Qianfan Plan", "in"), qianfan("qianfan-2", "Qianfan Work", "out"), qianfan("qianfan-api", "Qianfan API", "")], presets: [], excluded: [], gateway: { running: true, window: true } };
const providers = { providers: [qianfan("qianfan", "Qianfan Plan", "in"), qianfan("qianfan-2", "Qianfan Work", "out"), qianfan("qianfan-api", "Qianfan API", ""), qianfan("qianfan-old", "Qianfan Old", "ended")], presets: [], excluded: [], gateway: { running: true, window: true } };
const state = { agents: [], profiles: [], settings: { lang, theme: "light" } };
return async (route) => {
const url = new URL(route.request().url());
@@ -40,7 +42,7 @@ function serve(lang, posts) {
};
}
const words = { en: { out: "Sign out", cancel: "Cancel" }, zh: { out: "退出登录", cancel: "取消" } };
const words = { en: { out: "Sign out", cancel: "Cancel", ended: "Baidu Cloud ended this sign-in" }, zh: { out: "退出登录", cancel: "取消", ended: "百度智能云已结束这次登录" } };
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of ["en", "zh"]) {
@@ -82,6 +84,19 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
await wait(1);
assert.equal(posts.length, 2);
assert.equal(posts[1].path, "/api/qianfan/qianfan/signout");
assert.equal(await page.locator(".editor .stepplan .ended").count(), 0);
// the one Baidu ended says so and takes a new paste, for its own id
await page.locator(".editor .bar").getByRole("button", { name: words[lang].cancel, exact: true }).click();
await page.locator(".editor").waitFor({ state: "detached" });
await page.locator(".row.provider", { hasText: "Qianfan Old" }).click();
assert.match(await page.locator(".editor .stepplan .ended").innerText(), new RegExp(words[lang].ended));
const again = page.locator(".editor .stepplan input[type=password]");
await again.fill("BDUSS=new");
await again.press("Enter");
await wait(2);
assert.equal(posts.length, 3);
assert.equal(posts[2].path, "/api/qianfan/qianfan-old/session");
assert.deepEqual(errors, []);
});
}
+110 -18
View File
@@ -26,9 +26,16 @@ package provider
// the browser's developer tools, where the HttpOnly ones are too. magpie
// asks the console with it before keeping it, and keeps it in
// qianfan-auth.json beside providers.json, readable by the user alone, one
// per provider: two can be two Baidu accounts. The console doesn't renew
// it for magpie: when Baidu ends it the card says so, and the user brings
// a new one.
// per provider: two can be two Baidu accounts. A cookie the console sets
// in a reply that read the plan is kept, as the browser keeps it, so a
// session Baidu renews as it is used stays the one magpie holds. When
// Baidu ends it the card says so, the sign-in is marked ended (Ended), and
// the provider's editor asks for a new one again; a later read the console
// takes clears the mark.
//
// There is no AccessKey/SecretKey way to this: Baidu's OpenAPI (the
// Qianfan API catalog, Finance's billing API, the Token Plan Enterprise's
// seat APIs with an API key) has no read for a Token Plan Personal.
//
// The Enterprise plan (tokenplan/team) is read on the console from its
// seats' admin pages (tokenPlan/seat/admin/overview), not this one; it
@@ -101,6 +108,9 @@ func QianfanBookmarklet() string {
// Cookie header.
type qianfanSession struct {
Cookie string `json:"cookie"`
// Ended is when the console first sent this session to sign in again
// (RFC 3339), "" while it takes it
Ended string `json:"ended,omitempty"`
}
var qianfanMu sync.Mutex
@@ -151,12 +161,87 @@ func qianfanSignIn(id string) (qianfanSession, bool) {
return s, ok && s.Cookie != ""
}
// QianfanSignedIn reports whether magpie has a sign-in for the provider.
// QianfanSignedIn reports whether magpie has a sign-in for the provider,
// ended or not.
func QianfanSignedIn(id string) bool {
_, ok := qianfanSignIn(id)
return ok
}
// QianfanEnded reports whether the console has ended the provider's
// sign-in, so the editor asks for a new one.
func QianfanEnded(id string) bool {
s, ok := qianfanSignIn(id)
return ok && s.Ended != ""
}
// noteQianfan records what a read of the console with the provider's
// cookie said: the session ended, or the cookies its reply set. Nothing is
// written when the sign-in has changed since (a new paste) or nothing
// changes.
func noteQianfan(id, used string, ended bool, set []*http.Cookie) {
qianfanMu.Lock()
defer qianfanMu.Unlock()
all := loadQianfan()
s, ok := all[id]
if !ok || s.Cookie != used {
return
}
n := s
if ended {
if n.Ended == "" {
n.Ended = time.Now().UTC().Format(time.RFC3339)
}
} else {
n.Ended = ""
n.Cookie = mergeQianfanCookies(used, set)
}
if n == s {
return
}
all[id] = n
_ = saveQianfan(all)
}
// mergeQianfanCookies is the Cookie header with what a console reply set
// (for the resource's path) put in, as a browser would: a value replaced
// where it stood, a new one added, one deleted or expired taken out.
func mergeQianfanCookies(header string, set []*http.Cookie) string {
type kv struct{ k, v string }
var jar []kv
for _, part := range strings.Split(header, ";") {
part = strings.TrimSpace(part)
if part == "" {
continue
}
k, v, _ := strings.Cut(part, "=")
jar = append(jar, kv{k, v})
}
now := time.Now()
for _, c := range set {
if c.Name == "" || strings.ContainsAny(c.Name+c.Value, ";\r\n") ||
c.Path != "" && !strings.HasPrefix(qianfanResourcePath, c.Path) {
continue
}
gone := c.MaxAge < 0 || !c.Expires.IsZero() && !c.Expires.After(now)
i := slices.IndexFunc(jar, func(e kv) bool { return e.k == c.Name })
switch {
case gone && i >= 0:
jar = slices.Delete(jar, i, i+1)
case gone:
case i >= 0:
jar[i].v = c.Value
default:
jar = append(jar, kv{c.Name, c.Value})
}
}
out := make([]string, len(jar))
for i, e := range jar {
out[i] = e.k + "=" + e.v
}
return strings.Join(out, "; ")
}
// SignOutQianfan forgets the provider's sign-in, and no other's.
func SignOutQianfan(id string) error {
qianfanMu.Lock()
@@ -232,7 +317,8 @@ func SaveQianfanPaste(ctx context.Context, id, text string) error {
if err != nil {
return err
}
if _, err := qianfanResource(ctx, cookie); err != nil {
_, set, err := qianfanResource(ctx, cookie)
if err != nil {
if errors.Is(err, errQianfanSession) {
// the bookmarklet sees only the cookies a page may read
return errors.New("Baidu's console didn't take that sign-in: copy the Cookie header of the console's tokenPlanPersonal/resource request from your browser's developer tools (Network) and paste it here")
@@ -241,7 +327,7 @@ func SaveQianfanPaste(ctx context.Context, id, text string) error {
}
qianfanMu.Lock()
all := loadQianfan()
all[id] = qianfanSession{Cookie: cookie}
all[id] = qianfanSession{Cookie: mergeQianfanCookies(cookie, set)}
err = saveQianfan(all)
qianfanMu.Unlock()
forgetPlanQuotas()
@@ -260,11 +346,12 @@ func qianfanClient() *http.Client {
}
// qianfanResource asks the console for the account's Token Plan Personal
// as the session, and reads its result.
func qianfanResource(ctx context.Context, cookie string) (json.RawMessage, error) {
// as the session, and reads its result and the cookies a reply that read it
// set.
func qianfanResource(ctx context.Context, cookie string) (json.RawMessage, []*http.Cookie, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, qianfanConsole+qianfanResourcePath, nil)
if err != nil {
return nil, err
return nil, nil, err
}
req.Header.Set("Cookie", cookie)
req.Header.Set("Accept", "application/json;charset=UTF-8")
@@ -273,16 +360,16 @@ func qianfanResource(ctx context.Context, cookie string) (json.RawMessage, error
req.Header.Set("User-Agent", qianfanUA)
res, err := qianfanClient().Do(req)
if err != nil {
return nil, err
return nil, nil, err
}
defer res.Body.Close()
b, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20))
switch {
case res.StatusCode >= 300 && res.StatusCode < 400,
res.StatusCode == http.StatusUnauthorized, res.StatusCode == http.StatusForbidden:
return nil, errQianfanSession
return nil, nil, errQianfanSession
case res.StatusCode >= 400:
return nil, fmt.Errorf("Baidu's console answered %s", res.Status)
return nil, nil, fmt.Errorf("Baidu's console answered %s", res.Status)
}
var r struct {
Success any `json:"success"`
@@ -293,9 +380,9 @@ func qianfanResource(ctx context.Context, cookie string) (json.RawMessage, error
if json.Unmarshal(b, &r) != nil {
// a sign-in page served as 200 is a session ended too
if strings.Contains(strings.ToLower(string(b[:min(len(b), 2048)])), "<html") {
return nil, errQianfanSession
return nil, nil, errQianfanSession
}
return nil, fmt.Errorf("Baidu's console answered what isn't JSON: %s", volcHead(b))
return nil, nil, fmt.Errorf("Baidu's console answered what isn't JSON: %s", volcHead(b))
}
if r.Success != true {
msg := strings.TrimSpace(fmt.Sprint(r.Message))
@@ -304,14 +391,14 @@ func qianfanResource(ctx context.Context, cookie string) (json.RawMessage, error
}
code := strings.ToLower(fmt.Sprint(r.Code))
if strings.Contains(code, "login") || strings.Contains(code, "session") || strings.Contains(code, "unauth") {
return nil, errQianfanSession
return nil, nil, errQianfanSession
}
if msg == "" || msg == "<nil>" {
msg = volcHead(b)
}
return nil, fmt.Errorf("Baidu's console refused: %s", msg)
return nil, nil, fmt.Errorf("Baidu's console refused: %s", msg)
}
return r.Result, nil
return r.Result, res.Cookies(), nil
}
// qianfanItem is one plan the console lists, its apiKey left out.
@@ -433,7 +520,12 @@ func qianfanPlanQuota(ctx context.Context, p Provider) SubscriptionQuota {
q.Error = errQianfanSession.Error()
return q
}
raw, err := qianfanResource(ctx, s.Cookie)
raw, set, err := qianfanResource(ctx, s.Cookie)
if errors.Is(err, errQianfanSession) {
noteQianfan(p.ID, s.Cookie, true, nil)
} else if err == nil && (len(set) > 0 || s.Ended != "") {
noteQianfan(p.ID, s.Cookie, false, set)
}
if err != nil {
q.Error = err.Error()
return q
+82
View File
@@ -30,6 +30,9 @@ type fakeQianfanConsole struct {
cookie atomic.Value // the Cookie header it takes now
body atomic.Value
asked atomic.Int32
// renew, when set, is a session the console renews to as it answers:
// a reply sets its bce-session, and the old one is taken no longer
renew atomic.Value
}
func newFakeQianfanConsole(t *testing.T) *fakeQianfanConsole {
@@ -47,6 +50,12 @@ func newFakeQianfanConsole(t *testing.T) *fakeQianfanConsole {
http.Redirect(w, r, "https://login.bce.baidu.com/?redirect=x", http.StatusFound)
return
}
if r, _ := f.renew.Load().(string); r != "" {
w.Header().Add("Set-Cookie", "bce-session="+r+"; Path=/; Domain=.baidu.com; HttpOnly")
w.Header().Add("Set-Cookie", "elsewhere=1; Path=/qianfan/other")
f.cookie.Store("BDUSS=bd-1; bce-session=" + r + "; bce-user-info=u-1")
f.renew.Store("")
}
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(f.body.Load().(string)))
}))
@@ -227,3 +236,76 @@ func TestQianfanPlanCard(t *testing.T) {
t.Fatalf("forgotten: %v", err)
}
}
// A session Baidu ends is marked ended, so the editor asks for a new one
// (QianfanEnded), and the card still says signed out; a new paste, or a
// read the console takes again, clears the mark. A cookie the console
// renews in a reply is kept, so the next read goes with it.
func TestQianfanSessionEnded(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
forgetPlanQuotas()
f := newFakeQianfanConsole(t)
ctx := context.Background()
p := Provider{ID: "baidu-qianfan", Name: "Baidu Qianfan", Key: "bce-v3/k", Chat: "https://qianfan.baidubce.com/v2/tokenplan/personal"}
first := f.cookie.Load().(string)
if err := SaveQianfanPaste(ctx, p.ID, first); err != nil || QianfanEnded(p.ID) {
t.Fatalf("saved: %v", err)
}
// the console renews bce-session in its reply: magpie keeps the new one
f.renew.Store("s-2")
if q := qianfanPlanQuota(ctx, p); q.Error != "" {
t.Fatalf("renewing read: %+v", q)
}
if got := loadQianfan()[p.ID].Cookie; got != "BDUSS=bd-1; bce-session=s-2; bce-user-info=u-1" {
t.Fatalf("renewed cookie kept as %q", got)
}
if q := qianfanPlanQuota(ctx, p); q.Error != "" || QianfanEnded(p.ID) {
t.Fatalf("read after renewal: %+v", q)
}
// Baidu ends it: the card says so, and the editor asks again
f.cookie.Store("BDUSS=someone-else")
if q := qianfanPlanQuota(ctx, p); q.Error != errQianfanSession.Error() {
t.Fatalf("ended: %+v", q)
}
if !QianfanEnded(p.ID) || !QianfanSignedIn(p.ID) {
t.Fatal("an ended sign-in should be kept, marked ended")
}
ended := loadQianfan()[p.ID].Ended
qianfanPlanQuota(ctx, p)
if got := loadQianfan()[p.ID].Ended; got != ended {
t.Fatalf("the time it ended moved: %q then %q", ended, got)
}
// a new paste is a new sign-in, not ended
if err := SaveQianfanPaste(ctx, p.ID, "BDUSS=someone-else"); err != nil || QianfanEnded(p.ID) {
t.Fatalf("new paste: %v ended=%v", err, QianfanEnded(p.ID))
}
// a paste made while an older read was out isn't marked by that read
noteQianfan(p.ID, first, true, nil)
if QianfanEnded(p.ID) {
t.Fatal("a read with the old cookie marked the new sign-in ended")
}
}
func TestMergeQianfanCookies(t *testing.T) {
past := time.Now().Add(-time.Hour)
for _, c := range []struct {
set []*http.Cookie
want string
}{
{nil, "a=1; b=2"},
{[]*http.Cookie{{Name: "b", Value: "3"}}, "a=1; b=3"},
{[]*http.Cookie{{Name: "c", Value: "4", Path: "/api"}}, "a=1; b=2; c=4"},
{[]*http.Cookie{{Name: "a", Value: "", MaxAge: -1}}, "b=2"},
{[]*http.Cookie{{Name: "b", Value: "x", Expires: past}}, "a=1"},
{[]*http.Cookie{{Name: "c", Value: "4", Path: "/qianfan/other"}}, "a=1; b=2"},
{[]*http.Cookie{{Name: "c", Value: "4\r\nX: y"}}, "a=1; b=2"},
} {
if got := mergeQianfanCookies("a=1; b=2", c.set); got != c.want {
t.Errorf("%v: %q, want %q", c.set, got, c.want)
}
}
}