Merge the reviewed music-account changes into playback retry

This commit is contained in:
TIANYAO ZHANG committed 2026-11-18 17:02:20 +08:00
commit d34e249f8a
27 files changed
+3567 -392

No files matched your search

+53 -4
View File
@@ -3,12 +3,15 @@ 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 { musicRequestError } from "../../music/request-error.js";
import { YouTubeProvider } from "../../music/youtube.js";
import type { CookieStore } from "../../music/auth.js";
import type { Logger } from "../../logger.js";
import type { BotConfig, JellyfinConfig } from "../../data/config.js";
import type { BotDatabase } from "../../data/database.js";
import { requirePermission } from "../middleware/requirePermission.js";
import { requireNotGuest } from "../middleware/requireNotGuest.js";
import { resolveMusicCookie } from "./provider-scope.js";
export function createAuthRouter(
neteaseProvider: MusicProvider,
@@ -19,7 +22,10 @@ export function createAuthRouter(
kugouProvider?: MusicProvider,
spotifyProvider?: MusicProvider,
jellyfinProvider?: MusicProvider,
config?: BotConfig
config?: BotConfig,
// Per-user music accounts (#164 follow-up). Omitted by unit-test routers →
// every caller keeps seeing the bot's shared login status.
database?: BotDatabase,
): Router {
const router = Router();
const qqSession = qqProvider.managedSession;
@@ -40,13 +46,56 @@ export function createAuthRouter(
try {
const platform = req.query.platform as string;
const provider = getProvider(platform);
// Per-user accounts (#164 follow-up). Two different questions, two
// different answers:
//
// /api/auth/status → "is the BOT's shared login alive?" This is the
// admin console (Settings → 音乐平台), so an
// admin always gets the shared status even if
// they linked or were assigned a personal one.
// /api/me/music/status → "which account does THIS user actually play
// through?" (personal-music.ts) — that one does
// report the personal/granted view.
//
// For a non-admin the shared nickname/avatar must never be returned: that
// is exactly the leak this feature exists to close, so they get
// loggedIn:false instead until they have an account of their own.
const user = (req as { user?: { id?: string; role?: string } }).user;
// A platform without per-account login support (spotify / jellyfin /
// youtube) keeps reporting the shared status for everyone: the toggle only
// governs sources that can actually build a per-user view.
const perUser =
config?.perUserMusicAccounts === true &&
user?.role !== "admin" &&
typeof provider.withCookie === "function";
if (perUser) {
const own = resolveMusicCookie(req, provider.platform, { database, config });
if (own && typeof provider.withCookie === "function") {
const view = provider.withCookie(own.cookie);
const status = await view.getAuthStatus();
res.json({
platform: provider.platform,
personal: true,
source: own.source,
// Admin-facing name for an assigned account; absent for self-linked.
label: own.label,
...status,
});
return;
}
res.json({ platform: provider.platform, loggedIn: false, personal: true, source: "none" });
return;
}
const status = await provider.getAuthStatus();
logger.debug({ platform, loggedIn: status.loggedIn }, "Auth status check");
const renewal = platform === "qq" ? qqSession?.getStatus() : undefined;
res.json({ platform: provider.platform, ...status, ...renewal });
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 });
const error = musicRequestError(err);
logger.error({ err: error }, "Auth status check failed");
res.status(500).json({ error: error.message });
}
});
+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";
+10
View File
@@ -74,6 +74,7 @@ export function createBotRouter(
voiceDucking: config.voiceDucking,
localAudioEnabled: config.localAudioEnabled,
savedQueuesEnabled: config.savedQueuesEnabled,
perUserMusicAccounts: config.perUserMusicAccounts === true,
playKeepsQueue: config.playKeepsQueue,
// Silent re-resolve budget for a track whose URL came back empty.
playUrlRetries: config.playUrlRetries ?? 0,
@@ -97,6 +98,7 @@ export function createBotRouter(
guestMode,
adminGroups,
playUrlRetries,
perUserMusicAccounts,
} = req.body;
const hasIdle = idleTimeoutMinutes !== undefined;
@@ -121,10 +123,17 @@ export function createBotRouter(
return;
}
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;
if (hasLocalAudioEnabled) config.localAudioEnabled = localAudioEnabled;
if (hasPlayUrlRetries) config.playUrlRetries = playUrlRetries;
if (hasPerUserMusicAccounts) config.perUserMusicAccounts = perUserMusicAccounts;
// Voice ducking is a partial settings block. Merge only known, strictly
// valid fields so malformed JSON cannot replace the object or inject NaN /
@@ -299,6 +308,7 @@ export function createBotRouter(
voiceDucking: config.voiceDucking,
localAudioEnabled: config.localAudioEnabled,
savedQueuesEnabled: config.savedQueuesEnabled,
perUserMusicAccounts: config.perUserMusicAccounts === true,
playKeepsQueue: config.playKeepsQueue,
// Silent re-resolve budget for a track whose URL came back empty.
playUrlRetries: config.playUrlRetries ?? 0,
+273
View File
@@ -0,0 +1,273 @@
import { describe, it, expect, vi } from "vitest";
import express from "express";
import request from "supertest";
import pino from "pino";
import { createDatabase } from "../../data/database.js";
import { createUserStore } from "../../data/users.js";
import { createMusicAccountsRouter } from "./music-accounts.js";
function mount(opts: { cookieStore?: { save: any; load: any }; providers?: Record<string, any> } = {}) {
const db = createDatabase(":memory:");
const insert = db.db.prepare(
"INSERT INTO users (id, username, passwordHash, createdAt, updatedAt, role) VALUES (?,?,?,?,?,?)",
);
insert.run("u1", "alice", "x", 0, 0, "member");
insert.run("u2", "bob", "x", 0, 0, "member");
insert.run("u3", "carol", "x", 0, 0, "member");
insert.run("u4", "root2", "x", 0, 0, "admin");
const users = createUserStore(db.db);
const providers = opts.providers ?? {
netease: {
platform: "netease",
withCookie: vi.fn(() => ({ getAuthStatus: async () => ({ loggedIn: true, nickname: "主号" }) })),
},
};
const app = express();
app.use(express.json());
app.use((req, _res, next) => {
(req as any).user = { id: "admin", username: "admin", role: "admin" };
next();
});
app.use(
"/api/music-accounts",
createMusicAccountsRouter(db, users, providers as any, pino({ level: "silent" }), opts.cookieStore as any),
);
return { app, db, providers };
}
const SECRET = "MUSIC_U=abcdefghijklmnopqrstuvwxyz0123456789";
async function seed(app: express.Express, over: Record<string, unknown> = {}) {
const res = await request(app)
.post("/api/music-accounts")
.send({ platform: "netease", label: "主号", cookie: SECRET, ...over });
return res;
}
describe("admin music account pool", () => {
it("creates an account and never echoes the cookie", async () => {
const { app } = mount();
const res = await seed(app);
expect(res.status).toBe(201);
expect(res.body.label).toBe("主号");
expect(res.body.capacity).toBe(0);
expect(res.body.enabled).toBe(true);
expect(JSON.stringify(res.body)).not.toContain(SECRET);
expect(res.body.cookiePreview).toContain("…");
});
it("rejects an unknown platform and a missing cookie", async () => {
const { app } = mount();
expect((await seed(app, { platform: "deezer" })).status).toBe(400);
expect((await seed(app, { cookie: "" })).status).toBe(400);
expect((await seed(app, { label: "" })).status).toBe(400);
});
it("lists accounts with their holders and the assignable users", async () => {
const { app } = mount();
const created = await seed(app);
await request(app).post(`/api/music-accounts/${created.body.id}/assign`).send({ userId: "u1" });
const res = await request(app).get("/api/music-accounts");
expect(res.status).toBe(200);
expect(res.body.accounts).toHaveLength(1);
expect(res.body.accounts[0].granteeCount).toBe(1);
expect(res.body.accounts[0].grantees[0]).toMatchObject({ userId: "u1", username: "alice" });
// Guests are excluded from the dropdown by UserStore.listUsers().
expect(res.body.users.map((u: any) => u.username)).toEqual(["alice", "bob", "carol", "root2"]);
expect(JSON.stringify(res.body)).not.toContain(SECRET);
});
it("toggles enabled and capacity", async () => {
const { app } = mount();
const created = await seed(app);
const res = await request(app)
.patch(`/api/music-accounts/${created.body.id}`)
.send({ enabled: false, capacity: 1, label: "备用" });
expect(res.body).toEqual(expect.objectContaining({ enabled: false, capacity: 1, label: "备用" }));
});
it("enforces exclusive capacity (capacity = 1)", async () => {
const { app } = mount();
const created = await seed(app, { capacity: 1 });
const id = created.body.id;
expect((await request(app).post(`/api/music-accounts/${id}/assign`).send({ userId: "u1" })).status).toBe(200);
const second = await request(app).post(`/api/music-accounts/${id}/assign`).send({ userId: "u2" });
expect(second.status).toBe(409);
expect(second.body.error).toBe("account_exclusive");
expect(second.body.holders).toEqual([{ userId: "u1", username: "alice" }]);
// Re-assigning the SAME user is idempotent, not a conflict.
expect((await request(app).post(`/api/music-accounts/${id}/assign`).send({ userId: "u1" })).status).toBe(200);
});
it("enforces a numeric capacity", async () => {
const { app } = mount();
const created = await seed(app, { capacity: 2 });
const id = created.body.id;
expect((await request(app).post(`/api/music-accounts/${id}/assign`).send({ userId: "u1" })).status).toBe(200);
expect((await request(app).post(`/api/music-accounts/${id}/assign`).send({ userId: "u2" })).status).toBe(200);
const third = await request(app).post(`/api/music-accounts/${id}/assign`).send({ userId: "u3" });
expect(third.status).toBe(409);
expect(third.body.error).toBe("account_full");
});
it("allows unlimited grantees when capacity is 0", async () => {
const { app } = mount();
const created = await seed(app);
for (const userId of ["u1", "u2", "u3", "u4"]) {
expect(
(await request(app).post(`/api/music-accounts/${created.body.id}/assign`).send({ userId })).status,
).toBe(200);
}
// An admin can be a grantee too — "assigning an admin out" is allowed.
const list = await request(app).get("/api/music-accounts");
expect(list.body.accounts[0].grantees.map((g: any) => g.username).sort()).toEqual([
"alice", "bob", "carol", "root2",
]);
});
it("refuses an assignment to a missing user", async () => {
const { app } = mount();
const created = await seed(app);
expect(
(await request(app).post(`/api/music-accounts/${created.body.id}/assign`).send({ userId: "nope" })).status,
).toBe(404);
});
it("refuses an assignment from a disabled account", async () => {
const { app } = mount();
const created = await seed(app, { enabled: false });
const res = await request(app)
.post(`/api/music-accounts/${created.body.id}/assign`)
.send({ userId: "u1" });
expect(res.status).toBe(409);
expect(res.body.error).toBe("account_disabled");
});
it("replaces the previous assignment for the same platform", async () => {
const { app, db } = mount();
const first = await seed(app, { label: "一号" });
const second = await seed(app, { label: "二号" });
await request(app).post(`/api/music-accounts/${first.body.id}/assign`).send({ userId: "u1" });
const res = await request(app)
.post(`/api/music-accounts/${second.body.id}/assign`)
.send({ userId: "u1" });
expect(res.body.replacedAccountId).toBe(first.body.id);
// PK (userId, platform) keeps it to one assigned login per platform.
const grants = db.listAllMusicAccountGrants().filter((g) => g.userId === "u1");
expect(grants).toHaveLength(1);
expect(grants[0].accountId).toBe(second.body.id);
});
it("revokes a single assignment", async () => {
const { app, db } = mount();
const created = await seed(app);
await request(app).post(`/api/music-accounts/${created.body.id}/assign`).send({ userId: "u1" });
const res = await request(app).delete(`/api/music-accounts/${created.body.id}/assign/u1`);
expect(res.body).toEqual({ ok: true, removed: true });
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();
const created = await seed(app);
await request(app).post(`/api/music-accounts/${created.body.id}/assign`).send({ userId: "u1" });
expect((await request(app).delete(`/api/music-accounts/${created.body.id}`)).status).toBe(200);
expect(db.listMusicAccounts()).toHaveLength(0);
expect(db.getGrantedMusicAccount("u1", "netease")).toBeNull();
});
it("probes the login and reports unsupported platforms", async () => {
const { app } = mount();
const created = await seed(app);
const ok = await request(app).post(`/api/music-accounts/${created.body.id}/probe`);
expect(ok.body).toEqual({ ok: true, loggedIn: true, nickname: "主号" });
// kugou without a withCookie implementation → 501, not a crash.
const kugou = await seed(app, { platform: "kugou", label: "酷狗" });
expect(kugou.status).toBe(201);
expect((await request(app).post(`/api/music-accounts/${kugou.body.id}/probe`)).status).toBe(501);
});
it("imports the shared login into the pool", async () => {
const cookieStore = {
save: vi.fn(),
load: vi.fn(() => "MUSIC_U=shared"),
};
const { app } = mount({ cookieStore });
const res = await request(app)
.post("/api/music-accounts/import-shared")
.send({ platform: "netease", label: "从共享导入" });
expect(res.status).toBe(201);
expect(res.body.label).toBe("从共享导入");
expect(cookieStore.load).toHaveBeenCalledWith("netease");
});
it("409s import-shared when the bot has no shared login", async () => {
const cookieStore = { save: vi.fn(), load: vi.fn(() => "") };
const { app } = mount({ cookieStore });
const res = await request(app)
.post("/api/music-accounts/import-shared")
.send({ platform: "netease" });
expect(res.status).toBe(409);
expect(res.body.error).toBe("no_shared_login");
});
it("imports the running QQ cookie instead of the stale file copy", async () => {
const cookieStore = { save: vi.fn(), load: vi.fn(() => "uin=999; qm_keyst=stale") };
const qq = {
platform: "qq",
withCookie: vi.fn(),
// 托管会话轮换后,内存里已经是新 cookie,qq.json 还是旧的
getCookie: () => "uin=1; qm_keyst=rotated",
};
const { app, db } = mount({ cookieStore, providers: { qq } });
const res = await request(app)
.post("/api/music-accounts/import-shared")
.send({ platform: "qq", label: "QQ 主号" });
expect(res.status).toBe(201);
expect(db.listMusicAccounts()[0]?.cookie).toBe("uin=1; qm_keyst=rotated");
expect(cookieStore.load).not.toHaveBeenCalled();
// cookie 不出服务器:响应里不能出现完整值
expect(JSON.stringify(res.body)).not.toContain("rotated");
});
it("409s a QQ import when the running provider has no login", async () => {
const cookieStore = { save: vi.fn(), load: vi.fn(() => "uin=999; qm_keyst=stale") };
const qq = { platform: "qq", withCookie: vi.fn(), getCookie: () => "" };
const { app, db } = mount({ cookieStore, providers: { qq } });
const res = await request(app)
.post("/api/music-accounts/import-shared")
.send({ platform: "qq" });
expect(res.status).toBe(409);
expect(res.body.error).toBe("no_shared_login");
expect(db.listMusicAccounts()).toHaveLength(0);
});
});
+360
View File
@@ -0,0 +1,360 @@
import { Router } from "express";
import type { BotDatabase, MusicAccount } from "../../data/database.js";
import type { MusicProvider } from "../../music/provider.js";
import type { CookieStore } from "../../music/auth.js";
import type { UserStore } from "../../data/users.js";
import type { Logger } from "../../logger.js";
import { PERSONAL_MUSIC_PLATFORMS } from "./personal-music.js";
/**
* Admin console for the music-account pool (#164 follow-up).
*
* Why a pool instead of "everyone links their own account":
* - Most members do not own a paid NetEase/QQ/Kugou login, and the bot's
* shared account is usually the ADMIN's. Handing the shared login to some
* members while giving others their own is exactly the "mixed" case this
* feature has to support.
* - So the admin keeps a pool of logins (`music_accounts`) and assigns one to
* a member (`music_account_grants`). Assignment is per platform, and a
* member can hold at most one assigned account per platform.
*
* The controls that stop assignments from turning into a mess:
* 1. OWN BEATS ASSIGNED. A member who linked their own account ignores the
* assignment entirely (see provider-scope.ts). Assigning never overrides
* a member's own login.
* 2. CAPACITY. `capacity = 1` means exclusive: the API refuses to hand the
* same login to a second member (409). `capacity = 0` means unlimited
* (fine for a throwaway account, NOT for one whose recommendations you
* care about — every grantee writes to that account's history).
* 3. ENABLED FLAG. Disabling an account is an instant, reversible rollback:
* every grantee falls back to their own login / the shared login without
* the grants being deleted.
* 4. DELETE CASCADES. Removing an account deletes its grants in the same
* transaction (FK ON DELETE CASCADE), so no member is left pointing at a
* row that no longer exists.
* 5. COOKIES NEVER LEAVE THE SERVER. Every response carries a masked
* preview only; the full value is only ever written, never read back.
*
* The whole router is admin-only (requireAdmin at the mount point): a member
* with `bot.manage` still must not see what other people are assigned.
*/
export function createMusicAccountsRouter(
database: BotDatabase,
users: UserStore,
providers: Partial<Record<string, MusicProvider>>,
logger: Logger,
cookieStore?: CookieStore,
): Router {
const router = Router();
const knownPlatforms = new Set<string>(PERSONAL_MUSIC_PLATFORMS);
/**
* Cookies are bearer credentials: showing one in full once is enough to take
* the account over. The console only ever needs to tell two logins apart.
*/
const maskCookie = (cookie: string): string => {
if (!cookie) return "";
if (cookie.length <= 16) return "••••••";
return `${cookie.slice(0, 6)}…${cookie.slice(-4)} (${cookie.length} 字符)`;
};
const toWire = (a: MusicAccount) => {
const holders = database.listMusicAccountGrants(a.id);
return {
id: a.id,
platform: a.platform,
label: a.label,
cookiePreview: maskCookie(a.cookie),
ownerId: a.ownerId,
capacity: a.capacity,
enabled: a.enabled,
createdAt: a.createdAt,
updatedAt: a.updatedAt,
// The UI needs the count to grey out "assign" on an exclusive account.
granteeCount: holders.length,
grantees: holders.map((g) => ({
userId: g.userId,
username: g.username,
grantedAt: g.grantedAt,
})),
// A platform without withCookie stores the cookie but cannot build a
// per-account view yet — surfaced so the admin is not left guessing.
playbackSupported: typeof providers[a.platform]?.withCookie === "function",
};
};
const isPlatform = (v: unknown): v is (typeof PERSONAL_MUSIC_PLATFORMS)[number] =>
typeof v === "string" && knownPlatforms.has(v);
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 }));
router.get("/", (_req, res) => {
const accounts = database.listMusicAccounts().map(toWire);
res.json({
accounts,
users: assignableUsers(),
platforms: [...PERSONAL_MUSIC_PLATFORMS].map((p) => ({
platform: p,
// Only platforms that implement withCookie can actually play back a
// per-user login; the rest accept a paste but fall back to shared.
playbackSupported: typeof providers[p]?.withCookie === "function",
})),
});
});
router.post("/", (req, res) => {
const { platform, label, cookie, capacity, ownerId, enabled } = req.body ?? {};
if (!isPlatform(platform)) {
res.status(400).json({ error: "unsupported platform" });
return;
}
if (!nonEmpty(label, 64)) {
res.status(400).json({ error: "label is required (max 64 chars)" });
return;
}
if (!nonEmpty(cookie, 8192)) {
res.status(400).json({ error: "cookie is required" });
return;
}
if (!validCapacity(capacity)) {
res.status(400).json({ error: "capacity must be a non-negative integer" });
return;
}
if (ownerId !== undefined && ownerId !== null && typeof ownerId !== "string") {
res.status(400).json({ error: "ownerId must be a string or null" });
return;
}
if (enabled !== undefined && typeof enabled !== "boolean") {
res.status(400).json({ error: "enabled must be a boolean" });
return;
}
const created = database.createMusicAccount({
platform,
label: label.trim(),
cookie: cookie.trim(),
ownerId: ownerId ?? null,
capacity,
// Creating a disabled account is allowed: it lets the admin stage a
// cookie before handing it out.
enabled: enabled !== false,
});
logger.info({ accountId: created.id, platform, label: created.label }, "Music account added");
res.status(201).json(toWire(created));
});
router.patch("/:id", (req, res) => {
const account = database.getMusicAccount(req.params.id);
if (!account) {
res.status(404).json({ error: "not found" });
return;
}
const { label, cookie, capacity, enabled } = req.body ?? {};
if (label !== undefined && !nonEmpty(label, 64)) {
res.status(400).json({ error: "invalid label" });
return;
}
if (cookie !== undefined && !nonEmpty(cookie, 8192)) {
res.status(400).json({ error: "invalid cookie" });
return;
}
if (!validCapacity(capacity)) {
res.status(400).json({ error: "capacity must be a non-negative integer" });
return;
}
if (enabled !== undefined && typeof enabled !== "boolean") {
res.status(400).json({ error: "enabled must be a boolean" });
return;
}
// 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.
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",
);
res.json(toWire(database.getMusicAccount(account.id)!));
});
router.delete("/:id", (req, res) => {
const account = database.getMusicAccount(req.params.id);
if (!account) {
res.status(404).json({ error: "not found" });
return;
}
// FK ON DELETE CASCADE removes the grants with it, so no member is left
// pointing at a deleted row. `changes` on the parent is what we report.
const deleted = database.deleteMusicAccount(account.id);
logger.info(
{ accountId: account.id, platform: account.platform, deleted },
"Music account removed",
);
res.json({ ok: deleted, revokedGrants: true });
});
/**
* Assign an account to a user (member OR another admin — an admin can be a
* grantee too, they are just not forced onto the shared login).
*/
router.post("/:id/assign", (req, res) => {
const account = database.getMusicAccount(req.params.id);
if (!account) {
res.status(404).json({ error: "not_found" });
return;
}
const { userId } = req.body ?? {};
if (typeof userId !== "string" || !userId) {
res.status(400).json({ error: "userId is required" });
return;
}
const target = users.findById(userId);
if (!target || target.role === "guest") {
res.status(404).json({ error: "user not found" });
return;
}
// Enabled + capacity are enforced inside a single transaction in the data
// layer, so two concurrent assignments cannot both slip past the check.
const result = database.assignMusicAccount(userId, account.id, req.user!.id);
if (!result.ok) {
if (result.reason === "not_found") {
res.status(404).json({ error: "not_found" });
return;
}
if (result.reason === "disabled") {
res.status(409).json({ error: "account_disabled" });
return;
}
const holders = database.listMusicAccountGrants(account.id).map((h) => ({
userId: h.userId,
username: h.username,
}));
if (result.reason === "exclusive") {
res.status(409).json({ error: "account_exclusive", holders });
return;
}
res.status(409).json({ error: "account_full", capacity: account.capacity, holders });
return;
}
logger.info(
{ accountId: account.id, userId, replacedAccountId: result.replacedAccountId },
"Music account assigned",
);
res.json({
ok: true,
userId,
username: target.username,
accountId: account.id,
platform: account.platform,
replacedAccountId: result.replacedAccountId,
});
});
router.delete("/:id/assign/:userId", (req, res) => {
const account = database.getMusicAccount(req.params.id);
if (!account) {
res.status(404).json({ error: "not found" });
return;
}
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",
);
res.json({ ok: true, removed });
});
/** Live check: is this cookie still logged in? */
router.post("/:id/probe", async (req, res) => {
const account = database.getMusicAccount(req.params.id);
if (!account) {
res.status(404).json({ error: "not found" });
return;
}
const provider = providers[account.platform];
if (!provider || typeof provider.withCookie !== "function") {
res.status(501).json({ error: "playback not supported for this platform" });
return;
}
try {
const status = await provider.withCookie(account.cookie).getAuthStatus();
res.json({ ok: true, ...status });
} catch {
logger.warn({ accountId: account.id }, "Music account probe failed");
res.status(502).json({ error: "music_account_probe_failed", loggedIn: false });
}
});
/**
* Seed the pool with the login the bot already uses, so an admin who scanned
* the shared account can hand it to selected members without re-scanning.
*/
router.post("/import-shared", (req, res) => {
const { platform, label, capacity } = req.body ?? {};
// QQ 的共享登录以"运行中的 provider"为准:登录写的是它内存里的 cookie,
// qq.json 只是落盘副本。托管会话轮换凭据之后文件就旧了(#188),
// 从这里导入会把一个过期 cookie 塞进账号池。
const sharedQq = platform === "qq" ? providers.qq : undefined;
if (!sharedQq && !cookieStore) {
res.status(501).json({ error: "cookie store unavailable" });
return;
}
if (!isPlatform(platform)) {
res.status(400).json({ error: "unsupported platform" });
return;
}
if (!validCapacity(capacity)) {
res.status(400).json({ error: "capacity must be a non-negative integer" });
return;
}
// 没有 qq provider(例如单测只挂了 netease)时仍然回落到 cookie store,
// 所以这个改动对已有平台零影响。
let cookie: string | undefined;
if (sharedQq) {
try {
cookie = sharedQq.getCookie();
} catch {
// Provider 还没建立登录态时抛错等价于「没有可导入的登录」
cookie = "";
}
} else {
cookie = cookieStore?.load(platform);
}
if (!cookie || !cookie.trim()) {
res.status(409).json({ error: "no_shared_login", platform });
return;
}
const created = database.createMusicAccount({
platform,
label: nonEmpty(label, 64) ? label.trim() : `${platform} 共享账号`,
cookie: cookie.trim(),
// ownerId stays null: this login was provided by the bot, not a person.
ownerId: null,
capacity,
enabled: true,
});
logger.info({ accountId: created.id, platform }, "Shared login imported into pool");
res.status(201).json(toWire(created));
});
return router;
}
+13
View File
@@ -3,6 +3,7 @@ import express from "express";
import cookieParser from "cookie-parser";
import request from "supertest";
import pino from "pino";
import { AxiosError } from "axios";
import { mkdtempSync, rmSync, readFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
@@ -58,6 +59,18 @@ describe("music router GET /search offset pagination", () => {
expect(res.status).toBe(200);
expect(netease.search).toHaveBeenCalledWith("hello", 20, 0);
});
it("keeps provider request credentials out of search errors", async () => {
const logger = pino({ level: "silent" });
const logError = vi.spyOn(logger, "error");
const privateCookie = "MUSIC_U=test-private-session";
vi.mocked(netease.search).mockRejectedValueOnce(new AxiosError(`Provider request failed: ${privateCookie}`));
const route = express();
route.use("/api/music", createMusicRouter(netease, fakeProvider("qq"), fakeProvider("bilibili"), logger));
const res = await request(route).get("/api/music/search?q=test").expect(500);
expect(res.text).not.toContain(privateCookie);
expect(JSON.stringify(logError.mock.calls)).not.toContain(privateCookie);
});
});
describe("music router provider gating (enabledProviders) + jellyfin endpoints", () => {
+71 -36
View File
@@ -1,11 +1,14 @@
import express, { Router, type Response } from "express";
import express, { Router, type Request, type Response } from "express";
import type { MusicProvider, Song, Album, SearchResult } from "../../music/provider.js";
import { musicRequestError } from "../../music/request-error.js";
import { YouTubeProvider } from "../../music/youtube.js";
import type { Logger } from "../../logger.js";
import { isProviderEnabled, defaultPlatform, saveConfig, type BotConfig } from "../../data/config.js";
import type { BotDatabase } from "../../data/database.js";
import { requirePermission } from "../middleware/requirePermission.js";
import { requireNotGuest } from "../middleware/requireNotGuest.js";
import { authorize } from "../middleware/authorize.js";
import { resolveProviderForRequest } from "./provider-scope.js";
/**
* Body cap for a local upload. express.raw buffers the whole body in memory,
@@ -70,6 +73,10 @@ export function createMusicRouter(
// When set (alongside config), a quality change is persisted to config.json so
// it survives a restart (#125). Omitted by unit-test routers → no persistence.
configPath?: string,
// Per-user music accounts (#164 follow-up): when config.perUserMusicAccounts
// is on, a request carrying a linked account reads through that account
// instead of the bot's shared login. Omitted by unit-test routers → shared.
database?: BotDatabase,
): Router {
const router = Router();
const youtubeProvider: MusicProvider = new YouTubeProvider();
@@ -95,14 +102,25 @@ export function createMusicRouter(
* return immediately. Without a config (unit-test routers), everything
* stays enabled.
*/
function resolveProvider(platform: unknown, res: Response): MusicProvider | null {
function resolveProvider(
platform: unknown,
res: Response,
req?: Request,
): MusicProvider | null {
const requested = typeof platform === "string" && platform ? platform : undefined;
const target = requested ?? (config ? defaultPlatform(config) : "netease");
if (config && !isProviderEnabled(config, target)) {
res.status(400).json({ error: `音源未启用:${target} (provider disabled)` });
return null;
}
return getProvider(target);
// Per-user accounts: with the feature on, a user who linked their own
// 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), {
database,
config,
});
}
router.post(
@@ -164,7 +182,7 @@ export function createMusicRouter(
res.json({ songs: [], playlists: [], albums: [] });
return;
}
const provider = resolveProvider(platform, res);
const provider = resolveProvider(platform, res, req);
if (!provider) return;
// Server-side pagination: offset lets the web load past the first page.
// Clamp to >= 0 so a bad/negative value falls back to the first page.
@@ -176,8 +194,9 @@ export function createMusicRouter(
);
res.json(result);
} catch (err) {
logger.error({ err }, "Search failed");
res.status(500).json({ error: (err as Error).message });
const error = musicRequestError(err);
logger.error({ err: error }, "Search failed");
res.status(500).json({ error: error.message });
}
});
@@ -199,13 +218,24 @@ export function createMusicRouter(
// enabled — a self-hosted library match is almost always the wanted one.
const enabled = (p: string) => !config || isProviderEnabled(config, p);
const none: SearchResult = { songs: [], albums: [], playlists: [] };
// Unified search hits every source at once, so each one has to be scoped
// individually — otherwise a member with their own linked account would
// still get the admin's results merged in from the other platforms.
// Local audio and Jellyfin have no per-account login, so they stay shared.
const scope = { database, config };
const nProvider = resolveProviderForRequest(req, "netease", neteaseProvider, scope);
const qProvider = resolveProviderForRequest(req, "qq", qqProvider, scope);
const bProvider = resolveProviderForRequest(req, "bilibili", bilibiliProvider, scope);
const kProvider = kugouProvider
? resolveProviderForRequest(req, "kugou", kugouProvider, scope)
: kugouProvider;
const [jellyfinResult, neteaseResult, qqResult, bilibiliResult, localResult, kugouResult] = await Promise.allSettled([
jellyfinProvider && enabled("jellyfin") ? jellyfinProvider.search(q as string, parsedLimit) : Promise.resolve(none),
enabled("netease") ? neteaseProvider.search(q as string, parsedLimit) : Promise.resolve(none),
enabled("qq") ? qqProvider.search(q as string, parsedLimit) : Promise.resolve(none),
enabled("bilibili") ? bilibiliProvider.search(q as string, parsedLimit) : Promise.resolve(none),
enabled("netease") ? nProvider.search(q as string, parsedLimit) : Promise.resolve(none),
enabled("qq") ? qProvider.search(q as string, parsedLimit) : Promise.resolve(none),
enabled("bilibili") ? bProvider.search(q as string, parsedLimit) : Promise.resolve(none),
localProvider && isLocalAudioEnabled() ? localProvider.search(q as string, parsedLimit) : Promise.resolve(none),
kugouProvider && enabled("kugou") ? kugouProvider.search(q as string, parsedLimit) : Promise.resolve(none),
kProvider && enabled("kugou") ? kProvider.search(q as string, parsedLimit) : Promise.resolve(none),
]);
const songs = [
@@ -235,8 +265,9 @@ export function createMusicRouter(
res.json({ songs, albums, playlists, artists });
} catch (err) {
logger.error({ err }, "Unified search failed");
res.status(500).json({ error: (err as Error).message });
const error = musicRequestError(err);
logger.error({ err: error }, "Unified search failed");
res.status(500).json({ error: error.message });
}
});
@@ -246,7 +277,7 @@ export function createMusicRouter(
res.status(403).json({ error: "本地音频播放已关闭" });
return;
}
const provider = resolveProvider(req.query.platform, res);
const provider = resolveProvider(req.query.platform, res, req);
if (!provider) return;
const song = await provider.getSongDetail(req.params.id);
if (!song) {
@@ -255,57 +286,57 @@ export function createMusicRouter(
}
res.json(song);
} catch (err) {
res.status(500).json({ error: (err as Error).message });
res.status(500).json({ error: musicRequestError(err).message });
}
});
router.get("/playlist/:id", async (req, res) => {
try {
const provider = resolveProvider(req.query.platform, res);
const provider = resolveProvider(req.query.platform, res, req);
if (!provider) return;
const songs = await provider.getPlaylistSongs(req.params.id);
res.json({ songs });
} catch (err) {
res.status(500).json({ error: (err as Error).message });
res.status(500).json({ error: musicRequestError(err).message });
}
});
router.get("/recommend/playlists", async (req, res) => {
try {
const provider = resolveProvider(req.query.platform, res);
const provider = resolveProvider(req.query.platform, res, req);
if (!provider) return;
const playlists = await provider.getRecommendPlaylists();
res.json({ playlists });
} catch (err) {
res.status(500).json({ error: (err as Error).message });
res.status(500).json({ error: musicRequestError(err).message });
}
});
router.get("/album/:id", async (req, res) => {
try {
const provider = resolveProvider(req.query.platform, res);
const provider = resolveProvider(req.query.platform, res, req);
if (!provider) return;
const songs = await provider.getAlbumSongs(req.params.id);
res.json({ songs });
} catch (err) {
res.status(500).json({ error: (err as Error).message });
res.status(500).json({ error: musicRequestError(err).message });
}
});
router.get("/lyrics/:id", async (req, res) => {
try {
const provider = resolveProvider(req.query.platform, res);
const provider = resolveProvider(req.query.platform, res, req);
if (!provider) return;
const lyrics = await provider.getLyrics(req.params.id);
res.json({ lyrics });
} catch (err) {
res.status(500).json({ error: (err as Error).message });
res.status(500).json({ error: musicRequestError(err).message });
}
});
router.get("/artist/:id", async (req, res) => {
try {
const provider = resolveProvider(req.query.platform, res);
const provider = resolveProvider(req.query.platform, res, req);
if (!provider) return;
if (!provider.getArtistDetail) {
res.status(501).json({ error: "Not supported by this provider" });
@@ -329,13 +360,13 @@ export function createMusicRouter(
}
res.json({ artist, songs, albums });
} catch (err) {
res.status(500).json({ error: (err as Error).message });
res.status(500).json({ error: musicRequestError(err).message });
}
});
router.get("/recommend/songs", requireNotGuest, async (req, res) => {
try {
const provider = resolveProvider(req.query.platform, res);
const provider = resolveProvider(req.query.platform, res, req);
if (!provider) return;
if (!provider.getDailyRecommendSongs) {
res.status(501).json({ error: "Not supported by this provider" });
@@ -344,14 +375,15 @@ export function createMusicRouter(
const songs = await provider.getDailyRecommendSongs();
res.json({ songs });
} catch (err) {
logger.error({ err }, "Get daily recommend songs failed");
res.status(500).json({ error: (err as Error).message });
const error = musicRequestError(err);
logger.error({ err: error }, "Get daily recommend songs failed");
res.status(500).json({ error: error.message });
}
});
router.get("/personal/fm", requireNotGuest, async (req, res) => {
try {
const provider = resolveProvider(req.query.platform, res);
const provider = resolveProvider(req.query.platform, res, req);
if (!provider) return;
if (!provider.getPersonalFm) {
res.status(501).json({ error: "Not supported by this provider" });
@@ -360,14 +392,15 @@ export function createMusicRouter(
const songs = await provider.getPersonalFm();
res.json({ songs });
} catch (err) {
logger.error({ err }, "Get personal FM failed");
res.status(500).json({ error: (err as Error).message });
const error = musicRequestError(err);
logger.error({ err: error }, "Get personal FM failed");
res.status(500).json({ error: error.message });
}
});
router.get("/user/playlists", requireNotGuest, async (req, res) => {
try {
const provider = resolveProvider(req.query.platform, res);
const provider = resolveProvider(req.query.platform, res, req);
if (!provider) return;
if (!provider.getUserPlaylists) {
res.status(501).json({ error: "Not supported by this provider" });
@@ -376,14 +409,15 @@ export function createMusicRouter(
const playlists = await provider.getUserPlaylists();
res.json({ playlists });
} catch (err) {
logger.error({ err }, "Get user playlists failed");
res.status(500).json({ error: (err as Error).message });
const error = musicRequestError(err);
logger.error({ err: error }, "Get user playlists failed");
res.status(500).json({ error: error.message });
}
});
router.get("/playlist/:id/detail", async (req, res) => {
try {
const provider = resolveProvider(req.query.platform, res);
const provider = resolveProvider(req.query.platform, res, req);
if (!provider) return;
if (!provider.getPlaylistDetail) {
res.status(501).json({ error: "Not supported by this provider" });
@@ -396,8 +430,9 @@ export function createMusicRouter(
}
res.json({ playlist: detail });
} catch (err) {
logger.error({ err }, "Get playlist detail failed");
res.status(500).json({ error: (err as Error).message });
const error = musicRequestError(err);
logger.error({ err: error }, "Get playlist detail failed");
res.status(500).json({ error: error.message });
}
});
+164 -4
View File
@@ -6,7 +6,10 @@ import { createDatabase } from "../../data/database.js";
import { createPersonalMusicRouter } from "./personal-music.js";
import { createPlayerRouter } from "./player.js";
function mount() {
function mount(opts: {
config?: { perUserMusicAccounts?: boolean };
extraProviders?: Record<string, unknown>;
} = {}) {
const db = createDatabase(":memory:");
db.db
.prepare("INSERT INTO users (id, username, passwordHash, createdAt, updatedAt, role) VALUES (?,?,?,?,?,?)")
@@ -27,16 +30,38 @@ function mount() {
(req as any).user = { id: "u1", username: "alice", role: "member" };
next();
});
app.use("/api/me/music", createPersonalMusicRouter(db, provider, pino({ level: "silent" })));
app.use(
"/api/me/music",
createPersonalMusicRouter(
db,
{ netease: provider, ...(opts.extraProviders as object) },
pino({ level: "silent" }),
opts.config,
),
);
return { app, db, provider, personalView };
}
/** Seed an admin-owned account and assign it to u1. */
function assignAccount(db: ReturnType<typeof createDatabase>, label = "网易云-主号") {
const account = db.createMusicAccount({
platform: "netease",
label,
cookie: "MUSIC_U=granted",
});
db.assignMusicAccount("u1", account.id, "admin");
return account;
}
describe("personal music account router (#164)", () => {
it("reports not linked until the user logs in", async () => {
const { app } = mount();
const res = await request(app).get("/api/me/music/netease/status");
expect(res.status).toBe(200);
expect(res.body).toEqual({ linked: false, loggedIn: false });
expect(res.body).toEqual({
linked: false, loggedIn: false, source: "none", canUnlink: false, supportsQrLogin: true,
preferShared: false, featureEnabled: false,
});
});
it("creates a QR code", async () => {
@@ -64,7 +89,16 @@ describe("personal music account router (#164)", () => {
const { app, db, provider } = mount();
db.setUserMusicCookie("u1", "netease", "MUSIC_U=alice");
const res = await request(app).get("/api/me/music/netease/status");
expect(res.body).toEqual({ linked: true, loggedIn: true, nickname: "Alice163" });
expect(res.body).toEqual({
linked: true,
source: "personal",
canUnlink: true,
supportsQrLogin: true,
preferShared: false,
featureEnabled: false,
loggedIn: true,
nickname: "Alice163",
});
expect(provider.withCookie).toHaveBeenCalledWith("MUSIC_U=alice");
});
@@ -74,6 +108,62 @@ describe("personal music account router (#164)", () => {
expect((await request(app).delete("/api/me/music/netease")).status).toBe(200);
expect(db.getUserMusicCookie("u1", "netease")).toBeNull();
});
// 404 for a platform this build does not expose — keeps the param route from
// silently answering "not linked" for a typo'd URL.
it("404s an unknown platform", async () => {
const { app } = mount();
expect((await request(app).get("/api/me/music/deezer/status")).status).toBe(404);
});
// qq/kugou/bilibili ship withCookie but not pollQrLogin yet: linking is 501,
// while an admin-assigned account still works (see below).
it("501s QR login on a platform without per-user polling", async () => {
const { app } = mount({ extraProviders: { qq: { platform: "qq", withCookie: vi.fn() } } });
expect((await request(app).post("/api/me/music/qq/qrcode")).status).toBe(501);
});
describe("admin-assigned account", () => {
it("reports source=granted with the admin's label and forbids unlinking", async () => {
const { app, db, provider } = mount({ config: { perUserMusicAccounts: true } });
assignAccount(db);
const res = await request(app).get("/api/me/music/netease/status");
expect(res.body).toEqual({
linked: true,
source: "granted",
label: "网易云-主号",
canUnlink: false,
supportsQrLogin: true,
preferShared: false,
featureEnabled: true,
loggedIn: true,
nickname: "Alice163",
});
expect(provider.withCookie).toHaveBeenCalledWith("MUSIC_U=granted");
});
it("is invisible while the admin toggle is off", async () => {
const { app, db } = mount({ config: { perUserMusicAccounts: false } });
assignAccount(db);
const res = await request(app).get("/api/me/music/netease/status");
expect(res.body).toEqual({
linked: false, loggedIn: false, source: "none", canUnlink: false, supportsQrLogin: true,
preferShared: false, featureEnabled: false,
});
});
// Unlinking on the member side must never revoke what the admin granted:
// the two live in separate tables on purpose.
it("survives a member unlink and is reported as the fallback", async () => {
const { app, db } = mount({ config: { perUserMusicAccounts: true } });
assignAccount(db);
db.setUserMusicCookie("u1", "netease", "MUSIC_U=alice");
const res = await request(app).delete("/api/me/music/netease");
expect(res.body).toEqual({ ok: true, removed: true, fallback: "granted" });
expect(db.getUserMusicCookie("u1", "netease")).toBeNull();
expect(db.getGrantedMusicAccount("u1", "netease")?.cookie).toBe("MUSIC_U=granted");
});
});
});
describe("web FM uses the caller's linked NetEase account (#164)", () => {
@@ -123,3 +213,73 @@ describe("web FM uses the caller's linked NetEase account (#164)", () => {
expect(bot.startFm.mock.calls[0][0]).toBe(qq);
});
});
// ---------------------------------------------------------------------------
// "Play through the shared account" preference (#164 follow-up)
//
// The case this exists for: the member's own NetEase login has no VIP, the
// admin's does. The preference is per-platform and per-user, and it must not
// touch either stored login.
// ---------------------------------------------------------------------------
describe("personal music — shared-account preference", () => {
const ON = { config: { perUserMusicAccounts: true } };
it("defaults to the member's own account", async () => {
const { app } = mount(ON);
const res = await request(app).get("/api/me/music/netease/preference");
expect(res.status).toBe(200);
expect(res.body).toEqual({ platform: "netease", preferShared: false });
});
it("stores the choice and reports it back", async () => {
const { app } = mount(ON);
const put = await request(app).put("/api/me/music/netease/preference").send({ preferShared: true });
expect(put.status).toBe(200);
expect(put.body).toEqual({ platform: "netease", preferShared: true });
const get = await request(app).get("/api/me/music/netease/preference");
expect(get.body.preferShared).toBe(true);
});
it("keeps the choice per platform", async () => {
const { app } = mount({
...ON,
extraProviders: { qq: { platform: "qq", withCookie: () => ({ getAuthStatus: async () => ({ loggedIn: true }) }) } },
});
await request(app).put("/api/me/music/netease/preference").send({ preferShared: true });
const qq = await request(app).get("/api/me/music/qq/preference");
expect(qq.body.preferShared).toBe(false);
});
it("does not touch the stored login", async () => {
const { app, db } = mount(ON);
db.setUserMusicCookie("u1", "netease", "MUSIC_U=mine");
await request(app).put("/api/me/music/netease/preference").send({ preferShared: true });
expect(db.getUserMusicCookie("u1", "netease")).toBe("MUSIC_U=mine");
expect(db.getUserMusicPreference("u1", "netease")).toEqual({ preferShared: true });
});
it("surfaces the choice on the status payload the UI already reads", async () => {
const { app, db } = mount(ON);
db.setUserMusicCookie("u1", "netease", "MUSIC_U=mine");
await request(app).put("/api/me/music/netease/preference").send({ preferShared: true });
const res = await request(app).get("/api/me/music/netease/status");
expect(res.body.preferShared).toBe(true);
expect(res.body.featureEnabled).toBe(true);
});
it("rejects a non-boolean", async () => {
const { app } = mount(ON);
const res = await request(app).put("/api/me/music/netease/preference").send({ preferShared: "yes" });
expect(res.status).toBe(400);
});
it("refuses when the admin has the feature off", async () => {
const { app } = mount({ config: { perUserMusicAccounts: false } });
const res = await request(app).put("/api/me/music/netease/preference").send({ preferShared: true });
expect(res.status).toBe(409);
expect(res.body.error).toBe("per_user_accounts_disabled");
});
});
+184 -27
View File
@@ -2,6 +2,7 @@ import { Router } from "express";
import type { BotDatabase } from "../../data/database.js";
import type { MusicProvider, QrCodeResult } from "../../music/provider.js";
import type { Logger } from "../../logger.js";
import { perUserMusicEnabled, type MusicScopeDeps } from "./provider-scope.js";
/**
* A provider that can log a web user into their OWN account without touching
@@ -17,56 +18,165 @@ export function supportsPersonalLogin(
provider: MusicProvider | undefined,
): provider is MusicProvider & PersonalLoginProvider {
const p = provider as Partial<PersonalLoginProvider> | undefined;
return typeof p?.pollQrLogin === "function" && typeof p.withCookie === "function";
return typeof p?.pollQrLogin === "function" && typeof p?.withCookie === "function";
}
/** Platforms a member can link an account for. Kept in sync with the providers map. */
export const PERSONAL_MUSIC_PLATFORMS = ["netease", "qq", "kugou", "bilibili"] as const;
/**
* The caller's own NetEase account, used for their personal FM instead of the
* bot's shared login (#164). Every route acts on req.user only; the cookie is
* stored server-side and never sent back to the browser.
* A web user's own music account (#164), generalised to every platform that
* implements `withCookie` (#164 follow-up).
*
* Three states are reported, and the member UI needs all three:
* - `personal`: the caller scanned their own QR code. They may unlink it.
* - `granted` : an ADMIN assigned one of the pool accounts to them. It cannot
* be unlinked from here — only the admin can take it back —
* which is why `canUnlink` is part of the payload instead of
* the UI guessing from `linked`.
* - `none` : nothing linked; playback falls back to the bot's shared login.
*
* The cookie is stored server-side and never sent back to the browser; the
* `label` of an assigned account is what the member sees instead of a nickname.
*/
export function createPersonalMusicRouter(
database: BotDatabase,
neteaseProvider: MusicProvider,
providers: Partial<Record<string, MusicProvider>>,
logger: Logger,
config?: MusicScopeDeps["config"],
): Router {
const router = Router();
const platform = "netease";
router.use((_req, res, next) => {
if (!supportsPersonalLogin(neteaseProvider)) {
res.status(501).json({ error: "Personal login not supported" });
const providerFor = (platform: string): MusicProvider | undefined => providers[platform];
/** 404 for platforms this build does not expose at all. */
router.param("platform", (req, res, next, platform: string) => {
if (!providerFor(platform)) {
res.status(404).json({ error: `Unknown platform: ${platform}` });
return;
}
next();
});
const provider = neteaseProvider as MusicProvider & PersonalLoginProvider;
router.get("/netease/status", async (req, res) => {
const cookie = database.getUserMusicCookie(req.user!.id, platform);
if (!cookie) {
res.json({ linked: false, loggedIn: false });
/** Read the account state for one platform: own first, then admin-assigned. */
const describeAccount = (
userId: string,
platform: string,
): { source: "personal" | "granted" | "none"; cookie: string | null; label?: string; canUnlink: boolean } => {
const own = database.getUserMusicCookie(userId, platform);
if (own && own.trim()) {
return { source: "personal", cookie: own, canUnlink: true };
}
// An assignment only exists because the admin turned the feature on, so it
// stops applying the moment the toggle goes off (same rule as playback).
if (perUserMusicEnabled({ database, config })) {
const granted = database.getGrantedMusicAccount(userId, platform);
if (granted) {
return { source: "granted", cookie: granted.cookie, label: granted.label, canUnlink: false };
}
}
return { source: "none", cookie: null, canUnlink: false };
};
router.get("/:platform/status", async (req, res) => {
const platform = req.params.platform;
const provider = providerFor(platform)!;
const account = describeAccount(req.user!.id, platform);
// Lets the member UI hide "扫码绑定" on platforms that only accept an
// admin-assigned account (qq / kugou / bilibili today).
const supportsQrLogin = supportsPersonalLogin(provider);
// The member's explicit "play through the shared login" choice, so the UI
// can render the radio without a second round-trip.
const preferShared =
database.getUserMusicPreference(req.user!.id, platform)?.preferShared === true;
// The choice only exists while the admin has per-user accounts on; with it
// off everyone is already on the shared login and the radio is meaningless.
const featureEnabled = perUserMusicEnabled({ database, config });
if (!account.cookie) {
res.json({
linked: false,
loggedIn: false,
source: "none",
canUnlink: false,
supportsQrLogin,
preferShared,
featureEnabled,
});
return;
}
if (typeof provider.withCookie !== "function") {
// Account stored but this platform cannot build a per-account view yet.
res.json({
linked: true,
loggedIn: false,
source: account.source,
label: account.label,
canUnlink: account.canUnlink,
supportsQrLogin,
preferShared,
featureEnabled,
unsupported: true,
});
return;
}
try {
const status = await provider.withCookie(cookie).getAuthStatus();
res.json({ linked: true, ...status });
} catch (err) {
logger.warn({ err }, "Personal NetEase status check failed");
res.json({ linked: true, loggedIn: false });
const status = await provider.withCookie(account.cookie).getAuthStatus();
res.json({
linked: true,
source: account.source,
label: account.label,
canUnlink: account.canUnlink,
supportsQrLogin,
preferShared,
featureEnabled,
...status,
});
} catch {
logger.warn({ platform, source: account.source }, "Personal music status check failed");
res.json({
linked: true,
loggedIn: false,
source: account.source,
label: account.label,
canUnlink: account.canUnlink,
supportsQrLogin,
preferShared,
featureEnabled,
});
}
});
router.post("/netease/qrcode", async (_req, res) => {
router.post("/:platform/qrcode", async (req, res) => {
const platform = req.params.platform;
const provider = providerFor(platform)!;
if (!supportsPersonalLogin(provider)) {
// Only NetEase ships "poll and hand back the cookie" today. The other
// platforms can still receive an admin-assigned account.
res.status(501).json({
error: "Personal QR login is not implemented for this platform yet",
platform,
});
return;
}
try {
res.json(await provider.getQrCode());
} catch (err) {
logger.error({ err }, "Personal NetEase QR generation failed");
logger.error({ err, platform }, "Personal music QR generation failed");
res.status(500).json({ error: (err as Error).message });
}
});
router.get("/netease/qrcode/status", async (req, res) => {
router.get("/:platform/qrcode/status", async (req, res) => {
const platform = req.params.platform;
const provider = providerFor(platform)!;
if (!supportsPersonalLogin(provider)) {
res.status(501).json({
error: "Personal QR login is not implemented for this platform yet",
platform,
});
return;
}
const key = req.query.key;
if (typeof key !== "string" || !key) {
res.status(400).json({ error: "key is required" });
@@ -80,15 +190,62 @@ export function createPersonalMusicRouter(
}
res.json({ status });
} catch (err) {
logger.error({ err }, "Personal NetEase QR status check failed");
logger.error({ err, platform }, "Personal music QR status check failed");
res.status(500).json({ error: (err as Error).message });
}
});
router.delete("/netease", (req, res) => {
database.deleteUserMusicCookie(req.user!.id, platform);
logger.info({ userId: req.user!.id, platform }, "Personal music account unlinked");
res.json({ ok: true });
router.delete("/:platform", (req, res) => {
const platform = req.params.platform;
const userId = req.user!.id;
// Only the member's OWN login is removed. An admin-assigned account lives
// in a different table and must stay put — otherwise a member could revoke
// (or accidentally destroy) what the admin handed them.
const removed = database.deleteUserMusicCookie(userId, platform);
if (removed) {
logger.info({ userId, platform }, "Personal music account unlinked");
}
const remaining = describeAccount(userId, platform);
res.json({
ok: true,
removed,
// What playback falls back to now — the member UI shows the right hint.
fallback: remaining.source === "granted" ? "granted" : "shared",
});
});
/**
* Which login this member plays through.
*
* `preferShared: true` = ignore my own (and any assigned) account and use the
* bot's shared login — the admin's, usually the one with a membership. It is
* the answer to "my NetEase account has no VIP, the admin's does, and I want
* the paid track". Nothing is deleted: flipping it back restores the personal
* account exactly as it was.
*/
router.put("/:platform/preference", (req, res) => {
const platform = req.params.platform;
const { preferShared } = req.body ?? {};
if (typeof preferShared !== "boolean") {
res.status(400).json({ error: "preferShared must be a boolean" });
return;
}
// With the feature off there is nothing to choose between — everything
// already runs on the shared login. Refuse instead of storing a value that
// would silently do nothing.
if (!perUserMusicEnabled({ database, config })) {
res.status(409).json({ error: "per_user_accounts_disabled" });
return;
}
database.setUserMusicPreference(req.user!.id, platform, preferShared);
logger.info({ userId: req.user!.id, platform, preferShared }, "Music account preference set");
res.json({ platform, preferShared });
});
router.get("/:platform/preference", (req, res) => {
const platform = req.params.platform;
const pref = database.getUserMusicPreference(req.user!.id, platform);
res.json({ platform, preferShared: pref?.preferShared === true });
});
return router;
+53 -44
View File
@@ -1,14 +1,15 @@
import { Router } from "express";
import { Router, type Request } from "express";
import type { BotInstance } from "../../bot/instance.js";
import type { QueuedSong } from "../../audio/queue.js";
import type { BotManager } from "../../bot/manager.js";
import type { BotDatabase } from "../../data/database.js";
import type { MusicProvider, Song, ArtistSongPage, PlayFailure } from "../../music/provider.js";
import { musicRequestError } from "../../music/request-error.js";
import type { Logger } from "../../logger.js";
import { parseCommand } from "../../bot/commands.js";
import { requireBotAccess } from "../middleware/requirePermission.js";
import { authorize } from "../middleware/authorize.js";
import { supportsPersonalLogin } from "./personal-music.js";
import { resolveProviderForRequest } from "./provider-scope.js";
/** Hard cap on how many tracks one "播放全部" request may queue — a safety net
* against a pathological catalogue (and against an upstream paging bug). */
@@ -43,9 +44,39 @@ export function createPlayerRouter(
neteaseProvider?: MusicProvider,
qqProvider?: MusicProvider,
bilibiliProvider?: MusicProvider,
// Per-user music accounts (#164 follow-up). Omitted by unit-test routers →
// the feature reads as off and every request uses the shared login.
config?: { perUserMusicAccounts?: boolean },
): Router {
const router = Router();
/** Platform names the bot resolves as-is; anything else means NetEase. */
const PASSTHROUGH = new Set(["bilibili", "qq", "youtube", "local", "kugou", "jellyfin"]);
const sharedProviderFor = (bot: any, platform: unknown): MusicProvider =>
bot.getProviderFor(PASSTHROUGH.has(platform as string) ? platform : "netease");
/**
* The provider this request should read from. With per-user accounts enabled,
* a caller who linked their own account gets a view built from THEIR cookie;
* otherwise the bot's shared provider comes back untouched.
*/
const scopedProvider = (req: Request, bot: any, platform: unknown): MusicProvider => {
const shared = sharedProviderFor(bot, platform);
return resolveProviderForRequest(req, shared.platform, shared, { database, config });
};
/**
* Personal FM predates the admin toggle (#164), so a linked account has always
* driven it. `alwaysPersonal` keeps that guarantee while the toggle is off;
* with the toggle on, FM simply inherits the same account as everything else.
*/
const fmProvider = (req: Pick<Request, "user">, bot: any, platform: unknown): MusicProvider => {
const shared = sharedProviderFor(bot, platform);
return resolveProviderForRequest(req, shared.platform, shared, { database, config }, {
alwaysPersonal: true,
});
};
// Access check runs BEFORE the existence/resolver check so a member who is
// not allowed a bot always gets a uniform 403 — whether or not the bot
// exists — instead of a 404 that would leak which bot IDs are real.
@@ -168,20 +199,11 @@ export function createPlayerRouter(
rejectDisabledLocalAudio(res);
return;
}
let provider = bot.getProviderFor(
platform === "bilibili" || platform === "qq" || platform === "youtube" || platform === "local" || platform === "kugou" || platform === "jellyfin"
? platform
: "netease"
);
// A signed-in user who linked their own NetEase account gets FM from
// THEIR taste, not the bot's shared login (#164). Songs still resolve
// through the shared provider when played.
const user = (req as any).user;
if (provider.platform === "netease" && user && user.role !== "guest" && database) {
const cookie = database.getUserMusicCookie(user.id, "netease");
if (cookie && supportsPersonalLogin(provider)) provider = provider.withCookie(cookie);
}
const message = await bot.startFm(provider, requesterName(req));
// Resolve FM recommendations with the caller's account. The bot resolves
// each queued track's playback URL using the shared account.
const scope = { user: req.user };
const resolveFmProvider = () => fmProvider(scope, bot, platform);
const message = await bot.startFm(resolveFmProvider(), requesterName(req), resolveFmProvider);
res.json({
ok:
!message.startsWith("No FM songs") &&
@@ -190,7 +212,7 @@ export function createPlayerRouter(
message,
});
} catch (err) {
res.status(500).json({ error: (err as Error).message });
res.status(500).json({ error: musicRequestError(err).message });
}
});
@@ -352,11 +374,7 @@ export function createPlayerRouter(
}
// Use the bot's own provider lookup — it already knows about youtube,
// which the router's constructor params did not.
const provider = bot.getProviderFor(
platform === "bilibili" || platform === "qq" || platform === "youtube" || platform === "local" || platform === "kugou" || platform === "jellyfin"
? platform
: "netease"
);
const provider = scopedProvider(req, bot, platform);
// Stop current playback
bot.getPlayer().stop();
@@ -428,8 +446,9 @@ export function createPlayerRouter(
res.json({ ok: false, message: `${loadedMsg},但无法开始播放${reason ? `:${reason}` : "。"}` });
}
} catch (err) {
logger.error({ err }, "Play playlist failed");
res.status(500).json({ error: (err as Error).message });
const error = musicRequestError(err);
logger.error({ err: error }, "Play playlist failed");
res.status(500).json({ error: error.message });
}
});
@@ -442,11 +461,7 @@ export function createPlayerRouter(
rejectDisabledLocalAudio(res);
return;
}
const provider = bot.getProviderFor(
platform === "bilibili" || platform === "qq" || platform === "youtube" || platform === "local" || platform === "kugou" || platform === "jellyfin"
? platform
: "netease"
);
const provider = scopedProvider(req, bot, platform);
// Stop current playback
bot.getPlayer().stop();
@@ -503,8 +518,9 @@ export function createPlayerRouter(
res.json({ ok: false, message: `${loadedMsg},但无法开始播放${reason ? `:${reason}` : "。"}` });
}
} catch (err) {
logger.error({ err }, "play-album failed");
res.status(500).json({ error: (err as Error).message });
const error = musicRequestError(err);
logger.error({ err: error }, "play-album failed");
res.status(500).json({ error: error.message });
}
});
@@ -524,11 +540,7 @@ export function createPlayerRouter(
rejectDisabledLocalAudio(res);
return;
}
const provider = bot.getProviderFor(
platform === "bilibili" || platform === "qq" || platform === "youtube" || platform === "local" || platform === "kugou" || platform === "jellyfin"
? platform
: "netease"
);
const provider = scopedProvider(req, bot, platform);
if (typeof provider.getArtistSongs !== "function") {
res.status(501).json({ error: "Not supported by this provider" });
return;
@@ -595,8 +607,9 @@ export function createPlayerRouter(
});
res.json(body);
} catch (err) {
logger.error({ err }, "play-artist failed");
res.status(500).json({ error: (err as Error).message });
const error = musicRequestError(err);
logger.error({ err: error }, "play-artist failed");
res.status(500).json({ error: error.message });
}
});
@@ -762,11 +775,7 @@ export function createPlayerRouter(
rejectDisabledLocalAudio(res);
return;
}
const provider = bot.getProviderFor(
platform === "bilibili" || platform === "qq" || platform === "youtube" || platform === "local" || platform === "kugou" || platform === "jellyfin"
? platform
: "netease"
);
const provider = scopedProvider(req, bot, platform);
const song = await provider.getSongDetail(songId);
if (!song) {
@@ -785,7 +794,7 @@ export function createPlayerRouter(
res.json({ message: `Added: ${song.name} - ${song.artist} (position ${queue.size()})` });
} catch (err) {
res.status(500).json({ error: (err as Error).message });
res.status(500).json({ error: musicRequestError(err).message });
}
});
+460
View File
@@ -0,0 +1,460 @@
import { describe, expect, it } from "vitest";
import type { Request } from "express";
import type { BotDatabase, GrantedMusicAccount } from "../../data/database.js";
import type { MusicProvider } from "../../music/provider.js";
import {
grantedAccountFor,
perUserMusicEnabled,
personalCookieFor,
resolveMusicCookie,
resolveProviderForRequest,
} from "./provider-scope.js";
/** Minimal provider stand-in: only `platform` and an optional `withCookie` are
* consulted by the scope resolver. */
function fakeProvider(opts: {
platform?: string;
withCookie?: (cookie: string) => MusicProvider;
} = {}): MusicProvider {
const p: Partial<MusicProvider> = { platform: (opts.platform ?? "netease") as MusicProvider["platform"] };
if (opts.withCookie) p.withCookie = opts.withCookie;
return p as MusicProvider;
}
/**
* `own` is the member's self-linked cookie, `granted` an admin assignment.
* Both default to null so a test only states the state it cares about.
*/
function fakeDb(
own: string | null,
granted: GrantedMusicAccount | null = null,
preferShared = false,
): BotDatabase {
return {
getUserMusicCookie: () => own,
getGrantedMusicAccount: () => granted,
getUserMusicPreference: () =>
preferShared ? { preferShared: true } : null,
} as unknown as BotDatabase;
}
function fakeReq(user?: { id: string; role: string }): Request {
return { user } as unknown as Request;
}
const GRANTED: GrantedMusicAccount = {
accountId: "acc-1",
label: "网易云-主号",
cookie: "MUSIC_U=shared-with-member",
};
describe("provider-scope", () => {
it("is off unless config explicitly enables it", () => {
expect(perUserMusicEnabled({})).toBe(false);
expect(perUserMusicEnabled({ config: {} })).toBe(false);
expect(perUserMusicEnabled({ config: { perUserMusicAccounts: false } })).toBe(false);
expect(perUserMusicEnabled({ config: { perUserMusicAccounts: true } })).toBe(true);
});
it("returns the shared provider when the feature is off", () => {
const shared = fakeProvider({ withCookie: () => fakeProvider() });
const scoped = resolveProviderForRequest(fakeReq({ id: "u1", role: "member" }), "netease", shared, {
database: fakeDb("MUSIC_U=abc"),
config: { perUserMusicAccounts: false },
});
expect(scoped).toBe(shared);
});
it("returns the shared provider for guests even with a linked cookie", () => {
const shared = fakeProvider({ withCookie: () => fakeProvider() });
const scoped = resolveProviderForRequest(fakeReq({ id: "g1", role: "guest" }), "netease", shared, {
database: fakeDb("MUSIC_U=abc"),
config: { perUserMusicAccounts: true },
});
expect(scoped).toBe(shared);
});
it("falls back to the shared provider when the user has no linked cookie", () => {
const shared = fakeProvider({ withCookie: () => fakeProvider() });
const scoped = resolveProviderForRequest(fakeReq({ id: "u1", role: "member" }), "netease", shared, {
database: fakeDb(null),
config: { perUserMusicAccounts: true },
});
expect(scoped).toBe(shared);
});
it("falls back to the shared provider when the source has no per-account login", () => {
const shared = fakeProvider({ platform: "local" });
const scoped = resolveProviderForRequest(fakeReq({ id: "u1", role: "member" }), "local", shared, {
database: fakeDb("cookie"),
config: { perUserMusicAccounts: true },
});
expect(scoped).toBe(shared);
});
it("returns an account-scoped view when enabled, member, and linked", () => {
const personal = fakeProvider();
let seen = "";
const shared = fakeProvider({
withCookie: (cookie) => {
seen = cookie;
return personal;
},
});
const scoped = resolveProviderForRequest(fakeReq({ id: "u1", role: "member" }), "netease", shared, {
database: fakeDb("MUSIC_U=abc"),
config: { perUserMusicAccounts: true },
});
expect(scoped).toBe(personal);
expect(seen).toBe("MUSIC_U=abc");
});
it("degrades to the shared provider when withCookie throws", () => {
const shared = fakeProvider({
withCookie: () => {
throw new Error("bad cookie");
},
});
const scoped = resolveProviderForRequest(fakeReq({ id: "u1", role: "member" }), "netease", shared, {
database: fakeDb("broken"),
config: { perUserMusicAccounts: true },
});
expect(scoped).toBe(shared);
});
it("treats a blank stored cookie as unlinked", () => {
expect(
personalCookieFor(fakeReq({ id: "u1", role: "member" }), "netease", {
database: fakeDb(" "),
config: { perUserMusicAccounts: true },
}),
).toBeNull();
});
it("ignores requests with no authenticated user", () => {
const shared = fakeProvider({ withCookie: () => fakeProvider() });
expect(
resolveProviderForRequest(undefined, "netease", shared, {
database: fakeDb("MUSIC_U=abc"),
config: { perUserMusicAccounts: true },
}),
).toBe(shared);
});
// Personal FM shipped before the admin toggle existed (#164). A linked account
// has always driven it, so `alwaysPersonal` must keep working with the flag off
// — otherwise turning the feature off would silently regress that release.
it("still uses the linked account for personal FM while the toggle is off", () => {
const personal = fakeProvider();
const shared = fakeProvider({ withCookie: () => personal });
const scoped = resolveProviderForRequest(
fakeReq({ id: "u1", role: "member" }),
"netease",
shared,
{ database: fakeDb("MUSIC_U=abc"), config: { perUserMusicAccounts: false } },
{ alwaysPersonal: true },
);
expect(scoped).toBe(personal);
});
it("keeps guests on the shared provider even for personal FM", () => {
const shared = fakeProvider({ withCookie: () => fakeProvider() });
const scoped = resolveProviderForRequest(
fakeReq({ id: "g1", role: "guest" }),
"netease",
shared,
{ database: fakeDb("MUSIC_U=abc"), config: { perUserMusicAccounts: true } },
{ alwaysPersonal: true },
);
expect(scoped).toBe(shared);
});
// ---------------------------------------------------------------------
// Admin-assigned accounts (#164 follow-up)
// ---------------------------------------------------------------------
describe("admin-assigned accounts", () => {
it("resolves an assigned account when the member linked nothing themselves", () => {
const assigned = fakeProvider();
let seen = "";
const shared = fakeProvider({
withCookie: (cookie) => {
seen = cookie;
return assigned;
},
});
const scoped = resolveProviderForRequest(
fakeReq({ id: "u1", role: "member" }),
"netease",
shared,
{ database: fakeDb(null, GRANTED), config: { perUserMusicAccounts: true } },
);
expect(scoped).toBe(assigned);
expect(seen).toBe(GRANTED.cookie);
});
// Own-beats-assigned: linking your own account must never be silently
// overridden by whatever the admin handed out earlier.
it("prefers the member's own login over an assigned one", () => {
const ownView = fakeProvider();
const grantedView = fakeProvider();
let seen = "";
const shared = fakeProvider({
withCookie: (cookie) => {
seen = cookie;
return cookie === "MUSIC_U=own" ? ownView : grantedView;
},
});
const scoped = resolveProviderForRequest(
fakeReq({ id: "u1", role: "member" }),
"netease",
shared,
{ database: fakeDb("MUSIC_U=own", GRANTED), config: { perUserMusicAccounts: true } },
);
expect(scoped).toBe(ownView);
expect(seen).toBe("MUSIC_U=own");
});
// An assignment only exists because the admin turned the feature on, so it
// must stop applying the moment they turn it off — otherwise "disable"
// would leave members reading the admin's account.
it("ignores assignments while the toggle is off", () => {
const shared = fakeProvider({ withCookie: () => fakeProvider() });
expect(
grantedAccountFor(fakeReq({ id: "u1", role: "member" }), "netease", {
database: fakeDb(null, GRANTED),
config: { perUserMusicAccounts: false },
}),
).toBeNull();
expect(
resolveProviderForRequest(fakeReq({ id: "u1", role: "member" }), "netease", shared, {
database: fakeDb(null, GRANTED),
config: { perUserMusicAccounts: false },
}),
).toBe(shared);
});
it("never hands an assignment to a guest", () => {
expect(
grantedAccountFor(fakeReq({ id: "guest", role: "guest" }), "netease", {
database: fakeDb(null, GRANTED),
config: { perUserMusicAccounts: true },
}),
).toBeNull();
});
it("reports the source and label so the UI can say 由管理员分配", () => {
const resolved = resolveMusicCookie(
fakeReq({ id: "u1", role: "member" }),
"netease",
{ database: fakeDb(null, GRANTED), config: { perUserMusicAccounts: true } },
);
expect(resolved).toEqual({
source: "granted",
cookie: GRANTED.cookie,
label: "网易云-主号",
accountId: "acc-1",
});
});
it("reports source=personal for a self-linked account", () => {
const resolved = resolveMusicCookie(
fakeReq({ id: "u1", role: "member" }),
"netease",
{ database: fakeDb("MUSIC_U=own", GRANTED), config: { perUserMusicAccounts: true } },
);
expect(resolved).toEqual({ source: "personal", cookie: "MUSIC_U=own" });
});
it("returns null when neither source applies", () => {
expect(
resolveMusicCookie(fakeReq({ id: "u1", role: "member" }), "netease", {
database: fakeDb(null, null),
config: { perUserMusicAccounts: true },
}),
).toBeNull();
});
it("degrades to the shared provider when an assigned cookie is broken", () => {
const shared = fakeProvider({
withCookie: () => {
throw new Error("bad assigned cookie");
},
});
const scoped = resolveProviderForRequest(
fakeReq({ id: "u1", role: "member" }),
"netease",
shared,
{ database: fakeDb(null, GRANTED), config: { perUserMusicAccounts: true } },
);
expect(scoped).toBe(shared);
});
// Personal FM keeps the #164 guarantee for the member's OWN login; an
// assignment is not a #164 artefact and must not ride along.
it("does not use an assignment for personal FM while the toggle is off", () => {
const shared = fakeProvider({ withCookie: () => fakeProvider() });
const scoped = resolveProviderForRequest(
fakeReq({ id: "u1", role: "member" }),
"netease",
shared,
{ database: fakeDb(null, GRANTED), config: { perUserMusicAccounts: false } },
{ alwaysPersonal: true },
);
expect(scoped).toBe(shared);
});
});
});
// ---------------------------------------------------------------------------
// "Play through the shared account" preference
//
// The real case: the member's own NetEase login has no VIP, the admin's does.
// Switching to shared must override BOTH their own link and any assignment —
// it is an explicit instruction, not a fallback.
// ---------------------------------------------------------------------------
describe("provider-scope — shared-account preference", () => {
it("ignores the member's own cookie when they chose the shared login", () => {
const resolved = resolveMusicCookie(
fakeReq({ id: "u1", role: "member" }),
"netease",
{
database: fakeDb("MUSIC_U=mine", null, true),
config: { perUserMusicAccounts: true },
},
);
expect(resolved).toBeNull();
});
it("also overrides an admin assignment", () => {
const resolved = resolveMusicCookie(
fakeReq({ id: "u1", role: "member" }),
"netease",
{
database: fakeDb(null, GRANTED, true),
config: { perUserMusicAccounts: true },
},
);
expect(resolved).toBeNull();
});
it("outranks alwaysPersonal, so personal FM follows the choice too", () => {
const resolved = resolveMusicCookie(
fakeReq({ id: "u1", role: "member" }),
"netease",
{
database: fakeDb("MUSIC_U=mine", null, true),
config: { perUserMusicAccounts: true },
},
{ alwaysPersonal: true },
);
expect(resolved).toBeNull();
});
it("hands the untouched shared provider back", () => {
const shared = fakeProvider({ withCookie: () => fakeProvider() });
const scoped = resolveProviderForRequest(
fakeReq({ id: "u1", role: "member" }),
"netease",
shared,
{
database: fakeDb("MUSIC_U=mine", null, true),
config: { perUserMusicAccounts: true },
},
);
expect(scoped).toBe(shared);
});
it("is ignored while the admin has the feature off", () => {
const shared = fakeProvider({ withCookie: () => fakeProvider() });
const scoped = resolveProviderForRequest(
fakeReq({ id: "u1", role: "member" }),
"netease",
shared,
{
database: fakeDb("MUSIC_U=mine", null, true),
config: { perUserMusicAccounts: false },
},
);
expect(scoped).toBe(shared);
});
});
// ---------------------------------------------------------------------------
// Automatic playback fallback
//
// Same scenario, minus an explicit choice: keep the member's own account for
// search / playlists, but when THIS track cannot be resolved on it, try the
// shared login instead of greying the track out.
// ---------------------------------------------------------------------------
describe("provider-scope — playback falls back to the shared login", () => {
function view(
getSongUrl: (songId: string, quality?: string) => Promise<{ url: string } | null>,
): MusicProvider {
return { platform: "netease", getSongUrl } as unknown as MusicProvider;
}
function scopeWith(
personal: MusicProvider,
sharedUrl: () => Promise<{ url: string } | null>,
options: { fallbackToShared?: boolean } = {},
) {
const shared = view(sharedUrl);
(shared as Partial<MusicProvider>).withCookie = () => personal;
return resolveProviderForRequest(
fakeReq({ id: "u1", role: "member" }),
"netease",
shared,
{
database: fakeDb("MUSIC_U=mine"),
config: { perUserMusicAccounts: true },
},
options,
);
}
it("uses the shared login when the personal account returns no url", async () => {
const scoped = scopeWith(view(async () => null), async () => ({ url: "https://shared/x.mp3" }));
expect((await scoped.getSongUrl("1"))?.url).toBe("https://shared/x.mp3");
});
it("uses the shared login when the personal account throws", async () => {
const scoped = scopeWith(
view(async () => {
throw new Error("no membership");
}),
async () => ({ url: "https://shared/x.mp3" }),
);
expect((await scoped.getSongUrl("1"))?.url).toBe("https://shared/x.mp3");
});
it("keeps the personal result when it works", async () => {
const scoped = scopeWith(
view(async () => ({ url: "https://mine/x.mp3" })),
async () => ({ url: "https://shared/x.mp3" }),
);
expect((await scoped.getSongUrl("1"))?.url).toBe("https://mine/x.mp3");
});
it("can be switched off so playback stays on the member's account", async () => {
const scoped = scopeWith(
view(async () => null),
async () => ({ url: "https://shared/x.mp3" }),
{ fallbackToShared: false },
);
expect(await scoped.getSongUrl("1")).toBeNull();
});
it("leaves the shared instance itself untouched", async () => {
const shared = view(async () => ({ url: "https://shared/x.mp3" }));
(shared as Partial<MusicProvider>).withCookie = () => view(async () => null);
resolveProviderForRequest(
fakeReq({ id: "u1", role: "member" }),
"netease",
shared,
{ database: fakeDb("MUSIC_U=mine"), config: { perUserMusicAccounts: true } },
);
// Calling the shared provider directly must still hit its own implementation.
expect((await shared.getSongUrl("1"))?.url).toBe("https://shared/x.mp3");
});
});
+225
View File
@@ -0,0 +1,225 @@
import type { Request } from "express";
import type { BotDatabase, GrantedMusicAccount } from "../../data/database.js";
import type { MusicProvider } from "../../music/provider.js";
/**
* Resolves which music provider a WEB request should read from (#164 follow-up).
*
* The bot keeps one shared login per platform (data/cookies/<platform>.json).
* Before this module, a web user could only replace the SHARED login's taste for
* their own private FM — every search, playlist and playback URL still came from
* the admin's account, so members saw the admin's library.
*
* With `perUserMusicAccounts` enabled, the resolution order is:
*
* 1. the caller's OWN linked account (`user_music_cookies`, scanned by them)
* 2. an account an admin ASSIGNED (`music_account_grants`, admin-owned)
* 3. the bot's shared login (always the fallback)
*
* Own-beats-assigned is deliberate: someone who linked their own account keeps
* it even if an admin later hands them a pool account, and unlinking on the
* member side can never revoke an admin's assignment (different table).
*
* Everything falls back to the shared instance when:
* - the admin left the feature off (the default — zero behaviour change),
* - the caller is a guest (guests share one anonymous identity and cannot link
* an account; /api/me/music already rejects them),
* - the caller has no linked and no assigned account for that platform,
* - the assigned account was disabled by the admin (instant rollback), or
* - the platform has no per-account login implemented (`withCookie` absent).
*
* The cookie never reaches the browser: it is read from the database here and
* only ever lives inside the provider view.
*/
export interface MusicScopeDeps {
/** Omitted by unit-test routers → personal accounts are simply unavailable. */
database?: BotDatabase;
/** Omitted by unit-test routers → treated as "feature off". */
config?: { perUserMusicAccounts?: boolean };
}
interface ScopedUser {
id?: string;
role?: string;
}
type ScopeRequest = Pick<Request, "user">;
/** Whether per-user music accounts are switched on for this router instance. */
export function perUserMusicEnabled(deps: MusicScopeDeps): boolean {
return deps.config?.perUserMusicAccounts === true;
}
/**
* The caller, when they may hold a per-user account at all. Guests never
* qualify: they all map to one anonymous identity, so a linked or assigned
* account would leak across every guest on the instance.
*/
function scopedUser(req: ScopeRequest | undefined): ScopedUser | null {
if (!req) return null;
const user = (req as { user?: ScopedUser }).user;
if (!user?.id || user.role === "guest") return null;
return user;
}
/**
* The caller's own cookie for `platform`, or null when personal accounts do not
* apply to this request.
*
* `alwaysPersonal` keeps the pre-existing #164 behaviour for personal FM: that
* feature shipped BEFORE the admin toggle existed, so a linked account must keep
* driving someone's private FM even while the toggle is off. Turning the toggle
* on only widens the scope to search/playlists/playback URLs.
*/
export function personalCookieFor(
req: ScopeRequest | undefined,
platform: string,
deps: MusicScopeDeps,
alwaysPersonal = false,
): string | null {
if (!alwaysPersonal && !perUserMusicEnabled(deps)) return null;
const user = scopedUser(req);
if (!user || !deps.database) return null;
const cookie = deps.database.getUserMusicCookie(user.id!, platform);
return cookie && cookie.trim() ? cookie : null;
}
/**
* The admin-assigned account for this caller, or null.
*
* Unlike `personalCookieFor` this has NO `alwaysPersonal` escape hatch: an
* assignment only exists because the admin turned the feature on, so turning it
* off must hand everyone back to the shared login immediately. Doing otherwise
* would leave members reading an admin's account after the admin "disabled"
* the feature.
*/
export function grantedAccountFor(
req: ScopeRequest | undefined,
platform: string,
deps: MusicScopeDeps,
): GrantedMusicAccount | null {
if (!perUserMusicEnabled(deps)) return null;
const user = scopedUser(req);
if (!user || !deps.database) return null;
return deps.database.getGrantedMusicAccount(user.id!, platform);
}
/**
* Whether the member explicitly asked to play through the shared login.
*
* This exists for one concrete case: their own account has no membership, the
* admin's does, and they would rather hear the paid tracks than their own
* recommendations. Choosing it overrides BOTH their own link and any admin
* assignment — it is an explicit instruction, not a fallback.
*/
export function preferSharedFor(
req: ScopeRequest | undefined,
platform: string,
deps: MusicScopeDeps,
): boolean {
if (!perUserMusicEnabled(deps)) return false;
const user = scopedUser(req);
if (!user || !deps.database) return false;
return deps.database.getUserMusicPreference(user.id!, platform)?.preferShared === true;
}
/** Where the cookie driving this request came from. */
export interface ResolvedMusicCookie {
source: "personal" | "granted";
cookie: string;
/** Admin-facing name of an assigned account; undefined for self-linked ones. */
label?: string;
/** Set for `source: "granted"` so callers can show "由管理员分配". */
accountId?: string;
}
/**
* The single place that decides "which login does this request use".
* Returns null when the shared login applies.
*/
export function resolveMusicCookie(
req: ScopeRequest | undefined,
platform: string,
deps: MusicScopeDeps,
options: { alwaysPersonal?: boolean } = {},
): ResolvedMusicCookie | null {
// An explicit "use the shared account" outranks everything, including the
// `alwaysPersonal` escape hatch: someone who chose membership over their own
// recommendations wants the shared login for FM too.
if (preferSharedFor(req, platform, deps)) return null;
const own = personalCookieFor(req, platform, deps, options.alwaysPersonal);
if (own) return { source: "personal", cookie: own };
const granted = grantedAccountFor(req, platform, deps);
if (granted) {
return {
source: "granted",
cookie: granted.cookie,
label: granted.label,
accountId: granted.accountId,
};
}
return null;
}
/**
* Give `view` a single-shot fallback to the shared login when its own playback
* attempt comes up empty.
*
* The case this exists for: the member's own account is real but has no
* membership, so `/song/url/v1` answers `url: null` (or 400 for the paid track)
* while the admin's account plays it fine. Without this the member has to go
* into settings and switch manually before every such track.
*
* Only `getSongUrl` is wrapped — search, playlists and FM stay on the member's
* own account, which is the whole point of per-user logins. The wrapper keeps
* the shared instance untouched, so nothing leaks between callers.
*/
function withSharedPlaybackFallback(view: MusicProvider, shared: MusicProvider): MusicProvider {
// Guard for partial implementations (and for test doubles): without both
// sides resolvable there is nothing to fall back to.
if (typeof view.getSongUrl !== "function" || typeof shared.getSongUrl !== "function") {
return view;
}
const ownResolve = view.getSongUrl.bind(view);
view.getSongUrl = async (songId: string, quality?: string) => {
try {
const result = await ownResolve(songId, quality);
if (result?.url) return result;
} catch {
// A failure on the personal side (no membership, -460, expired cookie)
// is not a reason for this track to go grey — try the shared login.
}
return shared.getSongUrl(songId, quality);
};
return view;
}
/**
* Wrap `shared` in a per-account view when the request carries a usable login;
* otherwise return `shared` untouched.
*
* A provider whose `withCookie` throws (malformed/persisted cookie) degrades to
* the shared login rather than failing the request — a bad stored cookie must
* not break search/playback for that user.
*/
export function resolveProviderForRequest(
req: ScopeRequest | undefined,
platform: string,
shared: MusicProvider,
deps: MusicScopeDeps,
options: { alwaysPersonal?: boolean; fallbackToShared?: boolean } = {},
): MusicProvider {
const resolved = resolveMusicCookie(req, platform, deps, options);
if (!resolved) return shared;
if (typeof shared.withCookie !== "function") return shared;
let view: MusicProvider;
try {
view = shared.withCookie(resolved.cookie);
} catch {
return shared;
}
// On by default: the common complaint is "my account has no membership, the
// admin's does". Set false to keep playback strictly on the member's account.
if (options.fallbackToShared === false) return view;
return withSharedPlaybackFallback(view, shared);
}