mirror of
https://github.com/ZHANGTIANYAO1/teamspeak-music-bot.git
synced 2026-12-01 02:12:50 +08:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4ee1e6f812 |
No files matched your search
@@ -103,12 +103,12 @@ npm start
|
||||
|
||||
### 方式三:Docker 一键部署
|
||||
|
||||
需要 Docker 和 Docker Compose v2。默认从 GitHub Container Registry(GHCR)拉取预构建镜像,镜像已包含 Node.js、FFmpeg 和 Opus 编码器。
|
||||
所有依赖已内置(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,14 +116,15 @@ 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 pull && docker compose up -d # 更新预构建镜像
|
||||
docker-compose down # 停止
|
||||
docker-compose up -d --build # 代码更新后重新构建
|
||||
```
|
||||
|
||||
如果 TS3 服务器在其他机器上,编辑 `docker-compose.yml`:
|
||||
@@ -135,36 +136,6 @@ 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 下有两个脚本,按需二选一:
|
||||
@@ -331,8 +302,11 @@ npm start
|
||||
```bash
|
||||
cd scripts/docker
|
||||
|
||||
# 拉取预构建镜像并重新启动
|
||||
docker compose pull && docker compose up -d
|
||||
# 拉取最新代码
|
||||
git pull
|
||||
|
||||
# 重新构建并启动(数据自动保留)
|
||||
docker-compose up -d --build
|
||||
```
|
||||
|
||||
> 数据(数据库、Cookie、日志)保存在 Docker 命名卷 `tsmusicbot-data` 中,更新不会丢失。
|
||||
@@ -941,7 +915,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 pull && docker compose up -d`,离线导入或本地构建用户按各自的部署步骤升级。
|
||||
A:`git pull` 拉取最新代码,然后 `npm install && npm run build && npm start` 重新构建启动。Docker 用户执行 `docker-compose up -d --build`。
|
||||
|
||||
**Q:忘记管理员密码怎么办?**
|
||||
A:直接操作 SQLite 数据库。最简单的办法是清空 `users` 表然后重新进入 first-run 流程:`sqlite3 data/tsmusicbot.db "DELETE FROM users; DELETE FROM sessions;"`,重启后浏览器会自动跳转 `/first-run` 让你重新创建管理员。详细方法见 [从 WebUI 无鉴权版本升级](#从-webui-无鉴权版本升级重要)。
|
||||
|
||||
@@ -29,10 +29,6 @@ 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" })) };
|
||||
|
||||
@@ -1780,10 +1780,6 @@ 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[] = [];
|
||||
|
||||
@@ -65,17 +65,9 @@ describe("BotInstance persistent voice send failure", () => {
|
||||
expect(frames).toBe(50);
|
||||
h.tsClient.emit("voiceSendFailed", { consecutiveFailures: 100, durationMs: 2000 });
|
||||
vi.advanceTimersByTime(3000);
|
||||
// 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(frames).toBe(50);
|
||||
expect(h.player.getElapsed()).toBe(1);
|
||||
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(); }
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
describe("application log errors", () => {
|
||||
it("preserves HTTP diagnostics while omitting Axios request and response data", () => {
|
||||
const child = spawnSync(process.execPath, [
|
||||
"--import", "tsx", "--input-type=module", "--eval", `
|
||||
import { AxiosError } from "axios";
|
||||
import { createLogger } from "./src/logger.ts";
|
||||
|
||||
const config = { params: { cookie: "sample-request-cookie" } };
|
||||
const response = { status: 400, data: { code: -460, cookie: "sample-response-cookie" } };
|
||||
const err = new AxiosError("sample-sensitive-url", "ERR_BAD_REQUEST", config, undefined, response);
|
||||
const log = createLogger().child({ component: "test" });
|
||||
log.warn({ err }, "Provider failed");
|
||||
log.error({ reason: err }, "Unhandled rejection");
|
||||
log.error(new Error("ordinary error"));
|
||||
`,
|
||||
], { cwd: fileURLToPath(new URL("..", import.meta.url)), encoding: "utf8" });
|
||||
|
||||
expect(child.status, child.stderr).toBe(0);
|
||||
const [provider, rejection, ordinary] = child.stdout.trim().split("\n").map(line => JSON.parse(line));
|
||||
const expected = { type: "AxiosError", code: "ERR_BAD_REQUEST", status: 400, upstreamCode: -460 };
|
||||
expect(provider.err).toMatchObject(expected);
|
||||
expect(rejection.reason).toMatchObject(expected);
|
||||
expect(child.stdout).not.toContain("sample-");
|
||||
expect(ordinary.err.message).toBe("ordinary error");
|
||||
});
|
||||
});
|
||||
+20
-2
@@ -1,12 +1,30 @@
|
||||
import pino from "pino";
|
||||
import { isAxiosError } from "axios";
|
||||
import { mkdirSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
|
||||
export type Logger = pino.Logger;
|
||||
|
||||
function serializeHttpError(error: unknown): unknown {
|
||||
if (!isAxiosError<{ code?: unknown }>(error)) {
|
||||
return error instanceof Error ? pino.stdSerializers.err(error) : error;
|
||||
}
|
||||
const upstreamCode = error.response?.data?.code;
|
||||
return {
|
||||
type: "AxiosError",
|
||||
code: error.code,
|
||||
status: error.response?.status ?? error.status,
|
||||
upstreamCode: typeof upstreamCode === "number" ? upstreamCode : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
// Axios errors include the original request configuration and may contain
|
||||
// session cookies, authorization headers or secrets in the request URL.
|
||||
const serializers = { err: serializeHttpError, reason: serializeHttpError };
|
||||
|
||||
export function createLogger(logDir?: string): Logger {
|
||||
if (!logDir) {
|
||||
return pino({ level: "info" });
|
||||
return pino({ level: "info", serializers });
|
||||
}
|
||||
|
||||
mkdirSync(logDir, { recursive: true });
|
||||
@@ -32,5 +50,5 @@ export function createLogger(logDir?: string): Logger {
|
||||
console.error("Logger transport error:", err);
|
||||
});
|
||||
|
||||
return pino({ level: "debug" }, transport);
|
||||
return pino({ level: "debug", serializers }, transport);
|
||||
}
|
||||
@@ -1,75 +0,0 @@
|
||||
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("");
|
||||
});
|
||||
});
|
||||
+7
-39
@@ -1,22 +1,10 @@
|
||||
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;
|
||||
@@ -27,45 +15,25 @@ 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 {
|
||||
write(platform, storesCookieHeader(platform) ? normalizeCookie(cookie) : cookie);
|
||||
const filePath = path.join(cookieDir, `${platform}.json`);
|
||||
fs.writeFileSync(
|
||||
filePath,
|
||||
JSON.stringify({ cookie, updatedAt: new Date().toISOString() }),
|
||||
{ encoding: "utf-8", mode: 0o600 }
|
||||
);
|
||||
},
|
||||
|
||||
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"));
|
||||
if (typeof data?.cookie !== "string") return "";
|
||||
stored = data.cookie;
|
||||
return 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,4 +1,3 @@
|
||||
import { normalizeCookie } from "./cookie-normalize.js";
|
||||
import { createHash } from "node:crypto";
|
||||
import axios, { type AxiosInstance } from "axios";
|
||||
import type {
|
||||
@@ -462,7 +461,7 @@ export class BiliBiliProvider implements MusicProvider {
|
||||
}
|
||||
|
||||
setCookie(cookie: string): void {
|
||||
this.cookie = normalizeCookie(cookie);
|
||||
this.cookie = cookie;
|
||||
}
|
||||
|
||||
getCookie(): string {
|
||||
|
||||
@@ -1,85 +0,0 @@
|
||||
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("");
|
||||
});
|
||||
});
|
||||
@@ -1,91 +0,0 @@
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
+1
-4
@@ -15,7 +15,6 @@
|
||||
* 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";
|
||||
@@ -443,9 +442,7 @@ export class KugouProvider implements MusicProvider {
|
||||
// --- Cookie persistence (CookieStore stores a flat "k=v; k=v" string) ------
|
||||
setCookie(cookie: string): void {
|
||||
const map: CookieMap = {};
|
||||
// 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(";")) {
|
||||
for (const part of (cookie || "").split(";")) {
|
||||
const eq = part.indexOf("=");
|
||||
if (eq < 0) continue;
|
||||
const k = part.slice(0, eq).trim();
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { normalizeCookie } from "./cookie-normalize.js";
|
||||
import axios, { type AxiosInstance } from "axios";
|
||||
import type {
|
||||
MusicProvider,
|
||||
@@ -391,9 +390,7 @@ export class NeteaseProvider implements MusicProvider {
|
||||
}
|
||||
|
||||
setCookie(cookie: string): void {
|
||||
// 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);
|
||||
this.cookie = cookie;
|
||||
}
|
||||
|
||||
getCookie(): string {
|
||||
|
||||
+1
-4
@@ -1,4 +1,3 @@
|
||||
import { normalizeCookie } from "./cookie-normalize.js";
|
||||
import axios, { type AxiosInstance } from "axios";
|
||||
import type {
|
||||
MusicProvider,
|
||||
@@ -819,9 +818,7 @@ export class QQMusicProvider implements MusicProvider {
|
||||
}
|
||||
|
||||
setCookie(cookie: string): void {
|
||||
// Normalised: see music/cookie-normalize.ts for why a pasted Set-Cookie
|
||||
// line breaks every request.
|
||||
this.cookie = normalizeCookie(cookie);
|
||||
this.cookie = 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