Merge cookie normalization into QQ session renewal

This commit is contained in:
TIANYAO ZHANG committed 2026-11-18 16:43:49 +08:00
commit 9928035282
13 files changed
+342 -20

No files matched your search

+1 -1
View File
@@ -353,7 +353,7 @@ QQ 音源启用时,`QQ_MUSIC_MANAGED_SESSION` 默认为 `1`。在 **设置 →
已有 `cookies/qq.json` 可继续播放,扫码授权后才会获得续期所需的凭据。手动导入 Cookie 会替换当前登录并取消该账号的自动续期。设置页会显示上次成功续期时间、下次续期时间、重试状态或重新扫码提示。具备平台登录权限的用户也可以调用 `POST /api/auth/qq/refresh` 手动尝试续期。
设置 `QQ_MUSIC_MANAGED_SESSION=0` 并重启可关闭自动续期并使用原来的 `qq.json`。
设置 `QQ_MUSIC_MANAGED_SESSION=0` 并重启可关闭自动续期。机器人继续使用当前的 QQ 播放 Cookie,并从 `cookies/qq.json` 兼容读取旧部署的 Cookie。
### WebUI 页面说明
+75
View File
@@ -0,0 +1,75 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { createCookieStore } from "./auth.js";
let dir: string;
beforeEach(() => {
dir = fs.mkdtempSync(path.join(os.tmpdir(), "cookie-store-"));
});
afterEach(() => {
fs.rmSync(dir, { recursive: true, force: true });
});
/** The blob a live deployment actually had on disk (abridged). */
const BLOB =
"MUSIC_A_T=1456043741268; Max-Age=2147483647; Expires=Thu, 25 Nov 2094 21:48:40 GMT; Path=/api/clientlog;" +
";MUSIC_R_T=1456043923317; Max-Age=2147483647; Expires=Thu, 25 Nov 2094 21:48:40 GMT; Path=/eapi/feedback;" +
";MUSIC_U=00ABCDEF0123456789abcdef; Max-Age=1296000; Path=/";
describe("cookie store", () => {
it("normalises on save, so a pasted header never reaches the file", () => {
const store = createCookieStore(dir);
store.save("netease", BLOB);
const onDisk = JSON.parse(fs.readFileSync(path.join(dir, "netease.json"), "utf-8"));
expect(onDisk.cookie).toBe("MUSIC_A_T=1456043741268; MUSIC_R_T=1456043923317; MUSIC_U=00ABCDEF0123456789abcdef");
expect(onDisk.cookie).not.toContain("Max-Age");
});
it("repairs a file that was already written by an older build", () => {
const file = path.join(dir, "netease.json");
fs.writeFileSync(file, JSON.stringify({ cookie: BLOB }), "utf-8");
const store = createCookieStore(dir);
expect(store.load("netease")).toBe(
"MUSIC_A_T=1456043741268; MUSIC_R_T=1456043923317; MUSIC_U=00ABCDEF0123456789abcdef",
);
// Written back, so the next start does not have to repair it again.
const onDisk = JSON.parse(fs.readFileSync(file, "utf-8"));
expect(onDisk.cookie).not.toContain("Path=");
});
it("keeps a valid cookie byte-for-byte and does not rewrite the file", () => {
const file = path.join(dir, "netease.json");
const valid = "MUSIC_U=abc; __csrf=def";
fs.writeFileSync(file, JSON.stringify({ cookie: valid, updatedAt: "2026-01-01T00:00:00.000Z" }), "utf-8");
const before = fs.readFileSync(file, "utf-8");
expect(createCookieStore(dir).load("netease")).toBe(valid);
expect(fs.readFileSync(file, "utf-8")).toBe(before);
});
// jellyfin stores JSON (token / userId / deviceId), not a cookie header.
// Normalising it would shred every '=' and comma in the payload.
it("leaves the jellyfin credential blob untouched", () => {
const blob = JSON.stringify({ accessToken: "a=b", userId: "u1", deviceId: "d1" });
const store = createCookieStore(dir);
store.save("jellyfin", blob);
expect(store.load("jellyfin")).toBe(blob);
});
it("returns an empty string for a missing or corrupt file", () => {
const store = createCookieStore(dir);
expect(store.load("qq")).toBe("");
fs.writeFileSync(path.join(dir, "qq.json"), "{not json", "utf-8");
expect(store.load("qq")).toBe("");
});
it("ignores a well-formed JSON file with a non-string cookie", () => {
fs.writeFileSync(path.join(dir, "qq.json"), JSON.stringify({ cookie: { invalid: true } }));
expect(createCookieStore(dir).load("qq")).toBe("");
});
});
+39 -7
View File
@@ -1,11 +1,23 @@
import fs from "node:fs";
import path from "node:path";
import { normalizeCookie } from "./cookie-normalize.js";
import type { createQqSessionStore } from "./qq-session.js";
/** Platforms with a persisted credential blob. For jellyfin the "cookie" is a
* JSON string carrying the access token / userId / deviceId (see jellyfin.ts). */
type CookiePlatform = "netease" | "qq" | "bilibili" | "kugou" | "jellyfin";
/**
* Everything except jellyfin stores a `Cookie:` header value, which people paste
* by hand and therefore paste wrong — usually the whole `Set-Cookie` line, with
* `Max-Age` / `Expires` / `Path` in it. Those get read as cookie names and the
* sidecar answers 400, which the user sees as 「无法播放(区域/版权限制)」.
* jellyfin's blob is JSON and must not be touched.
*/
function storesCookieHeader(platform: CookiePlatform): boolean {
return platform !== "jellyfin";
}
export interface CookieStore {
save(platform: CookiePlatform, cookie: string): void;
load(platform: CookiePlatform): string;
@@ -16,30 +28,50 @@ export function createCookieStore(cookieDir: string, qqStore?: ReturnType<typeof
fs.mkdirSync(cookieDir, { recursive: true });
}
function write(platform: CookiePlatform, cookie: string): void {
const filePath = path.join(cookieDir, `${platform}.json`);
fs.writeFileSync(
filePath,
JSON.stringify({ cookie, updatedAt: new Date().toISOString() }),
{ encoding: "utf-8", mode: 0o600 }
);
}
return {
save(platform: CookiePlatform, cookie: string): void {
if (platform === "qq" && qqStore) {
qqStore.save({ cookie });
return;
}
const filePath = path.join(cookieDir, `${platform}.json`);
fs.writeFileSync(
filePath,
JSON.stringify({ cookie, updatedAt: new Date().toISOString() }),
{ encoding: "utf-8", mode: 0o600 }
);
write(platform, storesCookieHeader(platform) ? normalizeCookie(cookie) : cookie);
},
load(platform: CookiePlatform): string {
if (platform === "qq" && qqStore) return qqStore.load()?.cookie ?? "";
const filePath = path.join(cookieDir, `${platform}.json`);
if (!fs.existsSync(filePath)) return "";
let stored: string;
try {
const data = JSON.parse(fs.readFileSync(filePath, "utf-8"));
return data.cookie ?? "";
if (typeof data?.cookie !== "string") return "";
stored = data.cookie;
} catch {
return "";
}
if (!storesCookieHeader(platform)) return stored;
const clean = normalizeCookie(stored);
if (clean === stored) return clean;
// Repair in place: an existing deployment already has the header blob on
// disk, and fixing it here means the next request is clean without making
// anyone scan a QR code again. Best-effort — a read-only volume must not
// take the bot down, the cleaned value is still returned.
try {
write(platform, clean);
} catch {
/* keep serving the cleaned in-memory value */
}
return clean;
},
};
}
+2 -1
View File
@@ -1,3 +1,4 @@
import { normalizeCookie } from "./cookie-normalize.js";
import { createHash } from "node:crypto";
import axios, { type AxiosInstance } from "axios";
import type {
@@ -461,7 +462,7 @@ export class BiliBiliProvider implements MusicProvider {
}
setCookie(cookie: string): void {
this.cookie = cookie;
this.cookie = normalizeCookie(cookie);
}
getCookie(): string {
+85
View File
@@ -0,0 +1,85 @@
import { describe, expect, it } from "vitest";
import { isNormalizedCookie, normalizeCookie } from "./cookie-normalize.js";
/**
* The exact shape found in a live deployment's data/cookies/netease.json. Every
* `/song/url/v1` call answered 400 while this was stored, and the user saw
* 「无法播放(区域/版权限制)」 on every play attempt.
*/
const HEADER_BLOB = [
"MUSIC_A_T=1456043741268; Max-Age=2147483647; Expires=Thu, 25 Nov 2094 21:48:40 GMT; Path=/api/clientlog;",
";MUSIC_R_T=1456043923317; Max-Age=2147483647; Expires=Thu, 25 Nov 2094 21:48:40 GMT; Path=/eapi/feedback;",
";NMTID=00Oyuu_9EnDq_rMBEMIuKakmlo4dukAAAGht0p3Kw; Max-Age=315360000; Expires=Tue, 04 Nov 2036 18:34:33 GMT; Path=/;",
";MUSIC_U=00ABCDEF0123456789abcdef0123456789ABCDEF0123456789abcdef0123456789ABCDEF0123456789abcdef0123456; Max-Age=1296000; Expires=Mon, 23 Nov 2026 09:32:11 GMT; Path=/;",
";__csrf=8f14e45fceea167a5a36dedd4bea2543; Max-Age=1296000; Expires=Mon, 23 Nov 2026 09:32:11 GMT; Path=/;",
].join("");
describe("normalizeCookie", () => {
it("keeps only the real cookie pairs from a pasted Set-Cookie blob", () => {
expect(normalizeCookie(HEADER_BLOB)).toBe(
"MUSIC_A_T=1456043741268; MUSIC_R_T=1456043923317; NMTID=00Oyuu_9EnDq_rMBEMIuKakmlo4dukAAAGht0p3Kw; " +
"MUSIC_U=00ABCDEF0123456789abcdef0123456789ABCDEF0123456789abcdef0123456789ABCDEF0123456789abcdef0123456; " +
"__csrf=8f14e45fceea167a5a36dedd4bea2543",
);
});
it("drops every attribute name so it cannot be read as a cookie", () => {
const out = normalizeCookie(HEADER_BLOB);
for (const attr of ["Max-Age", "Expires", "Path", "Domain", "Secure", "HttpOnly", "SameSite"]) {
expect(out).not.toContain(`${attr}=`);
}
});
it("shrinks the query string enough to stop the 400", () => {
// The real blob repeats one attribute set per request path, so it grows
// several KB and the re-encoded query is what the sidecar rejects. The
// fixture is the same shape at a smaller scale; what matters is that the
// bulk (attributes) is gone and only the payload survives.
expect(normalizeCookie(HEADER_BLOB).length).toBeLessThan(HEADER_BLOB.length * 0.6);
});
it("leaves an already-valid cookie untouched", () => {
const valid = "MUSIC_U=abc123; __csrf=def456; NMTID=xyz";
expect(normalizeCookie(valid)).toBe(valid);
expect(isNormalizedCookie(valid)).toBe(true);
});
it("is idempotent", () => {
const once = normalizeCookie(HEADER_BLOB);
expect(normalizeCookie(once)).toBe(once);
});
it("strips a pasted `Set-Cookie:` / `Cookie:` prefix", () => {
expect(normalizeCookie("Set-Cookie: MUSIC_U=abc; Path=/")).toBe("MUSIC_U=abc");
expect(normalizeCookie("cookie: MUSIC_U=abc")).toBe("MUSIC_U=abc");
});
it("keeps each cookie from multiple pasted Set-Cookie lines", () => {
expect(normalizeCookie("Set-Cookie: MUSIC_U=abc; Path=/\r\nSet-Cookie: __csrf=def; HttpOnly"))
.toBe("MUSIC_U=abc; __csrf=def");
});
it("empties out a blob that carries no real cookie at all", () => {
expect(normalizeCookie("Max-Age=1; Expires=Thu, 25 Nov 2094 21:48:40 GMT; Path=/")).toBe("");
});
it("removes CR/LF left inside a value by a multi-line paste", () => {
expect(normalizeCookie("MUSIC_U=abc\r\ndef; __csrf=x")).toBe("MUSIC_U=abcdef; __csrf=x");
});
it("keeps the last value when a name repeats", () => {
expect(normalizeCookie("MUSIC_A_T=1; MUSIC_A_T=2")).toBe("MUSIC_A_T=2");
});
it("keeps '=' inside a value (base64 padding)", () => {
expect(normalizeCookie("MUSIC_U=abc==; Path=/")).toBe("MUSIC_U=abc==");
});
it("drops nameless fragments and empty values", () => {
expect(normalizeCookie(";; =x; MUSIC_U=abc; empty=;")).toBe("MUSIC_U=abc");
});
it("handles the empty string", () => {
expect(normalizeCookie("")).toBe("");
});
});
+91
View File
@@ -0,0 +1,91 @@
/**
* Cookies for the music platforms are pasted in by hand, and what people paste
* is usually not a cookie — it is the raw `Set-Cookie` header, attributes and
* all:
*
* MUSIC_A_T=145...; Max-Age=2147483647; Expires=Thu, 25 Nov 2094 ...; Path=/api/clientlog;
* ;MUSIC_R_T=145...; Max-Age=2147483647; Expires=...; Path=/eapi/feedback; ...
*
* Every `;`-separated fragment with an `=` is treated as a cookie pair, so
* `Max-Age`, `Expires` and `Path` become cookie NAMES. The string then gets
* passed to the sidecar API as `?cookie=...`, and two things happen:
*
* 1. the sidecar answers **400** instead of a song URL. Measured on a live
* deployment: 34 of 34 `/song/url/v1` calls failed with ERR_BAD_REQUEST
* while the cookie file held a header blob, and every one of those surfaced
* to the user as 「无法播放(区域/版权限制)」;
* 2. the query string grows to several KB (5 KB of header re-encoded becomes
* closer to 10 KB), which can also trip the HTTP request-line limit.
*
* Normalising both on the way in (setCookie) and on the way out (loading the
* stored file) repairs existing deployments without asking anyone to log in
* again. Nothing about a VALID cookie changes — see the tests.
*/
/**
* Attributes that belong to a Set-Cookie LINE, never to a Cookie header. Kept
* lowercase for the comparison. `size` is Chrome-specific, `partitioned` and
* `priority` are newer additions, and `comment`/`version` are RFC 2109 leftovers
* that still show up in hand-copied blobs.
*/
const SET_COOKIE_ATTRIBUTES = new Set([
"max-age",
"expires",
"path",
"domain",
"secure",
"httponly",
"samesite",
"priority",
"partitioned",
"version",
"comment",
"size",
"sameparty",
]);
/** RFC 6265 cookie-name (token) — anything else is header noise, not a name. */
const TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
/**
* Turn whatever was pasted into a syntactically valid `Cookie:` header value.
*
* - handles pasted `Set-Cookie:` / `Cookie:` header lines
* - drops attribute pairs (`Max-Age`, `Expires`, `Path`, ...)
* - drops fragments without `=` (`;;`, trailing separators)
* - drops values that are empty, which the sidecar reads as "unset anyway"
* - strips CR/LF, which a multi-line paste leaves inside values and which make
* the outgoing query string invalid
* - de-duplicates by name, last one wins (a header blob repeats MUSIC_A_T a
* dozen times for different paths; the payload is identical each time)
*
* Idempotent: normalising an already-normalised cookie returns it unchanged.
*/
export function normalizeCookie(raw: string): string {
if (!raw) return "";
const text = raw.trim().replace(/^[ \t]*(?:set-)?cookie[ \t]*:[ \t]*/gim, ";");
const pairs = new Map<string, string>();
for (const fragment of text.split(";")) {
const eq = fragment.indexOf("=");
if (eq <= 0) continue;
const name = fragment.slice(0, eq).trim();
// A value may legitimately contain '=' (base64 padding), so keep the rest.
const value = fragment.slice(eq + 1).replace(/[\r\n]+/g, "").trim();
if (!name || !value) continue;
if (!TOKEN.test(name)) continue;
if (SET_COOKIE_ATTRIBUTES.has(name.toLowerCase())) continue;
pairs.set(name, value);
}
return [...pairs].map(([name, value]) => `${name}=${value}`).join("; ");
}
/** True when `raw` is already a clean cookie header and normalising is a no-op. */
export function isNormalizedCookie(raw: string): boolean {
return normalizeCookie(raw) === raw;
}
+4 -1
View File
@@ -15,6 +15,7 @@
* residential IP is required. QR login and VIP audio could not be verified in
* the build environment.
*/
import { normalizeCookie } from "./cookie-normalize.js";
import axios, { type AxiosInstance } from "axios";
import crypto from "node:crypto";
import zlib from "node:zlib";
@@ -442,7 +443,9 @@ export class KugouProvider implements MusicProvider {
// --- Cookie persistence (CookieStore stores a flat "k=v; k=v" string) ------
setCookie(cookie: string): void {
const map: CookieMap = {};
for (const part of (cookie || "").split(";")) {
// Normalise first: a pasted `Set-Cookie` line would otherwise land
// Max-Age/Expires/Path in the map as cookie names.
for (const part of normalizeCookie(cookie).split(";")) {
const eq = part.indexOf("=");
if (eq < 0) continue;
const k = part.slice(0, eq).trim();
+4 -1
View File
@@ -1,3 +1,4 @@
import { normalizeCookie } from "./cookie-normalize.js";
import axios, { type AxiosInstance } from "axios";
import type {
MusicProvider,
@@ -390,7 +391,9 @@ export class NeteaseProvider implements MusicProvider {
}
setCookie(cookie: string): void {
this.cookie = cookie;
// Normalised so a pasted `Set-Cookie` line cannot put Max-Age/Expires/Path
// into the query string — that is what made the sidecar answer 400.
this.cookie = normalizeCookie(cookie);
}
getCookie(): string {
+18
View File
@@ -245,6 +245,24 @@ describe("managed QQ session", () => {
expect(client.refresh).not.toHaveBeenCalled();
});
it("normalises manual cookies in memory and at the shared session store", () => {
const raw = "Set-Cookie: uin=999; Path=/\r\nSet-Cookie: qm_keyst=manual; Secure";
const expected = "uin=999; qm_keyst=manual";
session.setCookie(raw);
expect(session.getCookie()).toBe(expected);
expect(store.load()?.cookie).toBe(expected);
createCookieStore(dir, store).save("qq", raw);
expect(store.load()?.cookie).toBe(expected);
});
it("normalises cookies migrated from old installations", () => {
const legacyFile = path.join(dir, "qq.json");
const raw = "uin=999; Path=/;;qm_keyst=legacy; Secure";
fs.writeFileSync(legacyFile, JSON.stringify({ cookie: raw }));
store = createQqSessionStore(file, legacyFile);
expect(store.load()).toEqual({ cookie: "uin=999; qm_keyst=legacy" });
});
it("uses the newer login when both older session files already exist", () => {
const legacyFile = path.join(dir, "qq.json");
const legacyCookie = "uin=999; qm_keyst=legacy";
+8 -5
View File
@@ -3,6 +3,7 @@ import { randomUUID } from "node:crypto";
import path from "node:path";
import type { Logger } from "../logger.js";
import type { QrCodeResult } from "./provider.js";
import { normalizeCookie } from "./cookie-normalize.js";
import { hasQqRenewalMaterial, parseQqCredential, qqPlaybackCookie, type QqCredential, type QqLoginClient, type QqPollResult } from "./qq-login.js";
interface QqSessionRecord {
@@ -37,7 +38,8 @@ export function createQqSessionStore(file: string, legacyFile?: string) {
try {
if (fs.statSync(legacyFile).mtimeMs <= newerThan) return;
const { cookie } = JSON.parse(fs.readFileSync(legacyFile, "utf8"));
if (typeof cookie === "string" && cookie) return { cookie };
const clean = typeof cookie === "string" ? normalizeCookie(cookie) : "";
if (clean) return { cookie: clean };
} catch { /* The legacy cookie is missing or unreadable. */ }
}
@@ -58,11 +60,12 @@ export function createQqSessionStore(file: string, legacyFile?: string) {
if (legacy) return legacy;
}
const credential = parseQqCredential(data.credential);
if (data.credential && (!credential || qqPlaybackCookie(credential) !== data.cookie)) {
const cookie = normalizeCookie(data.cookie);
if (data.credential && (!credential || qqPlaybackCookie(credential) !== cookie)) {
throw new Error("Invalid QQ session credential");
}
return {
cookie: data.cookie,
cookie,
credential,
reauthRequired: data.reauthRequired === true,
authorizedAt: timestamp(data.authorizedAt),
@@ -72,7 +75,7 @@ export function createQqSessionStore(file: string, legacyFile?: string) {
save(data: QqSessionRecord): void {
const temp = path.join(path.dirname(file), `.qq-session-${randomUUID()}.tmp`);
try {
fs.writeFileSync(temp, JSON.stringify({ version: 1, shared: true, ...data }), {
fs.writeFileSync(temp, JSON.stringify({ version: 1, shared: true, ...data, cookie: normalizeCookie(data.cookie) }), {
encoding: "utf8", mode: 0o600, flag: "wx", flush: true,
});
fs.renameSync(temp, file);
@@ -136,7 +139,7 @@ export class QQManagedSession {
}
setCookie(cookie: string): void {
this.replace({ cookie });
this.replace({ cookie: normalizeCookie(cookie) });
this.qrGeneration++;
this.qr = undefined;
}
+3 -2
View File
@@ -1,3 +1,4 @@
import { normalizeCookie } from "./cookie-normalize.js";
import axios, { type AxiosInstance } from "axios";
import type {
MusicProvider,
@@ -820,7 +821,7 @@ export class QQMusicProvider implements MusicProvider {
const body = res.data;
if (body?.isOk === true) {
const cookie: string = body.session?.cookie ?? "";
if (cookie) this.legacyCookie = cookie;
if (cookie) this.setCookie(cookie);
return "confirmed";
}
if (body?.refresh === true) return "expired";
@@ -831,7 +832,7 @@ export class QQMusicProvider implements MusicProvider {
setCookie(cookie: string): void {
if (this.managedSession) this.managedSession.setCookie(cookie);
else this.legacyCookie = cookie;
else this.legacyCookie = normalizeCookie(cookie);
// Reset radar pagination so a re-login (different account) starts from the
// first page rather than inheriting the previous account's cursor.
this.radarPage = 1;
+8
View File
@@ -124,6 +124,14 @@ describe("managed QQ authentication routes", () => {
expect(refresh).not.toHaveBeenCalled();
});
it("keeps the current QQ login when an import contains only response attributes", async () => {
const { app, qq } = mount(true);
await request(app).post("/api/auth/cookie")
.send({ platform: "qq", cookie: "Path=/; HttpOnly" })
.expect(400);
expect(qq.setCookie).not.toHaveBeenCalled();
});
it("continues persisting the legacy cookie when the feature is disabled", async () => {
const { app, legacyStore } = mount(false);
await request(app).get("/api/auth/qrcode/status").query({ platform: "qq", key: "legacy" }).expect(200);
+4 -2
View File
@@ -2,6 +2,7 @@ import { Router } from "express";
import type { ParamsDictionary } from "express-serve-static-core";
import type { MusicProvider } from "../../music/provider.js";
import type { QQMusicProvider } from "../../music/qq.js";
import { normalizeCookie } from "../../music/cookie-normalize.js";
import { YouTubeProvider } from "../../music/youtube.js";
import type { CookieStore } from "../../music/auth.js";
import type { Logger } from "../../logger.js";
@@ -190,8 +191,9 @@ export function createAuthRouter(
});
router.post("/cookie", requirePermission("platform.auth"), (req, res) => {
const { platform, cookie } = req.body;
if (typeof cookie !== "string" || !cookie.trim()) {
const { platform, cookie: raw } = req.body;
const cookie = typeof raw === "string" ? normalizeCookie(raw) : "";
if (!cookie) {
res.status(400).json({ error: "cookie is required" });
return;
}