mirror of
https://github.com/ZHANGTIANYAO1/teamspeak-music-bot.git
synced 2026-12-01 02:12:50 +08:00
Merge remote-tracking branch 'origin/main' into review/185-hardening
# Conflicts: # src/music/netease.ts
This commit is contained in:
commit
ea05787cb7
25 files changed
+1592
-34
No files matched your search
@@ -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);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user