mirror of
https://github.com/ZHANGTIANYAO1/teamspeak-music-bot.git
synced 2026-12-03 03:12:51 +08:00
feat(music): per-user music accounts with an admin-owned account pool
Every member saw the admin's library: the bot keeps one shared login per platform (data/cookies/<platform>.json) and search, playlists and playback URLs all read through it. #164 added a personal NetEase login, but only for 私人FM — the rest still came from the shared account. On top of that, most members do not own a paid login, so "everyone links their own" is not enough: the admin has to be able to hand out accounts. What this adds, behind one admin switch (`perUserMusicAccounts`, default off): - One login per request, resolved in this order: the caller's OWN linked account, then an account an admin ASSIGNED, then the bot's shared login. - An admin-owned pool (`music_accounts`) plus per-member assignments (`music_account_grants`, PK userId+platform = one per platform). Assignments are capacity-checked inside a transaction, so an exclusive account cannot be handed to two members by two concurrent clicks. `enabled = 0` is an instant rollback of every grant without deleting them. - Own-beats-assigned, and the two live in separate tables: a member scanning their own QR code never overwrites an admin's assignment, and unlinking on the member side never revokes what the admin granted. - QQ / Kugou / Bilibili now implement `withCookie`, so all four sources can be isolated. Only NetEase exposes QR self-linking (it is the only one with `pollQrLogin`); the rest accept an assigned account, which is the workflow that actually matters for members without a paid login. - `/api/music-accounts` is admin-only (`requireAdmin`, not `bot.manage`): members must never see which account was handed to whom. Cookies are masked in every response. Switch off = no behaviour change at all, except 私人FM keeps the #164 behaviour through `alwaysPersonal`.
This commit is contained in:
1 parent
17008ae52e
commit
61c24cc219
20 files changed
+2568
-114
No files matched your search
+49
-2
@@ -4,8 +4,10 @@ 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,
|
||||
@@ -16,7 +18,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();
|
||||
// YouTube is auth-less; we only use this instance so /auth/status can
|
||||
@@ -36,9 +41,51 @@ 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, status }, "Auth status check");
|
||||
res.json({ platform: provider.platform, ...status });
|
||||
res.json({ platform: provider.platform, source: "shared", ...status });
|
||||
} catch (err) {
|
||||
logger.error({ err }, "Auth status check failed");
|
||||
res.status(500).json({ error: (err as Error).message });
|
||||
|
||||
@@ -74,6 +74,7 @@ export function createBotRouter(
|
||||
voiceDucking: config.voiceDucking,
|
||||
localAudioEnabled: config.localAudioEnabled,
|
||||
savedQueuesEnabled: config.savedQueuesEnabled,
|
||||
perUserMusicAccounts: config.perUserMusicAccounts === true,
|
||||
playKeepsQueue: config.playKeepsQueue,
|
||||
adminGroups: config.adminGroups ?? [],
|
||||
guestMode: config.guestMode,
|
||||
@@ -94,6 +95,7 @@ export function createBotRouter(
|
||||
voiceDucking,
|
||||
guestMode,
|
||||
adminGroups,
|
||||
perUserMusicAccounts,
|
||||
} = req.body;
|
||||
|
||||
const hasIdle = idleTimeoutMinutes !== undefined;
|
||||
@@ -104,10 +106,14 @@ export function createBotRouter(
|
||||
|
||||
const hasAutoPause = typeof autoPauseOnEmpty === "boolean";
|
||||
const hasLocalAudioEnabled = typeof localAudioEnabled === "boolean";
|
||||
// Per-user music accounts: admin-only toggle (this route already requires
|
||||
// bot.manage). Strictly boolean — anything else leaves the value alone.
|
||||
const hasPerUserMusicAccounts = typeof perUserMusicAccounts === "boolean";
|
||||
|
||||
if (hasIdle) config.idleTimeoutMinutes = idleTimeoutMinutes;
|
||||
if (hasAutoPause) config.autoPauseOnEmpty = autoPauseOnEmpty;
|
||||
if (hasLocalAudioEnabled) config.localAudioEnabled = localAudioEnabled;
|
||||
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 /
|
||||
@@ -282,6 +288,7 @@ export function createBotRouter(
|
||||
voiceDucking: config.voiceDucking,
|
||||
localAudioEnabled: config.localAudioEnabled,
|
||||
savedQueuesEnabled: config.savedQueuesEnabled,
|
||||
perUserMusicAccounts: config.perUserMusicAccounts === true,
|
||||
playKeepsQueue: config.playKeepsQueue,
|
||||
adminGroups: config.adminGroups ?? [],
|
||||
guestMode: config.guestMode,
|
||||
|
||||
@@ -0,0 +1,220 @@
|
||||
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();
|
||||
});
|
||||
|
||||
// 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");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,337 @@
|
||||
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 string =>
|
||||
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;
|
||||
|
||||
/** 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 (capacity !== undefined && (typeof capacity !== "number" || capacity < 0)) {
|
||||
res.status(400).json({ error: "capacity must be a non-negative number" });
|
||||
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 (capacity !== undefined && (typeof capacity !== "number" || capacity < 0)) {
|
||||
res.status(400).json({ error: "capacity must be a non-negative number" });
|
||||
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.
|
||||
database.updateMusicAccount(account.id, {
|
||||
label: label === undefined ? undefined : label.trim(),
|
||||
cookie: cookie === undefined ? undefined : cookie.trim(),
|
||||
capacity,
|
||||
enabled,
|
||||
});
|
||||
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);
|
||||
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 (err) {
|
||||
logger.warn({ err, accountId: account.id }, "Music account probe failed");
|
||||
res.status(502).json({ error: (err as Error).message, 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) => {
|
||||
if (!cookieStore) {
|
||||
res.status(501).json({ error: "cookie store unavailable" });
|
||||
return;
|
||||
}
|
||||
const { platform, label, capacity } = req.body ?? {};
|
||||
if (!isPlatform(platform)) {
|
||||
res.status(400).json({ error: "unsupported platform" });
|
||||
return;
|
||||
}
|
||||
if (capacity !== undefined && (typeof capacity !== "number" || capacity < 0)) {
|
||||
res.status(400).json({ error: "capacity must be a non-negative number" });
|
||||
return;
|
||||
}
|
||||
const cookie = cookieStore.load(platform as Parameters<CookieStore["load"]>[0]);
|
||||
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;
|
||||
}
|
||||
+46
-18
@@ -1,11 +1,13 @@
|
||||
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 { 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 +72,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 +101,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/playback 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 +181,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.
|
||||
@@ -199,13 +216,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 = [
|
||||
@@ -246,7 +274,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) {
|
||||
@@ -261,7 +289,7 @@ export function createMusicRouter(
|
||||
|
||||
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 });
|
||||
@@ -272,7 +300,7 @@ export function createMusicRouter(
|
||||
|
||||
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 });
|
||||
@@ -283,7 +311,7 @@ export function createMusicRouter(
|
||||
|
||||
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 });
|
||||
@@ -294,7 +322,7 @@ export function createMusicRouter(
|
||||
|
||||
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 });
|
||||
@@ -305,7 +333,7 @@ export function createMusicRouter(
|
||||
|
||||
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" });
|
||||
@@ -335,7 +363,7 @@ export function createMusicRouter(
|
||||
|
||||
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" });
|
||||
@@ -351,7 +379,7 @@ export function createMusicRouter(
|
||||
|
||||
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" });
|
||||
@@ -367,7 +395,7 @@ export function createMusicRouter(
|
||||
|
||||
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" });
|
||||
@@ -383,7 +411,7 @@ export function createMusicRouter(
|
||||
|
||||
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" });
|
||||
|
||||
@@ -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,37 @@ 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,
|
||||
});
|
||||
});
|
||||
|
||||
it("creates a QR code", async () => {
|
||||
@@ -64,7 +88,14 @@ 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,
|
||||
loggedIn: true,
|
||||
nickname: "Alice163",
|
||||
});
|
||||
expect(provider.withCookie).toHaveBeenCalledWith("MUSIC_U=alice");
|
||||
});
|
||||
|
||||
@@ -74,6 +105,59 @@ 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,
|
||||
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,
|
||||
});
|
||||
});
|
||||
|
||||
// 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)", () => {
|
||||
|
||||
+134
-26
@@ -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,150 @@ 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);
|
||||
|
||||
if (!account.cookie) {
|
||||
res.json({
|
||||
linked: false,
|
||||
loggedIn: false,
|
||||
source: "none",
|
||||
canUnlink: false,
|
||||
supportsQrLogin,
|
||||
});
|
||||
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,
|
||||
unsupported: true,
|
||||
});
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const status = await provider.withCookie(cookie).getAuthStatus();
|
||||
res.json({ linked: true, ...status });
|
||||
const status = await provider.withCookie(account.cookie).getAuthStatus();
|
||||
res.json({
|
||||
linked: true,
|
||||
source: account.source,
|
||||
label: account.label,
|
||||
canUnlink: account.canUnlink,
|
||||
supportsQrLogin,
|
||||
...status,
|
||||
});
|
||||
} catch (err) {
|
||||
logger.warn({ err }, "Personal NetEase status check failed");
|
||||
res.json({ linked: true, loggedIn: false });
|
||||
logger.warn({ err, 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,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
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 +175,28 @@ 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",
|
||||
});
|
||||
});
|
||||
|
||||
return router;
|
||||
|
||||
+41
-35
@@ -1,4 +1,4 @@
|
||||
import { Router } from "express";
|
||||
import { Router, type Request } from "express";
|
||||
import type { BotManager } from "../../bot/manager.js";
|
||||
import type { BotDatabase } from "../../data/database.js";
|
||||
import type { MusicProvider, Song, ArtistSongPage } from "../../music/provider.js";
|
||||
@@ -6,7 +6,7 @@ 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). */
|
||||
@@ -41,9 +41,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: Request, 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.
|
||||
@@ -151,19 +181,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);
|
||||
}
|
||||
// A caller who linked their own account gets FM from THEIR taste instead
|
||||
// of the bot's shared login (#164). With per-user accounts enabled the
|
||||
// same account now also resolves playback, so VIP/high-quality tracks
|
||||
// come from that account rather than the admin's.
|
||||
const provider = fmProvider(req, bot, platform);
|
||||
const message = await bot.startFm(provider, requesterName(req));
|
||||
res.json({
|
||||
ok:
|
||||
@@ -335,11 +357,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,11 +446,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();
|
||||
@@ -513,11 +527,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;
|
||||
@@ -749,11 +759,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) {
|
||||
|
||||
@@ -0,0 +1,300 @@
|
||||
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): BotDatabase {
|
||||
return {
|
||||
getUserMusicCookie: () => own,
|
||||
getGrantedMusicAccount: () => granted,
|
||||
} 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);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,162 @@
|
||||
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;
|
||||
}
|
||||
|
||||
/** 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: Request | undefined, deps: MusicScopeDeps): 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: Request | undefined,
|
||||
platform: string,
|
||||
deps: MusicScopeDeps,
|
||||
alwaysPersonal = false,
|
||||
): string | null {
|
||||
if (!alwaysPersonal && !perUserMusicEnabled(deps)) return null;
|
||||
const user = scopedUser(req, deps);
|
||||
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: Request | undefined,
|
||||
platform: string,
|
||||
deps: MusicScopeDeps,
|
||||
): GrantedMusicAccount | null {
|
||||
if (!perUserMusicEnabled(deps)) return null;
|
||||
const user = scopedUser(req, deps);
|
||||
if (!user || !deps.database) return null;
|
||||
return deps.database.getGrantedMusicAccount(user.id!, platform);
|
||||
}
|
||||
|
||||
/** 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: Request | undefined,
|
||||
platform: string,
|
||||
deps: MusicScopeDeps,
|
||||
options: { alwaysPersonal?: boolean } = {},
|
||||
): ResolvedMusicCookie | 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;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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: Request | undefined,
|
||||
platform: string,
|
||||
shared: MusicProvider,
|
||||
deps: MusicScopeDeps,
|
||||
options: { alwaysPersonal?: boolean } = {},
|
||||
): MusicProvider {
|
||||
const resolved = resolveMusicCookie(req, platform, deps, options);
|
||||
if (!resolved) return shared;
|
||||
if (typeof shared.withCookie !== "function") return shared;
|
||||
try {
|
||||
return shared.withCookie(resolved.cookie);
|
||||
} catch {
|
||||
return shared;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user