Compare commits

..
Author SHA1 Message Date
TIANYAO ZHANG dd8e8c5950 docs: explain offline Docker deployment 2026-11-18 16:50:45 +08:00
TIANYAO ZHANG 568d49f837 Merge pull request #184 from jiayuLian/fix/cookie-normalize
fix(music): cookie 里存的是整条 Set-Cookie,导致 /song/url 一律返回 400
2026-11-18 16:47:31 +08:00
TIANYAO ZHANG f2a72e3162 Merge pull request #178 from zbn297427669/fix/upstream-test-declick-ramp
test: catch bot tests up with the de-click transport ramp
2026-11-18 16:45:49 +08:00
TIANYAO ZHANG 51debb915c fix(music): handle multiple cookie headers and invalid saved values 2026-11-18 16:39:42 +08:00
jiayuLian 4ac3309e34 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.
2026-11-08 17:41:58 +08:00
zbn297427669andClaude Code ba645e5ccb test: catch bot tests up with the de-click transport ramp
Upstream a0f0b49..6f165b5 added the pause/resume fade tail but shipped no
test updates, leaving 5 assertions red (also reproducible on pristine
upstream/main, so not merge-induced).

- instance-recovery/instance harnesses: stub players borrow
  AudioPlayer.prototype.pause/resume, which now call this.setTransportRamp().
  Give the stubs that method or they throw TypeError on pause/resume.
- voice-failure: pausing deliberately emits a fade tail, so the frame count
  no longer freezes at exactly 50. Assert the de-click fade completes, then
  that the scheduler and elapsed clock are genuinely frozen — the actual
  behavior under test.

No production code changed.

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-11-02 15:58:44 +08:00
12 changed files with 359 additions and 24 deletions

No files matched your search

+37 -11
View File
@@ -103,12 +103,12 @@ npm start
### 方式三:Docker 一键部署
所有依赖已内置(Node.js、FFmpeg、Opus 编码器),无需安装任何额外软件。
需要 Docker 和 Docker Compose v2。默认从 GitHub Container Registry(GHCR)拉取预构建镜像,镜像已包含 Node.js、FFmpeg 和 Opus 编码器。
```bash
git clone https://github.com/ZHANGTIANYAO1/teamspeak-music-bot.git
cd teamspeak-music-bot/scripts/docker
docker-compose up -d
docker compose up -d
```
打开浏览器访问 **http://localhost:3000**
@@ -116,15 +116,14 @@ docker-compose up -d
<details>
<summary>Docker 详细说明</summary>
- 首次构建需要几分钟(编译原生模块)
- 默认使用 `host` 网络模式,机器人可直接连接局域网 TS3 服务器
- 数据持久化在 Docker 命名卷 `tsmusicbot-data` 中(数据库、Cookie、日志)
- 内置健康检查(`/api/health`),支持 Docker 自动重启
```bash
docker logs -f tsmusicbot # 查看日志
docker-compose down # 停止
docker-compose up -d --build # 代码更新后重新构建
docker compose down # 停止
docker compose pull && docker compose up -d # 更新预构建镜像
```
如果 TS3 服务器在其他机器上,编辑 `docker-compose.yml`:
@@ -136,6 +135,36 @@ ports:
</details>
#### 无法访问 GHCR 时部署
**离线导入发布镜像。** 在能访问 GHCR 的机器上拉取项目官方发布镜像并导出。下面以 `1.15.4` 和 `linux/amd64` 为例,请选择所需发布版本以及部署服务器的架构(`linux/amd64` 或 `linux/arm64`)。Git 发布标签带 `v`,镜像标签不带 `v`。
```bash
image=ghcr.io/zhangtianyao1/teamspeak-music-bot:1.15.4
docker pull --platform linux/amd64 "$image"
docker image save -o tsmusicbot-1.15.4.tar "$image"
```
将归档和同版本的 `scripts/docker/docker-compose.yml` 复制到部署服务器。在 Compose 文件中把 `image:` 改为上面导入的完整镜像名和标签,然后在该文件所在目录运行:
```bash
docker image load -i tsmusicbot-1.15.4.tar
docker compose config --images
docker compose up -d --pull never
```
升级时导入新版本的镜像并更新 `image:` 的标签,再在同一部署目录运行启动命令,以继续使用现有的数据卷。
**从发布源码本地构建。** 若部署机可以访问构建依赖但无法访问 GHCR,可下载或克隆对应发布标签的源码。在 `scripts/docker/docker-compose.yml` 中把 `image:` 替换成下列配置,保持它位于 `services.tsmusicbot` 下:
```yaml
build:
context: ../..
dockerfile: scripts/docker/Dockerfile
```
进入源码的 `scripts/docker` 目录,运行 `docker compose up -d --build`。构建需要获取 `node:22-slim` 基础镜像,以及 Dockerfile 使用的 apt、npm 和原生依赖下载源。升级时切换到所需的新发布标签并重新构建。
### 方式四:Linux 安装脚本
Linux 下有两个脚本,按需二选一:
@@ -302,11 +331,8 @@ npm start
```bash
cd scripts/docker
# 拉取最新代码
git pull
# 重新构建并启动(数据自动保留)
docker-compose up -d --build
# 拉取预构建镜像并重新启动
docker compose pull && docker compose up -d
```
> 数据(数据库、Cookie、日志)保存在 Docker 命名卷 `tsmusicbot-data` 中,更新不会丢失。
@@ -915,7 +941,7 @@ A:B站搜索需要 buvid3 匿名 Cookie(程序启动时自动获取)。如
A:YouTube 是可选音源,需要手动安装 `yt-dlp`。详见 [可选:YouTube 音源](#可选youtube-音源) 章节。快速验证:在项目根目录执行 `bin/yt-dlp --version`(或系统 `yt-dlp --version`),能打印版本号即可。若 yt-dlp 已安装但仍搜索失败,通常是网络/地域问题或 yt-dlp 版本过旧(执行 `yt-dlp -U` 升级)。
**Q:如何更新到新版本?**
A:`git pull` 拉取最新代码,然后 `npm install && npm run build && npm start` 重新构建启动。Docker 用户执行 `docker-compose up -d --build`。
A:`git pull` 拉取最新代码,然后 `npm install && npm run build && npm start` 重新构建启动。使用预构建镜像的 Docker 用户执行 `docker compose pull && docker compose up -d`,离线导入或本地构建用户按各自的部署步骤升级。
**Q:忘记管理员密码怎么办?**
A:直接操作 SQLite 数据库。最简单的办法是清空 `users` 表然后重新进入 first-run 流程:`sqlite3 data/tsmusicbot.db "DELETE FROM users; DELETE FROM sessions;"`,重启后浏览器会自动跳转 `/first-run` 让你重新创建管理员。详细方法见 [从 WebUI 无鉴权版本升级](#从-webui-无鉴权版本升级重要)。
+4
View File
@@ -29,6 +29,10 @@ function makeBot() {
player.getVolume = () => 50;
player.pause = AudioPlayer.prototype.pause;
player.resume = AudioPlayer.prototype.resume;
// The real pause()/resume() drive the de-click transport ramp
// (a0f0b49..6f165b5). A stub player must expose it too, or the prototype
// methods throw "setTransportRamp is not a function".
player.setTransportRamp = vi.fn();
player.play = vi.fn((_url: string, position: number) => { player.sessionId++; player.elapsed = position; player.state = "playing"; });
player.stop = vi.fn(() => { player.sessionId++; player.state = "idle"; });
const provider = { getSongUrl: vi.fn(async (): Promise<{ url: string } | null> => ({ url: "fresh" })) };
+4
View File
@@ -1780,6 +1780,10 @@ describe("BotInstance trackEnd — stale playback sessions", () => {
player.getPlaybackSessionId = AudioPlayer.prototype.getPlaybackSessionId;
player.pause = AudioPlayer.prototype.pause;
player.resume = AudioPlayer.prototype.resume;
// The real pause()/resume() drive the de-click transport ramp
// (a0f0b49..6f165b5). A stub player must expose it too, or the prototype
// methods throw "setTransportRamp is not a function".
player.setTransportRamp = vi.fn();
player.play = vi.fn(() => { player.sessionId++; player.state = "playing"; });
const provider = { getSongUrl: vi.fn(async () => ({ url: "fresh" })) };
const advances: string[] = [];
+10 -2
View File
@@ -65,9 +65,17 @@ describe("BotInstance persistent voice send failure", () => {
expect(frames).toBe(50);
h.tsClient.emit("voiceSendFailed", { consecutiveFailures: 100, durationMs: 2000 });
vi.advanceTimersByTime(3000);
expect(frames).toBe(50);
expect(h.player.getElapsed()).toBe(1);
// Pausing emits a short de-click fade tail (pauseFrames) so the last
// audible frames ramp down instead of cutting off (a0f0b49). What this
// test guards is what happens AFTER that: the scheduler must go quiet
// and elapsed must stop advancing.
expect(h.player.getState()).toBe("paused");
const framesAfterFade = frames;
const elapsedAfterFade = h.player.getElapsed();
expect(framesAfterFade).toBeLessThan(50 + 20);
vi.advanceTimersByTime(3000);
expect(frames).toBe(framesAfterFade);
expect(h.player.getElapsed()).toBe(elapsedAfterFade);
} finally { h.player.stop(); }
});
+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,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,45 @@ 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 ?? "";
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 {
+4 -1
View File
@@ -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;