mirror of
https://github.com/ZHANGTIANYAO1/teamspeak-music-bot.git
synced 2026-11-30 18:02:50 +08:00
Merge pull request #188 from NoSetViolin/zty-main-pr
feat(qq): 支持 QQ 音乐登录凭据自动续期
This commit is contained in:
11 files changed
+1120
-21
No files matched your search
@@ -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 页面说明
|
||||
|
||||
| 页面 | 功能 |
|
||||
|
||||
+17
-4
@@ -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();
|
||||
|
||||
+7
-1
@@ -1,6 +1,7 @@
|
||||
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). */
|
||||
@@ -22,7 +23,7 @@ export interface CookieStore {
|
||||
load(platform: CookiePlatform): string;
|
||||
}
|
||||
|
||||
export function createCookieStore(cookieDir: string): CookieStore {
|
||||
export function createCookieStore(cookieDir: string, qqStore?: ReturnType<typeof createQqSessionStore>): CookieStore {
|
||||
if (!fs.existsSync(cookieDir)) {
|
||||
fs.mkdirSync(cookieDir, { recursive: true });
|
||||
}
|
||||
@@ -38,10 +39,15 @@ export function createCookieStore(cookieDir: string): CookieStore {
|
||||
|
||||
return {
|
||||
save(platform: CookiePlatform, cookie: string): void {
|
||||
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;
|
||||
|
||||
@@ -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,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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<QqPollResult>;
|
||||
refresh(credential: QqCredential): Promise<QqRefreshResult>;
|
||||
}
|
||||
|
||||
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<string, unknown> {
|
||||
return value && typeof value === "object" && !Array.isArray(value)
|
||||
? value as Record<string, unknown> : {};
|
||||
}
|
||||
|
||||
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<string, string> {
|
||||
const cookies = new Map<string, string>();
|
||||
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, string>): 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<QqCredential | undefined> {
|
||||
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<string>(`${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" };
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -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<typeof createQqSessionStore>;
|
||||
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");
|
||||
});
|
||||
});
|
||||
@@ -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<QrStatus>;
|
||||
}
|
||||
|
||||
export class QQManagedSession {
|
||||
private state: QqSessionRecord = { cookie: "" };
|
||||
private generation = 0;
|
||||
private qrGeneration = 0;
|
||||
private qr?: ActiveQr;
|
||||
private inFlight?: Promise<QqRenewalResult>;
|
||||
private pending?: { record: QqSessionRecord; result: "refreshed" | "reauth_required" };
|
||||
private timer?: ReturnType<typeof setTimeout>;
|
||||
private retryAt?: number;
|
||||
private nextAttempt?: number;
|
||||
private failures = 0;
|
||||
private stopped = false;
|
||||
|
||||
constructor(
|
||||
private readonly client: QqLoginClient,
|
||||
private readonly store: ReturnType<typeof createQqSessionStore>,
|
||||
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<QrCodeResult> {
|
||||
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<QrStatus> {
|
||||
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<QrStatus> {
|
||||
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<QqRenewalResult> {
|
||||
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<QqRenewalResult> {
|
||||
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();
|
||||
}
|
||||
}
|
||||
+17
-6
@@ -16,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:
|
||||
@@ -172,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;
|
||||
}
|
||||
@@ -769,6 +774,7 @@ export class QQMusicProvider implements MusicProvider {
|
||||
}
|
||||
|
||||
async getQrCode(): Promise<QrCodeResult> {
|
||||
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
|
||||
@@ -788,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";
|
||||
|
||||
@@ -809,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";
|
||||
@@ -819,9 +831,8 @@ export class QQMusicProvider implements MusicProvider {
|
||||
}
|
||||
|
||||
setCookie(cookie: string): void {
|
||||
// Normalised: see music/cookie-normalize.ts for why a pasted Set-Cookie
|
||||
// line breaks every request.
|
||||
this.cookie = normalizeCookie(cookie);
|
||||
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;
|
||||
|
||||
@@ -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");
|
||||
});
|
||||
});
|
||||
+43
-9
@@ -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<Pick<QQMusicProvider, "managedSession">>,
|
||||
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<ParamsDictionary>("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);
|
||||
}
|
||||
|
||||
@@ -441,6 +441,12 @@
|
||||
<div class="account-status" :class="{ logged: qqAuth.loggedIn }">
|
||||
{{ qqAuth.loggedIn ? `已登录: ${qqAuth.nickname}` : '未登录' }}
|
||||
</div>
|
||||
<div v-if="qqRenewalMessage" class="account-status">
|
||||
{{ qqRenewalMessage }}
|
||||
</div>
|
||||
<div v-if="qqAuth.renewalStatus" class="account-status">
|
||||
上次成功续期 {{ qqAuth.lastRefreshAt ? new Date(qqAuth.lastRefreshAt).toLocaleString() : '暂无记录' }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -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: '' });
|
||||
|
||||
Reference in new issue
Block a user