Integrate QQ renewal and enforce music account assignment rules

This commit is contained in:
TIANYAO ZHANG committed 2026-11-18 16:51:32 +08:00
commit 0808cde447
27 files changed
+1501 -76

No files matched your search

+77
View File
@@ -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
View File
@@ -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";
@@ -11,7 +14,7 @@ import { resolveMusicCookie } from "./provider-scope.js";
export function createAuthRouter(
neteaseProvider: MusicProvider,
qqProvider: MusicProvider,
qqProvider: MusicProvider & Partial<Pick<QQMusicProvider, "managedSession">>,
bilibiliProvider: MusicProvider,
logger: Logger,
cookieStore?: CookieStore,
@@ -24,6 +27,7 @@ export function createAuthRouter(
database?: BotDatabase,
): 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();
@@ -84,8 +88,9 @@ export function createAuthRouter(
}
const status = await provider.getAuthStatus();
logger.debug({ platform, status }, "Auth status check");
res.json({ platform: provider.platform, source: "shared", ...status });
logger.debug({ platform, loggedIn: status.loggedIn }, "Auth status check");
const renewal = platform === "qq" ? qqSession?.getStatus() : undefined;
res.json({ platform: provider.platform, source: "shared", ...status, ...renewal });
} catch (err) {
logger.error({ err }, "Auth status check failed");
res.status(500).json({ error: (err as Error).message });
@@ -97,7 +102,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");
@@ -105,7 +110,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) {
@@ -114,10 +123,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
@@ -135,6 +144,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
@@ -216,7 +238,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;
@@ -238,10 +261,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);
}
+10 -2
View File
@@ -677,12 +677,12 @@ describe("bot router /settings jellyfin block + enabledProviders", () => {
rmSync(tmpDir, { recursive: true, force: true });
});
function mountBot(): express.Express {
function mountBot(user: unknown = { role: "admin" }): express.Express {
const fakeManager = { getAllBots: () => [] } as unknown as BotManager;
const avatarStore = createAvatarStore(tmpDir);
const app = express();
app.use(express.json());
app.use((req, _res, next) => { (req as { user?: unknown }).user = { role: "admin" }; next(); });
app.use((req, _res, next) => { (req as { user?: unknown }).user = user; next(); });
app.use(
"/api/bot",
createBotRouter(
@@ -694,6 +694,14 @@ describe("bot router /settings jellyfin block + enabledProviders", () => {
return app;
}
it("reserves the music-account policy toggle for administrators", async () => {
const member = mountBot({ role: "member", capabilities: new Set(["bot.manage"]) });
await request(member).post("/api/bot/settings").send({ perUserMusicAccounts: true }).expect(403);
expect(config.perUserMusicAccounts).toBe(false);
await request(mountBot()).post("/api/bot/settings").send({ perUserMusicAccounts: true }).expect(200);
expect(config.perUserMusicAccounts).toBe(true);
});
it("GET /settings exposes a masked jellyfin block (no password/apiKey echo)", async () => {
config.jellyfin.serverUrl = "https://jf.example.com";
config.jellyfin.password = "secret";
+4 -2
View File
@@ -106,9 +106,11 @@ export function createBotRouter(
const hasAutoPause = typeof autoPauseOnEmpty === "boolean";
const hasLocalAudioEnabled = typeof localAudioEnabled === "boolean";
// Per-user music accounts: admin-only toggle (this route already requires
// bot.manage). Strictly boolean — anything else leaves the value alone.
const hasPerUserMusicAccounts = typeof perUserMusicAccounts === "boolean";
if (hasPerUserMusicAccounts && req.user?.role !== "admin") {
res.status(403).json({ error: "forbidden" });
return;
}
if (hasIdle) config.idleTimeoutMinutes = idleTimeoutMinutes;
if (hasAutoPause) config.autoPauseOnEmpty = autoPauseOnEmpty;
+22
View File
@@ -172,6 +172,28 @@ describe("admin music account pool", () => {
expect(db.getGrantedMusicAccount("u1", "netease")).toBeNull();
});
it("preserves a replacement assignment when an old assignment is revoked", async () => {
const { app, db } = mount();
const first = await seed(app, { label: "一号" });
const second = await seed(app, { label: "二号" });
for (const account of [first, second]) {
await request(app).post(`/api/music-accounts/${account.body.id}/assign`).send({ userId: "u1" }).expect(200);
}
const res = await request(app).delete(`/api/music-accounts/${first.body.id}/assign/u1`).expect(200);
expect(res.body.removed).toBe(false);
expect(db.getGrantedMusicAccount("u1", "netease")?.accountId).toBe(second.body.id);
});
it("does not lower the capacity below the current number of assignees", async () => {
const { app, db } = mount();
const id = (await seed(app)).body.id;
for (const userId of ["u1", "u2"]) {
await request(app).post(`/api/music-accounts/${id}/assign`).send({ userId }).expect(200);
}
await request(app).patch(`/api/music-accounts/${id}`).send({ capacity: 1 }).expect(409);
expect(db.getMusicAccount(id)?.capacity).toBe(0);
});
// Deleting the account must not leave grants pointing at a dead row.
it("cascades grantees when the account is deleted", async () => {
const { app, db } = mount();
+18 -11
View File
@@ -90,6 +90,9 @@ export function createMusicAccountsRouter(
const nonEmpty = (v: unknown, max: number): v is string =>
typeof v === "string" && v.trim().length > 0 && v.length <= max;
const validCapacity = (value: unknown): value is number | undefined =>
value === undefined || (typeof value === "number" && Number.isSafeInteger(value) && value >= 0);
/** Every real (non-guest) user, for the assign dropdown. */
const assignableUsers = () =>
users.listUsers().map((u) => ({ id: u.id, username: u.username, role: u.role }));
@@ -122,8 +125,8 @@ export function createMusicAccountsRouter(
res.status(400).json({ error: "cookie is required" });
return;
}
if (capacity !== undefined && (typeof capacity !== "number" || capacity < 0)) {
res.status(400).json({ error: "capacity must be a non-negative number" });
if (!validCapacity(capacity)) {
res.status(400).json({ error: "capacity must be a non-negative integer" });
return;
}
if (ownerId !== undefined && ownerId !== null && typeof ownerId !== "string") {
@@ -163,8 +166,8 @@ export function createMusicAccountsRouter(
res.status(400).json({ error: "invalid cookie" });
return;
}
if (capacity !== undefined && (typeof capacity !== "number" || capacity < 0)) {
res.status(400).json({ error: "capacity must be a non-negative number" });
if (!validCapacity(capacity)) {
res.status(400).json({ error: "capacity must be a non-negative integer" });
return;
}
if (enabled !== undefined && typeof enabled !== "boolean") {
@@ -174,12 +177,16 @@ export function createMusicAccountsRouter(
// Replacing the cookie invalidates any device-bound session (Kugou binds
// the token to guid/mid) — the existing grants keep pointing at the row,
// so the admin only has to paste a fresh cookie to fix everyone at once.
database.updateMusicAccount(account.id, {
const updated = database.updateMusicAccount(account.id, {
label: label === undefined ? undefined : label.trim(),
cookie: cookie === undefined ? undefined : cookie.trim(),
capacity,
enabled,
});
if (!updated) {
res.status(409).json({ error: "capacity_below_existing_grants" });
return;
}
logger.info(
{ accountId: account.id, enabled: enabled ?? account.enabled },
"Music account updated",
@@ -268,7 +275,7 @@ export function createMusicAccountsRouter(
res.status(404).json({ error: "not found" });
return;
}
const removed = database.deleteMusicAccountGrant(req.params.userId, account.platform);
const removed = database.deleteMusicAccountGrant(req.params.userId, account.platform, account.id);
logger.info(
{ accountId: account.id, userId: req.params.userId, removed },
"Music account assignment revoked",
@@ -291,9 +298,9 @@ export function createMusicAccountsRouter(
try {
const status = await provider.withCookie(account.cookie).getAuthStatus();
res.json({ ok: true, ...status });
} catch (err) {
logger.warn({ err, accountId: account.id }, "Music account probe failed");
res.status(502).json({ error: (err as Error).message, loggedIn: false });
} catch {
logger.warn({ accountId: account.id }, "Music account probe failed");
res.status(502).json({ error: "music_account_probe_failed", loggedIn: false });
}
});
@@ -315,8 +322,8 @@ export function createMusicAccountsRouter(
res.status(400).json({ error: "unsupported platform" });
return;
}
if (capacity !== undefined && (typeof capacity !== "number" || capacity < 0)) {
res.status(400).json({ error: "capacity must be a non-negative number" });
if (!validCapacity(capacity)) {
res.status(400).json({ error: "capacity must be a non-negative integer" });
return;
}
// 没有 qq provider(例如单测只挂了 netease)时仍然回落到 cookie store,
+1 -1
View File
@@ -113,7 +113,7 @@ export function createMusicRouter(
return null;
}
// Per-user accounts: with the feature on, a user who linked their own
// account reads search/playlists/lyrics/artists/playback through THAT
// account reads search/playlists/lyrics/artists through THAT
// login instead of the bot's shared one, so members stop seeing the
// admin's library. Everyone else keeps the shared provider unchanged.
return resolveProviderForRequest(req, target, getProvider(target), {
+2 -2
View File
@@ -132,8 +132,8 @@ export function createPersonalMusicRouter(
featureEnabled,
...status,
});
} catch (err) {
logger.warn({ err, platform, source: account.source }, "Personal music status check failed");
} catch {
logger.warn({ platform, source: account.source }, "Personal music status check failed");
res.json({
linked: true,
loggedIn: false,
+2 -4
View File
@@ -181,10 +181,8 @@ export function createPlayerRouter(
rejectDisabledLocalAudio(res);
return;
}
// A caller who linked their own account gets FM from THEIR taste instead
// of the bot's shared login (#164). With per-user accounts enabled the
// same account now also resolves playback, so VIP/high-quality tracks
// come from that account rather than the admin's.
// Resolve FM recommendations with the caller's account. The bot resolves
// each queued track's playback URL using the shared account.
const provider = fmProvider(req, bot, platform);
const message = await bot.startFm(provider, requesterName(req));
res.json({