diff --git a/src/index.ts b/src/index.ts index cf7d5c3..03bd050 100755 --- a/src/index.ts +++ b/src/index.ts @@ -80,16 +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"); const qqSession = (process.env.QQ_MUSIC_MANAGED_SESSION ?? "1") === "1" && isProviderEnabled(config, "qq") - ? new QQManagedSession(createQqLoginClient(), createQqSessionStore(path.join(COOKIE_DIR, "qq-session.json")), logger, qqCookie) + ? new QQManagedSession(createQqLoginClient(), qqStore, logger) : undefined; const qqProvider = new QQMusicProvider(apiServer.getQQMusicBaseUrl(), qqSession); - if (!qqSession && qqCookie) qqProvider.setCookie(qqCookie); + 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"); diff --git a/src/music/auth.ts b/src/music/auth.ts index 8100c8b..1ccfca9 100644 --- a/src/music/auth.ts +++ b/src/music/auth.ts @@ -1,5 +1,6 @@ import fs from "node:fs"; import path from "node:path"; +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). */ @@ -10,13 +11,17 @@ export interface CookieStore { 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 }); } return { save(platform: CookiePlatform, cookie: string): void { + if (platform === "qq" && qqStore) { + qqStore.save({ cookie }); + return; + } const filePath = path.join(cookieDir, `${platform}.json`); fs.writeFileSync( filePath, @@ -26,6 +31,7 @@ export function createCookieStore(cookieDir: string): CookieStore { }, load(platform: CookiePlatform): string { + if (platform === "qq" && qqStore) return qqStore.load()?.cookie ?? ""; const filePath = path.join(cookieDir, `${platform}.json`); if (!fs.existsSync(filePath)) return ""; try { diff --git a/src/music/qq-login.test.ts b/src/music/qq-login.test.ts index 43eb40c..67e3647 100644 --- a/src/music/qq-login.test.ts +++ b/src/music/qq-login.test.ts @@ -98,7 +98,26 @@ describe("QQ login transport", () => { 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 index 0e93394..fa1f04b 100644 --- a/src/music/qq-login.ts +++ b/src/music/qq-login.ts @@ -57,6 +57,7 @@ export function parseQqCredential(value: unknown, previous?: QqCredential): QqCr 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, @@ -65,8 +66,8 @@ export function parseQqCredential(value: unknown, previous?: QqCredential): QqCr 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), - keyExpiresIn: positiveInt(data.keyExpiresIn), + musickeyCreateTime: positiveInt(data.musickeyCreateTime ?? sameKey?.musickeyCreateTime), + keyExpiresIn: positiveInt(data.keyExpiresIn ?? sameKey?.keyExpiresIn), }; } diff --git a/src/music/qq-session.test.ts b/src/music/qq-session.test.ts index aa1ff18..15a709e 100644 --- a/src/music/qq-session.test.ts +++ b/src/music/qq-session.test.ts @@ -3,7 +3,8 @@ import os from "node:os"; import path from "node:path"; import pino from "pino"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { qqPlaybackCookie, type QqCredential, type QqLoginClient, type QqRefreshResult } from "./qq-login.js"; +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"); @@ -35,13 +36,14 @@ describe("managed QQ session", () => { pollQr: vi.fn().mockResolvedValue({ status: "confirmed", credential: first }), refresh: vi.fn().mockResolvedValue({ status: "refreshed", credential: second }), }; - session = new QQManagedSession(client, store, logger, "uin=123; qm_keyst=legacy"); + 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); }); @@ -66,7 +68,7 @@ describe("managed QQ session", () => { }); await vi.advanceTimersByTimeAsync(DAY / 2); session.stop(); - session = new QQManagedSession(client, store, logger, ""); + session = new QQManagedSession(client, store, logger); await vi.advanceTimersByTimeAsync(DAY / 2 - 1); expect(client.refresh).not.toHaveBeenCalled(); await vi.advanceTimersByTimeAsync(1); @@ -77,7 +79,7 @@ describe("managed QQ session", () => { await vi.advanceTimersByTimeAsync(DAY / 2); session.stop(); - session = new QQManagedSession(client, store, logger, ""); + session = new QQManagedSession(client, store, logger); expect(session.getStatus()).toEqual({ renewalStatus: "scheduled", nextRefreshAt: new Date(NOW.valueOf() + 2 * DAY).toISOString(), @@ -95,11 +97,26 @@ describe("managed QQ session", () => { 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, ""); + session = new QQManagedSession(client, store, logger); expect(session.getStatus()).toEqual({ renewalStatus: "scheduled", nextRefreshAt: new Date(NOW.valueOf() + DAY / 2).toISOString(), @@ -114,7 +131,7 @@ describe("managed QQ session", () => { expect(await a).toBe("refreshed"); expect(client.refresh).toHaveBeenCalledTimes(1); session.stop(); - session = new QQManagedSession(client, store, logger, ""); + session = new QQManagedSession(client, store, logger); vi.mocked(client.refresh).mockResolvedValueOnce({ status: "refreshed", credential: { ...second, musickey: "third-key" }, }); @@ -184,7 +201,7 @@ describe("managed QQ session", () => { vi.mocked(client.refresh).mockResolvedValueOnce({ status: "reauth_required" }); expect(await session.refresh()).toBe("reauth_required"); session.stop(); - session = new QQManagedSession(client, store, logger, ""); + 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); @@ -192,9 +209,13 @@ describe("managed QQ session", () => { }); 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(store.load()).toBeUndefined(); + expect(fs.existsSync(file)).toBe(false); vi.mocked(client.pollQr).mockResolvedValueOnce({ status: "confirmed", credential: { ...first, musickeyCreateTime: 0, keyExpiresIn: 0 }, }); @@ -206,4 +227,39 @@ describe("managed QQ session", () => { 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("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 index a5af8c1..eda1406 100644 --- a/src/music/qq-session.ts +++ b/src/music/qq-session.ts @@ -31,18 +31,32 @@ function expiryTime(credential: QqCredential): number | undefined { return timestamp((credential.musickeyCreateTime + credential.keyExpiresIn) * 1000); } -export function createQqSessionStore(file: string) { +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")); + if (typeof cookie === "string" && cookie) return { cookie }; + } 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; + 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); if (data.credential && (!credential || qqPlaybackCookie(credential) !== data.cookie)) { throw new Error("Invalid QQ session credential"); @@ -58,7 +72,7 @@ export function createQqSessionStore(file: string) { save(data: QqSessionRecord): void { const temp = path.join(path.dirname(file), `.qq-session-${randomUUID()}.tmp`); try { - fs.writeFileSync(temp, JSON.stringify({ version: 1, ...data }), { + fs.writeFileSync(temp, JSON.stringify({ version: 1, shared: true, ...data }), { encoding: "utf8", mode: 0o600, flag: "wx", flush: true, }); fs.renameSync(temp, file); @@ -94,10 +108,10 @@ export class QQManagedSession { private readonly client: QqLoginClient, private readonly store: ReturnType, private readonly logger: Logger, - legacyCookie: string, ) { try { - this.state = store.load() ?? { cookie: legacyCookie }; + const saved = store.load(); + if (saved) this.state = saved; } catch { logger.warn("Could not read QQ managed session"); } diff --git a/src/web/api/auth.test.ts b/src/web/api/auth.test.ts index cb19079..1edc116 100644 --- a/src/web/api/auth.test.ts +++ b/src/web/api/auth.test.ts @@ -130,4 +130,14 @@ describe("managed QQ authentication routes", () => { 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 7acb91f..ae3dbe4 100644 --- a/src/web/api/auth.ts +++ b/src/web/api/auth.ts @@ -212,8 +212,9 @@ export function createAuthRouter( return; } const provider = getProvider(platform); - if (platform === "qq" && qqSession) { + if (platform === "qq") { try { + if (!qqSession) cookieStore?.save("qq", cookie); provider.setCookie(cookie); res.json({ success: true }); } catch { @@ -225,7 +226,7 @@ export function createAuthRouter( 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); }