diff --git a/README.md b/README.md index 6544b48..3fc703f 100644 --- a/README.md +++ b/README.md @@ -347,6 +347,14 @@ sudo systemctl start tsmusicbot 4. (可选)在 **设置 → Jellyfin 音乐库** 连接自建 Jellyfin 服务器并打开「启用 Jellyfin 音源」(安装向导第 3 步保存连接时会自动启用;详见 [可选:Jellyfin 音源](#可选jellyfin-音源)) 5. 在 **设置 → 用户管理**(仅管理员可见)按需添加成员。成员默认可控制播放但无法管理其他用户;管理员还可为每个成员单独配置**能力**(播放控制 / 队列 / 机器人管理 / 平台登录 / 音质)和**可操作的机器人白名单**,未授权的机器人对该成员不可见、不可控 +### QQ 音乐自动续期 + +QQ 音源启用时,`QQ_MUSIC_MANAGED_SESSION` 默认为 `1`。在 **设置 → 音乐账号 → QQ 音乐** 用手机 QQ 扫码授权一次后,机器人每 24 小时自动续期,遇到有效期更短的凭据会在到期前提前续期。凭据和上次成功续期时间保存在数据目录的 `cookies/qq-session.json`,重启后继续按原时间安排续期。 + +已有 `cookies/qq.json` 可继续播放,扫码授权后才会获得续期所需的凭据。手动导入 Cookie 会替换当前登录并取消该账号的自动续期。设置页会显示上次成功续期时间、下次续期时间、重试状态或重新扫码提示。具备平台登录权限的用户也可以调用 `POST /api/auth/qq/refresh` 手动尝试续期。 + +设置 `QQ_MUSIC_MANAGED_SESSION=0` 并重启可关闭自动续期。机器人继续使用当前的 QQ 播放 Cookie,并从 `cookies/qq.json` 兼容读取旧部署的 Cookie。 + ### WebUI 页面说明 | 页面 | 功能 | diff --git a/src/audio/player.test.ts b/src/audio/player.test.ts index 74531f3..9763c5d 100644 --- a/src/audio/player.test.ts +++ b/src/audio/player.test.ts @@ -50,6 +50,7 @@ describe("buildFfmpegArgs", () => { "https://szbdyd.com/audio.m4s", "https://stream.mcdn.szbdyd.com/audio.m4s", "https://xy219x131x72x38xy.mcdn.bilivideo.cn.szbdyd.com/audio.m4s", + "https://b-bacb4fc51cs41d5p0dxdau053w.edge.mountaintoys.cn/audio.m4s", "HTTPS://UPOS-SZ-MIRRORCOS.BILIVIDEO.COM:443/audio.m4s", "https://upos-sz-mirrorcos.bilivideo.com./audio.m4s", ])("uses Bilibili headers and input-side seeking for the actual CDN host in %s", (url) => { @@ -70,6 +71,8 @@ describe("buildFfmpegArgs", () => { "https://bilibili.com.evil.example/audio.m4s", "https://evilbilibili.com/audio.m4s", "https://szbdyd.com.evil.example/audio.m4s", + "https://mountaintoys.cn.evil.example/audio.m4s", + "https://evilmountaintoys.cn/audio.m4s", "https://evil.example/audio.m4s?redirect=https://upos-sz-mirrorcos.bilivideo.com/x", "https://bilibili.com@evil.example/audio.m4s", ])("does not trust Bilibili text outside an allowed hostname in %s", (url) => { diff --git a/src/audio/player.ts b/src/audio/player.ts index c7d29ba..748c542 100644 --- a/src/audio/player.ts +++ b/src/audio/player.ts @@ -98,7 +98,7 @@ export function buildFfmpegArgs(url: string, seekSeconds: number): string[] { } const isHttp = httpHostname !== null; const isBilibili = httpHostname !== null && - ["bilivideo.com", "bilivideo.cn", "bilibili.com", "szbdyd.com"].some( + ["bilivideo.com", "bilivideo.cn", "bilibili.com", "szbdyd.com", "mountaintoys.cn"].some( domain => httpHostname === domain || httpHostname.endsWith(`.${domain}`), ); diff --git a/src/bot/instance-recovery.test.ts b/src/bot/instance-recovery.test.ts index 6f57aec..b556b7d 100644 --- a/src/bot/instance-recovery.test.ts +++ b/src/bot/instance-recovery.test.ts @@ -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" })) }; diff --git a/src/bot/instance.test.ts b/src/bot/instance.test.ts index 685a1e7..184c5a6 100644 --- a/src/bot/instance.test.ts +++ b/src/bot/instance.test.ts @@ -1544,6 +1544,36 @@ describe("BotInstance live-queue persistence (#119)", () => { }); describe("BotInstance Bilibili multi-P resolution", () => { + it("passes the page from a TeamSpeak video link to the Bilibili provider", async () => { + const song = { + id: "BV1yxHQeYEuE?p=2", + name: "Video - P2", + artist: "Uploader", + album: "", + duration: 180, + coverUrl: "", + platform: "bilibili" as const, + }; + const provider = { platform: "bilibili", getSongDetail: vi.fn().mockResolvedValue(song) }; + const ctx = { + config: { commandPrefix: "!" }, + assertProviderEnabled: vi.fn(), + getProviderFor: vi.fn().mockReturnValue(provider), + }; + const args = "[URL]https://www.bilibili.com/video/BV1yxHQeYEuE/?p=2[/URL]"; + + const result = await (BotInstance.prototype as any).resolvePlayQuery.call(ctx, { + name: "play", + args, + rawArgs: [args], + flags: new Set(), + }); + + expect(ctx.getProviderFor).toHaveBeenCalledWith("bilibili"); + expect(provider.getSongDetail).toHaveBeenCalledWith("BV1yxHQeYEuE?p=2"); + expect(result.song).toEqual(song); + }); + it("resolves multi-P search result to P1 with accurate duration and name", async () => { const multiPSongDetail = { id: "BV1multiP?p=1", @@ -1780,6 +1810,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[] = []; diff --git a/src/bot/song-ref.test.ts b/src/bot/song-ref.test.ts index d6e23f9..64fb568 100644 --- a/src/bot/song-ref.test.ts +++ b/src/bot/song-ref.test.ts @@ -101,6 +101,34 @@ describe("parseSongRef (#90 exact-song selection)", () => { expect(parseSongRef("https://www.bilibili.com/video/BV1yxHQeYEuE")).toEqual({ id: "BV1yxHQeYEuE", platform: "bilibili" }); expect(parseSongRef("https://b23.tv/BV1yxHQeYEuE")).toEqual({ id: "BV1yxHQeYEuE", platform: "bilibili" }); }); + + it.each([ + "https://www.bilibili.com/video/BV1yxHQeYEuE?p=2", + "https://b23.tv/BV1yxHQeYEuE?p=2", + "https://www.bilibili.com/video/BV1yxHQeYEuE/?from=share&p=2&vd_source=test#reply", + "https://www.bilibili.com/video/BV1yxHQeYEuE/?from=share?p=3&p=2", + "https://www.bilibili.com/video/BV1yxHQeYEuE/?p=%32", + "[URL]https://www.bilibili.com/video/BV1yxHQeYEuE/?p=2[/URL]", + "[url]https://www.bilibili.com/video/BV1yxHQeYEuE/?p=2#reply[/url]", + "[URL=https://www.bilibili.com/video/BV1yxHQeYEuE/?p=2]点击播放[/URL]", + "参考 https://example.com/?p=9 视频 https://www.bilibili.com/video/BV1yxHQeYEuE/?p=2 请播放", + ])("preserves the Bilibili page query in %s", (input) => { + expect(parseSongRef(input)).toEqual({ id: "BV1yxHQeYEuE?p=2", platform: "bilibili" }); + }); + + it.each([ + "?p=2extra", + "?p=-2", + "?page=2", + "?sp=2", + "?from=share?p=2", + "?from=share%3Fp%3D2", + "?from=share#reply&p=2", + "#reply?p=2", + ])("ignores an invalid or unrelated Bilibili page query %s", (query) => { + expect(parseSongRef(`https://www.bilibili.com/video/BV1yxHQeYEuE${query}`)) + .toEqual({ id: "BV1yxHQeYEuE", platform: "bilibili" }); + }); }); describe("parseSelectionIndex (#90 pick from last search)", () => { diff --git a/src/bot/song-ref.ts b/src/bot/song-ref.ts index 6578067..ba1d1aa 100644 --- a/src/bot/song-ref.ts +++ b/src/bot/song-ref.ts @@ -69,7 +69,11 @@ export function parseSongRef(raw: string): SongRef | null { // a "BV..." token never collides with them). const bv = /BV[0-9A-Za-z]{8,12}/.exec(q); if (bv && (/^BV[0-9A-Za-z]{8,12}$/.test(q) || /bilibili\.com|b23\.tv/i.test(q))) { - return { id: bv[0], platform: "bilibili" }; + // Extract the query attached to this BV id, including in [URL=...] tags. + const suffix = q.slice(bv.index + bv[0].length); + const query = /^\/?\?([^#\s[\]]*)/.exec(suffix)?.[1]; + const page = new URLSearchParams(query).get("p"); + return { id: page && /^\d+$/.test(page) ? `${bv[0]}?p=${page}` : bv[0], platform: "bilibili" }; } // NetEase song URL. Only treat `id=N` as a SONG id when the URL is not a diff --git a/src/bot/voice-failure.test.ts b/src/bot/voice-failure.test.ts index a81bd9f..794ea8a 100644 --- a/src/bot/voice-failure.test.ts +++ b/src/bot/voice-failure.test.ts @@ -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(); } }); diff --git a/src/index.ts b/src/index.ts index d7d14d1..03bd050 100755 --- a/src/index.ts +++ b/src/index.ts @@ -6,6 +6,8 @@ import { createLogger } from "./logger.js"; import { createApiServerManager } from "./music/api-server.js"; import { NeteaseProvider } from "./music/netease.js"; import { QQMusicProvider } from "./music/qq.js"; +import { createQqLoginClient } from "./music/qq-login.js"; +import { createQqSessionStore, QQManagedSession } from "./music/qq-session.js"; import { BiliBiliProvider } from "./music/bilibili.js"; import { LocalMusicProvider } from "./music/local.js"; import { KugouProvider } from "./music/kugou.js"; @@ -66,7 +68,6 @@ async function main() { await apiServer.start(); const neteaseProvider = new NeteaseProvider(apiServer.getNeteaseBaseUrl()); - const qqProvider = new QQMusicProvider(apiServer.getQQMusicBaseUrl()); const bilibiliProvider = new BiliBiliProvider(); const localProvider = new LocalMusicProvider(LOCAL_AUDIO_DIR); const kugouProvider = new KugouProvider(); @@ -79,12 +80,23 @@ async function main() { spotifyProvider.setCreds(config.spotify.clientId, config.spotify.clientSecret); } - const cookieStore = createCookieStore(COOKIE_DIR); + const qqStore = createQqSessionStore(path.join(COOKIE_DIR, "qq-session.json"), path.join(COOKIE_DIR, "qq.json")); + const cookieStore = createCookieStore(COOKIE_DIR, qqStore); const avatarStore = createAvatarStore(AVATAR_DIR); const neteaseCookie = cookieStore.load("netease"); if (neteaseCookie) neteaseProvider.setCookie(neteaseCookie); - const qqCookie = cookieStore.load("qq"); - if (qqCookie) qqProvider.setCookie(qqCookie); + const qqSession = (process.env.QQ_MUSIC_MANAGED_SESSION ?? "1") === "1" && isProviderEnabled(config, "qq") + ? new QQManagedSession(createQqLoginClient(), qqStore, logger) + : undefined; + const qqProvider = new QQMusicProvider(apiServer.getQQMusicBaseUrl(), qqSession); + if (!qqSession) { + try { + const cookie = cookieStore.load("qq"); + if (cookie) qqProvider.setCookie(cookie); + } catch { + logger.warn("Could not read QQ session"); + } + } const bilibiliCookie = cookieStore.load("bilibili"); if (bilibiliCookie) bilibiliProvider.setCookie(bilibiliCookie); const kugouCookie = cookieStore.load("kugou"); @@ -175,6 +187,7 @@ async function main() { const shutdown = () => { logger.info("Shutting down..."); + qqSession?.stop(); botManager.shutdown(); webServer.stop(); apiServer.stop(); diff --git a/src/music/auth.test.ts b/src/music/auth.test.ts new file mode 100644 index 0000000..9f1c278 --- /dev/null +++ b/src/music/auth.test.ts @@ -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(""); + }); +}); diff --git a/src/music/auth.ts b/src/music/auth.ts index 8100c8b..83997c0 100644 --- a/src/music/auth.ts +++ b/src/music/auth.ts @@ -1,39 +1,77 @@ 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; } -export function createCookieStore(cookieDir: string): CookieStore { +export function createCookieStore(cookieDir: string, qqStore?: ReturnType): CookieStore { if (!fs.existsSync(cookieDir)) { 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 } - ); + if (platform === "qq" && qqStore) { + qqStore.save({ cookie }); + return; + } + 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; }, }; } diff --git a/src/music/bilibili.ts b/src/music/bilibili.ts index 0b2fed3..e77d542 100644 --- a/src/music/bilibili.ts +++ b/src/music/bilibili.ts @@ -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 { diff --git a/src/music/cookie-normalize.test.ts b/src/music/cookie-normalize.test.ts new file mode 100644 index 0000000..66a7bf8 --- /dev/null +++ b/src/music/cookie-normalize.test.ts @@ -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(""); + }); +}); diff --git a/src/music/cookie-normalize.ts b/src/music/cookie-normalize.ts new file mode 100644 index 0000000..f98b680 --- /dev/null +++ b/src/music/cookie-normalize.ts @@ -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(); + 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; +} diff --git a/src/music/kugou.ts b/src/music/kugou.ts index 4a68a26..52e3781 100644 --- a/src/music/kugou.ts +++ b/src/music/kugou.ts @@ -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(); diff --git a/src/music/netease.test.ts b/src/music/netease.test.ts index 0eb39f9..bd108bb 100644 --- a/src/music/netease.test.ts +++ b/src/music/netease.test.ts @@ -1,4 +1,8 @@ +import { once } from "node:events"; +import { createServer } from "node:http"; +import type { AddressInfo } from "node:net"; import { describe, it, expect, vi } from "vitest"; +import { normalizeCookie } from "./cookie-normalize.js"; import { RiskControlError, SongUrlUnavailable } from "./provider.js"; import { parseLyrics, @@ -9,6 +13,64 @@ import { NeteaseProvider, } from "./netease.js"; +describe("NeteaseProvider playback user agent", () => { + it("matches the playback UA to each account's platform without changing cookies or other requests", async () => { + const requests: URL[] = []; + const server = createServer((req, res) => { + requests.push(new URL(req.url!, "http://localhost")); + res.setHeader("Content-Type", "application/json"); + res.end(JSON.stringify({ code: 200, data: [{ url: "https://example.com/song.mp3" }] })); + }); + server.listen(0, "127.0.0.1"); + await once(server, "listening"); + try { + const provider = new NeteaseProvider( + `http://127.0.0.1:${(server.address() as AddressInfo).port}`, + ); + const cases = [ + ["", "NeteaseMusicDesktop"], + ["MUSIC_U=shared", "NeteaseMusicDesktop"], + ["MUSIC_U=shared; os=pc", "NeteaseMusicDesktop"], + ["MUSIC_U=shared; os=android", "Android"], + ["MUSIC_U=shared; os=android; os=iphone", "iPhone"], + ["MUSIC_U=shared; os=iphone", "iPhone"], + ["MUSIC_U=shared; os=linux", "Linux"], + ["MUSIC_U=shared; os=unknown", "NeteaseMusicDesktop"], + ["MUSIC_U=shared; os=%69phone", "iPhone"], + ["MUSIC_U=shared; os=%invalid", "NeteaseMusicDesktop"], + ]; + for (const [cookie, uaFamily] of cases) { + provider.setCookie(cookie); + expect(await provider.getSongUrl("1", "standard")).toMatchObject({ url: "https://example.com/song.mp3" }); + const params = requests.at(-1)!.searchParams; + expect(params.get("ua")).toContain(uaFamily); + expect(params.get("level")).toBe("standard"); + const normalized = normalizeCookie(cookie); + expect(params.get("cookie")).toBe(normalized || null); + expect(provider.getCookie()).toBe(normalized); + } + + provider.setCookie("MUSIC_U=shared; os=pc"); + const personal = provider.withCookie("MUSIC_U=personal; os=android"); + await personal.getSongUrl("2"); + expect(requests.at(-1)!.searchParams.get("ua")).toContain("Android"); + expect(requests.at(-1)!.searchParams.get("cookie")).toBe("MUSIC_U=personal; os=android"); + await provider.getSongUrl("3"); + expect(requests.at(-1)!.searchParams.get("ua")).toContain("NeteaseMusicDesktop"); + expect(provider.getCookie()).toBe("MUSIC_U=shared; os=pc"); + + requests.length = 0; + await provider.search("hello"); + await provider.getQrCode(); + expect(requests).toHaveLength(6); + expect(requests.every((url) => !url.searchParams.has("ua"))).toBe(true); + } finally { + server.closeAllConnections(); + await new Promise((resolve, reject) => server.close((err) => err ? reject(err) : resolve())); + } + }); +}); + describe("NetEase adapter", () => { it("parses LRC format lyrics", () => { const lrc = `[00:00.00] 作词 : 周杰伦 diff --git a/src/music/netease.ts b/src/music/netease.ts index 1e8a3ad..5741d02 100644 --- a/src/music/netease.ts +++ b/src/music/netease.ts @@ -1,3 +1,4 @@ +import { normalizeCookie } from "./cookie-normalize.js"; import axios, { type AxiosInstance } from "axios"; import { RISK_CONTROL_CODE, RiskControlError, SongUrlUnavailable } from "./provider.js"; import type { PlayFailure } from "./provider.js"; @@ -204,6 +205,29 @@ export const NETEASE_QUALITY_LEVELS = [ { value: "jymaster", label: "超清母带", bitrate: 4000 }, ] as const; +function getPlaybackUserAgent(cookie: string): string { + let decoded = cookie; + try { + decoded = decodeURIComponent(cookie); + } catch { + // A malformed cookie escape must not prevent a playback request. + } + // The sidecar's cookie parser keeps the last value of a repeated key. + const platform = [...decoded.matchAll(/(?:^|;)\s*os\s*=\s*([^;=]*)(?=;|$)/g)].at(-1)?.[1].trim(); + // NCM API 4.32.0 defaults cookie profiles to PC but eapi's UA to iPhone. + // Match its client profiles here, and scope the override to playback only. + switch (platform) { + case "android": + return "NeteaseMusic/9.1.65.240927161425(9001065);Dalvik/2.1.0 (Linux; U; Android 14; 23013RK75C Build/UKQ1.230804.001)"; + case "iphone": + return "NeteaseMusic 9.0.90/5038 (iPhone; iOS 16.2; zh_CN)"; + case "linux": + return "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36"; + default: + return "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Safari/537.36 Chrome/91.0.4472.164 NeteaseMusicDesktop/3.0.18.203152"; + } +} + export class NeteaseProvider implements MusicProvider { readonly platform = "netease" as const; private api: AxiosInstance; @@ -280,7 +304,7 @@ export class NeteaseProvider implements MusicProvider { let res; try { res = await this.api.get("/song/url/v1", { - params: { id: songId, level, ...this.cookieParams }, + params: { id: songId, level, ua: getPlaybackUserAgent(this.cookie), ...this.cookieParams }, }); } catch (err) { // -460 arrives as HTTP 400, and left as-is it looks like "this track is @@ -503,7 +527,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 { diff --git a/src/music/qq-login.test.ts b/src/music/qq-login.test.ts new file mode 100644 index 0000000..67e3647 --- /dev/null +++ b/src/music/qq-login.test.ts @@ -0,0 +1,123 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const { get, post } = vi.hoisted(() => ({ get: vi.fn(), post: vi.fn() })); +vi.mock("axios", () => ({ default: { create: () => ({ get, post }), isAxiosError: () => false } })); + +import { createQqLoginClient, parseQqCredential } from "./qq-login.js"; + +const credential = { + musicid: 12345, musickey: "test-music-key", openid: "test-openid", access_token: "test-access", + refresh_token: "test-token", refresh_key: "test-refresh", expired_at: 1234, + musickeyCreateTime: 5678, keyExpiresIn: 3600, +}; + +describe("QQ login transport", () => { + beforeEach(() => { + vi.resetAllMocks(); + }); + + it("accepts the QQ QR image when Tencent omits its content type", async () => { + get.mockResolvedValueOnce({ + data: Buffer.from("89504e470d0a1a0a", "hex"), + headers: { "set-cookie": ["qrsig=test-sig; Path=/"] }, + }); + expect(await createQqLoginClient().getQr()).toMatchObject({ + img: "data:image/png;base64,iVBORw0KGgo=", sig: "test-sig", + }); + }); + + it("exchanges a confirmed QR for the full JSON credential", async () => { + get + .mockResolvedValueOnce({ + data: "ptuiCB('0','0','https://ssl.ptlogin2.graph.qq.com/check_sig?uin=12345&ptsigx=sigx','0','','');", + }) + .mockResolvedValueOnce({ headers: { "set-cookie": ["p_skey=test==; Path=/; Secure"] } }); + post + .mockResolvedValueOnce({ headers: { location: "https://y.qq.com/portal/wx_redirect.html?code=example&state=state" } }) + .mockResolvedValueOnce({ + headers: {}, + data: { code: 0, req_0: { code: 0, data: { ...credential, loginType: 2 } } }, + }); + expect(await createQqLoginClient().pollQr("test-sig")).toEqual({ status: "confirmed", credential }); + expect(post).toHaveBeenNthCalledWith( + 1, "https://graph.qq.com/oauth2.0/authorize", expect.any(URLSearchParams), + expect.objectContaining({ headers: { Cookie: "p_skey=test==" } }), + ); + expect(post).toHaveBeenNthCalledWith( + 2, "https://u.y.qq.com/cgi-bin/musicu.fcg", + expect.objectContaining({ + req_0: { module: "QQConnectLogin.LoginServer", method: "QQLogin", param: { code: "example" } }, + }), + expect.anything(), + ); + }); + + it("sends the login type 2 refresh payload and validates the CGI status", async () => { + post.mockResolvedValue({ + headers: {}, + data: { code: 0, req_0: { code: 104604, data: { ...credential, musickey: "do-not-use" } } }, + }); + expect(await createQqLoginClient().refresh(credential)).toEqual({ status: "rate_limited" }); + expect(post).toHaveBeenCalledWith( + "https://u.y.qq.com/cgi-bin/musicu.fcg", + expect.objectContaining({ + comm: expect.objectContaining({ tmeLoginType: "2" }), + req_0: { + module: "music.login.LoginServer", method: "Login", + param: { + loginMode: 2, musicid: 12345, musickey: "test-music-key", openid: "test-openid", + access_token: "test-access", refresh_token: "test-token", refresh_key: "test-refresh", expired_in: 1234, + }, + }, + }), + expect.anything(), + ); + post.mockResolvedValueOnce({ headers: {}, data: { code: 104401 } }); + expect(await createQqLoginClient().refresh(credential)).toEqual({ status: "reauth_required" }); + post.mockResolvedValueOnce({ headers: {}, data: { code: 0, req_0: { code: 0, data: { musicid: 12345 } } } }); + expect(await createQqLoginClient().refresh(credential)).toEqual({ status: "upstream_error" }); + }); + + it("accepts playback-only QQ credentials and rejects other types or invalid keys", () => { + expect(parseQqCredential({ str_musicid: "12345", musickey: "music-key" })).toMatchObject({ + musicid: 12345, musickey: "music-key", refresh_key: "", + }); + expect(parseQqCredential({ ...credential, loginType: 1 })).toBeUndefined(); + expect(parseQqCredential({ ...credential, musickey: "music-key\r\n" })).toBeUndefined(); + }); + + it("keeps unchanged OAuth fields when QQ returns a partial rotation for the same account", async () => { + post.mockResolvedValueOnce({ + headers: {}, + data: { code: 0, req_0: { code: 0, data: { + musicid: 12345, musickey: "rotated-key", refresh_token: "rotated-token", + } } }, + }); + expect(await createQqLoginClient().refresh(credential)).toMatchObject({ + status: "refreshed", + credential: { + musicid: 12345, musickey: "rotated-key", refresh_token: "rotated-token", + openid: credential.openid, access_token: credential.access_token, + musickeyCreateTime: 0, keyExpiresIn: 0, + }, + }); + }); + + it("fills missing expiration fields only for the same account and playback key", async () => { + const sameKey = { musicid: credential.musicid, musickey: credential.musickey, refresh_token: "rotated-token" }; + post.mockResolvedValueOnce({ + headers: {}, + data: { code: 0, req_0: { code: 0, data: sameKey } }, + }); + expect(await createQqLoginClient().refresh(credential)).toMatchObject({ + status: "refreshed", + credential: { refresh_token: "rotated-token", musickeyCreateTime: 5678, keyExpiresIn: 3600 }, + }); + expect(parseQqCredential({ ...sameKey, keyExpiresIn: 7200 }, credential)).toMatchObject({ + musickeyCreateTime: 5678, keyExpiresIn: 7200, + }); + expect(parseQqCredential({ ...sameKey, musicid: 999 }, credential)).toMatchObject({ + musickeyCreateTime: 0, keyExpiresIn: 0, + }); + }); +}); diff --git a/src/music/qq-login.ts b/src/music/qq-login.ts new file mode 100644 index 0000000..fa1f04b --- /dev/null +++ b/src/music/qq-login.ts @@ -0,0 +1,229 @@ +import axios from "axios"; +import { randomUUID } from "node:crypto"; + +export interface QqCredential { + musicid: number; + musickey: string; + openid: string; + access_token: string; + refresh_token: string; + refresh_key: string; + expired_at: number; + musickeyCreateTime: number; + keyExpiresIn: number; +} + +export type QqPollResult = + | { status: "waiting" | "scanned" | "expired" } + | { status: "confirmed"; credential: QqCredential }; + +export type QqRefreshResult = + | { status: "refreshed"; credential: QqCredential } + | { status: "reauth_required" | "rate_limited" | "upstream_error" }; + +export interface QqLoginClient { + getQr(): Promise<{ img: string; sig: string }>; + pollQr(sig: string): Promise; + refresh(credential: QqCredential): Promise; +} + +const QR_HOST = "https://ssl.ptlogin2.qq.com"; +const REFERER = "https://xui.ptlogin2.qq.com/"; +const QQ_JUMP = "https://graph.qq.com/oauth2.0/login_jump"; +const MUSIC_REDIRECT = "https://y.qq.com/portal/wx_redirect.html"; +const APP_ID = "100497308"; +const LOGIN_SCOPE = { daid: "383", pt_3rd_aid: APP_ID }; +const AUTH_REJECTED = new Set([1000, 104400, 104401, 20261, 20272, 20274, 20277, 20278, 20279, 20450]); + +function record(value: unknown): Record { + return value && typeof value === "object" && !Array.isArray(value) + ? value as Record : {}; +} + +function token(value: unknown): string { + return typeof value === "string" && /^[\x21-\x3a\x3c-\x7e]+$/.test(value) ? value : ""; +} + +function positiveInt(value: unknown): number { + const n = typeof value === "string" && /^\d+$/.test(value) ? Number(value) : value; + return typeof n === "number" && Number.isSafeInteger(n) && n > 0 ? n : 0; +} + +export function parseQqCredential(value: unknown, previous?: QqCredential): QqCredential | undefined { + const data = record(value); + const type = data.loginType ?? data.login_type; + if (type !== undefined && type !== 2 && type !== "2") return; + const musicid = positiveInt(data.musicid) || positiveInt(data.str_musicid); + const musickey = token(data.musickey); + if (!musicid || !musickey) return; + const sameAccount = previous?.musicid === musicid ? previous : undefined; + const sameKey = sameAccount?.musickey === musickey ? sameAccount : undefined; + return { + musicid, + musickey, + openid: token(data.openid ?? sameAccount?.openid), + access_token: token(data.access_token ?? sameAccount?.access_token), + refresh_token: token(data.refresh_token ?? sameAccount?.refresh_token), + refresh_key: token(data.refresh_key), + expired_at: positiveInt(data.expired_at ?? sameAccount?.expired_at), + musickeyCreateTime: positiveInt(data.musickeyCreateTime ?? sameKey?.musickeyCreateTime), + keyExpiresIn: positiveInt(data.keyExpiresIn ?? sameKey?.keyExpiresIn), + }; +} + +export function hasQqRenewalMaterial(credential?: QqCredential): credential is QqCredential { + // QQ's web QR flow may return OAuth tokens without a separate refresh key. + return Boolean(credential?.refresh_key || (credential?.openid && credential.access_token && credential.refresh_token)); +} + +export function qqPlaybackCookie({ musicid, musickey }: QqCredential): string { + return `uin=${musicid}; qqmusic_uin=${musicid}; qm_keyst=${musickey}; qqmusic_key=${musickey}; login_type=2; tmeLoginType=2`; +} + +function hash33(value: string, seed: number): number { + let hash = seed; + for (let i = 0; i < value.length; i++) hash = (hash * 33 + value.charCodeAt(i)) | 0; + return hash & 0x7fffffff; +} + +function setCookies(headers: string[] = []): Map { + const cookies = new Map(); + for (const header of headers) { + const pair = header.split(";", 1)[0]; + const equals = pair.indexOf("="); + if (equals < 1) continue; + const value = token(pair.slice(equals + 1)); + if (value) cookies.set(pair.slice(0, equals), value); + } + return cookies; +} + +function cookieHeader(cookies: Map): string { + return Array.from(cookies, ([key, value]) => `${key}=${value}`).join("; "); +} + +export function createQqLoginClient(): QqLoginClient { + const http = axios.create({ timeout: 10_000, maxRedirects: 0 }); + + // QQMusicApi's web CGI profile. Keep authorization fields in the HTTPS body. + async function musicu(module: string, method: string, param: object, credential?: QqCredential) { + const gTk = String(hash33(credential?.musickey ?? "", 5381)); + const res = await http.post("https://u.y.qq.com/cgi-bin/musicu.fcg", { + comm: { + ct: "24", cv: "4747474", platform: "yqq.json", chid: "0", + uin: String(credential?.musicid ?? 0), g_tk: gTk, g_tk_new_20200303: gTk, + format: "json", inCharset: "utf-8", outCharset: "utf-8", notice: "0", + need_new_code: "1", tmeLoginType: "2", + }, + req_0: { module, method, param }, + }, { headers: { Referer: "https://y.qq.com/" } }); + const body = record(res.data); + const item = record(body.req_0); + return { code: body.code === 0 ? item.code : body.code, data: item.data, cookies: setCookies(res.headers["set-cookie"]) }; + } + + async function authorize(redirect: string): Promise { + const url = new URL(redirect); + const uin = url.searchParams.get("uin"); + const sigx = url.searchParams.get("ptsigx"); + if (!uin || !/^\d+$/.test(uin) || !sigx) return; + const noFollow = (status: number) => status >= 200 && status < 400; + const checked = await http.get("https://ssl.ptlogin2.graph.qq.com/check_sig", { + params: { + ...LOGIN_SCOPE, uin, ptsigx: sigx, pttype: "1", service: "ptqrlogin", + nodirect: "0", s_url: QQ_JUMP, ptlang: "2052", ptredirect: "100", + aid: "716027609", j_later: "0", low_login_hour: "0", regmaster: "0", + pt_login_type: "3", pt_aid: "0", pt_aaid: "16", pt_light: "0", + }, + headers: { Referer: REFERER }, + validateStatus: noFollow, + }); + const cookies = setCookies(checked.headers["set-cookie"]); + const pSkey = cookies.get("p_skey"); + if (!pSkey) return; + + const authorized = await http.post("https://graph.qq.com/oauth2.0/authorize", new URLSearchParams({ + response_type: "code", client_id: APP_ID, redirect_uri: `${MUSIC_REDIRECT}?login_type=1&surl=https://y.qq.com/`, + scope: "get_user_info,get_app_friends", state: "state", switch: "", + from_ptlogin: "1", src: "1", update_auth: "1", openapi: "1010_1030", + g_tk: String(hash33(pSkey, 5381)), auth_time: String(Date.now()), ui: randomUUID(), + }), { headers: { Cookie: cookieHeader(cookies) }, validateStatus: noFollow }); + if (typeof authorized.headers.location !== "string") return; + const callback = new URL(authorized.headers.location); + if (callback.origin + callback.pathname !== MUSIC_REDIRECT) return; + const code = callback.searchParams.get("code"); + if (!code) return; + + const result = await musicu("QQConnectLogin.LoginServer", "QQLogin", { code }); + if (result.code !== 0) return; + return parseQqCredential(result.data) ?? parseQqCredential({ + musicid: result.cookies.get("qqmusic_uin") ?? uin, + musickey: result.cookies.get("qqmusic_key") ?? result.cookies.get("qm_keyst"), + }); + } + + return { + async getQr() { + try { + const res = await http.get(`${QR_HOST}/ptqrshow`, { + params: { ...LOGIN_SCOPE, appid: "716027609", e: "2", l: "M", s: "3", d: "72", v: "4", t: Math.random() }, + headers: { Referer: REFERER }, + responseType: "arraybuffer", + }); + const sig = setCookies(res.headers["set-cookie"]).get("qrsig"); + // Tencent can send the PNG without a Content-Type header. + const bytes = Buffer.from(res.data); + const isPng = bytes.subarray(0, 8).toString("hex") === "89504e470d0a1a0a"; + const isJpeg = bytes.subarray(0, 3).toString("hex") === "ffd8ff"; + if (sig && (isPng || isJpeg)) { + return { img: `data:image/${isPng ? "png" : "jpeg"};base64,${bytes.toString("base64")}`, sig }; + } + } catch { /* Do not expose the request or response. */ } + throw new Error("QQ QR code unavailable"); + }, + async pollQr(sig) { + let response: string; + try { + const res = await http.get(`${QR_HOST}/ptqrlogin`, { + params: { + ...LOGIN_SCOPE, u1: QQ_JUMP, ptqrtoken: hash33(sig, 0), ptredirect: "0", + h: "1", t: "1", g: "1", from_ui: "1", ptlang: "2052", + action: `0-0-${Date.now()}`, js_ver: "20102616", js_type: "1", + pt_uistyle: "40", aid: "716027609", has_onekey: "1", + }, + headers: { Referer: REFERER, Cookie: `qrsig=${sig}` }, + responseType: "text", + }); + response = res.data; + } catch { return { status: "waiting" }; } + + const fields = /^\s*ptuiCB\((.*)\)/.exec(response)?.[1].match(/'((?:\\.|[^'])*)'/g); + const code = fields?.[0]?.slice(1, -1); + if (code === "66") return { status: "waiting" }; + if (code === "67") return { status: "scanned" }; + if (code === "0" && fields?.[2]) { + try { + const credential = await authorize(fields[2].slice(1, -1)); + if (credential) return { status: "confirmed", credential }; + } catch { /* A used QR cannot safely replay the authorization code. */ } + } + return { status: "expired" }; + }, + async refresh(credential) { + const { openid, access_token, refresh_token, expired_at, musicid, musickey, refresh_key } = credential; + try { + const result = await musicu("music.login.LoginServer", "Login", { + openid, access_token, refresh_token, expired_in: expired_at, musicid, musickey, refresh_key, loginMode: 2, + }, credential); + const code = Number(result.code); + if (code === 104604 || code === 2001) return { status: "rate_limited" }; + if (AUTH_REJECTED.has(code)) return { status: "reauth_required" }; + const next = result.code === 0 ? parseQqCredential(result.data, credential) : undefined; + if (next) return { status: "refreshed", credential: next }; + } catch (err) { + if (axios.isAxiosError(err) && err.response?.status === 429) return { status: "rate_limited" }; + } + return { status: "upstream_error" }; + }, + }; +} diff --git a/src/music/qq-session.test.ts b/src/music/qq-session.test.ts new file mode 100644 index 0000000..1ede6d4 --- /dev/null +++ b/src/music/qq-session.test.ts @@ -0,0 +1,283 @@ +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import pino from "pino"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { createCookieStore } from "./auth.js"; +import { parseQqCredential, qqPlaybackCookie, type QqCredential, type QqLoginClient, type QqRefreshResult } from "./qq-login.js"; +import { createQqSessionStore, QQManagedSession } from "./qq-session.js"; + +const NOW = new Date("2026-11-09T00:00:00.000Z"); +const MINUTE = 60_000; +const DAY = 24 * 60 * MINUTE; +const first: QqCredential = { + musicid: 123456, musickey: "first-key", refresh_key: "first-refresh", + openid: "test-openid", access_token: "test-access", refresh_token: "test-refresh", + expired_at: 123, musickeyCreateTime: NOW.valueOf() / 1000, keyExpiresIn: 3 * DAY / 1000, +}; +const second = { ...first, musickey: "second-key", refresh_key: "second-refresh" }; + +describe("managed QQ session", () => { + let dir: string; + let file: string; + let store: ReturnType; + let client: QqLoginClient; + let session: QQManagedSession; + const logger = pino({ level: "silent" }); + + beforeEach(() => { + vi.useFakeTimers(); + vi.setSystemTime(NOW); + dir = fs.mkdtempSync(path.join(os.tmpdir(), "tsbot-qq-")); + file = path.join(dir, "qq-session.json"); + store = createQqSessionStore(file); + client = { + getQr: vi.fn().mockResolvedValue({ img: "test-image", sig: "private-qr-sig" }), + pollQr: vi.fn().mockResolvedValue({ status: "confirmed", credential: first }), + refresh: vi.fn().mockResolvedValue({ status: "refreshed", credential: second }), + }; + session = new QQManagedSession(client, store, logger); + }); + + afterEach(() => { + session.stop(); + vi.useRealTimers(); + fs.rmSync(file, { force: true }); + fs.rmSync(path.join(dir, "qq.json"), { force: true }); + fs.rmdirSync(dir); + }); + + async function scan() { + const qr = await session.getQrCode(); + expect(qr.key).not.toContain("private-qr-sig"); + expect(await Promise.all([ + session.checkQrCodeStatus(qr.key), + session.checkQrCodeStatus(qr.key), + ])).toEqual(["confirmed", "confirmed"]); + expect(client.pollQr).toHaveBeenCalledTimes(1); + } + + it("persists the scan, refreshes after 24 hours and keeps the next due date across restarts", async () => { + await scan(); + expect(store.load()?.credential).toEqual(first); + if (process.platform !== "win32") expect(fs.statSync(file).mode & 0o777).toBe(0o600); + expect(session.getStatus()).toEqual({ + renewalStatus: "scheduled", + nextRefreshAt: new Date(NOW.valueOf() + DAY).toISOString(), + lastRefreshAt: null, + }); + await vi.advanceTimersByTimeAsync(DAY / 2); + session.stop(); + session = new QQManagedSession(client, store, logger); + await vi.advanceTimersByTimeAsync(DAY / 2 - 1); + expect(client.refresh).not.toHaveBeenCalled(); + await vi.advanceTimersByTimeAsync(1); + expect(client.refresh).toHaveBeenCalledWith(first); + expect(store.load()?.credential).toEqual(second); + expect(session.getCookie()).toContain("qm_keyst=second-key"); + expect(store.load()?.lastRefreshAt).toBe(NOW.valueOf() + DAY); + + await vi.advanceTimersByTimeAsync(DAY / 2); + session.stop(); + session = new QQManagedSession(client, store, logger); + expect(session.getStatus()).toEqual({ + renewalStatus: "scheduled", + nextRefreshAt: new Date(NOW.valueOf() + 2 * DAY).toISOString(), + lastRefreshAt: new Date(NOW.valueOf() + DAY).toISOString(), + }); + }); + + it("renews before expiry when a QQ key lasts less than one day", async () => { + const shortLived = { ...first, keyExpiresIn: 3600 }; + vi.mocked(client.pollQr).mockResolvedValueOnce({ status: "confirmed", credential: shortLived }); + await scan(); + await vi.advanceTimersByTimeAsync(54 * MINUTE - 1); + expect(client.refresh).not.toHaveBeenCalled(); + await vi.advanceTimersByTimeAsync(1); + expect(client.refresh).toHaveBeenCalledWith(shortLived); + }); + + it("keeps scheduling before expiry after a same-key token rotation", async () => { + const shortLived = { ...first, keyExpiresIn: 3600 }; + vi.mocked(client.pollQr).mockResolvedValueOnce({ status: "confirmed", credential: shortLived }); + await scan(); + vi.setSystemTime(NOW.valueOf() + 54 * MINUTE); + const rotated = parseQqCredential({ + musicid: first.musicid, musickey: first.musickey, refresh_token: "rotated-token", + }, shortLived)!; + vi.mocked(client.refresh).mockResolvedValueOnce({ status: "refreshed", credential: rotated }); + + expect(await session.refresh()).toBe("refreshed"); + expect(store.load()?.credential?.refresh_token).toBe("rotated-token"); + expect(session.getStatus().nextRefreshAt).toBe(new Date(NOW.valueOf() + 55 * MINUTE).toISOString()); + }); + + it("schedules older saved sessions using QQ's issue time without inventing a last renewal", () => { + const older = { ...first, musickeyCreateTime: (NOW.valueOf() - DAY / 2) / 1000 }; + store.save({ cookie: qqPlaybackCookie(older), credential: older }); + session.stop(); + session = new QQManagedSession(client, store, logger); + expect(session.getStatus()).toEqual({ + renewalStatus: "scheduled", + nextRefreshAt: new Date(NOW.valueOf() + DAY / 2).toISOString(), + lastRefreshAt: null, + }); + }); + + it("shares an in-flight refresh and uses the rotated credential after restart", async () => { + await scan(); + const a = session.refresh(); + expect(session.refresh()).toBe(a); + expect(await a).toBe("refreshed"); + expect(client.refresh).toHaveBeenCalledTimes(1); + session.stop(); + session = new QQManagedSession(client, store, logger); + vi.mocked(client.refresh).mockResolvedValueOnce({ + status: "refreshed", credential: { ...second, musickey: "third-key" }, + }); + expect(await session.refresh()).toBe("refreshed"); + expect(client.refresh).toHaveBeenLastCalledWith(second); + expect(session.getCookie()).toContain("qm_keyst=third-key"); + }); + + it("refreshes a web login with OAuth authorization even when QQ omits refresh_key", async () => { + const webCredential = { ...first, refresh_key: "" }; + vi.mocked(client.pollQr).mockResolvedValueOnce({ status: "confirmed", credential: webCredential }); + await scan(); + expect(session.getStatus().renewalStatus).toBe("scheduled"); + expect(await session.refresh()).toBe("refreshed"); + expect(client.refresh).toHaveBeenCalledWith(webCredential); + }); + + it("keeps the current cookie on rate limiting and retries after the backoff", async () => { + await scan(); + vi.mocked(client.refresh).mockResolvedValueOnce({ status: "rate_limited" }); + expect(await session.refresh()).toBe("rate_limited"); + expect(session.getStatus()).toMatchObject({ renewalStatus: "retrying" }); + expect(await session.refresh()).toBe("cooldown"); + expect(store.load()?.credential).toEqual(first); + await vi.advanceTimersByTimeAsync(15 * MINUTE); + expect(client.refresh).toHaveBeenCalledTimes(2); + expect(store.load()?.credential).toEqual(second); + }); + + it("retries only the disk write when QQ has already rotated the credential", async () => { + await scan(); + vi.spyOn(store, "save").mockImplementationOnce(() => { throw new Error("test write failed"); }); + expect(await session.refresh()).toBe("persist_failed"); + expect(session.getCookie()).toContain("qm_keyst=first-key"); + expect(session.getStatus().lastRefreshAt).toBeNull(); + await vi.advanceTimersByTimeAsync(5 * MINUTE); + expect(client.refresh).toHaveBeenCalledTimes(1); + expect(store.load()?.credential).toEqual(second); + expect(session.getCookie()).toContain("qm_keyst=second-key"); + expect(session.getStatus().lastRefreshAt).toBe(new Date(NOW.valueOf() + 5 * MINUTE).toISOString()); + }); + + it("discards a late response when an operator imports another account", async () => { + await scan(); + let resolve!: (response: QqRefreshResult) => void; + vi.mocked(client.refresh).mockImplementationOnce(() => new Promise((done) => { resolve = done; })); + const refresh = session.refresh(); + session.setCookie("uin=999; qm_keyst=manual"); + resolve({ status: "refreshed", credential: second }); + expect(await refresh).toBe("superseded"); + expect(store.load()).toMatchObject({ cookie: "uin=999; qm_keyst=manual" }); + expect(store.load()?.credential).toBeUndefined(); + expect(await session.refresh()).toBe("reauth_required"); + }); + + it("does not accept another account from the upstream refresh endpoint", async () => { + await scan(); + vi.mocked(client.refresh).mockResolvedValueOnce({ + status: "refreshed", credential: { ...second, musicid: 999 }, + }); + expect(await session.refresh()).toBe("upstream_error"); + expect(store.load()?.credential).toEqual(first); + }); + + it("persists a suspension when QQ explicitly rejects renewal", async () => { + await scan(); + vi.mocked(client.refresh).mockResolvedValueOnce({ status: "reauth_required" }); + expect(await session.refresh()).toBe("reauth_required"); + session.stop(); + session = new QQManagedSession(client, store, logger); + expect(session.getStatus()).toEqual({ renewalStatus: "reauth_required", nextRefreshAt: null, lastRefreshAt: null }); + expect(await session.refresh()).toBe("reauth_required"); + expect(client.refresh).toHaveBeenCalledTimes(1); + expect(session.getCookie()).toContain("qm_keyst=first-key"); + }); + + it("preserves a legacy cookie and renews daily even when QQ omits the key expiration", async () => { + createCookieStore(dir).save("qq", "uin=123; qm_keyst=legacy"); + session.stop(); + store = createQqSessionStore(file, path.join(dir, "qq.json")); + session = new QQManagedSession(client, store, logger); + expect(session.getCookie()).toContain("qm_keyst=legacy"); + expect(session.getStatus()).toEqual({ renewalStatus: "cookie_only", nextRefreshAt: null, lastRefreshAt: null }); + expect(fs.existsSync(file)).toBe(false); + vi.mocked(client.pollQr).mockResolvedValueOnce({ + status: "confirmed", credential: { ...first, musickeyCreateTime: 0, keyExpiresIn: 0 }, + }); + await scan(); + expect(session.getStatus()).toMatchObject({ + renewalStatus: "scheduled", + nextRefreshAt: new Date(NOW.valueOf() + DAY).toISOString(), + }); + await vi.advanceTimersByTimeAsync(DAY); + expect(client.refresh).toHaveBeenCalledTimes(1); + }); + + it("shares the current login across managed and unmanaged restarts", async () => { + const legacyFile = path.join(dir, "qq.json"); + store = createQqSessionStore(file, legacyFile); + session.stop(); + session = new QQManagedSession(client, store, logger); + await scan(); + session.stop(); + + const cookies = createCookieStore(dir, store); + expect(cookies.load("qq")).toBe(qqPlaybackCookie(first)); + cookies.save("qq", "uin=999; qm_keyst=imported"); + session = new QQManagedSession(client, createQqSessionStore(file, legacyFile), logger); + expect(session.getCookie()).toBe("uin=999; qm_keyst=imported"); + expect(await session.refresh()).toBe("reauth_required"); + 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"; + fs.writeFileSync(file, JSON.stringify({ version: 1, cookie: qqPlaybackCookie(first), credential: first })); + createCookieStore(dir).save("qq", legacyCookie); + fs.utimesSync(file, 1, 1); + fs.utimesSync(legacyFile, 2, 2); + store = createQqSessionStore(file, legacyFile); + expect(store.load()).toEqual({ cookie: legacyCookie }); + + fs.utimesSync(file, 3, 3); + expect(store.load()?.credential).toEqual(first); + + store.save({ cookie: "uin=42; qm_keyst=shared" }); + fs.utimesSync(file, 1, 1); + expect(store.load()?.cookie).toBe("uin=42; qm_keyst=shared"); + }); +}); diff --git a/src/music/qq-session.ts b/src/music/qq-session.ts new file mode 100644 index 0000000..aed9bc7 --- /dev/null +++ b/src/music/qq-session.ts @@ -0,0 +1,294 @@ +import fs from "node:fs"; +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 { + cookie: string; + credential?: QqCredential; + reauthRequired?: boolean; + authorizedAt?: number; + lastRefreshAt?: number; +} + +type QrStatus = QqPollResult["status"]; +export type QqRenewalStatus = "cookie_only" | "scheduled" | "retrying" | "reauth_required"; +export type QqRenewalResult = "refreshed" | "reauth_required" | "upstream_error" | "rate_limited" | "persist_failed" | "cooldown" | "superseded"; + +const MINUTE = 60_000; +const DAY = 24 * 60 * MINUTE; +const QR_TTL = 3 * MINUTE; + +function timestamp(value: unknown): number | undefined { + return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 && value <= 8.64e15 + ? value : undefined; +} + +function expiryTime(credential: QqCredential): number | undefined { + if (!credential.musickeyCreateTime || !credential.keyExpiresIn) return; + return timestamp((credential.musickeyCreateTime + credential.keyExpiresIn) * 1000); +} + +export function createQqSessionStore(file: string, legacyFile?: string) { + function loadLegacy(newerThan = -Infinity): QqSessionRecord | undefined { + if (!legacyFile) return; + try { + if (fs.statSync(legacyFile).mtimeMs <= newerThan) return; + const { cookie } = JSON.parse(fs.readFileSync(legacyFile, "utf8")); + const clean = typeof cookie === "string" ? normalizeCookie(cookie) : ""; + if (clean) return { cookie: clean }; + } catch { /* The legacy cookie is missing or unreadable. */ } + } + + return { + load(): QqSessionRecord | undefined { + let raw: string; + try { + raw = fs.readFileSync(file, "utf8"); + } catch (err) { + if ((err as NodeJS.ErrnoException).code === "ENOENT") return loadLegacy(); + throw err; + } + const data = JSON.parse(raw); + if (data?.version !== 1 || typeof data.cookie !== "string") throw new Error("Invalid QQ session record"); + // Before the stores were shared, a newer login could be in the legacy file. + if (data.shared !== true && legacyFile) { + const legacy = loadLegacy(fs.statSync(file).mtimeMs); + if (legacy) return legacy; + } + const credential = parseQqCredential(data.credential); + const cookie = normalizeCookie(data.cookie); + if (data.credential && (!credential || qqPlaybackCookie(credential) !== cookie)) { + throw new Error("Invalid QQ session credential"); + } + return { + cookie, + credential, + reauthRequired: data.reauthRequired === true, + authorizedAt: timestamp(data.authorizedAt), + lastRefreshAt: timestamp(data.lastRefreshAt), + }; + }, + 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, cookie: normalizeCookie(data.cookie) }), { + encoding: "utf8", mode: 0o600, flag: "wx", flush: true, + }); + fs.renameSync(temp, file); + } finally { + try { fs.unlinkSync(temp); } catch { /* Already renamed or unavailable. */ } + } + }, + }; +} + +interface ActiveQr { + key: string; + sig: string; + expiresAt: number; + terminal?: "confirmed" | "expired"; + poll?: Promise; +} + +export class QQManagedSession { + private state: QqSessionRecord = { cookie: "" }; + private generation = 0; + private qrGeneration = 0; + private qr?: ActiveQr; + private inFlight?: Promise; + private pending?: { record: QqSessionRecord; result: "refreshed" | "reauth_required" }; + private timer?: ReturnType; + private retryAt?: number; + private nextAttempt?: number; + private failures = 0; + private stopped = false; + + constructor( + private readonly client: QqLoginClient, + private readonly store: ReturnType, + private readonly logger: Logger, + ) { + try { + const saved = store.load(); + if (saved) this.state = saved; + } catch { + logger.warn("Could not read QQ managed session"); + } + this.schedule(); + } + + getCookie(): string { + return this.state.cookie; + } + + getStatus(): { renewalStatus: QqRenewalStatus; nextRefreshAt: string | null; lastRefreshAt: string | null } { + const renewalStatus = this.retryAt ? "retrying" + : this.state.reauthRequired ? "reauth_required" + : !hasQqRenewalMaterial(this.state.credential) ? "cookie_only" + : "scheduled"; + const { lastRefreshAt } = this.state; + return { + renewalStatus, + nextRefreshAt: this.nextAttempt === undefined ? null : new Date(this.nextAttempt).toISOString(), + lastRefreshAt: lastRefreshAt === undefined ? null : new Date(lastRefreshAt).toISOString(), + }; + } + + setCookie(cookie: string): void { + this.replace({ cookie: normalizeCookie(cookie) }); + this.qrGeneration++; + this.qr = undefined; + } + + async getQrCode(): Promise { + const generation = ++this.qrGeneration; + this.qr = undefined; + const { img, sig } = await this.client.getQr(); + if (this.stopped || generation !== this.qrGeneration) throw new Error("QQ QR code superseded"); + const key = randomUUID(); + this.qr = { key, sig, expiresAt: Date.now() + QR_TTL }; + return { key, qrUrl: "", qrImg: img }; + } + + async checkQrCodeStatus(key: string): Promise { + const qr = this.qr; + if (!qr || qr.key !== key || this.stopped || qr.expiresAt <= Date.now()) return "expired"; + if (qr.terminal) return qr.terminal; + qr.poll ??= this.poll(qr).finally(() => { qr.poll = undefined; }); + return qr.poll; + } + + private async poll(qr: ActiveQr): Promise { + const result = await this.client.pollQr(qr.sig); + if (this.stopped || this.qr !== qr || qr.expiresAt <= Date.now()) return "expired"; + if (result.status === "confirmed") { + try { + this.replace({ + cookie: qqPlaybackCookie(result.credential), + credential: result.credential, + authorizedAt: Date.now(), + }); + } catch { + this.logger.warn("Could not save QQ login"); + return qr.terminal = "expired"; + } + qr.terminal = "confirmed"; + } + if (result.status === "expired") qr.terminal = "expired"; + return result.status; + } + + private replace(record: QqSessionRecord): void { + this.store.save(record); + this.state = record; + this.generation++; + this.inFlight = undefined; + this.pending = undefined; + this.retryAt = undefined; + this.failures = 0; + this.schedule(); + } + + private schedule(earliest = 0): void { + clearTimeout(this.timer); + this.nextAttempt = undefined; + if (this.stopped) return; + const credential = this.state.credential; + this.nextAttempt = this.retryAt; + if (this.nextAttempt === undefined && !this.state.reauthRequired && hasQqRenewalMaterial(credential)) { + const now = Date.now(); + // Older session records predate local timestamps. Use QQ's key creation + // time to establish their first due date without inventing a renewal history. + const keyCreatedAt = credential.musickeyCreateTime + ? timestamp(credential.musickeyCreateTime * 1000) : undefined; + const anchor = this.state.lastRefreshAt ?? this.state.authorizedAt ?? keyCreatedAt; + const dailyAt = anchor === undefined ? now : Math.min(anchor, now) + DAY; + const expiresAt = expiryTime(credential); + const leadTime = Math.min(30 * MINUTE, credential.keyExpiresIn * 100); + const dueAt = expiresAt === undefined ? dailyAt : Math.min(dailyAt, expiresAt - leadTime); + this.nextAttempt = Math.max(earliest, now, dueAt); + } + if (this.nextAttempt === undefined) return; + this.timer = setTimeout(() => { + if (this.nextAttempt !== undefined && Date.now() < this.nextAttempt) this.schedule(earliest); + else void this.refresh(); + }, Math.min(2 ** 31 - 1, this.nextAttempt - Date.now())); + this.timer.unref(); + } + + refresh(): Promise { + if (this.stopped) return Promise.resolve("superseded"); + if (this.inFlight) return this.inFlight; + if (this.retryAt && Date.now() < this.retryAt) return Promise.resolve("cooldown"); + if (this.pending) return Promise.resolve(this.commitPending()); + const credential = this.state.credential; + if (!hasQqRenewalMaterial(credential) || this.state.reauthRequired) return Promise.resolve("reauth_required"); + const generation = this.generation; + this.inFlight = this.renew(credential, generation).finally(() => { + if (generation === this.generation) this.inFlight = undefined; + }); + return this.inFlight; + } + + private async renew(credential: QqCredential, generation: number): Promise { + const result = await this.client.refresh(credential).catch(() => ({ status: "upstream_error" } as const)); + if (this.stopped || this.generation !== generation) return "superseded"; + if (result.status === "reauth_required") { + this.pending = { record: { ...this.state, reauthRequired: true }, result: "reauth_required" }; + return this.commitPending(); + } + if (result.status === "refreshed") { + const next = result.credential; + const renewed = next.musickey !== credential.musickey + || (expiryTime(next) ?? 0) > (expiryTime(credential) ?? 0) + || (next.refresh_key && next.refresh_key !== credential.refresh_key) + || (next.refresh_token && next.refresh_token !== credential.refresh_token); + if (next.musicid === credential.musicid && renewed) { + this.pending = { + record: { cookie: qqPlaybackCookie(next), credential: next, reauthRequired: !hasQqRenewalMaterial(next) }, + result: "refreshed", + }; + return this.commitPending(); + } + } + const outcome = result.status === "rate_limited" ? "rate_limited" : "upstream_error"; + this.defer(outcome); + return outcome; + } + + private commitPending(): QqRenewalResult { + const pending = this.pending!; + const record = pending.result === "refreshed" + ? { ...pending.record, lastRefreshAt: Date.now() } + : pending.record; + try { + this.store.save(record); + } catch { + this.defer("persist_failed"); + return "persist_failed"; + } + this.state = record; + this.pending = undefined; + this.retryAt = undefined; + this.failures = 0; + this.schedule(Date.now() + MINUTE); + this.logger.info({ outcome: pending.result }, "QQ session renewal"); + return pending.result; + } + + private defer(outcome: "rate_limited" | "upstream_error" | "persist_failed"): void { + const initialMinutes = outcome === "rate_limited" ? 15 : 5; + this.retryAt = Date.now() + Math.min(60, initialMinutes * 2 ** this.failures++) * MINUTE; + this.schedule(); + this.logger.warn({ outcome }, "QQ session renewal deferred"); + } + + stop(): void { + this.stopped = true; + this.schedule(); + } +} diff --git a/src/music/qq.ts b/src/music/qq.ts index 261f05c..327879f 100644 --- a/src/music/qq.ts +++ b/src/music/qq.ts @@ -1,3 +1,4 @@ +import { normalizeCookie } from "./cookie-normalize.js"; import axios, { type AxiosInstance } from "axios"; import type { MusicProvider, @@ -15,6 +16,7 @@ import type { ArtistSongPage, } from "./provider.js"; import { parseLyrics } from "./netease.js"; +import type { QQManagedSession } from "./qq-session.js"; // Primary search client: u.y.qq.com/cgi-bin/musicu.fcg (JSON sub-request // batch). Was broken ca. 2026-05 due to two upstream API changes: @@ -171,17 +173,21 @@ function computeGtk(pSkey: string): number { export class QQMusicProvider implements MusicProvider { readonly platform = "qq" as const; private api: AxiosInstance; - private cookie = ""; + private legacyCookie = ""; private quality = "exhigh"; private radarPage = 1; - constructor(baseUrl: string) { + constructor(baseUrl: string, readonly managedSession?: QQManagedSession) { this.api = axios.create({ baseURL: baseUrl, timeout: 10000, }); } + private get cookie(): string { + return this.managedSession?.getCookie() ?? this.legacyCookie; + } + setQuality(quality: string): void { this.quality = quality; } @@ -768,6 +774,7 @@ export class QQMusicProvider implements MusicProvider { } async getQrCode(): Promise { + if (this.managedSession) return this.managedSession.getQrCode(); // @sansenjian/qq-music-api 2.x returns { img, qrsig, ptqrtoken } via // customResponse (no { response: ... } wrapping). /checkQQLoginQr // requires BOTH qrsig AND ptqrtoken — passing only one gives a 400 @@ -787,6 +794,12 @@ export class QQMusicProvider implements MusicProvider { async checkQrCodeStatus( key: string ): Promise<"waiting" | "scanned" | "confirmed" | "expired"> { + if (this.managedSession) { + const previous = this.cookie; + const status = await this.managedSession.checkQrCodeStatus(key); + if (status === "confirmed" && this.cookie !== previous) this.radarPage = 1; + return status; + } const [qrsig, ptqrtoken] = key.split("|"); if (!qrsig || !ptqrtoken) return "expired"; @@ -808,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.cookie = cookie; + if (cookie) this.setCookie(cookie); return "confirmed"; } if (body?.refresh === true) return "expired"; @@ -818,7 +831,8 @@ export class QQMusicProvider implements MusicProvider { } setCookie(cookie: string): void { - this.cookie = cookie; + if (this.managedSession) this.managedSession.setCookie(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; diff --git a/src/web/api/auth.test.ts b/src/web/api/auth.test.ts index 4598d38..ec905d1 100644 --- a/src/web/api/auth.test.ts +++ b/src/web/api/auth.test.ts @@ -3,6 +3,7 @@ import express from "express"; import request from "supertest"; import pino from "pino"; import type { MusicProvider } from "../../music/provider.js"; +import type { QQMusicProvider } from "../../music/qq.js"; import { getDefaultConfig, type JellyfinConfig } from "../../data/config.js"; import { createAuthRouter } from "./auth.js"; @@ -72,3 +73,79 @@ describe("auth router POST /jellyfin/test", () => { expect(testConnection).not.toHaveBeenCalled(); }); }); + +describe("managed QQ authentication routes", () => { + function mount(managed: boolean, user: unknown = { role: "admin" }) { + const renewal = { + renewalStatus: "scheduled" as const, + nextRefreshAt: "2026-11-10T00:00:00.000Z", + lastRefreshAt: "2026-11-09T00:00:00.000Z", + }; + const refresh = vi.fn().mockResolvedValue("refreshed"); + const qq = { + platform: "qq", + managedSession: managed ? { refresh, getStatus: () => renewal } : undefined, + checkQrCodeStatus: vi.fn().mockResolvedValue("confirmed"), + setCookie: vi.fn(), + getCookie: () => "private-test-cookie", + getAuthStatus: vi.fn().mockResolvedValue({ loggedIn: true }), + } as unknown as QQMusicProvider; + const legacyStore = { load: vi.fn(), save: vi.fn() }; + const app = express(); + app.use(express.json()); + app.use((req, _res, next) => { (req as { user?: unknown }).user = user; next(); }); + app.use("/api/auth", createAuthRouter( + fakeProvider("netease"), qq, fakeProvider("bilibili"), pino({ level: "silent" }), legacyStore, + )); + return { app, qq, refresh, legacyStore }; + } + + it("returns status only and delegates persistence to the managed session", async () => { + const { app, qq, refresh, legacyStore } = mount(true); + await request(app).get("/api/auth/qrcode/status").query({ platform: "qq", key: "opaque" }).expect(200); + await request(app).post("/api/auth/cookie").send({ platform: "qq", cookie: "uin=1" }).expect(200); + expect(qq.setCookie).toHaveBeenCalledWith("uin=1"); + expect(legacyStore.save).not.toHaveBeenCalled(); + const status = await request(app).get("/api/auth/status").query({ platform: "qq" }).expect(200); + expect(status.body.lastRefreshAt).toBe("2026-11-09T00:00:00.000Z"); + const res = await request(app).post("/api/auth/qq/refresh").expect(200); + expect(res.body).toEqual({ + outcome: "refreshed", renewalStatus: "scheduled", nextRefreshAt: "2026-11-10T00:00:00.000Z", + lastRefreshAt: "2026-11-09T00:00:00.000Z", + }); + expect(refresh).toHaveBeenCalledTimes(1); + }); + + it("guards managed QQ polling and refresh with platform.auth", async () => { + const { app, qq, refresh } = mount(true, { role: "member", capabilities: new Set() }); + await request(app).get("/api/auth/qrcode/status").query({ platform: "qq", key: "opaque" }).expect(403); + await request(app).post("/api/auth/qq/refresh").expect(403); + expect(qq.checkQrCodeStatus).not.toHaveBeenCalled(); + 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); + expect(legacyStore.save).toHaveBeenCalledWith("qq", "private-test-cookie"); + await request(app).post("/api/auth/qq/refresh").expect(404); + }); + + it("keeps the current QQ cookie when an unmanaged import cannot be saved", async () => { + const { app, qq, legacyStore } = mount(false); + legacyStore.save.mockImplementationOnce(() => { throw new Error("test write failed"); }); + await request(app).post("/api/auth/cookie").send({ platform: "qq", cookie: "uin=999" }).expect(503); + expect(qq.setCookie).not.toHaveBeenCalled(); + await request(app).post("/api/auth/cookie").send({ platform: "qq", cookie: "uin=999" }).expect(200); + expect(legacyStore.save).toHaveBeenLastCalledWith("qq", "uin=999"); + expect(qq.setCookie).toHaveBeenCalledWith("uin=999"); + }); +}); diff --git a/src/web/api/auth.ts b/src/web/api/auth.ts index e4cd049..d75fbc5 100644 --- a/src/web/api/auth.ts +++ b/src/web/api/auth.ts @@ -1,5 +1,8 @@ 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"; @@ -9,7 +12,7 @@ import { requireNotGuest } from "../middleware/requireNotGuest.js"; export function createAuthRouter( neteaseProvider: MusicProvider, - qqProvider: MusicProvider, + qqProvider: MusicProvider & Partial>, bilibiliProvider: MusicProvider, logger: Logger, cookieStore?: CookieStore, @@ -19,6 +22,7 @@ export function createAuthRouter( config?: BotConfig ): Router { const router = Router(); + const qqSession = qqProvider.managedSession; // YouTube is auth-less; we only use this instance so /auth/status can // report whether yt-dlp is actually installed (loggedIn=false otherwise). const youtubeProvider: MusicProvider = new YouTubeProvider(); @@ -37,8 +41,9 @@ export function createAuthRouter( const platform = req.query.platform as string; const provider = getProvider(platform); const status = await provider.getAuthStatus(); - logger.debug({ platform, status }, "Auth status check"); - res.json({ platform: provider.platform, ...status }); + logger.debug({ platform, loggedIn: status.loggedIn }, "Auth status check"); + const renewal = platform === "qq" ? qqSession?.getStatus() : undefined; + res.json({ platform: provider.platform, ...status, ...renewal }); } catch (err) { logger.error({ err }, "Auth status check failed"); res.status(500).json({ error: (err as Error).message }); @@ -50,7 +55,7 @@ export function createAuthRouter( const { platform } = req.body; const provider = getProvider(platform); const qr = await provider.getQrCode(); - logger.info({ platform, key: qr.key }, "QR code generated"); + logger.info({ platform }, "QR code generated"); res.json(qr); } catch (err) { logger.error({ err }, "QR code generation failed"); @@ -58,7 +63,11 @@ export function createAuthRouter( } }); - router.get("/qrcode/status", requireNotGuest, async (req, res) => { + const requirePlatformAuth = requirePermission("platform.auth"); + router.get("/qrcode/status", requireNotGuest, (req, res, next) => { + if (qqSession && req.query.platform === "qq") requirePlatformAuth(req, res, next); + else next(); + }, async (req, res) => { try { const { key, platform } = req.query; if (!key) { @@ -67,10 +76,10 @@ export function createAuthRouter( } const provider = getProvider(platform as string); const status = await provider.checkQrCodeStatus(key as string); - logger.info({ platform, status, key }, "QR status check"); + logger.info({ platform, status }, "QR status check"); // When confirmed, persist cookie - if (status === "confirmed") { + if (status === "confirmed" && !(platform === "qq" && qqSession)) { const cookie = provider.getCookie(); const plat = (platform as string) === "bilibili" ? "bilibili" as const : (platform as string) === "kugou" ? "kugou" as const @@ -88,6 +97,19 @@ export function createAuthRouter( } }); + router.post("/qq/refresh", requirePlatformAuth, async (_req, res) => { + if (!qqSession) { + res.status(404).json({ outcome: "disabled" }); + return; + } + const outcome = await qqSession.refresh(); + const status = outcome === "refreshed" ? 200 + : outcome === "cooldown" || outcome === "rate_limited" ? 429 + : outcome === "reauth_required" || outcome === "superseded" ? 409 + : outcome === "persist_failed" ? 503 : 502; + res.status(status).json({ outcome, ...qqSession.getStatus() }); + }); + // Jellyfin has no QR/cookie flow — the connection is admin-configured. This // round-trips /System/Info so Settings can verify form values BEFORE saving. // Empty/missing credential fields fall back to the stored config, so a @@ -169,7 +191,8 @@ export function createAuthRouter( }); router.post("/cookie", requirePermission("platform.auth"), (req, res) => { - const { platform, cookie } = req.body; + const { platform, cookie: raw } = req.body; + const cookie = typeof raw === "string" ? normalizeCookie(raw) : ""; if (!cookie) { res.status(400).json({ error: "cookie is required" }); return; @@ -191,10 +214,21 @@ export function createAuthRouter( return; } const provider = getProvider(platform); + if (platform === "qq") { + try { + if (!qqSession) cookieStore?.save("qq", cookie); + provider.setCookie(cookie); + res.json({ success: true }); + } catch { + logger.warn("Could not save imported QQ cookie"); + res.status(503).json({ error: "Could not save QQ cookie" }); + } + return; + } provider.setCookie(cookie); const plat = platform === "bilibili" ? "bilibili" as const : platform === "kugou" ? "kugou" as const - : platform === "qq" ? "qq" as const : "netease" as const; + : "netease" as const; if (cookieStore) { cookieStore.save(plat, cookie); } diff --git a/web/src/views/Settings.vue b/web/src/views/Settings.vue index 2228df1..168d4be 100755 --- a/web/src/views/Settings.vue +++ b/web/src/views/Settings.vue @@ -441,6 +441,12 @@ + + @@ -1418,7 +1424,22 @@ const kugouLoginMode = ref<'qr' | 'cookie' | null>(null); // Auth status const neteaseAuth = reactive({ loggedIn: false, nickname: '', avatarUrl: '' }); -const qqAuth = reactive({ loggedIn: false, nickname: '', avatarUrl: '' }); +const qqAuth = reactive({ + loggedIn: false, nickname: '', avatarUrl: '', + renewalStatus: '' as '' | 'cookie_only' | 'scheduled' | 'retrying' | 'reauth_required', + nextRefreshAt: null as string | null, + lastRefreshAt: null as string | null, +}); +const qqRenewalMessage = computed(() => { + const next = qqAuth.nextRefreshAt ? new Date(qqAuth.nextRefreshAt).toLocaleString() : ''; + switch (qqAuth.renewalStatus) { + case 'cookie_only': return '没有续期凭据,请扫码授权'; + case 'reauth_required': return '续期已暂停,请重新扫码'; + case 'scheduled': return `下次自动续期 ${next}`; + case 'retrying': return `续期将于 ${next} 重试`; + default: return ''; + } +}); const bilibiliAuth = reactive({ loggedIn: false, nickname: '', avatarUrl: '' }); const kugouAuth = reactive({ loggedIn: false, nickname: '', avatarUrl: '' }); const jellyfinAuth = reactive({ loggedIn: false, nickname: '' });