mirror of
https://github.com/ZHANGTIANYAO1/teamspeak-music-bot.git
synced 2026-12-02 19:02:50 +08:00
fix(music): normalise pasted cookies so /song/url stops answering 400
A cookie file on a live deployment held this: MUSIC_A_T=1456043741268; Max-Age=2147483647; Expires=Thu, 25 Nov 2094 ...; Path=/api/clientlog;;MUSIC_R_T=...; Max-Age=...; Path=/eapi/feedback; ... That is a `Set-Cookie` header pasted whole. The cookie is then handed to the sidecar as `?cookie=<the whole thing>`, so `Max-Age`, `Expires` and `Path` are read as cookie NAMES and the string grows to several KB before URL-encoding. Measured on that box (data/logs/bot.log): - 34 of 34 `/song/url/v1` calls failed with `ERR_BAD_REQUEST` (HTTP 400); - the same failure is still happening today, e.g. 17:14 and 17:20 local; - every one surfaced to the user as 「无法播放(区域/版权限制)」. So the message people were chasing for weeks is not a copyright signal at all — it is the sidecar rejecting a malformed request. `normalizeCookie()` drops attribute pairs, the `Set-Cookie:` prefix, CR/LF and duplicate names, and keeps only real `name=value` pairs. It is applied: - on `save()`, so nothing malformed reaches the file again; - on `load()`, and **written back when it differs** — an existing deployment is repaired in place without asking anyone to scan a QR code again; - in `setCookie()` of all four providers, including Kugou, which parses into a map and would otherwise store `max-age` as a device field. jellyfin is excluded: its blob is JSON (accessToken/userId/deviceId), not a cookie header, and normalising it would shred the payload. A test pins that. Valid cookies are untouched — `normalizeCookie` is idempotent and byte-exact on a clean string, and a clean file is not rewritten. This does not overlap with the play-URL retry PR: that one retries a genuine `url: null`, this one stops the request from being rejected before it is sent. Both are needed — retrying a 400 just gets four more 400s.
This commit is contained in:
1 parent
17008ae52e
commit
4ac3309e34
8 files changed
+295
-11
No files matched your search
@@ -0,0 +1,70 @@
|
||||
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("");
|
||||
});
|
||||
});
|
||||
+38
-7
@@ -1,10 +1,22 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { normalizeCookie } from "./cookie-normalize.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;
|
||||
@@ -15,25 +27,44 @@ export function createCookieStore(cookieDir: string): CookieStore {
|
||||
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 {
|
||||
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 {
|
||||
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 ?? "";
|
||||
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;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
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("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("");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,93 @@
|
||||
/**
|
||||
* 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.
|
||||
*
|
||||
* - drops a leading `Set-Cookie:` / `Cookie:` prefix (people copy the whole line)
|
||||
* - 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 "";
|
||||
|
||||
let text = raw.trim();
|
||||
const prefix = /^(?:set-)?cookie\s*:\s*/i.exec(text);
|
||||
if (prefix) text = text.slice(prefix[0].length);
|
||||
|
||||
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
@@ -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();
|
||||
|
||||
@@ -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 {
|
||||
|
||||
+4
-1
@@ -1,3 +1,4 @@
|
||||
import { normalizeCookie } from "./cookie-normalize.js";
|
||||
import axios, { type AxiosInstance } from "axios";
|
||||
import type {
|
||||
MusicProvider,
|
||||
@@ -818,7 +819,9 @@ export class QQMusicProvider implements MusicProvider {
|
||||
}
|
||||
|
||||
setCookie(cookie: string): void {
|
||||
this.cookie = cookie;
|
||||
// Normalised: see music/cookie-normalize.ts for why a pasted Set-Cookie
|
||||
// line breaks every request.
|
||||
this.cookie = 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;
|
||||
|
||||
Reference in new issue
Block a user