Compare commits

..
Author SHA1 Message Date
saopig1 3422d45eeb Merge PR #93: fix(audio) smooth, monotonic volume curve (#84)
# Conflicts:
#	src/audio/player.test.ts
#	src/audio/player.ts
2026-06-16 16:29:27 +08:00
saopig1 f7626f40b3 Merge PR #92: fix(player) recover B站 long-stream playback stalls (#89) 2026-06-16 16:26:15 +08:00
saopig1 de2c956c31 Merge PR #91: fix(config) generate config.json under the persisted data dir (#86) 2026-06-16 16:26:15 +08:00
saopig1andClaude Opus 4.8 3802c90d2d fix(audio): smooth, monotonic volume curve (#84)
applyVolume() mapped 0-100 with a two-piece, discontinuous curve: gain =
(vol/100)*0.2 for vol<100 (so the whole 0-99 range only spanned 0..0.198, making
80->99 feel flat) then a raw passthrough at vol===100 (a ~5x jump to full
loudness). That produced the reported dead zone + sudden ear-blast at 100.

Replace it with a single continuous, strictly-monotonic curve
volumeToFactor(v) = 0.2*x + 0.8*x^8 (x = v/100): 0 at 0, exactly 1.0 at 100, no
flat region and no discontinuity, so the slider feels proportional and full
loudness is still reserved at 100. Extracted as an exported pure function and
unit-tested (boundaries, strict monotonicity, dead-zone removal, no jump at 100).

Note: per the maintainer's note on #84 the >80% suppression was intentional
ear-protection; this change makes the upper range (above ~75%) audibly louder
than before in exchange for a proportional slider — applied per maintainer
decision.

Fixes #84

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-16 16:21:09 +08:00
saopig1andClaude Opus 4.8 839f777a75 fix(player): recover B站 long-stream playback stalls instead of going silent (#89)
Two issues caused a long BiliBili stream to stop partway (~16 min) and never resume:

1. FFmpeg lacked -reconnect_at_eof. B站 CDN sessions can close the connection
   mid-file (premature EOF); without this flag FFmpeg treats that EOF as
   end-of-input and stops. Added it (HTTP only) so FFmpeg re-issues a Range
   request and finishes the stream.

2. The frame loop only ended a live-but-silent FFmpeg when within 5s of the song
   end (isNearEnd). Far from the end, emptyFrameAttempts grew unbounded, no
   trackEnd was emitted, and audio went permanently silent ('无法继续播放').
   Added a far-from-end stall watchdog (MAX_STALL_ATTEMPTS ~= 60s) via a pure,
   tested shouldEndOnStall() helper, so a genuinely dead stream advances instead
   of hanging — while a transient underrun on a healthy stream is left alone.

Tests: assert -reconnect_at_eof 1 is present (before -i) for HTTP and absent for
local files; shouldEndOnStall covers near-end fast end, far-from-end no-false-skip,
and far-from-end eventual recovery.

Fixes #89

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-16 15:46:08 +08:00
saopig1andClaude Opus 4.8 dd6affca6d fix(config): store config.json under the persisted data dir (#86)
CONFIG_PATH resolved to ROOT_DIR/config.json (/app/config.json in Docker), but only
DATA_DIR (/app/data) is the mounted volume — every other artifact (DB, cookies, logs,
avatars) already lives under DATA_DIR. So on first run the default config was written
into the ephemeral image layer (never appearing in the volume), and a manually-placed
data/config.json was ignored because the bot read/wrote the root path.

- Move CONFIG_PATH to DATA_DIR/config.json so it lands in the volume and manual edits
  take effect.
- Add migrateLegacyConfig(): one-time move of an existing root-level config.json into
  the data dir, so existing local installs keep their settings (no silent reset).
- Tests for first-run persistence + the three migration cases.
- README directory tree updated to data/config.json.

Fixes #86

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-16 15:33:59 +08:00
saopig1 bea2f92508 Merge PR #80: feat(perm) fine-grained account permissions
Conflict resolution + cross-PR integration:
- player.ts: kept #88's POST /:botId/fm route AND gated it with
  requirePermission('player.control') so the new control endpoint honors #80's
  permission model (it was added without gating).
- bot.ts: kept #81's relocated /settings routes (the relocation fixes the GET
  /settings shadow bug) and dropped #80's now-duplicate bottom copy; gated
  POST /settings with requirePermission('bot.manage').
- Navbar.vue: composed #82's dedicated-link scope with #80's permission filter —
  displayedBots is now the INTERSECTION (scope ∩ controllable allow-list).
- database.ts: kept BOTH new table sets (#87 favorite_playlists + #80
  user_permissions/user_bot_access).
- bot.test.ts: updated to createRequireAuth(sessions, permissions) for #80's new
  two-arg signature.

#80 review fixes (credential exposure / IDOR, adversarially verified):
- GET /:id/config now requires bot.manage + bot access AND redacts ts6ApiKey +
  identity from the response (was readable by any authenticated member).
- GET /:id and GET /:id/avatar now require bot access (were ungated read oracles).
2026-06-16 15:05:57 +08:00
saopig1 f19f56a666 fix(favorites): error handling + state hydration + input validation [#87 review]
- addFavorite/removeFavorite now wrap axios in try/catch: a 409 (already favorited,
  common on a stale heart) or 404 resyncs instead of throwing an unhandled promise
  rejection; other errors surface a toast.
- fetchHomeData refreshes favorites BEFORE the TTL cache-return (was appended after
  the early return, so warm-cache loads never refreshed); removed the now-redundant
  trailing call. App.vue onMounted also hydrates favorites so deep-links to Search/
  Playlist show correct hearts.
- favorites API: GET /check rejects non-string (array) query params with 400 instead
  of a 500; POST defaults req.body to {} so a missing JSON body yields the intended 400.
2026-06-16 14:53:18 +08:00
saopig1 140020f63a Merge PR #87: local favorites feature
# Conflicts:
#	web/src/stores/player.ts
2026-06-16 14:50:25 +08:00
saopig1 6e10764d28 fix(qq-fm): guard FM start when offline + reset radar page on re-login [#88 review]
- startFm() now refuses with 'Bot is not connected to TeamSpeak' before mutating the
  queue, so POST /api/player/:id/fm can no longer wipe the queue and flip the bot into
  FM mode while disconnected (the !fm chat command already had this guard).
- The /fm route's success detection also treats 'not connected' as a failure so the
  toast type is correct.
- QQMusicProvider.setCookie() resets radarPage to 1 so a re-login with a different
  account no longer inherits the previous account's radar pagination cursor.
2026-06-16 14:48:01 +08:00
saopig1 9bfe831022 Merge PR #88: feat(qq) QQ Music radar / personal FM stream 2026-06-16 14:45:51 +08:00
saopig1 bbdd4cbc78 fix(autopause): decouple auto-pause toggle from idle-timeout save [#81 review]
The checkbox @change was wired to saveIdleTimeout, which POSTed BOTH idleTimeoutMinutes
and autoPauseOnEmpty: toggling silently committed an unsaved idle edit, and an empty/
non-numeric idle field made the combined POST 400 (errors swallowed), leaving the
checkbox flipped but not persisted. Give the toggle its own saveAutoPause() sending only
the boolean; 保存 now sends only idleTimeoutMinutes.
2026-06-16 14:45:01 +08:00
saopig1 c57cd35f09 Merge PR #81: feat(autopause) pause when bot channel empties 2026-06-16 14:43:54 +08:00
saopig1 1a1f365cf1 fix(scope): clear scope when the scoped bot is removed [#82 review]
removeBotStatus (botRemoved WS frame or admin deleting the scoped bot) left
scopedBotId dangling: isScoped stayed true, displayedBots went empty, and activeBot
silently fell back to bots[0], locking the UI onto a phantom bot. Clear the scope
when the scoped bot disappears.
2026-06-16 14:43:18 +08:00
saopig1 d1544bab42 Merge PR #82: feat(scope) lock UI to a bot via dedicated link 2026-06-16 14:42:32 +08:00
lTinchl e0d17cf404 feat(qq): add radar FM stream 2026-06-06 21:09:57 +08:00
Kun-ovO b2de607391 本地收藏功能 2026-05-31 23:27:02 +08:00
saopig1 34655e5f50 feat(autopause): autoPauseOnEmpty toggle in Settings 2026-05-30 14:58:35 +08:00
saopig1andClaude Opus 4.8 491bc53dec feat(autopause): expose autoPauseOnEmpty via /api/bot/settings
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-05-30 14:55:18 +08:00
saopig1 8f5bb26b3a feat(autopause): re-emit client enter/leave/move for instant pause/resume 2026-05-30 14:50:52 +08:00
saopig1andClaude Opus 4.8 4ba4b013b0 feat(autopause): drive pause/resume from channel occupancy in BotInstance
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-05-30 14:46:50 +08:00
saopig1 484202e90d feat(autopause): pure occupancy-decision function 2026-05-30 14:44:28 +08:00
saopig1 9f0ac74fbc docs(plan): auto-pause on empty channel implementation plan (#79 item 3) 2026-05-30 14:43:38 +08:00
saopig1andClaude Opus 4.8 51c954993a docs(spec): auto-pause on empty channel design (#79 item 3)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-05-30 14:42:13 +08:00
saopig1andClaude Opus 4.8 907a6651f5 fix(perm): access-check before bot-existence (no 403/404 leak); label permissions audit action
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-05-30 14:12:04 +08:00
saopig1andClaude Opus 4.8 1ca1ca9d0c test(perm): assert /me capabilities+bots; dry backfill token list
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-05-30 14:06:59 +08:00
saopig1andClaude Opus 4.8 d70664067c feat(perm): admin permission editor in user management
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-05-30 14:03:54 +08:00
saopig1 5177b41951 feat(perm): gate Queue.vue remove/clear/play-at controls by capability 2026-05-30 14:00:27 +08:00
saopig1 bb86f7e9ed feat(perm): gate idle-timeout + bot-profile settings on bot.manage 2026-05-30 13:56:46 +08:00
saopig1andClaude Opus 4.8 221f7c8dcf feat(perm): hide UI a member lacks capability for
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-05-30 13:55:31 +08:00
saopig1 cf76e0f69a feat(perm): frontend session capabilities + can()/canControlBot() 2026-05-30 13:51:34 +08:00
saopig1andClaude Opus 4.8 abf60141d9 feat(perm): one-time backfill of existing members to full access
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-05-30 13:47:44 +08:00
saopig1andClaude Opus 4.8 ce15f36e5e feat(perm): admin permissions API + audit + new-member basic tier
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-05-30 13:44:12 +08:00
saopig1andClaude Opus 4.8 1f0f162f66 feat(perm): filter GET /api/bot to allowed bots; prune access on bot delete
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-05-30 13:38:57 +08:00
saopig1andClaude Opus 4.8 cd6f2c6078 feat(perm): enforce capabilities + bot access on action routes
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-05-30 13:32:08 +08:00
saopig1andClaude Opus 4.8 696b224f8d feat(perm): load capabilities + bot access onto req.user; expose via /me
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-05-30 13:21:24 +08:00
saopig1 7a8666efbb feat(perm): resolvePermissionContext (admin = super-user) 2026-05-30 13:17:06 +08:00
saopig1 f0c979ce71 docs(spec): use 'capabilities' consistently for req.user field 2026-05-30 13:15:44 +08:00
saopig1 d810a2ec0f test(perm): cover requireBotAccess 401 + missing-param cases 2026-05-30 13:15:01 +08:00
saopig1andClaude Opus 4.8 554501cc74 feat(perm): requirePermission + requireBotAccess middleware
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-05-30 13:10:39 +08:00
saopig1andClaude Opus 4.8 aaf6ba2ab4 feat(perm): permission store + capability tokens + tables
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-05-30 13:05:38 +08:00
saopig1andClaude Opus 4.8 547aaa304e docs(plan): account permissions implementation plan (#79-E)
11 TDD tasks: permission store + tables, requirePermission/requireBotAccess, req.user wiring, route enforcement, bot-list filtering, admin API + audit, one-time member backfill, and frontend gating + permission editor.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-05-30 12:49:57 +08:00
saopig1andClaude Opus 4.8 f09a589940 docs(spec): fine-grained account permissions design (#79-E)
Capability flags (player.control/player.queue/bot.manage/platform.auth/quality) + per-member bot allow-list, layered under the existing member role; admin is super-user. Backend-enforced via requirePermission/requireBotAccess; existing members backfilled to full on upgrade, new members get a basic tier.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-05-30 12:44:24 +08:00
TIANYAO ZHANG a861b41809 Merge pull request #78 from ZHANGTIANYAO1/feat/shuffle-bag-random-modes
feat(queue): 随机循环改为洗牌袋,每首歌播完一轮再重复 (优化随机循环逻辑)
2026-05-29 22:16:35 +08:00
saopig1andClaude Opus 4.8 e9b3ba0075 feat(queue): shuffle-bag random modes so every song plays before repeating
随机循环 (rloop) used true random-with-replacement, so some songs repeated constantly while others were starved (issue #70). Both random modes now draw from a shuffle bag: every song plays exactly once per cycle in random order. They differ only at cycle end — 随机 (random) stops, 随机循环 (rloop) reshuffles and continues, excluding the just-played song from the first pick of the new cycle to avoid a back-to-back repeat across the boundary. Songs added mid-cycle stay eligible within the current cycle.

随机's visible behavior is unchanged (it already avoided in-cycle repeats); the two branches now share one selection path. Adds shuffle-bag tests (per-cycle permutation, even distribution, no cross-boundary repeat, mid-cycle add).

Closes #70

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-05-29 22:08:40 +08:00
TIANYAO ZHANG 0401534b88 Merge pull request #77 from ZHANGTIANYAO1/fix/webui-referrer-policy-csrf
fix(web): referrer-policy same-origin 修复扫码登录不弹二维码 + cookie 无法保存
2026-05-29 21:30:35 +08:00
saopig1andClaude Opus 4.8 f720da49d6 fix(web): referrer-policy same-origin so same-origin POSTs keep a real Origin
no-referrer downgraded the Origin header to the literal "null" on same-origin non-GET requests (per the WHATWG Fetch "Append a request Origin header" algorithm), which the /api/* csrfOriginCheck then rejected with 403 "bad origin" — silently breaking QR login, cookie save, and every other WebUI POST/PUT/DELETE/PATCH (playback, bot management, user admin). /api/session/* was unaffected because it mounts before the CSRF gate, which is why WebUI login still worked.

same-origin keeps the real Origin on same-origin requests (CSRF passes) while still sending no Referer cross-origin, so B站/NetEase/QQ CDN cover thumbnails keep loading. Adds referrer-policy.test.ts pinning the policy and a csrf.test.ts case for the Origin: "null" rejection.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-05-29 21:25:20 +08:00
58 changed files with 3942 additions and 290 deletions

No files matched your search

+5 -5
View File
@@ -383,11 +383,11 @@ teamspeak-music-bot/
│ └── docker/ # Docker 部署文件 │ └── docker/ # Docker 部署文件
│ ├── Dockerfile │ ├── Dockerfile
│ └── docker-compose.yml │ └── docker-compose.yml
├── data/ # 运行时数据(自动创建,不上传) └── data/ # 运行时数据(自动创建,不上传)
│ ├── tsmusicbot.db # SQLite 数据库 ├── config.json # 配置文件(首次运行自动生成,可手动编辑)
│ ├── cookies/ # 登录 Cookie ├── tsmusicbot.db # SQLite 数据库
│ └── logs/ # 日志文件 ├── cookies/ # 登录 Cookie
└── config.json # 配置文件(首次运行自动生成,不上传) └── logs/ # 日志文件
``` ```
## 技术栈 ## 技术栈
@@ -0,0 +1,811 @@
# Account Permissions Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Let an admin grant each member account a set of capabilities and a list of bots they may control, enforced on the backend.
**Architecture:** Capability tokens + per-member bot allow-list stored in two new SQLite tables, loaded onto `req.user` per request (live, no re-login), enforced by `requirePermission` / `requireBotAccess` middleware mirroring the existing `requireAdmin`. Admin stays a super-user. Existing members are backfilled to full access on upgrade; new members get a basic tier. The Vue UI hides what a member can't do and gives admins a permission editor.
**Tech Stack:** Node ESM + TypeScript, Express, better-sqlite3, Vitest + supertest, Vue 3 + Pinia.
**Spec:** `docs/superpowers/specs/2026-05-30-account-permissions-design.md`
**Conventions:** All file paths are repo-relative. Tests run with `npx vitest run <path>`. Backend is TDD (test first, watch fail, implement, watch pass, commit). Commit after each task.
---
## File Structure
**Create:**
- `src/data/permissions.ts` — capability constants + `PermissionStore` (tables accessed here)
- `src/data/permissions.test.ts` — store + constants tests
- `src/web/middleware/requirePermission.ts` — `requirePermission(cap)` + `requireBotAccess(param)`
- `src/web/middleware/requirePermission.test.ts` — middleware tests
**Modify:**
- `src/data/database.ts` — `initTables`: add the two tables + index; migration backfill of existing members
- `src/data/audit.ts` — add `"user.permissions_changed"` to `AuditAction`
- `src/web/middleware/requireAuth.ts` — widen `req.user`; load capabilities + bot access
- `src/web/auth/validateSession.ts` — (no change; just confirm) — actually unchanged
- `src/web/api/session.ts` — `/me` returns capabilities + bots; inline auth attaches them
- `src/web/server.ts` — construct `PermissionStore`, pass into routers/middleware
- `src/web/api/player.ts` — `requireBotAccess` on `/:botId`; per-route `requirePermission`
- `src/web/api/bot.ts` — `requirePermission("bot.manage")` + `requireBotAccess("id")`
- `src/web/api/auth.ts` — `requirePermission("platform.auth")`
- `src/web/api/music.ts` — `requirePermission("quality")` on the quality POST; filter `GET /api/bot`? no — bot list is in bot.ts
- `src/web/api/bot.ts` — filter `GET /` to allowed bots for members
- `src/web/api/users.ts` — `GET/PUT /api/users/:id/permissions`
- `src/bot/manager.ts` — `removeBot` calls `permissions.pruneBot(botId)`
- Frontend: `web/src/composables/useSession.ts`, `web/src/components/Navbar.vue`, `web/src/components/Player.vue`, `web/src/views/Settings.vue`, `web/src/stores/player.ts`
---
## Task 1: Capability constants + PermissionStore + tables
**Files:**
- Create: `src/data/permissions.ts`
- Create: `src/data/permissions.test.ts`
- Modify: `src/data/database.ts` (initTables)
- [ ] **Step 1: Write the failing test**
`src/data/permissions.test.ts`:
```typescript
import { describe, it, expect, beforeEach, afterEach } from "vitest";
import fs from "node:fs";
import path from "node:path";
import os from "node:os";
import { createDatabase, type BotDatabase } from "./database.js";
import { createPermissionStore } from "./permissions.js";
import { CAPABILITIES, BASIC_TIER_CAPABILITIES } from "./permissions.js";
describe("PermissionStore", () => {
let dbFile: string;
let db: BotDatabase;
beforeEach(() => {
dbFile = path.join(os.tmpdir(), `perm-test-${Date.now()}-${Math.random().toString(36).slice(2)}.db`);
db = createDatabase(dbFile);
// a user row is required for FK; insert directly
db.db.prepare(
"INSERT INTO users (id, username, passwordHash, createdAt, updatedAt, role) VALUES (?,?,?,?,?,?)"
).run("u1", "alice", "x", Date.now(), Date.now(), "member");
});
afterEach(() => {
db.close();
try { fs.rmSync(dbFile, { force: true }); } catch {}
try { fs.rmSync(dbFile + "-wal", { force: true }); } catch {}
try { fs.rmSync(dbFile + "-shm", { force: true }); } catch {}
});
it("exposes the five capability tokens and a basic tier", () => {
expect(CAPABILITIES).toEqual([
"player.control", "player.queue", "bot.manage", "platform.auth", "quality",
]);
expect(BASIC_TIER_CAPABILITIES).toEqual(["player.control", "player.queue"]);
});
it("defaults to no capabilities and no bots", () => {
const store = createPermissionStore(db.db);
expect(store.getCapabilities("u1")).toEqual([]);
expect(store.getBotAccess("u1")).toEqual([]);
});
it("round-trips capabilities and a specific bot list", () => {
const store = createPermissionStore(db.db);
store.setPermissions("u1", { capabilities: ["player.control", "quality"], bots: ["botA", "botB"] });
expect(store.getCapabilities("u1").sort()).toEqual(["player.control", "quality"]);
expect(store.getBotAccess("u1")).toEqual(["botA", "botB"]);
});
it("stores the all-bots flag as 'all'", () => {
const store = createPermissionStore(db.db);
store.setPermissions("u1", { capabilities: ["player.control"], bots: "all" });
expect(store.getBotAccess("u1")).toBe("all");
});
it("setPermissions replaces prior capabilities and bots", () => {
const store = createPermissionStore(db.db);
store.setPermissions("u1", { capabilities: ["player.control"], bots: ["botA"] });
store.setPermissions("u1", { capabilities: ["quality"], bots: "all" });
expect(store.getCapabilities("u1")).toEqual(["quality"]);
expect(store.getBotAccess("u1")).toBe("all");
});
it("ignores unknown capability tokens", () => {
const store = createPermissionStore(db.db);
store.setPermissions("u1", { capabilities: ["player.control", "bogus" as any], bots: [] });
expect(store.getCapabilities("u1")).toEqual(["player.control"]);
});
it("pruneBot removes a bot from every user's allow-list", () => {
const store = createPermissionStore(db.db);
store.setPermissions("u1", { capabilities: [], bots: ["botA", "botB"] });
store.pruneBot("botA");
expect(store.getBotAccess("u1")).toEqual(["botB"]);
});
});
```
- [ ] **Step 2: Run test to verify it fails**
Run: `npx vitest run src/data/permissions.test.ts`
Expected: FAIL — `createPermissionStore` / `CAPABILITIES` not found (module missing).
- [ ] **Step 3: Create `src/data/permissions.ts`**
```typescript
import type Database from "better-sqlite3";
export const CAPABILITIES = [
"player.control",
"player.queue",
"bot.manage",
"platform.auth",
"quality",
] as const;
export type Capability = (typeof CAPABILITIES)[number];
/** Marker token stored in user_permissions meaning "all bots, incl. future". */
export const BOTS_ALL = "bots.all";
/** Capabilities granted to a newly-created member by default. */
export const BASIC_TIER_CAPABILITIES: Capability[] = ["player.control", "player.queue"];
export function isCapability(x: string): x is Capability {
return (CAPABILITIES as readonly string[]).includes(x);
}
export type BotAccess = "all" | string[];
export interface PermissionStore {
getCapabilities(userId: string): Capability[];
getBotAccess(userId: string): BotAccess;
setPermissions(userId: string, input: { capabilities: string[]; bots: BotAccess }): void;
pruneBot(botId: string): void;
}
export function createPermissionStore(db: Database.Database): PermissionStore {
const selCaps = db.prepare("SELECT permission FROM user_permissions WHERE userId = ?");
const delCaps = db.prepare("DELETE FROM user_permissions WHERE userId = ?");
const insCap = db.prepare("INSERT OR IGNORE INTO user_permissions (userId, permission) VALUES (?, ?)");
const selBots = db.prepare("SELECT botId FROM user_bot_access WHERE userId = ?");
const delBots = db.prepare("DELETE FROM user_bot_access WHERE userId = ?");
const insBot = db.prepare("INSERT OR IGNORE INTO user_bot_access (userId, botId) VALUES (?, ?)");
const pruneBotStmt = db.prepare("DELETE FROM user_bot_access WHERE botId = ?");
return {
getCapabilities(userId) {
return (selCaps.all(userId) as { permission: string }[])
.map((r) => r.permission)
.filter((p): p is Capability => isCapability(p));
},
getBotAccess(userId) {
const all = (selCaps.all(userId) as { permission: string }[]).some((r) => r.permission === BOTS_ALL);
if (all) return "all";
return (selBots.all(userId) as { botId: string }[]).map((r) => r.botId);
},
setPermissions(userId, input) {
const caps = input.capabilities.filter(isCapability);
const tx = db.transaction(() => {
delCaps.run(userId);
delBots.run(userId);
for (const c of caps) insCap.run(userId, c);
if (input.bots === "all") {
insCap.run(userId, BOTS_ALL);
} else {
for (const b of input.bots) insBot.run(userId, b);
}
});
tx();
},
pruneBot(botId) {
pruneBotStmt.run(botId);
},
};
}
```
- [ ] **Step 4: Add tables in `src/data/database.ts` initTables**
Find `initTables` (creates users/sessions/user_audit). Add, after the `user_audit` CREATE:
```typescript
db.exec(`
CREATE TABLE IF NOT EXISTS user_permissions (
userId TEXT NOT NULL,
permission TEXT NOT NULL,
PRIMARY KEY (userId, permission),
FOREIGN KEY (userId) REFERENCES users(id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS user_bot_access (
userId TEXT NOT NULL,
botId TEXT NOT NULL,
PRIMARY KEY (userId, botId),
FOREIGN KEY (userId) REFERENCES users(id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_user_bot_access_userId ON user_bot_access(userId);
`);
```
(If `initTables` uses individual `db.exec` calls, match that style. The `BotDatabase` type already exposes `.db` and `.close()` — confirm by reading the file; the test uses `db.db` and `db.close()`.)
- [ ] **Step 5: Run tests to verify they pass**
Run: `npx vitest run src/data/permissions.test.ts`
Expected: PASS (7 tests).
- [ ] **Step 6: Commit**
```bash
git add src/data/permissions.ts src/data/permissions.test.ts src/data/database.ts
git commit -m "feat(perm): permission store + capability tokens + tables"
```
---
## Task 2: requirePermission + requireBotAccess middleware
**Files:**
- Create: `src/web/middleware/requirePermission.ts`
- Create: `src/web/middleware/requirePermission.test.ts`
- Modify: `src/web/middleware/requireAuth.ts` (widen `req.user`)
- [ ] **Step 1: Widen the `req.user` augmentation in `src/web/middleware/requireAuth.ts`**
Change the `declare module` block so `req.user` carries capabilities + bot access:
```typescript
declare module "express-serve-static-core" {
interface Request {
user?: {
id: string;
username: string;
role: "admin" | "member";
capabilities: Set<string>;
bots: "all" | Set<string>;
};
}
}
```
(The loading of these fields is done in Task 4 — for now this only widens the type. Existing assignments to `req.user` will fail to typecheck until Task 4; that is expected and Task 4 fixes them. If you need the build green between tasks, do Task 2 + Task 4 back-to-back before running `tsc`.)
- [ ] **Step 2: Write the failing middleware test**
`src/web/middleware/requirePermission.test.ts`:
```typescript
import { describe, it, expect } from "vitest";
import express from "express";
import request from "supertest";
import { requirePermission, requireBotAccess } from "./requirePermission.js";
function appWith(user: any) {
const app = express();
app.use((req, _res, next) => { (req as any).user = user; next(); });
app.post("/cap", requirePermission("quality"), (_req, res) => res.json({ ok: true }));
app.post("/bot/:botId", requireBotAccess("botId"), (_req, res) => res.json({ ok: true }));
return app;
}
const member = (caps: string[], bots: "all" | string[]) => ({
id: "u1", username: "a", role: "member",
capabilities: new Set(caps), bots: bots === "all" ? "all" : new Set(bots),
});
const admin = { id: "a", username: "admin", role: "admin", capabilities: new Set(), bots: "all" };
describe("requirePermission", () => {
it("401 when unauthenticated", async () => {
const app = express();
app.post("/cap", requirePermission("quality"), (_r, res) => res.json({ ok: true }));
expect((await request(app).post("/cap")).status).toBe(401);
});
it("403 when member lacks the capability", async () => {
expect((await request(appWith(member([], "all"))).post("/cap")).status).toBe(403);
});
it("200 when member has the capability", async () => {
expect((await request(appWith(member(["quality"], "all"))).post("/cap")).status).toBe(200);
});
it("200 for admin regardless of capabilities", async () => {
expect((await request(appWith(admin)).post("/cap")).status).toBe(200);
});
});
describe("requireBotAccess", () => {
it("200 when bots = all", async () => {
expect((await request(appWith(member([], "all"))).post("/bot/b1")).status).toBe(200);
});
it("200 when botId in allow-list", async () => {
expect((await request(appWith(member([], ["b1"]))).post("/bot/b1")).status).toBe(200);
});
it("403 when botId not in allow-list", async () => {
expect((await request(appWith(member([], ["b2"]))).post("/bot/b1")).status).toBe(403);
});
it("200 for admin", async () => {
expect((await request(appWith(admin)).post("/bot/b1")).status).toBe(200);
});
});
```
- [ ] **Step 3: Run test to verify it fails**
Run: `npx vitest run src/web/middleware/requirePermission.test.ts`
Expected: FAIL — module `./requirePermission.js` not found.
- [ ] **Step 4: Create `src/web/middleware/requirePermission.ts`**
```typescript
import type { Request, Response, NextFunction, RequestHandler } from "express";
export function requirePermission(capability: string): RequestHandler {
return (req: Request, res: Response, next: NextFunction) => {
if (!req.user) { res.status(401).json({ error: "unauthenticated" }); return; }
if (req.user.role === "admin" || req.user.capabilities.has(capability)) { next(); return; }
res.status(403).json({ error: "forbidden" });
};
}
export function requireBotAccess(paramName = "botId"): RequestHandler {
return (req: Request, res: Response, next: NextFunction) => {
if (!req.user) { res.status(401).json({ error: "unauthenticated" }); return; }
if (req.user.role === "admin" || req.user.bots === "all") { next(); return; }
const botId = req.params[paramName];
if (botId && req.user.bots.has(botId)) { next(); return; }
res.status(403).json({ error: "forbidden" });
};
}
```
- [ ] **Step 5: Run test to verify it passes**
Run: `npx vitest run src/web/middleware/requirePermission.test.ts`
Expected: PASS (8 tests).
- [ ] **Step 6: Commit**
```bash
git add src/web/middleware/requirePermission.ts src/web/middleware/requirePermission.test.ts src/web/middleware/requireAuth.ts
git commit -m "feat(perm): requirePermission + requireBotAccess middleware"
```
---
## Task 3: Effective-permissions resolver (admin = all)
**Files:**
- Modify: `src/data/permissions.ts` (add `resolveContext` helper)
- Modify: `src/data/permissions.test.ts` (add tests)
- [ ] **Step 1: Add failing tests** to `src/data/permissions.test.ts`:
```typescript
import { resolvePermissionContext } from "./permissions.js";
describe("resolvePermissionContext", () => {
it("admin gets all capabilities and all bots regardless of stored rows", () => {
const store = createPermissionStore(db.db);
const ctx = resolvePermissionContext("admin", "u1", store);
expect([...ctx.capabilities].sort()).toEqual([...CAPABILITIES].sort());
expect(ctx.bots).toBe("all");
});
it("member reflects stored capabilities + bot access", () => {
const store = createPermissionStore(db.db);
store.setPermissions("u1", { capabilities: ["player.control"], bots: ["b1"] });
const ctx = resolvePermissionContext("member", "u1", store);
expect([...ctx.capabilities]).toEqual(["player.control"]);
expect(ctx.bots).toEqual(new Set(["b1"]));
});
});
```
- [ ] **Step 2: Run to verify fail**
Run: `npx vitest run src/data/permissions.test.ts`
Expected: FAIL — `resolvePermissionContext` not exported.
- [ ] **Step 3: Add to `src/data/permissions.ts`**
```typescript
export interface PermissionContext {
capabilities: Set<string>;
bots: "all" | Set<string>;
}
export function resolvePermissionContext(
role: "admin" | "member",
userId: string,
store: PermissionStore
): PermissionContext {
if (role === "admin") {
return { capabilities: new Set(CAPABILITIES), bots: "all" };
}
const access = store.getBotAccess(userId);
return {
capabilities: new Set(store.getCapabilities(userId)),
bots: access === "all" ? "all" : new Set(access),
};
}
```
- [ ] **Step 4: Run to verify pass**
Run: `npx vitest run src/data/permissions.test.ts`
Expected: PASS.
- [ ] **Step 5: Commit**
```bash
git add src/data/permissions.ts src/data/permissions.test.ts
git commit -m "feat(perm): resolvePermissionContext (admin = super-user)"
```
---
## Task 4: Load permissions onto req.user (requireAuth + session inline + /me)
**Files:**
- Modify: `src/web/middleware/requireAuth.ts`
- Modify: `src/web/api/session.ts`
- Modify: `src/web/server.ts`
- [ ] **Step 1: Thread `PermissionStore` into `createRequireAuth`**
`src/web/middleware/requireAuth.ts` — change the factory signature and set the new fields:
```typescript
import { resolvePermissionContext, type PermissionStore } from "../../data/permissions.js";
export function createRequireAuth(sessions: SessionStore, permissions: PermissionStore): RequestHandler {
return function requireAuth(req, res, next) {
const result = validateSessionFromHeaders(req.headers.cookie, sessions);
if (!result) {
res.clearCookie(SESSION_COOKIE_NAME, { path: "/" });
res.status(401).json({ error: "unauthenticated" });
return;
}
const ctx = resolvePermissionContext(result.role, result.userId, permissions);
req.user = {
id: result.userId, username: result.username, role: result.role,
capabilities: ctx.capabilities, bots: ctx.bots,
};
const token = extractSessionToken(req.headers.cookie);
if (token) {
res.cookie(SESSION_COOKIE_NAME, token, {
httpOnly: true, sameSite: "lax", secure: req.secure, path: "/", maxAge: SESSION_TTL_MS,
});
}
next();
};
}
```
- [ ] **Step 2: Update `src/web/server.ts`**
Construct the store next to the others and pass it in:
```typescript
import { createPermissionStore } from "../data/permissions.js";
// ...
const permissions = createPermissionStore(options.database.db);
// ...
const requireAuth = createRequireAuth(sessions, permissions);
```
Keep `permissions` in scope — it's passed to routers in Tasks 5–7.
- [ ] **Step 3: Update session inline auth + `/me` in `src/web/api/session.ts`**
`createSessionRouter` must accept `permissions` and (a) attach capabilities in `requireAuthInline`, (b) include them in `/me`. Pass `permissions` from `server.ts` into `createSessionRouter(users, sessions, audit, logger, permissions)`. In the `/me` handler, return:
```typescript
const ctx = resolvePermissionContext(validation.role, validation.userId, permissions);
res.json({
id: validation.userId, username: validation.username, role: validation.role,
capabilities: [...ctx.capabilities],
bots: ctx.bots === "all" ? "all" : [...ctx.bots],
});
```
(Match the existing `/me` shape; just add `capabilities` + `bots`. Read the file to find the exact response object.)
- [ ] **Step 4: Verify build + existing tests**
Run: `npx tsc --noEmit`
Expected: exit 0 (the widened `req.user` is now populated everywhere it's read).
Run: `npx vitest run src/web`
Expected: PASS (existing auth/session/csrf tests still green; if a test constructs `createRequireAuth(sessions)` it must be updated to pass a `createPermissionStore(db)`).
- [ ] **Step 5: Commit**
```bash
git add src/web/middleware/requireAuth.ts src/web/server.ts src/web/api/session.ts
git commit -m "feat(perm): load capabilities + bot access onto req.user; expose via /me"
```
---
## Task 5: Enforce capabilities on the action routes
**Files:**
- Modify: `src/web/api/player.ts`, `src/web/api/bot.ts`, `src/web/api/auth.ts`, `src/web/api/music.ts`
- Modify: `src/web/api/player.test.ts` (or create `src/web/api/permissions-enforcement.test.ts`)
- [ ] **Step 1: Write a failing integration test** at `src/web/api/permissions-enforcement.test.ts` that builds the real app (or the relevant router) with a stubbed `req.user` and asserts:
- member without `player.control` → `POST /api/player/:botId/pause` → 403
- member with `player.control` + bot in allow-list → 200 (bot resolves)
- member with `player.control` but bot NOT in allow-list → 403
- member without `player.queue` → `POST /api/player/:botId/clear` → 403
- member without `bot.manage` → `POST /api/bot` → 403
- member without `platform.auth` → `POST /api/auth/cookie` → 403
- member without `quality` → `POST /api/music/quality` → 403
- admin → all 200/allowed
Use the same `appWith(user)` injection pattern as Task 2 (insert a middleware that sets `req.user` before the router) and a fake `BotManager`/providers so routes resolve. Model it on the existing `src/web/api/*.test.ts` setup (read one first for the harness).
- [ ] **Step 2: Run to verify fail** — `npx vitest run src/web/api/permissions-enforcement.test.ts` → FAIL (routes currently allow everyone).
- [ ] **Step 3: Apply gates.**
`src/web/api/player.ts` — the shared `/:botId` middleware already resolves the bot. Add bot-access there, and add per-action capability guards. Define the queue-capability routes vs control routes:
```typescript
import { requirePermission, requireBotAccess } from "../middleware/requirePermission.js";
// after the existing router.use("/:botId", resolveBot):
router.use("/:botId", requireBotAccess("botId"));
const control = requirePermission("player.control");
const queue = requirePermission("player.queue");
// control: play, pause, resume, next, prev, stop, seek, volume, mode, play-song, play-at, play-by-id, play-playlist, play-album, play-next-song
// queue: add, add-song, add-by-id, clear, playlist, /queue/:index (DELETE)
// Apply per route, e.g.:
router.post("/:botId/pause", control, async (req, res) => { /* existing */ });
router.post("/:botId/add", queue, async (req, res) => { /* existing */ });
router.delete("/:botId/queue/:index", queue, async (req, res) => { /* existing */ });
```
(Insert the `control`/`queue` middleware as the 2nd arg of each existing `router.post/delete`. Do not change handler bodies. `PUT /:botId/profile` → `requirePermission("bot.manage")`.)
`src/web/api/bot.ts` — gate management + per-bot:
```typescript
const manage = requirePermission("bot.manage");
router.post("/", manage, ...); // create (no botId)
router.put("/:id", manage, requireBotAccess("id"), ...);
router.delete("/:id", manage, requireBotAccess("id"), ...);
router.post("/:id/start", manage, requireBotAccess("id"), ...);
router.post("/:id/stop", manage, requireBotAccess("id"), ...);
router.put("/:id/avatar", manage, requireBotAccess("id"), ...);
router.delete("/:id/avatar", manage, requireBotAccess("id"), ...);
router.post("/settings", manage, ...); // global idle timeout
```
`src/web/api/auth.ts` — gate every mutating route with `requirePermission("platform.auth")`:
`POST /qrcode`, `POST /sms/send`, `POST /sms/verify`, `POST /cookie`. (Leave `GET /status`, `GET /qrcode/status` open — read-only.)
`src/web/api/music.ts` — gate the one mutating route:
`router.post("/quality", requirePermission("quality"), ...)`.
- [ ] **Step 4: Run to verify pass** — `npx vitest run src/web/api/permissions-enforcement.test.ts` → PASS. Then `npx vitest run src/web` → all green.
- [ ] **Step 5: Commit**
```bash
git add src/web/api/player.ts src/web/api/bot.ts src/web/api/auth.ts src/web/api/music.ts src/web/api/permissions-enforcement.test.ts
git commit -m "feat(perm): enforce capabilities + bot access on action routes"
```
---
## Task 6: Filter the bot list for members
**Files:**
- Modify: `src/web/api/bot.ts` (`GET /`)
- Modify: `src/bot/manager.ts` (`removeBot` → `permissions.pruneBot`)
- Modify: test from Task 5
- [ ] **Step 1: Add failing test** — member with `bots: ["b1"]` calling `GET /api/bot` sees only `b1`; admin sees all.
- [ ] **Step 2: Run → fail.**
- [ ] **Step 3: Implement.** In `GET /` of `bot.ts`:
```typescript
const all = getAllBots().map((b) => b.getStatus());
const u = req.user!;
const bots = u.role === "admin" || u.bots === "all"
? all
: all.filter((b) => (u.bots as Set<string>).has(b.id));
res.json({ bots });
```
In `src/bot/manager.ts`, give `BotManager` access to the `PermissionStore` (constructor param) and call `this.permissions.pruneBot(id)` inside `removeBot(id)` after deletion, so deleted bots drop out of allow-lists. Thread `permissions` from `index.ts`/`server.ts` into `BotManager`.
- [ ] **Step 4: Run → pass; `npx vitest run src/web src/bot` green.**
- [ ] **Step 5: Commit**
```bash
git add src/web/api/bot.ts src/bot/manager.ts src/web/api/permissions-enforcement.test.ts
git commit -m "feat(perm): filter GET /api/bot to allowed bots; prune access on bot delete"
```
---
## Task 7: Management API (GET/PUT permissions) + audit
**Files:**
- Modify: `src/data/audit.ts` (add action)
- Modify: `src/web/api/users.ts` (+ permissions endpoints; new-member default)
- Modify: `src/web/server.ts` (pass `permissions` into `createUsersRouter`)
- Create/extend: `src/web/api/users.test.ts`
- [ ] **Step 1: Add `"user.permissions_changed"`** to the `AuditAction` union in `src/data/audit.ts`.
- [ ] **Step 2: Write failing tests** for the users router (admin-only):
- `GET /api/users/:id/permissions` → `{ capabilities: [], bots: [] }` for a fresh member.
- `PUT /api/users/:id/permissions` with `{capabilities:["player.control"], bots:"all"}` → 200; subsequent GET reflects it; an audit row `user.permissions_changed` exists.
- `PUT` with an unknown capability token → it is dropped (not stored).
- New member created via `POST /api/users` → GET permissions returns basic tier (`["player.control","player.queue"]`, bots `"all"`).
- [ ] **Step 3: Run → fail.**
- [ ] **Step 4: Implement** in `src/web/api/users.ts` (router already admin-gated at mount). Accept `permissions: PermissionStore` param. Add:
```typescript
import { CAPABILITIES, isCapability, BASIC_TIER_CAPABILITIES } from "../../data/permissions.js";
router.get("/:id/permissions", (req, res) => {
const user = users.findById(req.params.id);
if (!user) { res.status(404).json({ error: "not_found" }); return; }
res.json({ capabilities: permissions.getCapabilities(user.id), bots: permissions.getBotAccess(user.id) });
});
router.put("/:id/permissions", (req, res) => {
const user = users.findById(req.params.id);
if (!user) { res.status(404).json({ error: "not_found" }); return; }
const body = req.body ?? {};
const caps = Array.isArray(body.capabilities) ? body.capabilities.filter(isCapability) : [];
const bots = body.bots === "all" ? "all" : (Array.isArray(body.bots) ? body.bots.map(String) : []);
permissions.setPermissions(user.id, { capabilities: caps, bots });
audit.record({
actorId: req.user!.id, actorUsername: req.user!.username,
targetUserId: user.id, targetUsername: user.username,
action: "user.permissions_changed",
});
res.json({ success: true });
});
```
In the existing `POST /api/users` handler, after creating a member, seed the basic tier:
```typescript
if (created.role === "member") {
permissions.setPermissions(created.id, { capabilities: BASIC_TIER_CAPABILITIES, bots: "all" });
}
```
- [ ] **Step 5: Run → pass; `npx vitest run src/web` green.**
- [ ] **Step 6: Commit**
```bash
git add src/data/audit.ts src/web/api/users.ts src/web/server.ts src/web/api/users.test.ts
git commit -m "feat(perm): admin permissions API + audit + new-member basic tier"
```
---
## Task 8: One-time migration backfill (existing members → full)
**Files:**
- Modify: `src/data/database.ts` (`migrateSchema` or a dedicated backfill)
- Create: `src/data/permissions-migration.test.ts`
- [ ] **Step 1: Write failing test** — given a fresh db with an existing `member` user and NO permission rows, after `createDatabase()` runs the backfill, that member has all 5 capabilities + `bots.all`; an `admin` user gets nothing (bypasses). Backfill is idempotent (running twice does not duplicate / does not re-grant a member who was later restricted to empty).
Idempotency approach: store a one-shot marker. Use a `meta` row or check: only backfill members who currently have ZERO permission rows AND only on first introduction. Simplest robust marker: a row in a tiny `schema_meta(key TEXT PK, value TEXT)` table, key `perm_backfill_done`. If present, skip.
- [ ] **Step 2: Run → fail.**
- [ ] **Step 3: Implement** a `backfillMemberPermissions(db)` run once inside `createDatabase` after `initTables`:
```typescript
db.exec(`CREATE TABLE IF NOT EXISTS schema_meta (key TEXT PRIMARY KEY, value TEXT)`);
const done = db.prepare("SELECT value FROM schema_meta WHERE key = 'perm_backfill_done'").get();
if (!done) {
const members = db.prepare("SELECT id FROM users WHERE role = 'member'").all() as { id: string }[];
const insCap = db.prepare("INSERT OR IGNORE INTO user_permissions (userId, permission) VALUES (?, ?)");
const tx = db.transaction(() => {
for (const m of members) {
for (const c of ["player.control","player.queue","bot.manage","platform.auth","quality","bots.all"]) {
insCap.run(m.id, c);
}
}
db.prepare("INSERT INTO schema_meta (key, value) VALUES ('perm_backfill_done', ?)").run(String(Date.now()));
});
tx();
}
```
- [ ] **Step 4: Run → pass.**
- [ ] **Step 5: Commit**
```bash
git add src/data/database.ts src/data/permissions-migration.test.ts
git commit -m "feat(perm): one-time backfill of existing members to full access"
```
---
## Task 9: Frontend — session capabilities + helpers
**Files:**
- Modify: `web/src/composables/useSession.ts`
- [ ] **Step 1:** Extend the `User` type with `capabilities: string[]` and `bots: 'all' | string[]`; populate from `/api/session/me`, `/login`, `/setup` responses (the backend now returns them).
- [ ] **Step 2:** Add computed helpers:
```typescript
function can(cap: string): boolean {
const u = currentUser.value;
return !!u && (u.role === 'admin' || (u.capabilities ?? []).includes(cap));
}
function canControlBot(botId: string): boolean {
const u = currentUser.value;
if (!u) return false;
if (u.role === 'admin' || u.bots === 'all') return true;
return Array.isArray(u.bots) && u.bots.includes(botId);
}
```
Export `can` and `canControlBot` from the composable.
- [ ] **Step 3:** Manual check: log in as admin → `can('quality')` true; (after backend done) a restricted member → false. Build: `cd web && npx vue-tsc --noEmit`.
- [ ] **Step 4: Commit** `git add web/src/composables/useSession.ts && git commit -m "feat(perm): frontend session capabilities + can()/canControlBot()"`
---
## Task 10: Frontend — gate UI by capability + filter bots
**Files:**
- Modify: `web/src/components/Navbar.vue`, `web/src/components/Player.vue`, `web/src/views/Settings.vue`, `web/src/stores/player.ts`
- [ ] **Step 1:** Navbar bot selector: render only controllable bots — `v-for="bot in store.bots"` becomes a filtered computed `controllableBots = store.bots.filter(b => session.canControlBot(b.id))`. (The backend already filters `GET /api/bot`, so this is belt-and-suspenders + correctness if both lists diverge.) Ensure `store.activeBot` fallback never lands on a bot the user can't control.
- [ ] **Step 2:** Player.vue: wrap control buttons with `v-if="session.can('player.control')"` and queue actions with `v-if="session.can('player.queue')"`.
- [ ] **Step 3:** Settings.vue: wrap the platform login cards with `v-if="session.can('platform.auth')"`, the audio-quality control with `v-if="session.can('quality')"`, and bot create/edit/delete with `v-if="session.can('bot.manage')"`.
- [ ] **Step 4:** Manual verification (see Verification section). Build: `cd web && npx vue-tsc --noEmit`.
- [ ] **Step 5: Commit** `git add web/src/components/Navbar.vue web/src/components/Player.vue web/src/views/Settings.vue web/src/stores/player.ts && git commit -m "feat(perm): hide UI a member lacks capability for"`
---
## Task 11: Frontend — admin permission editor
**Files:**
- Modify: `web/src/views/Settings.vue` (User Management section)
- [ ] **Step 1:** In each member row of the admin User-Management list, add a "权限" button opening an editor (inline panel or dialog) with: 5 capability checkboxes (labels: 播放控制 / 队列管理 / 机器人管理 / 平台登录凭据 / 音质设置), and a bot allow-list — an "全部机器人" toggle plus, when off, a checkbox per bot from `store.bots`.
- [ ] **Step 2:** On open, `GET /api/users/:id/permissions`; on save, `PUT /api/users/:id/permissions` with `{capabilities, bots}` then re-fetch. Admin rows show "全部权限(管理员)" and no editor.
- [ ] **Step 3:** Manual verification. Build: `cd web && npx vue-tsc --noEmit`.
- [ ] **Step 4: Commit** `git add web/src/views/Settings.vue && git commit -m "feat(perm): admin permission editor in user management"`
---
## Final verification
- [ ] `npx tsc --noEmit` → exit 0
- [ ] `npx vitest run src/` → all green (clean-checkout-equivalent; ignore stale `dist/` twins — see note)
- [ ] `cd web && npx vue-tsc --noEmit` → exit 0
- [ ] `npm run build` → succeeds
- [ ] Manual (run the bot, log in): admin sees everything; create a member, restrict to `player.control` on one bot → member sees only that bot, can play/pause but cannot add to queue, cannot open platform login / quality / bot management; backend returns 403 on a forged request to a disallowed action (verify with curl + the member's session cookie).
> **Note (pre-existing):** `tsconfig.json` compiles `*.test.ts` into `dist/`, and vitest also runs the `dist/` twins after a build — so `npx vitest run` (no path) double-runs and can fail on stale artifacts. Scope verification to `npx vitest run src/`. (A separate cleanup PR could add `exclude: ['**/dist/**']` to a vitest config.)
## Out of scope (separate PRs, per spec)
#1 guest mode · #2 dedicated-link bot hiding UX · #3 auto-pause on empty channel · #4 dedicated-link refresh bug.
@@ -0,0 +1,196 @@
# Auto-pause on Empty Channel — Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: superpowers:subagent-driven-development. Steps use checkbox (`- [ ]`) syntax.
**Goal:** Auto-pause playback when the bot's channel empties (no disconnect) and auto-resume when someone returns — only resuming tracks we auto-paused — gated by the existing global `autoPauseOnEmpty` flag.
**Architecture:** A pure decision function decides pause/resume from (player state, autoPaused, flag, userCount). `BotInstance` owns an `autoPaused` flag and a `checkChannelOccupancy()` that the existing 30s idle poll AND new TS enter/leave/move events both call. The toggle is wired into `/api/bot/settings` + the Settings UI.
**Tech:** Node ESM + TS, Vitest, Express, Vue 3.
**Spec:** `docs/superpowers/specs/2026-05-30-autopause-empty-channel-design.md`
---
## Task 1: Pure occupancy-decision function
**Files:** Create `src/bot/auto-pause.ts`, `src/bot/auto-pause.test.ts`.
- [ ] **Step 1 — failing test** `src/bot/auto-pause.test.ts`:
```typescript
import { describe, it, expect } from "vitest";
import { decideOccupancyAction } from "./auto-pause.js";
describe("decideOccupancyAction", () => {
// (playerState, autoPaused, enabled, userCount) => "pause" | "resume" | "none"
it("pauses when empty while playing and enabled", () => {
expect(decideOccupancyAction("playing", false, true, 0)).toBe("pause");
});
it("does not pause when the feature is disabled", () => {
expect(decideOccupancyAction("playing", false, false, 0)).toBe("none");
});
it("does not pause when idle (nothing playing)", () => {
expect(decideOccupancyAction("idle", false, true, 0)).toBe("none");
});
it("does not pause when already paused", () => {
expect(decideOccupancyAction("paused", false, true, 0)).toBe("none");
});
it("resumes when re-populated and we auto-paused", () => {
expect(decideOccupancyAction("paused", true, true, 2)).toBe("resume");
});
it("does NOT resume a user-paused track on re-population", () => {
expect(decideOccupancyAction("paused", false, true, 2)).toBe("none");
});
it("does nothing when re-populated and already playing", () => {
expect(decideOccupancyAction("playing", false, true, 2)).toBe("none");
});
it("resume is independent of the enabled flag (we already auto-paused)", () => {
expect(decideOccupancyAction("paused", true, false, 1)).toBe("resume");
});
});
```
- [ ] **Step 2 — run, expect fail:** `npx vitest run src/bot/auto-pause.test.ts` → module missing.
- [ ] **Step 3 — implement** `src/bot/auto-pause.ts`:
```typescript
export type PlayerStateName = "idle" | "playing" | "paused";
export type OccupancyAction = "pause" | "resume" | "none";
/**
* Decide what auto-pause should do given the channel occupancy.
* - empty (userCount <= 0): pause iff enabled and currently playing.
* - re-populated (userCount > 0): resume iff we previously auto-paused and are still paused.
* `autoPaused` distinguishes our auto-pause from a user pause, so user pauses are never resumed.
*/
export function decideOccupancyAction(
playerState: PlayerStateName,
autoPaused: boolean,
enabled: boolean,
userCount: number,
): OccupancyAction {
const empty = userCount <= 0;
if (empty) {
if (enabled && playerState === "playing") return "pause";
return "none";
}
if (autoPaused && playerState === "paused") return "resume";
return "none";
}
```
- [ ] **Step 4 — run, expect pass:** `npx vitest run src/bot/auto-pause.test.ts` → 8 pass.
- [ ] **Step 5 — commit:** `git add src/bot/auto-pause.ts src/bot/auto-pause.test.ts && git commit -m "feat(autopause): pure occupancy-decision function"`
---
## Task 2: Wire decision into BotInstance (autoPaused flag + checkChannelOccupancy)
**Files:** Modify `src/bot/instance.ts`.
Context: `_startIdlePoller` (~lines 190-206) polls every 30s, computes `userCount = (await getClientsInChannel()).length - 1`, and calls `_scheduleIdleCheck()` (empty) / `_cancelIdleTimer()` (occupied). `cmdPause`/`cmdResume` (~484-494), `cmdStop` (~496-505), and the playback start (`cmdPlay`/resolveAndPlay) wrap `player`. There's an unused `channelUserCount` field (~line 68). The instance has `this.config` (BotConfig) and `this.player`.
- [ ] **Step 1 — add state + helper.** Add a private field `private autoPaused = false;`. Create a method that centralizes occupancy handling and is called with a freshly-computed userCount:
```typescript
import { decideOccupancyAction } from "./auto-pause.js";
private handleOccupancy(userCount: number): void {
// idle-disconnect (unchanged behavior)
if (userCount <= 0) this._scheduleIdleCheck();
else this._cancelIdleTimer();
// auto-pause
const action = decideOccupancyAction(
this.player.getState() as "idle" | "playing" | "paused",
this.autoPaused,
this.config.autoPauseOnEmpty,
userCount,
);
if (action === "pause") {
this.player.pause();
this.autoPaused = true;
this.emit("stateChange");
} else if (action === "resume") {
this.player.resume();
this.autoPaused = false;
this.emit("stateChange");
}
}
```
- [ ] **Step 2 — route the idle poller through it.** In `_startIdlePoller`, replace the inline `userCount`→schedule/cancel logic with: compute `userCount` then `this.handleOccupancy(userCount)`. (Keep the 30s interval + the same getClientsInChannel call + error handling.) Remove the now-redundant inline schedule/cancel branch (it lives in `handleOccupancy`).
- [ ] **Step 3 — clear autoPaused on user actions + lifecycle.** In `cmdPause`, `cmdResume`, `cmdStop`, and the play-start path (`cmdPlay`/wherever playback (re)starts), set `this.autoPaused = false`. In the `disconnected` handler and on (re)connect, set `this.autoPaused = false`. (These ensure a user pause is never auto-resumed and the flag resets across connections.)
- [ ] **Step 4 — `updateAutoPause`.** Add (mirrors `updateIdleTimeout`):
```typescript
updateAutoPause(enabled: boolean): void {
this.config.autoPauseOnEmpty = enabled;
// if turning off, leave current playback as-is; if a track was auto-paused, optionally resume:
if (!enabled && this.autoPaused && this.player.getState() === "paused") {
this.player.resume();
this.autoPaused = false;
this.emit("stateChange");
}
}
```
- [ ] **Step 5 — verify:** `npx tsc --noEmit` → exit 0. `npx vitest run src/bot src/audio` → pass (existing tests unaffected).
- [ ] **Step 6 — commit:** `git add src/bot/instance.ts && git commit -m "feat(autopause): drive pause/resume from channel occupancy in BotInstance"`
---
## Task 3: Re-emit TS member events for instant reaction
**Files:** Modify `src/ts-protocol/client.ts`, `src/bot/instance.ts`.
Context: `client.ts` forwards `textMessage`/`disconnected`/`connected` and only debug-logs `clientEnter` (~lines 219-224); `clientLeave`/`clientMoved` are not handled. `BotInstance.setupTsEvents()` (~lines 132-156) wires tsClient events.
- [ ] **Step 1 — re-emit in client.ts.** Where `clientEnter` is logged, also `this.emit("clientEnter", info)`. Add subscriptions for `clientLeave` and `clientMoved` that `this.emit(...)` them upward (match the existing forwarding style; just propagate, no payload transformation needed since the instance re-queries).
- [ ] **Step 2 — react in instance.ts.** In `setupTsEvents()`, add handlers: on `clientEnter` / `clientLeave` / `clientMoved`, call a small `async refreshOccupancy()` that does `const clients = await this.getClientsInChannel(); this.handleOccupancy(clients.length - 1);` (guarded with try/catch + only when connected). This gives near-instant pause/resume; the 30s poll remains the fallback.
- [ ] **Step 3 — verify:** `npx tsc --noEmit` → 0. `npx vitest run src/bot` → pass.
- [ ] **Step 4 — commit:** `git add src/ts-protocol/client.ts src/bot/instance.ts && git commit -m "feat(autopause): re-emit client enter/leave/move for instant pause/resume"`
---
## Task 4: API wiring for the toggle
**Files:** Modify `src/web/api/bot.ts`; add/extend a test.
Context: `GET /api/bot/settings` returns `{ idleTimeoutMinutes }`; `POST /api/bot/settings` validates `idleTimeoutMinutes`, sets `config.idleTimeoutMinutes`, `saveConfig`, then loops `botManager.getAllBots()` → `bot.updateIdleTimeout(...)`. This route is `requirePermission("bot.manage")`-gated.
- [ ] **Step 1 — failing API test** (extend the existing bot settings test or add one): `GET /api/bot/settings` returns `autoPauseOnEmpty` (boolean); `POST /api/bot/settings` with `{ autoPauseOnEmpty: false }` persists it (a follow-up GET reflects false) and calls `updateAutoPause` on bots. Model the harness on the existing settings test.
- [ ] **Step 2 — run, expect fail.**
- [ ] **Step 3 — implement.** In `GET /settings`, add `autoPauseOnEmpty: options.config.autoPauseOnEmpty` to the response. In `POST /settings`, if `typeof req.body.autoPauseOnEmpty === "boolean"`, set `config.autoPauseOnEmpty`, include it in the `saveConfig`, and loop bots calling `bot.updateAutoPause(config.autoPauseOnEmpty)`. Keep the existing `idleTimeoutMinutes` handling intact (handle both fields in one save).
- [ ] **Step 4 — verify:** `npx vitest run src/web` → pass; `npx tsc --noEmit` → 0.
- [ ] **Step 5 — commit:** `git add src/web/api/bot.ts <test> && git commit -m "feat(autopause): expose autoPauseOnEmpty via /api/bot/settings"`
---
## Task 5: Frontend toggle in Settings
**Files:** Modify `web/src/views/Settings.vue` (and the settings load/save it uses).
Context: The **行为设置** section (already `v-if="can('bot.manage')"`) holds the idle-timeout control, loaded via `loadIdleTimeout()` (GET /api/bot/settings) and saved via `saveIdleTimeout()` (POST). Read these first.
- [ ] **Step 1 — implement.** Add an `autoPauseOnEmpty` ref. In the settings load, populate it from the GET response. Add a checkbox/toggle in the 行为设置 section labelled e.g. "频道无人时自动暂停" bound to it, and include `autoPauseOnEmpty` in the POST payload of the save function (alongside `idleTimeoutMinutes`, or via its own save — match the existing pattern). Use existing form/toggle CSS classes.
- [ ] **Step 2 — verify:** `cd web && npx vue-tsc --noEmit` → exit 0; read template back for correctness.
- [ ] **Step 3 — commit:** `git add web/src/views/Settings.vue && git commit -m "feat(autopause): autoPauseOnEmpty toggle in Settings"`
---
## Final verification
- [ ] `npx tsc --noEmit` → 0
- [ ] `npx vitest run src/` → all pass
- [ ] `cd web && npx vue-tsc --noEmit` → 0
- [ ] `npm run build` → succeeds
- [ ] Manual: with a bot playing, leave its channel → music auto-pauses (no disconnect); rejoin → resumes. Manually pause, leave, rejoin → stays paused. Toggle off in Settings → no auto-pause.
@@ -0,0 +1,167 @@
# Fine-grained account permissions — design
**Issue:** [#79](https://github.com/ZHANGTIANYAO1/teamspeak-music-bot/issues/79) (item E — the maintainer's permission-management idea)
**Date:** 2026-05-30
**Status:** Approved (brainstorm), pending implementation plan
## Scope
Issue #79 bundles five things. This spec covers **only item E**: allow an admin to
grant each non-admin (member) account a set of capabilities and a list of bots they
may control. The other items are handled in separate PRs and are **out of scope**
here:
- #1 Guest mode (login-less playback)
- #2 Dedicated-link hides other bots (subsumed conceptually by E's bot allow-list, but the link-specific UX is separate)
- #3 Auto-pause when channel empty
- #4 Dedicated link loses bot binding on refresh (a bug)
## Problem
Today the bot has a coarse two-role system: `admin | member` (single `role` column,
read live per request). `requireAdmin` gates only `/api/users` and `/api/audit`.
**Every other action — create/edit/delete bots, start/stop, all playback & queue
control, set platform login cookies, set audio quality — is open to any logged-in
member, on every bot.** Admins want to delegate limited control to members without
handing them full power.
## Decisions (from brainstorm)
1. **Model = capability flags + per-member bot allow-list** (not a per-bot×per-action
matrix, not role templates).
2. **Defaults:** on upgrade, existing members are backfilled with full capabilities +
all bots (no behavior change); newly-created members get a **basic tier**.
3. **Bot allow-list semantics:** an explicit "all bots" toggle OR a specific list;
empty list = no bots controllable. Members **cannot see** bots outside their
allow-list (hidden, not merely disabled).
4. **Capability set (5 toggles)** — see below; basic tier = playback + queue + all bots.
5. **Admin is a super-user** (bypasses all checks). The last admin cannot be demoted
(existing invariant preserved). Permission grants/revokes are written to the
existing audit log.
## Capability taxonomy
| Capability token | Covers | Scope |
|---|---|---|
| `player.control` | play/pause/resume/next/prev/stop/seek/volume/mode | per-bot (allow-list) |
| `player.queue` | search-add / clear / remove / play-at / playlist / album / play-song | per-bot (allow-list) |
| `bot.manage` | create / edit / delete / start / stop / avatar / profile / idle settings | global (create) + per-bot (operate a specific bot) |
| `platform.auth` | set NetEase/QQ/Bilibili cookie, QR, SMS | **global** (shared credentials) |
| `quality` | set audio quality per platform | **global** |
Bot scope is independent of capabilities: a member with `player.control` can only
exercise it on bots in their allow-list (or all, if the "all bots" flag is set).
`platform.auth` and `quality` are global capabilities with no bot scope.
**Basic tier** (new members): `{ player.control, player.queue }` + `bots.all = true`.
A new member can play/queue on every bot but cannot manage bots, change credentials,
or change quality.
## Data model (SQLite, additive — follows existing `CREATE TABLE IF NOT EXISTS` pattern)
```sql
-- capability tokens + the "all bots" flag (stored as token 'bots.all')
CREATE TABLE IF NOT EXISTS user_permissions (
userId TEXT NOT NULL,
permission TEXT NOT NULL,
PRIMARY KEY (userId, permission),
FOREIGN KEY (userId) REFERENCES users(id) ON DELETE CASCADE
);
-- specific bot allow-list (only consulted when 'bots.all' is NOT present)
CREATE TABLE IF NOT EXISTS user_bot_access (
userId TEXT NOT NULL,
botId TEXT NOT NULL,
PRIMARY KEY (userId, botId),
FOREIGN KEY (userId) REFERENCES users(id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_user_bot_access_userId ON user_bot_access(userId);
```
- Admins have no rows (they bypass). Only members are constrained.
- `bots.all` present ⇒ all bots (incl. future ones). Absent ⇒ only `user_bot_access`
rows; empty ⇒ none.
- `foreign_keys = ON` and WAL are already enabled; cascade-on-user-delete works.
- `user_bot_access.botId` references bot instance ids; when a bot is deleted, its
access rows should be cleaned up (either an FK to the bot table if one exists, or an
explicit cleanup in `BotManager.removeBot` / `PermissionStore.pruneBot(botId)`).
New `PermissionStore` in `src/data/permissions.ts` (mirrors `createUserStore` /
`createSessionStore`: prepared statements + an interface). Methods:
`getCapabilities(userId)`, `getBotAccess(userId)` → `'all' | string[]`,
`setPermissions(userId, { capabilities, bots })`, `pruneBot(botId)`.
## Backend enforcement (real 403 — not just hidden UI)
- **`req.user` widened** to carry `capabilities: Set<string>` and bot access. Loaded in
`requireAuth` (one extra lookup, or a JOIN in the session query). The same
`{id,username,role,capabilities,bots}` shape must be kept in sync in the three places
it is built today: `requireAuth.ts`, `session.ts` `requireAuthInline`, and the WS
upgrade handler in `server.ts` (WS only needs it if a push action becomes gated).
Because it's read live, permission changes take effect immediately (no re-login).
- **`requirePermission(cap)`** middleware (new, mirrors `requireAdmin.ts`): 401 if no
user; allow if `role === 'admin'` or `capabilities.has(cap)`; else 403.
- **`requireBotAccess`** helper: allow if admin or `bots.all` or botId ∈ access list;
else 403. Mounted on the player router's existing `/:botId` choke-point
(`src/web/api/player.ts`) and on each `:id` route in `src/web/api/bot.ts`
(start/stop/edit/delete/avatar/profile).
- **Route → capability mapping:**
- `/api/player/:botId/*` playback actions → `player.control` (+ `requireBotAccess`)
- `/api/player/:botId/*` queue actions → `player.queue` (+ `requireBotAccess`)
- `/api/bot` create, `/api/bot/:id` edit/delete, `/api/bot/:id/start|stop|avatar|profile`, `/api/bot/settings` → `bot.manage` (+ `requireBotAccess` for the `:id` ones)
- `/api/auth/*` (cookie/QR/SMS) → `platform.auth`
- `/api/music/quality` POST → `quality`
- **`GET /api/bot`** filters its result to the caller's allowed bots for members
(admins see all). This is what "hides" disallowed bots in the UI.
## Management API (admin-only, added to the existing users router)
- `GET /api/users/:id/permissions` → `{ capabilities: string[], bots: 'all' | string[] }`
- `PUT /api/users/:id/permissions` → body `{ capabilities, bots }`; validates tokens
against the known set and botIds against existing bots; writes audit
`user.permissions_changed`.
- `GET /api/session/me` is extended to include the **current** user's
`{ capabilities, bots }` so the frontend can gate UI. (admins report effectively-all.)
## Frontend
- `useSession` extends `User` with `capabilities` + bot scope and exposes
`can(cap)` and `canControlBot(botId)` helpers.
- **Navbar bot selector** filters `store.bots` to controllable bots (others hidden);
`activeBot` fallback and `fetchBots` default only ever land on an allowed bot.
- **Player / Settings** hide controls and whole sections a member lacks: platform
login, audio quality, and bot create/edit/delete are hidden without the matching
capability; playback/queue buttons hidden without `player.control` / `player.queue`.
- **Admin permission editor:** in the Settings → User Management list, each member row
gets a "权限" editor — capability checkboxes + a bot allow-list with an "全部机器人"
toggle. Saving calls `PUT /api/users/:id/permissions`.
## Defaults & migration
- New tables created idempotently in `initTables`.
- **One-time backfill** (guarded so it runs once): every existing `member` gets all
five capabilities + `bots.all`. Admins are skipped (they bypass). This preserves
current behavior for existing members on upgrade.
- **New member default** (`POST /api/users` with role member): capabilities
`{ player.control, player.queue }` + `bots.all` (basic tier).
- Pre-existing accounts default to `role = 'admin'` per the current schema — those are
super-users and unaffected.
## Testing (TDD)
- `PermissionStore` unit tests (set/get capabilities + bot access; `'all'` vs list vs
empty; `pruneBot`).
- `requirePermission` / `requireBotAccess` middleware tests (admin bypass; has/lacks
cap → 200/403; bot in/out of allow-list; `bots.all`).
- API tests: member without cap → 403; with cap → 200; bot not allowed → 403/hidden;
`GET /api/bot` filtered for members, full for admin; `PUT .../permissions` validates
+ audits.
- Migration test: existing members backfilled to full + `bots.all`; new member gets
basic tier.
## Non-goals
- No per-bot×per-capability matrix, no custom role templates (YAGNI).
- Guest mode, dedicated-link UX, auto-pause, and the refresh bug (#1–#4) are separate.
- No change to the admin/member role concept itself; this layers capabilities under
the existing `member` role.
@@ -0,0 +1,101 @@
# Auto-pause on empty channel — design
**Issue:** [#79](https://github.com/ZHANGTIANYAO1/teamspeak-music-bot/issues/79) item 3
**Date:** 2026-05-30
**Status:** Approved (brainstorm), pending implementation plan
## Problem
When everyone leaves the bot's voice channel, music keeps playing to an empty room.
The maintainer wants an option to **auto-pause when the channel is empty** (no disconnect)
and resume when someone returns.
## Decisions (from brainstorm)
- **Global toggle**, reusing the **already-declared but currently dead** `config.autoPauseOnEmpty`
(`src/data/config.ts`, default `true`). No per-bot granularity (YAGNI).
- **Event-driven, near-instant** reaction (not the 30s poll alone) — subscribe to TS client
enter/leave/move events; keep the existing 30s idle poll as a fallback.
- **Auto-resume only what we auto-paused** — a user-paused track is never auto-resumed.
- Independent of the existing **idle-disconnect** (`idleTimeoutMinutes`): both share the same
emptiness signal but act independently (pause immediately; disconnect after N minutes).
## Current state (verified)
- `client.ts` `getClientsInChannel()` returns all clients in the bot's channel *including the
bot*; callers compute "others" as `length - 1`. No persistent roster.
- The library emits `clientEnter` / `clientLeave` / `clientMoved`; `client.ts` currently only
*logs* `clientEnter` and does not re-emit leave/moved.
- The idle poller in `instance.ts` (`_startIdlePoller`, every 30s) already computes
`userCount = getClientsInChannel().length - 1` and, when `<= 0`, schedules an
idle-disconnect after `idleTimeoutMinutes`.
- `player.pause()` / `player.resume()` already pause/resume **without disconnecting** (ffmpeg
stays alive, no voice sent). The player only knows `idle|playing|paused` — there is **no**
auto-vs-user-pause distinction today.
- `BotConfig.autoPauseOnEmpty` exists (default true) but is **read nowhere**.
## Design
### Occupancy signal (shared)
Extract the idle poller's count into one method on `BotInstance`:
`checkChannelOccupancy()` → queries `getClientsInChannel()`, computes `userCount = length - 1`,
and drives **both** the existing idle-disconnect timer (unchanged behavior) **and** the new
auto-pause logic below. It is called by:
1. the existing 30s poll (fallback), and
2. new TS event handlers.
### Event subscription
`client.ts`: subscribe to and **re-emit** `clientEnter`, `clientLeave`, `clientMoved` up to
`BotInstance`. `BotInstance.setupTsEvents()` calls `checkChannelOccupancy()` on each (a re-query
is simplest, since `clientLeave` carries no channel id). This gives near-instant pause/resume;
the poll remains as a safety net.
### Auto-pause logic (inside `checkChannelOccupancy`)
Add a private `autoPaused = false` flag to `BotInstance`.
- **Empty** (`userCount <= 0`): if `config.autoPauseOnEmpty` **and** `player.getState() === "playing"`
→ `player.pause()`, `autoPaused = true`, emit `stateChange`. (Idle-disconnect timer still
scheduled as today.)
- **Re-populated** (`userCount > 0`): if `autoPaused` **and** `player.getState() === "paused"`
→ `player.resume()`, `autoPaused = false`, emit `stateChange`. (Idle timer cancelled as today.)
### `autoPaused` bookkeeping (so user pauses are respected)
Clear `autoPaused = false` in `cmdPause`, `cmdResume`, `cmdStop`, `cmdPlay`, and on
connect/disconnect (the `disconnected` handler calls `player.stop()` → idle). Net effect: only a
track *we* auto-paused gets auto-resumed; a user-paused track stays paused when someone returns.
### Config wiring
- `GET /api/bot/settings`: include `autoPauseOnEmpty` in the payload (alongside `idleTimeoutMinutes`).
- `POST /api/bot/settings`: accept + validate a boolean `autoPauseOnEmpty`, `saveConfig`, and
propagate to live bots via a new `BotInstance.updateAutoPause(enabled)` (mirrors
`updateIdleTimeout`). Since the instance reads `this.config.autoPauseOnEmpty` live, propagation
can be as simple as updating the stored config reference / a field the check reads.
- Frontend `Settings.vue` → the **行为设置** section (already `bot.manage`-gated): add a toggle
for `autoPauseOnEmpty` next to the idle-timeout control; load it in the settings fetch and send
it on save.
## Components / files
- `src/ts-protocol/client.ts` — subscribe + re-emit `clientEnter`/`clientLeave`/`clientMoved`.
- `src/bot/instance.ts` — `autoPaused` field; `checkChannelOccupancy()` (refactored from the
idle poller, drives idle + auto-pause); event handlers; clear `autoPaused` in user commands +
connect/disconnect; `updateAutoPause(enabled)`.
- `src/web/api/bot.ts` — `GET`/`POST /settings` handle `autoPauseOnEmpty`.
- `web/src/views/Settings.vue` (+ player store settings load/save) — the toggle.
- `src/data/config.ts` — field already exists (no change beyond confirming default).
## Testing
- **Decision unit test (TDD):** extract the pause/resume decision into a testable method, e.g.
`applyOccupancy(userCount)` operating on an injected fake player (`getState`/`pause`/`resume`)
+ the `autoPaused` flag + the config flag. Cases: empty+playing+enabled → pause + `autoPaused`;
re-populated+`autoPaused`+paused → resume + clear; re-populated when NOT `autoPaused` (user
pause) → no resume; flag disabled → no pause; empty while idle (not playing) → no-op.
- **API test:** `GET`/`POST /api/bot/settings` round-trips `autoPauseOnEmpty` (validates boolean,
persists, propagates).
- Live TS event wiring is verified by code review + a manual run (can't unit-test a real server).
## Non-goals
- No per-bot toggle (global only). No change to idle-disconnect behavior. No new dependency.
- Reaction relies on events the bot can already see (same-channel members are always in view);
no extra channel subscription needed.
+68 -1
View File
@@ -2,7 +2,7 @@ import { describe, it, expect } from "vitest";
import { mkdtempSync, writeFileSync, existsSync } from "node:fs"; import { mkdtempSync, writeFileSync, existsSync } from "node:fs";
import { tmpdir } from "node:os"; import { tmpdir } from "node:os";
import { join } from "node:path"; import { join } from "node:path";
import { buildFfmpegArgs, shouldUsePowerShellDownload, cleanupTempDir } from "./player.js"; import { buildFfmpegArgs, shouldUsePowerShellDownload, cleanupTempDir, shouldEndOnStall, volumeToFactor } from "./player.js";
function getHeadersArg(args: string[]): string { function getHeadersArg(args: string[]): string {
const idx = args.indexOf("-headers"); const idx = args.indexOf("-headers");
@@ -45,6 +45,14 @@ describe("buildFfmpegArgs", () => {
expect(Number(args[idx + 1])).toBeGreaterThanOrEqual(30); expect(Number(args[idx + 1])).toBeGreaterThanOrEqual(30);
}); });
it("sets -reconnect_at_eof 1 (before -i) so long B站 streams resume after premature EOF (#89)", () => {
const args = buildFfmpegArgs("https://x.bilivideo.com/audio.m4s", 0);
const idx = args.indexOf("-reconnect_at_eof");
expect(idx).toBeGreaterThan(-1);
expect(args[idx + 1]).toBe("1");
expect(idx).toBeLessThan(args.indexOf("-i")); // input options must precede -i
});
it("inserts -ss before -i when seekSeconds > 0", () => { it("inserts -ss before -i when seekSeconds > 0", () => {
const args = buildFfmpegArgs("https://example.com/song.mp3", 42); const args = buildFfmpegArgs("https://example.com/song.mp3", 42);
const ssIdx = args.indexOf("-ss"); const ssIdx = args.indexOf("-ss");
@@ -62,6 +70,7 @@ describe("buildFfmpegArgs", () => {
it("omits HTTP-only flags when input is a local file path", () => { it("omits HTTP-only flags when input is a local file path", () => {
const args = buildFfmpegArgs("C:/temp/song.mp3", 0); const args = buildFfmpegArgs("C:/temp/song.mp3", 0);
expect(args).not.toContain("-reconnect"); expect(args).not.toContain("-reconnect");
expect(args).not.toContain("-reconnect_at_eof");
expect(args).not.toContain("-reconnect_on_network_error"); expect(args).not.toContain("-reconnect_on_network_error");
expect(args).not.toContain("-reconnect_on_http_error"); expect(args).not.toContain("-reconnect_on_http_error");
expect(args).not.toContain("-headers"); expect(args).not.toContain("-headers");
@@ -80,6 +89,37 @@ describe("buildFfmpegArgs", () => {
}); });
}); });
describe("volumeToFactor (#84 smooth volume curve)", () => {
it("is 0 at vol 0 and exactly 1.0 at vol 100 (full loudness still reserved at 100)", () => {
expect(volumeToFactor(0)).toBe(0);
expect(volumeToFactor(100)).toBe(1);
});
it("clamps out-of-range input", () => {
expect(volumeToFactor(-20)).toBe(0);
expect(volumeToFactor(150)).toBe(1);
});
it("is strictly monotonic across the whole range (no dead zone)", () => {
for (let v = 0; v < 100; v++) {
expect(volumeToFactor(v + 1)).toBeGreaterThan(volumeToFactor(v));
}
});
it("removes the old flat 80-99 dead zone", () => {
// Old mapping moved only 0.16 -> 0.198 across 80..99; new curve climbs clearly.
expect(volumeToFactor(99) - volumeToFactor(80)).toBeGreaterThan(0.3);
});
it("removes the discontinuity at 100 (old jump was ~0.8)", () => {
expect(volumeToFactor(100) - volumeToFactor(99)).toBeLessThan(0.1);
});
it("keeps the low range gentle", () => {
expect(volumeToFactor(50)).toBeLessThan(0.12);
});
});
describe("shouldUsePowerShellDownload", () => { describe("shouldUsePowerShellDownload", () => {
const jdymusicUrl = const jdymusicUrl =
"http://m801.music.126.net/20260507/abc/jdymusic/obj/xyz/song.mp3?vuutv=tok"; "http://m801.music.126.net/20260507/abc/jdymusic/obj/xyz/song.mp3?vuutv=tok";
@@ -133,3 +173,30 @@ describe("cleanupTempDir", () => {
expect(() => cleanupTempDir(dir)).not.toThrow(); expect(() => cleanupTempDir(dir)).not.toThrow();
}); });
}); });
describe("shouldEndOnStall (#89 mid-track stall watchdog)", () => {
const MAX_EMPTY = 250; // ~5s near-end threshold
const MAX_STALL = 3000; // ~60s far-from-end watchdog
it("ends quickly near the end once the empty threshold is reached (normal EOF)", () => {
expect(shouldEndOnStall(MAX_EMPTY, true, MAX_EMPTY, MAX_STALL)).toBe(true);
expect(shouldEndOnStall(MAX_EMPTY - 1, true, MAX_EMPTY, MAX_STALL)).toBe(false);
});
it("does NOT end far from the end at the near-end threshold (avoids false skips on transient underruns)", () => {
// This is the core regression: a brief underrun mid-song must not end the track.
expect(shouldEndOnStall(MAX_EMPTY, false, MAX_EMPTY, MAX_STALL)).toBe(false);
expect(shouldEndOnStall(MAX_STALL - 1, false, MAX_EMPTY, MAX_STALL)).toBe(false);
});
it("eventually ends far from the end once the long stall watchdog trips (dead stream recovers)", () => {
// The pre-fix bug: far-from-end stalls grew unbounded and never ended -> permanent silence.
expect(shouldEndOnStall(MAX_STALL, false, MAX_EMPTY, MAX_STALL)).toBe(true);
expect(shouldEndOnStall(MAX_STALL + 500, false, MAX_EMPTY, MAX_STALL)).toBe(true);
});
it("never ends before any threshold", () => {
expect(shouldEndOnStall(0, true, MAX_EMPTY, MAX_STALL)).toBe(false);
expect(shouldEndOnStall(10, false, MAX_EMPTY, MAX_STALL)).toBe(false);
});
});
+66 -7
View File
@@ -91,6 +91,11 @@ export function buildFfmpegArgs(url: string, seekSeconds: number): string[] {
if (isHttp) { if (isHttp) {
args.push( args.push(
"-reconnect", "1", "-reconnect", "1",
// Long B站 streams sit on a CDN whose session/token can close the
// connection mid-file (premature EOF). Without this, FFmpeg treats that
// EOF as end-of-input and stops ~partway through (see #89); with it, it
// re-issues a Range request from the current offset to finish the stream.
"-reconnect_at_eof", "1",
"-reconnect_streamed", "1", "-reconnect_streamed", "1",
"-reconnect_delay_max", "30", "-reconnect_delay_max", "30",
"-reconnect_on_network_error", "1", "-reconnect_on_network_error", "1",
@@ -103,6 +108,43 @@ export function buildFfmpegArgs(url: string, seekSeconds: number): string[] {
return args; return args;
} }
/**
* Decide whether to end the current track when FFmpeg is still alive but has
* produced no decodable audio for `emptyAttempts` consecutive frame ticks.
*
* - Near the song end we end quickly (`maxEmptyAttempts`): a normal EOF.
* - Far from the end we wait much longer (`maxStallAttempts`) before giving up,
* so a transient buffer underrun on a healthy stream does NOT cause a false
* skip — but a genuinely dead stream (e.g. a long B站 stream whose CDN session
* expired mid-playback, #89) still recovers by advancing instead of going
* permanently silent.
*/
export function shouldEndOnStall(
emptyAttempts: number,
isNearEnd: boolean,
maxEmptyAttempts: number,
maxStallAttempts: number,
): boolean {
if (isNearEnd && emptyAttempts >= maxEmptyAttempts) return true;
if (emptyAttempts >= maxStallAttempts) return true;
return false;
}
/**
* Maps a 0-100 volume value to a linear PCM gain factor (#84).
*
* Continuous and strictly monotonic over [0,100]: 0 at vol 0 and exactly 1.0 at
* vol 100. The previous mapping was a two-piece step — gain = (vol/100)*0.2 for
* vol<100 (so the whole 0-99 range only spanned 0..0.198, making 80->99 feel
* flat) then a raw passthrough at vol===100 (a ~5x jump). This single curve keeps
* the low end gentle but ramps smoothly toward full loudness near the top, so the
* slider feels proportional with no dead zone and no discontinuity at 100.
*/
export function volumeToFactor(volume: number): number {
const x = Math.max(0, Math.min(100, volume)) / 100;
return 0.2 * x + 0.8 * Math.pow(x, 8);
}
export interface PlayerEvents { export interface PlayerEvents {
frame: (opusFrame: Buffer) => void; frame: (opusFrame: Buffer) => void;
trackEnd: () => void; trackEnd: () => void;
@@ -138,6 +180,11 @@ export class AudioPlayer extends EventEmitter {
private currentTempDir: string | null = null; private currentTempDir: string | null = null;
private emptyFrameAttempts = 0; private emptyFrameAttempts = 0;
private static readonly MAX_EMPTY_ATTEMPTS = 250; // ~5秒的20ms帧循环(增加容错) private static readonly MAX_EMPTY_ATTEMPTS = 250; // ~5秒的20ms帧循环(增加容错)
// Far-from-end stall watchdog (#89): if FFmpeg is alive but produces no audio
// for this many consecutive frame ticks (~60s at 20ms/frame), treat the stream
// as dead and advance instead of staying silent forever. Set high so a normal
// transient underrun never trips it.
private static readonly MAX_STALL_ATTEMPTS = 3000;
private currentSongDuration = 0; // 当前歌曲总时长(秒) private currentSongDuration = 0; // 当前歌曲总时长(秒)
constructor(logger: Logger) { constructor(logger: Logger) {
@@ -436,16 +483,27 @@ export class AudioPlayer extends EventEmitter {
if (this.ffmpeg !== null && this.pcmBuffer.length < PCM_FRAME_BYTES) { if (this.ffmpeg !== null && this.pcmBuffer.length < PCM_FRAME_BYTES) {
this.emptyFrameAttempts++; this.emptyFrameAttempts++;
// 只有同时满足:达到空帧阈值 + 接近结尾,才判定为播放结束 // End the track when FFmpeg has gone silent: quickly if we're near the
if (this.emptyFrameAttempts >= AudioPlayer.MAX_EMPTY_ATTEMPTS && isNearEnd) { // end (normal EOF), or after a much longer stall window if we're not
this.logger.info({ // (a dead/expired stream — #89 — so playback recovers instead of going
// permanently silent).
if (
shouldEndOnStall(
this.emptyFrameAttempts,
isNearEnd,
AudioPlayer.MAX_EMPTY_ATTEMPTS,
AudioPlayer.MAX_STALL_ATTEMPTS,
)
) {
this.logger.info({
sessionId: this.sessionId, sessionId: this.sessionId,
emptyAttempts: this.emptyFrameAttempts, emptyAttempts: this.emptyFrameAttempts,
bufferSize: this.pcmBuffer.length, bufferSize: this.pcmBuffer.length,
elapsed: Math.round(elapsed), elapsed: Math.round(elapsed),
duration: this.currentSongDuration, duration: this.currentSongDuration,
remaining: Math.round(this.currentSongDuration - elapsed) remaining: Math.round(this.currentSongDuration - elapsed),
}, "FFmpeg stopped outputting data near end, ending track"); nearEnd: isNearEnd,
}, "FFmpeg stopped outputting data, ending track");
this.frameLoopRunning = false; this.frameLoopRunning = false;
if (this.state !== "idle") { if (this.state !== "idle") {
this.state = "idle"; this.state = "idle";
@@ -509,8 +567,9 @@ export class AudioPlayer extends EventEmitter {
} }
private applyVolume(pcm: Buffer): Buffer { private applyVolume(pcm: Buffer): Buffer {
if (this.volume === 100) return Buffer.from(pcm); const factor = volumeToFactor(this.volume);
const factor = (this.volume / 100) * 0.2; // factor === 1 only at volume 100; skip the per-sample loop at full loudness.
if (factor >= 1) return Buffer.from(pcm);
const out = Buffer.alloc(pcm.length); const out = Buffer.alloc(pcm.length);
for (let i = 0; i < pcm.length; i += 2) { for (let i = 0; i < pcm.length; i += 2) {
let sample = Math.round(pcm.readInt16LE(i) * factor); let sample = Math.round(pcm.readInt16LE(i) * factor);
+80
View File
@@ -484,4 +484,84 @@ describe("PlayQueue", () => {
expect(promoted?.id).toBe("x"); expect(promoted?.id).toBe("x");
}); });
}); });
// Issue #70: 随机循环 (rloop) used true random-with-replacement, so some
// songs repeated often while others were starved. It should behave like a
// shuffle bag (NetEase/QQ style): play every song once per cycle in random
// order, then reshuffle and continue, avoiding an immediate cross-cycle repeat.
describe("random-loop shuffle bag (issue #70)", () => {
it("plays every song exactly once per cycle before repeating", () => {
queue.setMode(PlayMode.RandomLoop);
const N = 12;
for (let i = 0; i < N; i++) queue.add(makeSong(`s${i}`));
queue.play();
const cycle1 = [queue.current()!.id];
for (let i = 0; i < N - 1; i++) cycle1.push(queue.next()!.id);
const cycle2: string[] = [];
for (let i = 0; i < N; i++) cycle2.push(queue.next()!.id);
// Each cycle is a full permutation of all N songs — zero repeats within
// a cycle, and both cycles cover the same complete set.
expect(new Set(cycle1).size).toBe(N);
expect(new Set(cycle2).size).toBe(N);
expect(new Set(cycle1)).toEqual(new Set(cycle2));
});
it("distributes plays evenly across songs over many cycles (no starvation)", () => {
queue.setMode(PlayMode.RandomLoop);
const N = 6;
const CYCLES = 20;
for (let i = 0; i < N; i++) queue.add(makeSong(`s${i}`));
queue.play();
const counts = new Map<string, number>();
counts.set(queue.current()!.id, 1);
for (let i = 0; i < CYCLES * N - 1; i++) {
const id = queue.next()!.id;
counts.set(id, (counts.get(id) ?? 0) + 1);
}
// Shuffle bag => each song plays exactly CYCLES times. True random
// would skew heavily.
for (let i = 0; i < N; i++) {
expect(counts.get(`s${i}`)).toBe(CYCLES);
}
});
it("does not replay the same song across a cycle boundary", () => {
queue.setMode(PlayMode.RandomLoop);
const N = 5;
for (let i = 0; i < N; i++) queue.add(makeSong(`s${i}`));
queue.play();
// Walk to the last song of cycle 1, then cross into cycle 2.
for (let i = 0; i < N - 1; i++) queue.next();
const lastOfCycle1 = queue.current()!.id;
const firstOfCycle2 = queue.next()!.id;
expect(firstOfCycle2).not.toBe(lastOfCycle1);
});
it("includes a song added mid-cycle within the current cycle", () => {
queue.setMode(PlayMode.RandomLoop);
queue.add(makeSong("A"));
queue.add(makeSong("B"));
queue.play(); // A
queue.next(); // B — both originals now played this cycle
queue.add(makeSong("C")); // added mid-cycle, still unplayed
// C is the only unplayed song, so it must come next (not a reshuffle).
expect(queue.next()?.id).toBe("C");
});
it("keeps looping forever with multiple songs (never returns null)", () => {
queue.setMode(PlayMode.RandomLoop);
queue.add(makeSong("A"));
queue.add(makeSong("B"));
queue.add(makeSong("C"));
queue.play();
for (let i = 0; i < 30; i++) {
expect(queue.next()).not.toBeNull();
}
});
});
}); });
+30 -21
View File
@@ -155,33 +155,42 @@ export class PlayQueue {
return this.songs[target]; return this.songs[target];
} }
} }
// 前进栈为空,走纯随机逻辑
if (this.mode === PlayMode.Random) { // Shuffle bag: pick uniformly from the songs not yet played this
const unplayed: number[] = []; // cycle, so every song plays once before any repeats (NetEase/QQ
for (let i = 0; i < this.songs.length; i++) { // style). Songs added mid-cycle aren't in playedIndices, so they're
if (!this.playedIndices.has(i)) unplayed.push(i); // naturally eligible within the current cycle.
} const unplayed: number[] = [];
if (unplayed.length === 0) return null; for (let i = 0; i < this.songs.length; i++) {
const nextIndex = if (!this.playedIndices.has(i)) unplayed.push(i);
unplayed[Math.floor(Math.random() * unplayed.length)]; }
this.pushHistory(this.currentIndex);
this.currentIndex = nextIndex; if (unplayed.length === 0) {
this.playedIndices.add(nextIndex); // Cycle complete.
return this.songs[nextIndex]; if (this.mode === PlayMode.Random) return null; // 随机:播完即停
} else { // 随机循环:reshuffle and keep going forever.
if (this.songs.length === 1) { if (this.songs.length === 1) {
this.pushHistory(this.currentIndex); this.pushHistory(this.currentIndex);
this.currentIndex = 0; this.currentIndex = 0;
this.playedIndices = new Set([0]);
return this.songs[0]; return this.songs[0];
} }
let idx: number; // Start a fresh cycle: every song is eligible again, but exclude
do { // the song that just played from THIS pick only, so it doesn't
idx = Math.floor(Math.random() * this.songs.length); // repeat back-to-back across the boundary. It stays eligible for
} while (idx === this.currentIndex); // the rest of the new cycle, so every song still plays exactly once.
this.pushHistory(this.currentIndex); this.playedIndices = new Set();
this.currentIndex = idx; for (let i = 0; i < this.songs.length; i++) {
return this.songs[idx]; if (i !== this.currentIndex) unplayed.push(i);
}
} }
const nextIndex =
unplayed[Math.floor(Math.random() * unplayed.length)];
this.pushHistory(this.currentIndex);
this.currentIndex = nextIndex;
this.playedIndices.add(nextIndex);
return this.songs[nextIndex];
} }
} }
} }
+29
View File
@@ -0,0 +1,29 @@
import { describe, it, expect } from "vitest";
import { decideOccupancyAction } from "./auto-pause.js";
describe("decideOccupancyAction", () => {
it("pauses when empty while playing and enabled", () => {
expect(decideOccupancyAction("playing", false, true, 0)).toBe("pause");
});
it("does not pause when the feature is disabled", () => {
expect(decideOccupancyAction("playing", false, false, 0)).toBe("none");
});
it("does not pause when idle (nothing playing)", () => {
expect(decideOccupancyAction("idle", false, true, 0)).toBe("none");
});
it("does not pause when already paused", () => {
expect(decideOccupancyAction("paused", false, true, 0)).toBe("none");
});
it("resumes when re-populated and we auto-paused", () => {
expect(decideOccupancyAction("paused", true, true, 2)).toBe("resume");
});
it("does NOT resume a user-paused track on re-population", () => {
expect(decideOccupancyAction("paused", false, true, 2)).toBe("none");
});
it("does nothing when re-populated and already playing", () => {
expect(decideOccupancyAction("playing", false, true, 2)).toBe("none");
});
it("resume is independent of the enabled flag (we already auto-paused)", () => {
expect(decideOccupancyAction("paused", true, false, 1)).toBe("resume");
});
});
+23
View File
@@ -0,0 +1,23 @@
export type PlayerStateName = "idle" | "playing" | "paused";
export type OccupancyAction = "pause" | "resume" | "none";
/**
* Decide what auto-pause should do given channel occupancy.
* - empty (userCount <= 0): pause iff enabled and currently playing.
* - re-populated (userCount > 0): resume iff we previously auto-paused and are still paused.
* `autoPaused` distinguishes our auto-pause from a user pause, so user pauses are never resumed.
*/
export function decideOccupancyAction(
playerState: PlayerStateName,
autoPaused: boolean,
enabled: boolean,
userCount: number,
): OccupancyAction {
const empty = userCount <= 0;
if (empty) {
if (enabled && playerState === "playing") return "pause";
return "none";
}
if (autoPaused && playerState === "paused") return "resume";
return "none";
}
+109 -26
View File
@@ -17,6 +17,7 @@ import type { BotDatabase, ProfileConfig } from "../data/database.js";
import type { BotConfig } from "../data/config.js"; import type { BotConfig } from "../data/config.js";
import { BotProfileManager } from "./profile.js"; import { BotProfileManager } from "./profile.js";
import type { AvatarStore } from "../data/avatars.js"; import type { AvatarStore } from "../data/avatars.js";
import { decideOccupancyAction } from "./auto-pause.js";
export interface BotInstanceOptions { export interface BotInstanceOptions {
id: string; id: string;
@@ -66,8 +67,10 @@ export class BotInstance extends EventEmitter {
private isAdvancing = false; private isAdvancing = false;
private idleTimer: ReturnType<typeof setTimeout> | null = null; private idleTimer: ReturnType<typeof setTimeout> | null = null;
private channelUserCount = 0; private channelUserCount = 0;
private autoPaused = false;
private profileManager: BotProfileManager; private profileManager: BotProfileManager;
private isFmMode = false; private isFmMode = false;
private fmProvider: MusicProvider | null = null;
constructor(options: BotInstanceOptions) { constructor(options: BotInstanceOptions) {
super(); super();
@@ -143,6 +146,8 @@ export class BotInstance extends EventEmitter {
// short-circuited on !this.connected, leaving player stuck as "playing". // short-circuited on !this.connected, leaving player stuck as "playing".
this.connected = false; this.connected = false;
this.player.stop(); this.player.stop();
// A lifecycle change must not leave a stale auto-resume armed.
this.autoPaused = false;
// Only emit externally once per lifecycle so clients don't see a // Only emit externally once per lifecycle so clients don't see a
// duplicate "disconnected" after an explicit disconnect() call. // duplicate "disconnected" after an explicit disconnect() call.
if (this.disconnectEmitted) return; if (this.disconnectEmitted) return;
@@ -151,8 +156,26 @@ export class BotInstance extends EventEmitter {
}); });
this.tsClient.on("connected", () => { this.tsClient.on("connected", () => {
// Fresh connection — clear any stale auto-pause flag from a prior session.
this.autoPaused = false;
this._startIdlePoller(); this._startIdlePoller();
}); });
// React near-instantly to channel membership changes. The 30s idle
// poller remains the fallback if any of these events are missed.
this.tsClient.on("clientEnter", () => void this.refreshOccupancy());
this.tsClient.on("clientLeave", () => void this.refreshOccupancy());
this.tsClient.on("clientMoved", () => void this.refreshOccupancy());
}
private async refreshOccupancy(): Promise<void> {
if (!this.connected) return;
try {
const clients = await this.tsClient.getClientsInChannel();
this.handleOccupancy(clients.length - 1);
} catch {
// ignore — the 30s poll is the fallback
}
} }
async connect(): Promise<void> { async connect(): Promise<void> {
@@ -187,6 +210,16 @@ export class BotInstance extends EventEmitter {
if (minutes === 0) this._cancelIdleTimer(); if (minutes === 0) this._cancelIdleTimer();
} }
/** 外部更新 autoPauseOnEmpty(由 API 保存时调用) */
updateAutoPause(enabled: boolean): void {
this.config.autoPauseOnEmpty = enabled;
if (!enabled && this.autoPaused && this.player.getState() === "paused") {
this.player.resume();
this.autoPaused = false;
this.emit("stateChange");
}
}
private _startIdlePoller(): void { private _startIdlePoller(): void {
// 每 30 秒检查一次频道人数 // 每 30 秒检查一次频道人数
const poll = async () => { const poll = async () => {
@@ -194,17 +227,35 @@ export class BotInstance extends EventEmitter {
try { try {
const clients = await this.tsClient.getClientsInChannel(); const clients = await this.tsClient.getClientsInChannel();
const userCount = clients.length - 1; // 排除 bot 自身 const userCount = clients.length - 1; // 排除 bot 自身
if (userCount <= 0) { this.handleOccupancy(userCount);
this._scheduleIdleCheck();
} else {
this._cancelIdleTimer();
}
} catch { /* ignore */ } } catch { /* ignore */ }
setTimeout(poll, 30_000); setTimeout(poll, 30_000);
}; };
setTimeout(poll, 30_000); setTimeout(poll, 30_000);
} }
private handleOccupancy(userCount: number): void {
// idle-disconnect (unchanged behavior)
if (userCount <= 0) this._scheduleIdleCheck();
else this._cancelIdleTimer();
// auto-pause
const action = decideOccupancyAction(
this.player.getState(),
this.autoPaused,
this.config.autoPauseOnEmpty,
userCount,
);
if (action === "pause") {
this.player.pause();
this.autoPaused = true;
this.emit("stateChange");
} else if (action === "resume") {
this.player.resume();
this.autoPaused = false;
this.emit("stateChange");
}
}
private _scheduleIdleCheck(): void { private _scheduleIdleCheck(): void {
if (this.idleTimer !== null) return; // 已经在倒计时,不重复创建 if (this.idleTimer !== null) return; // 已经在倒计时,不重复创建
const minutes = this.config.idleTimeoutMinutes ?? 0; const minutes = this.config.idleTimeoutMinutes ?? 0;
@@ -319,7 +370,7 @@ export class BotInstance extends EventEmitter {
case "album": case "album":
return this.cmdAlbum(cmd); return this.cmdAlbum(cmd);
case "fm": case "fm":
return this.cmdFm(); return this.cmdFm(cmd);
case "artist": case "artist":
return this.cmdArtist(cmd); return this.cmdArtist(cmd);
case "vote": case "vote":
@@ -343,6 +394,11 @@ export class BotInstance extends EventEmitter {
return platform === "qq" ? this.qqProvider : this.neteaseProvider; return platform === "qq" ? this.qqProvider : this.neteaseProvider;
} }
private disableFmMode(): void {
this.isFmMode = false;
this.fmProvider = null;
}
private getProvider(flags: Set<string>): MusicProvider { private getProvider(flags: Set<string>): MusicProvider {
if (flags.has("b")) return this.bilibiliProvider; if (flags.has("b")) return this.bilibiliProvider;
if (flags.has("q")) return this.qqProvider; if (flags.has("q")) return this.qqProvider;
@@ -381,6 +437,9 @@ export class BotInstance extends EventEmitter {
} }
song.url = url; song.url = url;
this.player.play(url, 0, song.duration); this.player.play(url, 0, song.duration);
// Fresh playback (re)start — clear auto-pause so a later occupancy
// change won't try to "resume" a track the user already restarted.
this.autoPaused = false;
this.database.addPlayHistory({ this.database.addPlayHistory({
botId: this.id, botId: this.id,
songId: song.id, songId: song.id,
@@ -390,10 +449,8 @@ export class BotInstance extends EventEmitter {
platform: song.platform, platform: song.platform,
coverUrl: song.coverUrl, coverUrl: song.coverUrl,
}); });
// Update bot presence (fire-and-forget — never blocks playback) // Keep TeamSpeak-side profile updates on the same path for play/next/FM.
this.profileManager.onSongChange(song).catch((err) => { await this.syncProfileToSong(song);
this.logger.warn({ err }, "Profile update failed after song change");
});
this.emit("stateChange"); this.emit("stateChange");
return true; return true;
} catch (err) { } catch (err) {
@@ -402,6 +459,14 @@ export class BotInstance extends EventEmitter {
} }
} }
private async syncProfileToSong(song: QueuedSong | null): Promise<void> {
try {
await this.profileManager.onSongChange(song);
} catch (err) {
this.logger.warn({ err }, "Profile update failed after song change");
}
}
private async cmdPlay(cmd: ParsedCommand): Promise<string> { private async cmdPlay(cmd: ParsedCommand): Promise<string> {
if (!cmd.args) return "Usage: !play <song name or URL>"; if (!cmd.args) return "Usage: !play <song name or URL>";
const provider = this.getProvider(cmd.flags); const provider = this.getProvider(cmd.flags);
@@ -411,7 +476,7 @@ export class BotInstance extends EventEmitter {
const song = result.songs[0]; const song = result.songs[0];
this.queue.clear(); this.queue.clear();
this.isFmMode = false; this.disableFmMode();
this.queue.add({ ...song, platform: provider.platform }); this.queue.add({ ...song, platform: provider.platform });
this.queue.play(); this.queue.play();
@@ -483,20 +548,25 @@ export class BotInstance extends EventEmitter {
private cmdPause(): string { private cmdPause(): string {
this.player.pause(); this.player.pause();
// User-initiated pause — clear auto-pause so occupancy won't auto-resume it.
this.autoPaused = false;
this.emit("stateChange"); this.emit("stateChange");
return "Paused"; return "Paused";
} }
private cmdResume(): string { private cmdResume(): string {
this.player.resume(); this.player.resume();
// User-initiated resume — drop any auto-pause flag.
this.autoPaused = false;
this.emit("stateChange"); this.emit("stateChange");
return "Resumed"; return "Resumed";
} }
private cmdStop(): string { private cmdStop(): string {
this.player.stop(); this.player.stop();
this.autoPaused = false;
this.queue.clear(); this.queue.clear();
this.isFmMode = false; this.disableFmMode();
this.profileManager.onSongChange(null).catch((err) => { this.profileManager.onSongChange(null).catch((err) => {
this.logger.warn({ err }, "Profile restore failed on stop"); this.logger.warn({ err }, "Profile restore failed on stop");
}); });
@@ -554,7 +624,7 @@ export class BotInstance extends EventEmitter {
private cmdClear(): string { private cmdClear(): string {
this.player.stop(); this.player.stop();
this.queue.clear(); this.queue.clear();
this.isFmMode = false; this.disableFmMode();
this.profileManager.onSongChange(null).catch((err) => { this.profileManager.onSongChange(null).catch((err) => {
this.logger.warn({ err }, "Profile restore failed on clear"); this.logger.warn({ err }, "Profile restore failed on clear");
}); });
@@ -627,7 +697,7 @@ export class BotInstance extends EventEmitter {
if (songs.length === 0) return "Playlist is empty or not found"; if (songs.length === 0) return "Playlist is empty or not found";
this.queue.clear(); this.queue.clear();
this.isFmMode = false; this.disableFmMode();
for (const song of songs) { for (const song of songs) {
this.queue.add({ ...song, platform: provider.platform }); this.queue.add({ ...song, platform: provider.platform });
} }
@@ -662,7 +732,7 @@ export class BotInstance extends EventEmitter {
if (songs.length === 0) return "Album is empty or not found"; if (songs.length === 0) return "Album is empty or not found";
this.queue.clear(); this.queue.clear();
this.isFmMode = false; this.disableFmMode();
for (const song of songs) { for (const song of songs) {
this.queue.add({ ...song, platform: provider.platform }); this.queue.add({ ...song, platform: provider.platform });
} }
@@ -672,26 +742,38 @@ export class BotInstance extends EventEmitter {
return `Loaded ${songs.length} songs. Now playing: ${first?.name ?? "unknown"}`; return `Loaded ${songs.length} songs. Now playing: ${first?.name ?? "unknown"}`;
} }
private async cmdFm(): Promise<string> { private async cmdFm(cmd: ParsedCommand): Promise<string> {
if (!this.neteaseProvider.getPersonalFm) { return this.startFm(this.getProvider(cmd.flags));
return "Personal FM is only available for NetEase Cloud Music"; }
async startFm(provider: MusicProvider = this.neteaseProvider): Promise<string> {
// Match the !fm chat-command guard: refuse before mutating the queue when
// offline, so the web /fm route can't wipe the queue + flip into FM mode
// while nothing can actually play.
if (!this.connected) {
return "Bot is not connected to TeamSpeak";
} }
const songs = await this.neteaseProvider.getPersonalFm(); if (!provider.getPersonalFm) {
return `Personal FM is not available for ${provider.platform}`;
}
const songs = await provider.getPersonalFm();
if (songs.length === 0) if (songs.length === 0)
return "No FM songs available (need to login first)"; return "No FM songs available (need to login first)";
this.queue.clear(); this.queue.clear();
for (const song of songs) { for (const song of songs) {
this.queue.add({ ...song, platform: "netease" }); this.queue.add({ ...song, platform: provider.platform });
} }
this.queue.setMode(PlayMode.Random); this.queue.setMode(PlayMode.Random);
this.isFmMode = true; this.isFmMode = true;
this.fmProvider = provider;
this.player.resetFailures(); this.player.resetFailures();
const first = this.queue.play(); const first = this.queue.play();
if (first) await this.resolveAndPlay(first); if (first) await this.resolveAndPlay(first);
this.emit("stateChange"); this.emit("stateChange");
return `Personal FM started: ${first?.name ?? "unknown"} - ${first?.artist ?? ""}`; const label = provider.platform === "qq" ? "QQ Radar FM" : "Personal FM";
return `${label} started: ${first?.name ?? "unknown"} - ${first?.artist ?? ""}`;
} }
private async cmdArtist(cmd: ParsedCommand): Promise<string> { private async cmdArtist(cmd: ParsedCommand): Promise<string> {
@@ -712,7 +794,7 @@ export class BotInstance extends EventEmitter {
} }
this.queue.clear(); this.queue.clear();
this.isFmMode = false; this.disableFmMode();
for (const song of filtered) { for (const song of filtered) {
this.queue.add({ ...song, platform: provider.platform }); this.queue.add({ ...song, platform: provider.platform });
} }
@@ -726,14 +808,15 @@ export class BotInstance extends EventEmitter {
} }
private async refillFm(): Promise<void> { private async refillFm(): Promise<void> {
if (!this.isFmMode || !this.neteaseProvider.getPersonalFm) return; const provider = this.fmProvider;
if (!this.isFmMode || !provider?.getPersonalFm) return;
try { try {
const songs = await this.neteaseProvider.getPersonalFm(); const songs = await provider.getPersonalFm();
if (songs.length === 0) return; if (songs.length === 0) return;
for (const song of songs) { for (const song of songs) {
this.queue.add({ ...song, platform: "netease" }); this.queue.add({ ...song, platform: provider.platform });
} }
this.logger.debug({ count: songs.length }, "FM queue refilled"); this.logger.debug({ count: songs.length, platform: provider.platform }, "FM queue refilled");
} catch (err) { } catch (err) {
this.logger.error({ err }, "Failed to refill FM queue"); this.logger.error({ err }, "Failed to refill FM queue");
} }
+6 -1
View File
@@ -12,6 +12,7 @@ import type { Logger } from "../logger.js";
import type { ServerProtocol } from "../ts-protocol/client.js"; import type { ServerProtocol } from "../ts-protocol/client.js";
import type { AvatarStore } from "../data/avatars.js"; import type { AvatarStore } from "../data/avatars.js";
import type { PermissionStore } from "../data/permissions.js";
/** /**
* Run bot.connect() with a hard deadline. If the handshake hangs (e.g. the * Run bot.connect() with a hard deadline. If the handshake hangs (e.g. the
@@ -76,6 +77,7 @@ export class BotManager extends EventEmitter {
private config: BotConfig; private config: BotConfig;
private logger: Logger; private logger: Logger;
private avatarStore: AvatarStore; private avatarStore: AvatarStore;
private permissions: PermissionStore;
constructor( constructor(
neteaseProvider: MusicProvider, neteaseProvider: MusicProvider,
@@ -84,7 +86,8 @@ export class BotManager extends EventEmitter {
database: BotDatabase, database: BotDatabase,
config: BotConfig, config: BotConfig,
logger: Logger, logger: Logger,
avatarStore: AvatarStore avatarStore: AvatarStore,
permissions: PermissionStore
) { ) {
super(); super();
this.neteaseProvider = neteaseProvider; this.neteaseProvider = neteaseProvider;
@@ -95,6 +98,7 @@ export class BotManager extends EventEmitter {
this.config = config; this.config = config;
this.logger = logger; this.logger = logger;
this.avatarStore = avatarStore; this.avatarStore = avatarStore;
this.permissions = permissions;
} }
async createBot(params: CreateBotParams): Promise<BotInstance> { async createBot(params: CreateBotParams): Promise<BotInstance> {
@@ -152,6 +156,7 @@ export class BotManager extends EventEmitter {
this.bots.delete(id); this.bots.delete(id);
} }
this.database.deleteBotInstance(id); this.database.deleteBotInstance(id);
this.permissions.pruneBot(id);
this.emit("botInstanceRemoved", id); this.emit("botInstanceRemoved", id);
this.logger.info({ botId: id }, "Bot instance removed"); this.logger.info({ botId: id }, "Bot instance removed");
} }
+2 -1
View File
@@ -6,7 +6,8 @@ export type AuditAction =
| "user.deleted" | "user.deleted"
| "user.password_reset" | "user.password_reset"
| "user.password_changed" | "user.password_changed"
| "user.role_changed"; | "user.role_changed"
| "user.permissions_changed";
export interface AuditEntry { export interface AuditEntry {
id: number; id: number;
+55 -2
View File
@@ -1,8 +1,8 @@
import { describe, it, expect, afterEach } from "vitest"; import { describe, it, expect, afterEach } from "vitest";
import { join } from "node:path"; import { join } from "node:path";
import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { mkdtempSync, rmSync, writeFileSync, existsSync, readFileSync } from "node:fs";
import { tmpdir } from "node:os"; import { tmpdir } from "node:os";
import { getDefaultConfig, loadConfig, saveConfig } from "./config.js"; import { getDefaultConfig, loadConfig, saveConfig, migrateLegacyConfig } from "./config.js";
describe("config", () => { describe("config", () => {
const dirs: string[] = []; const dirs: string[] = [];
@@ -51,4 +51,57 @@ describe("config", () => {
expect(loaded.commandPrefix).toBe("!"); expect(loaded.commandPrefix).toBe("!");
expect(loaded.autoPauseOnEmpty).toBe(true); expect(loaded.autoPauseOnEmpty).toBe(true);
}); });
// --- #86: config.json must live under (and be created in) the persisted data dir ---
it("first run writes config.json into the data dir and reads it back", () => {
const root = makeTmpDir();
const dataDir = join(root, "data");
const configPath = join(dataDir, "config.json"); // mirrors index.ts CONFIG_PATH
// Boot sequence: load (missing -> defaults) then save.
const config = loadConfig(configPath);
saveConfig(configPath, config);
expect(existsSync(configPath)).toBe(true);
// A subsequent hand-edited file under the SAME persisted path is honored.
writeFileSync(configPath, JSON.stringify({ webPort: 9999 }), "utf-8");
expect(loadConfig(configPath).webPort).toBe(9999);
});
it("migrates a legacy root config into the data dir, preserving values", () => {
const root = makeTmpDir();
const legacyPath = join(root, "config.json");
const newPath = join(root, "data", "config.json");
writeFileSync(legacyPath, JSON.stringify({ webPort: 4242, publicUrl: "http://x" }), "utf-8");
const migrated = migrateLegacyConfig(legacyPath, newPath);
expect(migrated).toBe(true);
expect(existsSync(newPath)).toBe(true);
expect(existsSync(legacyPath)).toBe(false); // legacy moved, not duplicated
const loaded = loadConfig(newPath);
expect(loaded.webPort).toBe(4242);
expect(loaded.publicUrl).toBe("http://x");
});
it("does NOT overwrite an existing data-dir config during migration", () => {
const root = makeTmpDir();
const legacyPath = join(root, "config.json");
const newPath = join(root, "data", "config.json");
writeFileSync(legacyPath, JSON.stringify({ webPort: 1111 }), "utf-8");
saveConfig(newPath, { ...getDefaultConfig(), webPort: 2222 });
const migrated = migrateLegacyConfig(legacyPath, newPath);
expect(migrated).toBe(false); // new location wins, untouched
expect(loadConfig(newPath).webPort).toBe(2222);
expect(existsSync(legacyPath)).toBe(true); // legacy left intact when not migrated
});
it("migration is a no-op when there is no legacy config", () => {
const root = makeTmpDir();
const migrated = migrateLegacyConfig(join(root, "config.json"), join(root, "data", "config.json"));
expect(migrated).toBe(false);
});
}); });
+33 -1
View File
@@ -1,4 +1,4 @@
import { readFileSync, writeFileSync, mkdirSync } from "node:fs"; import { readFileSync, writeFileSync, mkdirSync, existsSync, copyFileSync, rmSync } from "node:fs";
import { dirname } from "node:path"; import { dirname } from "node:path";
export interface BotConfig { export interface BotConfig {
@@ -58,3 +58,35 @@ export function saveConfig(path: string, config: BotConfig): void {
mkdirSync(dirname(path), { recursive: true }); mkdirSync(dirname(path), { recursive: true });
writeFileSync(path, JSON.stringify(config, null, 2), "utf-8"); writeFileSync(path, JSON.stringify(config, null, 2), "utf-8");
} }
/**
* One-time migration for the config location fix (#86).
*
* Older versions wrote config.json to the app/repo ROOT, which is NOT inside the
* persisted data directory (the Docker volume is mounted at data/). That meant the
* file never landed in the volume on first run and a manually-placed data/config.json
* was ignored. config.json now lives under the data dir alongside the DB/cookies/logs.
*
* If a legacy root-level config exists and the new data-dir config does not yet exist,
* move it so existing local installs keep their customized settings. Best-effort:
* any failure is swallowed and loadConfig falls back to defaults.
*
* @returns true if a legacy config was migrated, false otherwise.
*/
export function migrateLegacyConfig(legacyPath: string, newPath: string): boolean {
try {
if (legacyPath === newPath) return false;
if (existsSync(newPath)) return false; // new location already populated — leave it
if (!existsSync(legacyPath)) return false; // nothing to migrate
mkdirSync(dirname(newPath), { recursive: true });
copyFileSync(legacyPath, newPath); // copy first (works across filesystems)
try {
rmSync(legacyPath);
} catch {
/* leave the legacy file if it can't be removed; the new one wins */
}
return true;
} catch {
return false;
}
}
+105
View File
@@ -1,4 +1,5 @@
import Database from "better-sqlite3"; import Database from "better-sqlite3";
import { CAPABILITIES, BOTS_ALL } from "./permissions.js";
export interface PlayHistoryEntry { export interface PlayHistoryEntry {
botId: string; botId: string;
@@ -51,6 +52,17 @@ export const DEFAULT_PROFILE_CONFIG: ProfileConfig = {
nowPlayingMsgEnabled: true, nowPlayingMsgEnabled: true,
}; };
export interface FavoritePlaylist {
id: number;
userId: string;
platform: string;
playlistId: string;
name: string;
coverUrl: string;
songCount: number;
createdAt: string;
}
export interface BotDatabase { export interface BotDatabase {
db: Database.Database; db: Database.Database;
addPlayHistory(entry: PlayHistoryEntry): void; addPlayHistory(entry: PlayHistoryEntry): void;
@@ -62,6 +74,10 @@ export interface BotDatabase {
saveProfileConfig(botId: string, config: ProfileConfig): void; saveProfileConfig(botId: string, config: ProfileConfig): void;
getCustomAvatarPath(botId: string): string | null; getCustomAvatarPath(botId: string): string | null;
setCustomAvatarPath(botId: string, path: string | null): void; setCustomAvatarPath(botId: string, path: string | null): void;
addFavorite(userId: string, playlist: { platform: string; playlistId: string; name: string; coverUrl: string; songCount: number }): void;
removeFavorite(userId: string, playlistId: string, platform: string): boolean;
getFavorites(userId: string): FavoritePlaylist[];
isFavorited(userId: string, playlistId: string, platform: string): boolean;
close(): void; close(): void;
} }
@@ -165,15 +181,68 @@ function initTables(db: Database.Database): void {
action TEXT NOT NULL action TEXT NOT NULL
); );
CREATE INDEX IF NOT EXISTS idx_user_audit_timestamp ON user_audit(timestamp DESC); CREATE INDEX IF NOT EXISTS idx_user_audit_timestamp ON user_audit(timestamp DESC);
CREATE TABLE IF NOT EXISTS favorite_playlists (
id INTEGER PRIMARY KEY AUTOINCREMENT,
userId TEXT NOT NULL,
platform TEXT NOT NULL,
playlistId TEXT NOT NULL,
name TEXT NOT NULL,
coverUrl TEXT NOT NULL DEFAULT '',
songCount INTEGER NOT NULL DEFAULT 0,
createdAt TEXT NOT NULL DEFAULT (datetime('now')),
FOREIGN KEY (userId) REFERENCES users(id) ON DELETE CASCADE,
UNIQUE(userId, platform, playlistId)
);
CREATE INDEX IF NOT EXISTS idx_favorites_userId ON favorite_playlists(userId);
CREATE TABLE IF NOT EXISTS user_permissions (
userId TEXT NOT NULL,
permission TEXT NOT NULL,
PRIMARY KEY (userId, permission),
FOREIGN KEY (userId) REFERENCES users(id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS user_bot_access (
userId TEXT NOT NULL,
botId TEXT NOT NULL,
PRIMARY KEY (userId, botId),
FOREIGN KEY (userId) REFERENCES users(id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_user_bot_access_userId ON user_bot_access(userId);
`); `);
} }
/**
* One-time backfill: existing `member` users created before the
* account-permissions feature are granted full access (all 5 capabilities +
* the `bots.all` marker), exactly once per database. Admins are skipped (they
* bypass permission checks). New members created after this runs are not
* affected — they get the basic tier via POST /api/users. A marker row in
* `schema_meta` makes this idempotent.
*/
export function backfillMemberPermissions(db: Database.Database): void {
db.exec(`CREATE TABLE IF NOT EXISTS schema_meta (key TEXT PRIMARY KEY, value TEXT)`);
const done = db.prepare("SELECT value FROM schema_meta WHERE key = 'perm_backfill_done'").get();
if (done) return;
const members = db.prepare("SELECT id FROM users WHERE role = 'member'").all() as { id: string }[];
const insCap = db.prepare("INSERT OR IGNORE INTO user_permissions (userId, permission) VALUES (?, ?)");
const tokens = [...CAPABILITIES, BOTS_ALL];
const tx = db.transaction(() => {
for (const m of members) {
for (const t of tokens) insCap.run(m.id, t);
}
db.prepare("INSERT INTO schema_meta (key, value) VALUES ('perm_backfill_done', ?)").run(String(members.length));
});
tx();
}
export function createDatabase(dbPath: string): BotDatabase { export function createDatabase(dbPath: string): BotDatabase {
const db = new Database(dbPath); const db = new Database(dbPath);
db.pragma("journal_mode = WAL"); db.pragma("journal_mode = WAL");
db.pragma("foreign_keys = ON"); db.pragma("foreign_keys = ON");
initTables(db); initTables(db);
migrateSchema(db); migrateSchema(db);
backfillMemberPermissions(db);
const insertHistory = db.prepare(` const insertHistory = db.prepare(`
INSERT INTO play_history (botId, songId, songName, artist, album, platform, coverUrl) INSERT INTO play_history (botId, songId, songName, artist, album, platform, coverUrl)
@@ -226,6 +295,24 @@ export function createDatabase(dbPath: string): BotDatabase {
const selectCustomAvatar = db.prepare(`SELECT custom_avatar_path FROM bot_instances WHERE id = ?`); const selectCustomAvatar = db.prepare(`SELECT custom_avatar_path FROM bot_instances WHERE id = ?`);
const updateCustomAvatar = db.prepare(`UPDATE bot_instances SET custom_avatar_path = ? WHERE id = ?`); const updateCustomAvatar = db.prepare(`UPDATE bot_instances SET custom_avatar_path = ? WHERE id = ?`);
const insertFavorite = db.prepare(`
INSERT INTO favorite_playlists (userId, platform, playlistId, name, coverUrl, songCount)
VALUES (@userId, @platform, @playlistId, @name, @coverUrl, @songCount)
`);
const deleteFavorite = db.prepare(`
DELETE FROM favorite_playlists WHERE userId = ? AND playlistId = ? AND platform = ?
`);
const selectFavorites = db.prepare(`
SELECT id, userId, platform, playlistId, name, coverUrl, songCount, createdAt
FROM favorite_playlists WHERE userId = ? ORDER BY createdAt DESC
`);
const checkFavorited = db.prepare(`
SELECT 1 FROM favorite_playlists WHERE userId = ? AND playlistId = ? AND platform = ?
`);
return { return {
db, db,
@@ -297,6 +384,24 @@ export function createDatabase(dbPath: string): BotDatabase {
updateCustomAvatar.run(path, botId); updateCustomAvatar.run(path, botId);
}, },
addFavorite(userId, playlist) {
insertFavorite.run({ userId, ...playlist });
},
removeFavorite(userId, playlistId, platform) {
const result = deleteFavorite.run(userId, playlistId, platform);
return result.changes > 0;
},
getFavorites(userId) {
return selectFavorites.all(userId) as FavoritePlaylist[];
},
isFavorited(userId, playlistId, platform) {
const row = checkFavorited.get(userId, playlistId, platform);
return row !== undefined;
},
close() { close() {
db.close(); db.close();
}, },
+58
View File
@@ -0,0 +1,58 @@
import { describe, it, expect, afterEach } from "vitest";
import fs from "node:fs";
import path from "node:path";
import os from "node:os";
import { createDatabase, backfillMemberPermissions, type BotDatabase } from "./database.js";
import { createPermissionStore, CAPABILITIES } from "./permissions.js";
describe("backfillMemberPermissions", () => {
let dbFile: string;
let db: BotDatabase;
function fresh() {
dbFile = path.join(os.tmpdir(), `mig-${Date.now()}-${Math.random().toString(36).slice(2)}.db`);
db = createDatabase(dbFile);
}
afterEach(() => {
db.close();
for (const s of ["", "-wal", "-shm"]) {
try {
fs.rmSync(dbFile + s, { force: true });
} catch {}
}
});
it("grants existing members full access + bots.all, skips admins, once", () => {
fresh();
// simulate a pre-feature DB: clear the marker that createDatabase set, add users, no perm rows
db.db.prepare("DELETE FROM schema_meta WHERE key = 'perm_backfill_done'").run();
const now = Date.now();
const ins = db.db.prepare(
"INSERT INTO users (id,username,passwordHash,createdAt,updatedAt,role) VALUES (?,?,?,?,?,?)"
);
ins.run("m1", "mem", "x", now, now, "member");
ins.run("a1", "adm", "x", now, now, "admin");
backfillMemberPermissions(db.db);
const store = createPermissionStore(db.db);
expect(store.getCapabilities("m1").sort()).toEqual([...CAPABILITIES].sort());
expect(store.getBotAccess("m1")).toBe("all");
expect(store.getCapabilities("a1")).toEqual([]);
expect(store.getBotAccess("a1")).toEqual([]);
});
it("is idempotent — running again does not change or re-grant", () => {
fresh();
db.db.prepare("DELETE FROM schema_meta WHERE key = 'perm_backfill_done'").run();
const now = Date.now();
db.db
.prepare("INSERT INTO users (id,username,passwordHash,createdAt,updatedAt,role) VALUES (?,?,?,?,?,?)")
.run("m1", "mem", "x", now, now, "member");
backfillMemberPermissions(db.db);
// member restricted afterwards
createPermissionStore(db.db).setPermissions("m1", { capabilities: [], bots: [] });
// second run must NOT re-grant (marker present)
backfillMemberPermissions(db.db);
expect(createPermissionStore(db.db).getCapabilities("m1")).toEqual([]);
});
});
+90
View File
@@ -0,0 +1,90 @@
import { describe, it, expect, beforeEach, afterEach } from "vitest";
import fs from "node:fs";
import path from "node:path";
import os from "node:os";
import { createDatabase, type BotDatabase } from "./database.js";
import { createPermissionStore } from "./permissions.js";
import { CAPABILITIES, BASIC_TIER_CAPABILITIES, resolvePermissionContext } from "./permissions.js";
describe("PermissionStore", () => {
let dbFile: string;
let db: BotDatabase;
beforeEach(() => {
dbFile = path.join(os.tmpdir(), `perm-test-${Date.now()}-${Math.random().toString(36).slice(2)}.db`);
db = createDatabase(dbFile);
db.db.prepare(
"INSERT INTO users (id, username, passwordHash, createdAt, updatedAt, role) VALUES (?,?,?,?,?,?)"
).run("u1", "alice", "x", Date.now(), Date.now(), "member");
});
afterEach(() => {
db.close();
try { fs.rmSync(dbFile, { force: true }); } catch {}
try { fs.rmSync(dbFile + "-wal", { force: true }); } catch {}
try { fs.rmSync(dbFile + "-shm", { force: true }); } catch {}
});
it("exposes the five capability tokens and a basic tier", () => {
expect(CAPABILITIES).toEqual([
"player.control", "player.queue", "bot.manage", "platform.auth", "quality",
]);
expect(BASIC_TIER_CAPABILITIES).toEqual(["player.control", "player.queue"]);
});
it("defaults to no capabilities and no bots", () => {
const store = createPermissionStore(db.db);
expect(store.getCapabilities("u1")).toEqual([]);
expect(store.getBotAccess("u1")).toEqual([]);
});
it("round-trips capabilities and a specific bot list", () => {
const store = createPermissionStore(db.db);
store.setPermissions("u1", { capabilities: ["player.control", "quality"], bots: ["botA", "botB"] });
expect(store.getCapabilities("u1").sort()).toEqual(["player.control", "quality"]);
expect(store.getBotAccess("u1")).toEqual(["botA", "botB"]);
});
it("stores the all-bots flag as 'all'", () => {
const store = createPermissionStore(db.db);
store.setPermissions("u1", { capabilities: ["player.control"], bots: "all" });
expect(store.getBotAccess("u1")).toBe("all");
});
it("setPermissions replaces prior capabilities and bots", () => {
const store = createPermissionStore(db.db);
store.setPermissions("u1", { capabilities: ["player.control"], bots: ["botA"] });
store.setPermissions("u1", { capabilities: ["quality"], bots: "all" });
expect(store.getCapabilities("u1")).toEqual(["quality"]);
expect(store.getBotAccess("u1")).toBe("all");
});
it("ignores unknown capability tokens", () => {
const store = createPermissionStore(db.db);
store.setPermissions("u1", { capabilities: ["player.control", "bogus" as any], bots: [] });
expect(store.getCapabilities("u1")).toEqual(["player.control"]);
});
it("pruneBot removes a bot from every user's allow-list", () => {
const store = createPermissionStore(db.db);
store.setPermissions("u1", { capabilities: [], bots: ["botA", "botB"] });
store.pruneBot("botA");
expect(store.getBotAccess("u1")).toEqual(["botB"]);
});
describe("resolvePermissionContext", () => {
it("admin gets all capabilities and all bots regardless of stored rows", () => {
const store = createPermissionStore(db.db);
const ctx = resolvePermissionContext("admin", "u1", store);
expect([...ctx.capabilities].sort()).toEqual([...CAPABILITIES].sort());
expect(ctx.bots).toBe("all");
});
it("member reflects stored capabilities + bot access", () => {
const store = createPermissionStore(db.db);
store.setPermissions("u1", { capabilities: ["player.control"], bots: ["b1"] });
const ctx = resolvePermissionContext("member", "u1", store);
expect([...ctx.capabilities]).toEqual(["player.control"]);
expect(ctx.bots).toEqual(new Set(["b1"]));
});
});
});
+89
View File
@@ -0,0 +1,89 @@
import type Database from "better-sqlite3";
export const CAPABILITIES = [
"player.control",
"player.queue",
"bot.manage",
"platform.auth",
"quality",
] as const;
export type Capability = (typeof CAPABILITIES)[number];
/** Marker token stored in user_permissions meaning "all bots, incl. future". */
export const BOTS_ALL = "bots.all";
/** Capabilities granted to a newly-created member by default. */
export const BASIC_TIER_CAPABILITIES: Capability[] = ["player.control", "player.queue"];
export function isCapability(x: string): x is Capability {
return (CAPABILITIES as readonly string[]).includes(x);
}
export type BotAccess = "all" | string[];
export interface PermissionStore {
getCapabilities(userId: string): Capability[];
getBotAccess(userId: string): BotAccess;
setPermissions(userId: string, input: { capabilities: string[]; bots: BotAccess }): void;
pruneBot(botId: string): void;
}
export function createPermissionStore(db: Database.Database): PermissionStore {
const selCaps = db.prepare("SELECT permission FROM user_permissions WHERE userId = ?");
const delCaps = db.prepare("DELETE FROM user_permissions WHERE userId = ?");
const insCap = db.prepare("INSERT OR IGNORE INTO user_permissions (userId, permission) VALUES (?, ?)");
const selBots = db.prepare("SELECT botId FROM user_bot_access WHERE userId = ?");
const delBots = db.prepare("DELETE FROM user_bot_access WHERE userId = ?");
const insBot = db.prepare("INSERT OR IGNORE INTO user_bot_access (userId, botId) VALUES (?, ?)");
const pruneBotStmt = db.prepare("DELETE FROM user_bot_access WHERE botId = ?");
return {
getCapabilities(userId) {
return (selCaps.all(userId) as { permission: string }[])
.map((r) => r.permission)
.filter((p): p is Capability => isCapability(p));
},
getBotAccess(userId) {
const all = (selCaps.all(userId) as { permission: string }[]).some((r) => r.permission === BOTS_ALL);
if (all) return "all";
return (selBots.all(userId) as { botId: string }[]).map((r) => r.botId);
},
setPermissions(userId, input) {
const caps = input.capabilities.filter(isCapability);
const tx = db.transaction(() => {
delCaps.run(userId);
delBots.run(userId);
for (const c of caps) insCap.run(userId, c);
if (input.bots === "all") {
insCap.run(userId, BOTS_ALL);
} else {
for (const b of input.bots) insBot.run(userId, b);
}
});
tx();
},
pruneBot(botId) {
pruneBotStmt.run(botId);
},
};
}
export interface PermissionContext {
capabilities: Set<string>;
bots: "all" | Set<string>;
}
export function resolvePermissionContext(
role: "admin" | "member",
userId: string,
store: PermissionStore
): PermissionContext {
if (role === "admin") {
return { capabilities: new Set(CAPABILITIES), bots: "all" };
}
const access = store.getBotAccess(userId);
return {
capabilities: new Set(store.getCapabilities(userId)),
bots: access === "all" ? "all" : new Set(access),
};
}
+14 -3
View File
@@ -1,6 +1,6 @@
import path from "node:path"; import path from "node:path";
import { fileURLToPath } from "node:url"; import { fileURLToPath } from "node:url";
import { loadConfig, saveConfig } from "./data/config.js"; import { loadConfig, saveConfig, migrateLegacyConfig } from "./data/config.js";
import { createDatabase } from "./data/database.js"; import { createDatabase } from "./data/database.js";
import { createLogger } from "./logger.js"; import { createLogger } from "./logger.js";
import { createApiServerManager } from "./music/api-server.js"; import { createApiServerManager } from "./music/api-server.js";
@@ -9,13 +9,18 @@ import { QQMusicProvider } from "./music/qq.js";
import { BiliBiliProvider } from "./music/bilibili.js"; import { BiliBiliProvider } from "./music/bilibili.js";
import { createCookieStore } from "./music/auth.js"; import { createCookieStore } from "./music/auth.js";
import { createAvatarStore } from "./data/avatars.js"; import { createAvatarStore } from "./data/avatars.js";
import { createPermissionStore } from "./data/permissions.js";
import { BotManager } from "./bot/manager.js"; import { BotManager } from "./bot/manager.js";
import { createWebServer } from "./web/server.js"; import { createWebServer } from "./web/server.js";
const __dirname = path.dirname(fileURLToPath(import.meta.url)); const __dirname = path.dirname(fileURLToPath(import.meta.url));
const ROOT_DIR = path.resolve(__dirname, ".."); const ROOT_DIR = path.resolve(__dirname, "..");
const DATA_DIR = path.join(ROOT_DIR, "data"); const DATA_DIR = path.join(ROOT_DIR, "data");
const CONFIG_PATH = path.join(ROOT_DIR, "config.json"); // config.json lives under the persisted data dir (the Docker volume) alongside the
// DB/cookies/logs, so it survives container restarts and manual edits take effect
// (#86). LEGACY_CONFIG_PATH is the old root-level location we migrate from once.
const CONFIG_PATH = path.join(DATA_DIR, "config.json");
const LEGACY_CONFIG_PATH = path.join(ROOT_DIR, "config.json");
const DB_PATH = path.join(DATA_DIR, "tsmusicbot.db"); const DB_PATH = path.join(DATA_DIR, "tsmusicbot.db");
const LOG_DIR = path.join(DATA_DIR, "logs"); const LOG_DIR = path.join(DATA_DIR, "logs");
const COOKIE_DIR = path.join(DATA_DIR, "cookies"); const COOKIE_DIR = path.join(DATA_DIR, "cookies");
@@ -23,6 +28,9 @@ const AVATAR_DIR = path.join(DATA_DIR, "avatars");
const STATIC_DIR = path.join(ROOT_DIR, "web", "dist"); const STATIC_DIR = path.join(ROOT_DIR, "web", "dist");
async function main() { async function main() {
// Migrate a pre-#86 root-level config.json into the data dir so existing
// installs keep their settings; no-op if already migrated or none exists.
migrateLegacyConfig(LEGACY_CONFIG_PATH, CONFIG_PATH);
const config = loadConfig(CONFIG_PATH); const config = loadConfig(CONFIG_PATH);
saveConfig(CONFIG_PATH, config); saveConfig(CONFIG_PATH, config);
@@ -56,6 +64,8 @@ async function main() {
const bilibiliCookie = cookieStore.load("bilibili"); const bilibiliCookie = cookieStore.load("bilibili");
if (bilibiliCookie) bilibiliProvider.setCookie(bilibiliCookie); if (bilibiliCookie) bilibiliProvider.setCookie(bilibiliCookie);
const permissions = createPermissionStore(db.db);
const botManager = new BotManager( const botManager = new BotManager(
neteaseProvider, neteaseProvider,
qqProvider, qqProvider,
@@ -63,7 +73,8 @@ async function main() {
db, db,
config, config,
logger, logger,
avatarStore avatarStore,
permissions
); );
await botManager.loadSavedBots(); await botManager.loadSavedBots();
+25 -1
View File
@@ -1,7 +1,31 @@
import { describe, it, expect } from "vitest"; import { describe, it, expect } from "vitest";
import { mapQqAlbums } from "./qq.js"; import { mapQqAlbums, mapQqSongs } from "./qq.js";
describe("QQ adapter", () => { describe("QQ adapter", () => {
it("mapQqSongs maps QQMusicApi-style song entries", () => {
const out = mapQqSongs([
{
mid: "001abc",
name: "Radar Song",
singer: [{ name: "Singer A" }, { name: "Singer B" }],
album: { name: "Album A", mid: "alb001" },
interval: 243,
},
]);
expect(out).toEqual([
{
id: "001abc",
name: "Radar Song",
artist: "Singer A / Singer B",
album: "Album A",
duration: 243,
coverUrl: "https://y.gtimg.cn/music/photo_new/T002R300x300M000alb001.jpg",
platform: "qq",
},
]);
});
it("mapQqAlbums maps albumMID-style raw entries", () => { it("mapQqAlbums maps albumMID-style raw entries", () => {
const raw = [ const raw = [
{ {
+109 -46
View File
@@ -39,6 +39,24 @@ const qqFavApi = axios.create({
headers: { referer: "https://y.qq.com/" }, headers: { referer: "https://y.qq.com/" },
}); });
export function mapQqSongs(raw: any[] | null | undefined): Song[] {
if (!Array.isArray(raw)) return [];
return raw.map((s) => {
const albumMid = s.album?.mid ?? s.album?.pmid ?? s.albummid ?? s.albumMid ?? "";
return {
id: String(s.mid ?? s.songmid ?? s.songMID ?? s.id ?? s.songid ?? s.songId ?? ""),
name: s.title ?? s.name ?? s.songname ?? "",
artist: (s.singer ?? s.singers ?? []).map((a: any) => a.name ?? a.title ?? "").filter(Boolean).join(" / "),
album: s.album?.name ?? s.album?.title ?? s.albumname ?? "",
duration: s.interval ?? Math.round((s.duration ?? 0) / 1000),
coverUrl: albumMid
? `https://y.gtimg.cn/music/photo_new/T002R300x300M000${albumMid}.jpg`
: "",
platform: "qq" as const,
};
}).filter((s) => s.id);
}
export function mapQqAlbums(raw: any[] | null | undefined): Album[] { export function mapQqAlbums(raw: any[] | null | undefined): Album[] {
if (!Array.isArray(raw)) return []; if (!Array.isArray(raw)) return [];
return raw.map((a) => { return raw.map((a) => {
@@ -72,6 +90,7 @@ export class QQMusicProvider implements MusicProvider {
private api: AxiosInstance; private api: AxiosInstance;
private cookie = ""; private cookie = "";
private quality = "exhigh"; private quality = "exhigh";
private radarPage = 1;
constructor(baseUrl: string) { constructor(baseUrl: string) {
this.api = axios.create({ this.api = axios.create({
@@ -92,6 +111,30 @@ export class QQMusicProvider implements MusicProvider {
return this.cookie ? { cookie: this.cookie } : {}; return this.cookie ? { cookie: this.cookie } : {};
} }
private get directCookieHeaders(): Record<string, string> {
return this.cookie ? { Cookie: this.cookie } : {};
}
private buildMusicuPayload(module: string, method: string, param: Record<string, unknown>): Record<string, unknown> {
const uinMatch = /(?:^|; )(?:uin|qqmusic_uin)=o?0?(\d+)/.exec(this.cookie);
const pSkeyMatch = /(?:^|; )p_skey=([^;]+)/.exec(this.cookie);
return {
comm: {
ct: 24,
cv: 4747474,
platform: "yqq.json",
uin: uinMatch ? uinMatch[1] : "0",
g_tk: pSkeyMatch ? computeGtk(pSkeyMatch[1]) : 5381,
format: "json",
inCharset: "utf-8",
outCharset: "utf-8",
notice: 0,
need_new_code: 1,
},
req_0: { module, method, param },
};
}
async search(query: string, limit = 20): Promise<SearchResult> { async search(query: string, limit = 20): Promise<SearchResult> {
// Primary: u.y.qq.com/cgi-bin/musicu.fcg — supports songs + albums + // Primary: u.y.qq.com/cgi-bin/musicu.fcg — supports songs + albums +
// playlists. Fixed per https://github.com/ZHANGTIANYAO1/teamspeak-music-bot/issues/61 // playlists. Fixed per https://github.com/ZHANGTIANYAO1/teamspeak-music-bot/issues/61
@@ -141,17 +184,7 @@ export class QQMusicProvider implements MusicProvider {
res.data?.req_0?.data?.body?.song?.list ?? []; res.data?.req_0?.data?.body?.song?.list ?? [];
if (songList.length === 0) return null; if (songList.length === 0) return null;
const songs: Song[] = songList.map((s: any) => ({ const songs = mapQqSongs(songList);
id: String(s.mid ?? s.id),
name: s.title ?? s.name ?? "",
artist: (s.singer ?? []).map((a: any) => a.name).join(" / "),
album: s.album?.name ?? s.album?.title ?? "",
duration: s.interval ?? 0,
coverUrl: s.album?.mid
? `https://y.gtimg.cn/music/photo_new/T002R300x300M000${s.album.mid}.jpg`
: "",
platform: "qq",
}));
const albumList: any[] = res.data?.req_album?.data?.body?.album?.list ?? []; const albumList: any[] = res.data?.req_album?.data?.body?.album?.list ?? [];
const albums = mapQqAlbums(albumList); const albums = mapQqAlbums(albumList);
@@ -203,17 +236,7 @@ export class QQMusicProvider implements MusicProvider {
? (songRes.value.data?.data?.song?.list ?? []) ? (songRes.value.data?.data?.song?.list ?? [])
: []; : [];
const songs: Song[] = songList.map((s: any) => ({ const songs = mapQqSongs(songList);
id: String(s.songmid ?? s.songid ?? ""),
name: s.songname ?? s.name ?? "",
artist: (s.singer ?? []).map((a: any) => a.name).join(" / "),
album: s.albumname ?? s.album?.name ?? "",
duration: s.interval ?? 0,
coverUrl: s.albummid
? `https://y.gtimg.cn/music/photo_new/T002R300x300M000${s.albummid}.jpg`
: "",
platform: "qq",
}));
const albumList: any[] = const albumList: any[] =
albumRes.status === "fulfilled" albumRes.status === "fulfilled"
@@ -339,19 +362,7 @@ export class QQMusicProvider implements MusicProvider {
}); });
const cdlist = res.data?.response?.cdlist ?? []; const cdlist = res.data?.response?.cdlist ?? [];
if (cdlist.length === 0) return []; if (cdlist.length === 0) return [];
return (cdlist[0].songlist ?? []).map((s: any) => ({ return mapQqSongs(cdlist[0].songlist ?? []);
id: String(s.mid ?? s.songmid ?? s.songid),
name: s.songname ?? s.name ?? "",
artist: (s.singer ?? []).map((a: any) => a.name).join(" / "),
album: s.albumname ?? "",
duration: s.interval ?? 0,
coverUrl: s.album?.mid
? `https://y.gtimg.cn/music/photo_new/T002R300x300M000${s.album.mid}.jpg`
: s.albummid
? `https://y.gtimg.cn/music/photo_new/T002R300x300M000${s.albummid}.jpg`
: "",
platform: "qq",
}));
} }
async getPlaylistDetail(playlistId: string): Promise<PlaylistDetail | null> { async getPlaylistDetail(playlistId: string): Promise<PlaylistDetail | null> {
@@ -386,17 +397,7 @@ export class QQMusicProvider implements MusicProvider {
const res = await this.api.get("/getAlbumInfo", { const res = await this.api.get("/getAlbumInfo", {
params: { albummid: albumId, ...this.cookieParams }, params: { albummid: albumId, ...this.cookieParams },
}); });
return (res.data?.response?.data?.list ?? []).map((s: any) => ({ return mapQqSongs(res.data?.response?.data?.list ?? []);
id: String(s.songmid ?? s.songid),
name: s.songname ?? "",
artist: (s.singer ?? []).map((a: any) => a.name).join(" / "),
album: s.albumname ?? "",
duration: s.interval ?? 0,
coverUrl: s.albummid
? `https://y.gtimg.cn/music/photo_new/T002R300x300M000${s.albummid}.jpg`
: "",
platform: "qq",
}));
} }
async getLyrics(songId: string): Promise<LyricLine[]> { async getLyrics(songId: string): Promise<LyricLine[]> {
@@ -461,6 +462,9 @@ export class QQMusicProvider implements MusicProvider {
setCookie(cookie: string): void { setCookie(cookie: string): void {
this.cookie = cookie; this.cookie = cookie;
// Reset radar pagination so a re-login (different account) starts from the
// first page rather than inheriting the previous account's cursor.
this.radarPage = 1;
} }
getCookie(): string { getCookie(): string {
@@ -522,6 +526,65 @@ export class QQMusicProvider implements MusicProvider {
} }
} }
async getPersonalFm(): Promise<Song[]> {
const radarSongs = await this.getRadarRecommendSongs();
if (radarSongs.length > 0) return radarSongs;
return this.getGuessRecommendSongs();
}
private async getRadarRecommendSongs(): Promise<Song[]> {
try {
const page = this.radarPage;
const res = await qqMusicuApi.post(
"/cgi-bin/musicu.fcg",
this.buildMusicuPayload(
"music.recommend.TrackRelationServer",
"GetRadarSong",
{
Page: page,
ReqType: 0,
FavSongs: [],
EntranceSongs: [],
}
),
{ headers: { referer: "https://y.qq.com/", ...this.directCookieHeaders } }
);
const tracks = (res.data?.req_0?.data?.VecSongs ?? [])
.map((item: any) => item?.Track)
.filter(Boolean);
const songs = mapQqSongs(tracks);
if (songs.length > 0) {
this.radarPage = page + 1;
}
return songs;
} catch {
return [];
}
}
private async getGuessRecommendSongs(): Promise<Song[]> {
try {
const res = await qqMusicuApi.post(
"/cgi-bin/musicu.fcg",
this.buildMusicuPayload(
"music.radioProxy.MbTrackRadioSvr",
"get_radio_track",
{
id: 99,
num: 5,
from: 0,
scene: 0,
song_ids: [],
}
),
{ headers: { referer: "https://y.qq.com/", ...this.directCookieHeaders } }
);
return mapQqSongs(res.data?.req_0?.data?.Tracks ?? []);
} catch {
return [];
}
}
async getUserPlaylists(): Promise<Playlist[]> { async getUserPlaylists(): Promise<Playlist[]> {
if (!this.cookie) return []; if (!this.cookie) return [];
const uinMatch = /(?:^|; )uin=o?0?(\d+)/.exec(this.cookie); const uinMatch = /(?:^|; )uin=o?0?(\d+)/.exec(this.cookie);
+16
View File
@@ -12,6 +12,8 @@ import {
type Identity, type Identity,
type TextMessage, type TextMessage,
type ClientInfo, type ClientInfo,
type ClientLeftViewEvent,
type ClientMovedEvent,
type FileUploadInfo, type FileUploadInfo,
} from "@honeybbq/teamspeak-client"; } from "@honeybbq/teamspeak-client";
import type { Logger } from "../logger.js"; import type { Logger } from "../logger.js";
@@ -221,6 +223,20 @@ export class TS3Client extends EventEmitter {
{ nickname: info.nickname, id: info.id }, { nickname: info.nickname, id: info.id },
"Client entered" "Client entered"
); );
this.emit("clientEnter", info);
});
this.client.on("clientLeave", (ev: ClientLeftViewEvent) => {
this.logger.debug({ id: ev.id }, "Client left");
this.emit("clientLeave", ev);
});
this.client.on("clientMoved", (ev: ClientMovedEvent) => {
this.logger.debug(
{ id: ev.id, targetChannelID: ev.targetChannelID.toString() },
"Client moved"
);
this.emit("clientMoved", ev);
}); });
await this.client.connect(); await this.client.connect();
+3 -1
View File
@@ -6,6 +6,7 @@ import { createDatabase, type BotDatabase } from "../../data/database.js";
import { createUserStore } from "../../data/users.js"; import { createUserStore } from "../../data/users.js";
import { createSessionStore } from "../../data/sessions.js"; import { createSessionStore } from "../../data/sessions.js";
import { createAuditStore } from "../../data/audit.js"; import { createAuditStore } from "../../data/audit.js";
import { createPermissionStore } from "../../data/permissions.js";
import { createRequireAuth } from "../middleware/requireAuth.js"; import { createRequireAuth } from "../middleware/requireAuth.js";
import { createAuditRouter } from "./audit.js"; import { createAuditRouter } from "./audit.js";
import { SESSION_COOKIE_NAME } from "../auth/validateSession.js"; import { SESSION_COOKIE_NAME } from "../auth/validateSession.js";
@@ -20,6 +21,7 @@ describe("audit router", () => {
const users = createUserStore(botDb.db); const users = createUserStore(botDb.db);
const sessions = createSessionStore(botDb.db); const sessions = createSessionStore(botDb.db);
const audit = createAuditStore(botDb.db); const audit = createAuditStore(botDb.db);
const permissions = createPermissionStore(botDb.db);
const alice = await users.createUser("alice", "pw-alice", "admin"); const alice = await users.createUser("alice", "pw-alice", "admin");
cookie = `${SESSION_COOKIE_NAME}=${sessions.createSession(alice.id).token}`; cookie = `${SESSION_COOKIE_NAME}=${sessions.createSession(alice.id).token}`;
for (let i = 0; i < 3; i++) { for (let i = 0; i < 3; i++) {
@@ -32,7 +34,7 @@ describe("audit router", () => {
app = express(); app = express();
app.use(express.json()); app.use(express.json());
app.use(cookieParser()); app.use(cookieParser());
app.use("/api", createRequireAuth(sessions)); app.use("/api", createRequireAuth(sessions, permissions));
app.use("/api/audit", createAuditRouter(audit)); app.use("/api/audit", createAuditRouter(audit));
}); });
+5 -4
View File
@@ -3,6 +3,7 @@ import type { MusicProvider } from "../../music/provider.js";
import { YouTubeProvider } from "../../music/youtube.js"; import { YouTubeProvider } from "../../music/youtube.js";
import type { CookieStore } from "../../music/auth.js"; import type { CookieStore } from "../../music/auth.js";
import type { Logger } from "../../logger.js"; import type { Logger } from "../../logger.js";
import { requirePermission } from "../middleware/requirePermission.js";
export function createAuthRouter( export function createAuthRouter(
neteaseProvider: MusicProvider, neteaseProvider: MusicProvider,
@@ -35,7 +36,7 @@ export function createAuthRouter(
} }
}); });
router.post("/qrcode", async (req, res) => { router.post("/qrcode", requirePermission("platform.auth"), async (req, res) => {
try { try {
const { platform } = req.body; const { platform } = req.body;
const provider = getProvider(platform); const provider = getProvider(platform);
@@ -77,7 +78,7 @@ export function createAuthRouter(
} }
}); });
router.post("/sms/send", async (req, res) => { router.post("/sms/send", requirePermission("platform.auth"), async (req, res) => {
try { try {
const { phone } = req.body; const { phone } = req.body;
if (!phone) { if (!phone) {
@@ -97,7 +98,7 @@ export function createAuthRouter(
} }
}); });
router.post("/sms/verify", async (req, res) => { router.post("/sms/verify", requirePermission("platform.auth"), async (req, res) => {
try { try {
const { phone, code } = req.body; const { phone, code } = req.body;
if (!phone || !code) { if (!phone || !code) {
@@ -118,7 +119,7 @@ export function createAuthRouter(
} }
}); });
router.post("/cookie", (req, res) => { router.post("/cookie", requirePermission("platform.auth"), (req, res) => {
const { platform, cookie } = req.body; const { platform, cookie } = req.body;
if (!cookie) { if (!cookie) {
res.status(400).json({ error: "cookie is required" }); res.status(400).json({ error: "cookie is required" });
+90
View File
@@ -0,0 +1,90 @@
import { describe, it, expect } from "vitest";
import express from "express";
import request from "supertest";
import pino from "pino";
import { createBotRouter } from "./bot.js";
const logger = pino({ level: "silent" });
// Fake bot whose getStatus() exposes its id, matching the real status shape.
function makeFakeBot(id: string) {
return {
id,
getStatus: () => ({ id }),
};
}
function makeBotManager() {
const b1 = makeFakeBot("b1");
const b2 = makeFakeBot("b2");
return {
getBot: (id: string) => (id === "b1" ? b1 : id === "b2" ? b2 : undefined),
getAllBots: () => [b1, b2],
getBotConfig: () => undefined,
createBot: async () => b1,
updateBot: () => {},
removeBot: async () => {},
startBot: async () => {},
stopBot: () => {},
} as any;
}
function makeApp(user: any) {
const app = express();
app.use(express.json());
app.use((req, _res, next) => { (req as any).user = user; next(); });
app.use(
"/api/bot",
createBotRouter(
makeBotManager(),
{ idleTimeoutMinutes: 0 } as any,
"/tmp/config.json",
logger,
{ getBotInstances: () => [], getCustomAvatarPath: () => null, setCustomAvatarPath: () => {} } as any,
{ read: () => null, write: () => "x", remove: () => {} } as any,
),
);
return app;
}
const member = (bots: "all" | string[]) => ({
id: "u1",
username: "alice",
role: "member" as const,
capabilities: new Set<string>(),
bots: bots === "all" ? ("all" as const) : new Set(bots),
});
const admin = {
id: "a",
username: "admin",
role: "admin" as const,
capabilities: new Set<string>(),
bots: "all" as const,
};
describe("GET /api/bot bot-list filtering", () => {
it("member with bots:Set([b1]) sees only b1", async () => {
const app = makeApp(member(["b1"]));
const res = await request(app).get("/api/bot");
expect(res.status).toBe(200);
const ids = (res.body.bots as { id: string }[]).map((b) => b.id);
expect(ids).toEqual(["b1"]);
});
it("admin sees both b1 and b2", async () => {
const app = makeApp(admin);
const res = await request(app).get("/api/bot");
expect(res.status).toBe(200);
const ids = (res.body.bots as { id: string }[]).map((b) => b.id).sort();
expect(ids).toEqual(["b1", "b2"]);
});
it("member with bots:'all' sees both b1 and b2", async () => {
const app = makeApp(member("all"));
const res = await request(app).get("/api/bot");
expect(res.status).toBe(200);
const ids = (res.body.bots as { id: string }[]).map((b) => b.id).sort();
expect(ids).toEqual(["b1", "b2"]);
});
});
+161
View File
@@ -0,0 +1,161 @@
import { describe, it, expect, beforeEach, afterEach } from "vitest";
import express from "express";
import cookieParser from "cookie-parser";
import request from "supertest";
import pino from "pino";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { createDatabase, type BotDatabase } from "../../data/database.js";
import { createUserStore } from "../../data/users.js";
import { createSessionStore } from "../../data/sessions.js";
import { createAvatarStore } from "../../data/avatars.js";
import { createRequireAuth } from "../middleware/requireAuth.js";
import { createPermissionStore } from "../../data/permissions.js";
import { createBotRouter } from "./bot.js";
import { getDefaultConfig, type BotConfig } from "../../data/config.js";
import { SESSION_COOKIE_NAME } from "../auth/validateSession.js";
import type { BotManager } from "../../bot/manager.js";
/** Records every updateIdleTimeout / updateAutoPause call so the test can assert propagation. */
function makeFakeBot() {
return {
idleTimeoutCalls: [] as number[],
autoPauseCalls: [] as boolean[],
updateIdleTimeout(minutes: number) {
this.idleTimeoutCalls.push(minutes);
},
updateAutoPause(enabled: boolean) {
this.autoPauseCalls.push(enabled);
},
};
}
describe("bot router /settings", () => {
let botDb: BotDatabase;
let app: express.Express;
let cookie: string;
let config: BotConfig;
let configPath: string;
let tmpDir: string;
let fakeBots: ReturnType<typeof makeFakeBot>[];
beforeEach(async () => {
botDb = createDatabase(":memory:");
const users = createUserStore(botDb.db);
const sessions = createSessionStore(botDb.db);
const alice = await users.createUser("alice", "pw-alice", "admin");
cookie = `${SESSION_COOKIE_NAME}=${sessions.createSession(alice.id).token}`;
tmpDir = mkdtempSync(join(tmpdir(), "botsettings-"));
configPath = join(tmpDir, "config.json");
config = { ...getDefaultConfig(), idleTimeoutMinutes: 15, autoPauseOnEmpty: true };
fakeBots = [makeFakeBot(), makeFakeBot()];
const fakeManager = {
getAllBots: () => fakeBots,
} as unknown as BotManager;
const avatarStore = createAvatarStore(tmpDir);
app = express();
app.use(express.json());
app.use(cookieParser());
app.use("/api", createRequireAuth(sessions, createPermissionStore(botDb.db)));
app.use(
"/api/bot",
createBotRouter(fakeManager, config, configPath, pino({ level: "silent" }), botDb, avatarStore),
);
});
afterEach(() => {
botDb.close();
rmSync(tmpDir, { recursive: true, force: true });
});
it("requires auth", async () => {
const res = await request(app).get("/api/bot/settings");
expect(res.status).toBe(401);
});
it("GET /settings includes autoPauseOnEmpty reflecting config", async () => {
const res = await request(app).get("/api/bot/settings").set("Cookie", cookie);
expect(res.status).toBe(200);
expect(res.body.idleTimeoutMinutes).toBe(15);
expect(res.body.autoPauseOnEmpty).toBe(true);
});
it("POST /settings with autoPauseOnEmpty:false persists and propagates to bots", async () => {
const res = await request(app)
.post("/api/bot/settings")
.set("Cookie", cookie)
.send({ autoPauseOnEmpty: false });
expect(res.status).toBe(200);
// in-memory config mutated
expect(config.autoPauseOnEmpty).toBe(false);
// propagated to every live bot
for (const bot of fakeBots) {
expect(bot.autoPauseCalls).toEqual([false]);
}
// follow-up GET reflects the new value
const followUp = await request(app).get("/api/bot/settings").set("Cookie", cookie);
expect(followUp.body.autoPauseOnEmpty).toBe(false);
});
it("POST /settings still handles idleTimeoutMinutes (no regression)", async () => {
const res = await request(app)
.post("/api/bot/settings")
.set("Cookie", cookie)
.send({ idleTimeoutMinutes: 42 });
expect(res.status).toBe(200);
expect(config.idleTimeoutMinutes).toBe(42);
for (const bot of fakeBots) {
expect(bot.idleTimeoutCalls).toEqual([42]);
}
const followUp = await request(app).get("/api/bot/settings").set("Cookie", cookie);
expect(followUp.body.idleTimeoutMinutes).toBe(42);
});
it("POST /settings handles both fields together", async () => {
const res = await request(app)
.post("/api/bot/settings")
.set("Cookie", cookie)
.send({ idleTimeoutMinutes: 7, autoPauseOnEmpty: false });
expect(res.status).toBe(200);
expect(config.idleTimeoutMinutes).toBe(7);
expect(config.autoPauseOnEmpty).toBe(false);
for (const bot of fakeBots) {
expect(bot.idleTimeoutCalls).toEqual([7]);
expect(bot.autoPauseCalls).toEqual([false]);
}
});
it("POST /settings with only autoPauseOnEmpty does not touch idleTimeout bots", async () => {
const res = await request(app)
.post("/api/bot/settings")
.set("Cookie", cookie)
.send({ autoPauseOnEmpty: false });
expect(res.status).toBe(200);
for (const bot of fakeBots) {
expect(bot.idleTimeoutCalls).toEqual([]);
expect(bot.autoPauseCalls).toEqual([false]);
}
});
it("POST /settings ignores non-boolean autoPauseOnEmpty without 400", async () => {
const res = await request(app)
.post("/api/bot/settings")
.set("Cookie", cookie)
.send({ idleTimeoutMinutes: 5, autoPauseOnEmpty: "yes" });
expect(res.status).toBe(200);
// idleTimeout still applied
expect(config.idleTimeoutMinutes).toBe(5);
// autoPause left at its prior value, not propagated
expect(config.autoPauseOnEmpty).toBe(true);
for (const bot of fakeBots) {
expect(bot.autoPauseCalls).toEqual([]);
}
});
});
+60 -34
View File
@@ -5,6 +5,7 @@ import { saveConfig } from "../../data/config.js";
import type { Logger } from "../../logger.js"; import type { Logger } from "../../logger.js";
import type { BotDatabase } from "../../data/database.js"; import type { BotDatabase } from "../../data/database.js";
import type { AvatarStore } from "../../data/avatars.js"; import type { AvatarStore } from "../../data/avatars.js";
import { requirePermission, requireBotAccess } from "../middleware/requirePermission.js";
export function createBotRouter( export function createBotRouter(
botManager: BotManager, botManager: BotManager,
@@ -16,12 +17,55 @@ export function createBotRouter(
): Router { ): Router {
const router = Router(); const router = Router();
router.get("/", (_req, res) => { router.get("/", (req, res) => {
const bots = botManager.getAllBots().map((b) => b.getStatus()); const all = botManager.getAllBots().map((b) => b.getStatus());
const u = req.user!;
const bots =
u.role === "admin" || u.bots === "all"
? all
: all.filter((b) => u.bots instanceof Set && u.bots.has(b.id));
res.json({ bots }); res.json({ bots });
}); });
router.get("/:id", (req, res) => { // GET /api/bot/settings — 读取全局 bot 行为设置
// NOTE: must be registered before "/:id" so it isn't shadowed by the param route.
router.get("/settings", (_req, res) => {
res.json({
idleTimeoutMinutes: config.idleTimeoutMinutes ?? 0,
autoPauseOnEmpty: config.autoPauseOnEmpty,
});
});
// POST /api/bot/settings — 保存全局 bot 行为设置 (gated: changing global bot
// behavior is a bot.manage operation, consistent with PR #80's permission model)
router.post("/settings", requirePermission("bot.manage"), (req, res) => {
const { idleTimeoutMinutes, autoPauseOnEmpty } = req.body;
const hasIdle = idleTimeoutMinutes !== undefined;
if (hasIdle && (typeof idleTimeoutMinutes !== "number" || idleTimeoutMinutes < 0)) {
res.status(400).json({ error: "idleTimeoutMinutes must be a non-negative number" });
return;
}
const hasAutoPause = typeof autoPauseOnEmpty === "boolean";
if (hasIdle) config.idleTimeoutMinutes = idleTimeoutMinutes;
if (hasAutoPause) config.autoPauseOnEmpty = autoPauseOnEmpty;
saveConfig(configPath, config);
// 通知所有 bot 实例更新
for (const bot of botManager.getAllBots()) {
if (hasIdle) bot.updateIdleTimeout(config.idleTimeoutMinutes);
if (hasAutoPause) bot.updateAutoPause(config.autoPauseOnEmpty);
}
res.json({
idleTimeoutMinutes: config.idleTimeoutMinutes ?? 0,
autoPauseOnEmpty: config.autoPauseOnEmpty,
});
});
router.get("/:id", requireBotAccess("id"), (req, res) => {
const bot = botManager.getBot(req.params.id); const bot = botManager.getBot(req.params.id);
if (!bot) { if (!bot) {
res.status(404).json({ error: "Bot not found" }); res.status(404).json({ error: "Bot not found" });
@@ -31,16 +75,19 @@ export function createBotRouter(
}); });
// Get saved config for a bot // Get saved config for a bot
router.get("/:id/config", (req, res) => { router.get("/:id/config", requirePermission("bot.manage"), requireBotAccess("id"), (req, res) => {
const saved = botManager.getBotConfig(req.params.id); const saved = botManager.getBotConfig(req.params.id);
if (!saved) { if (!saved) {
res.status(404).json({ error: "Bot config not found" }); res.status(404).json({ error: "Bot config not found" });
return; return;
} }
res.json(saved); // Never expose the TS identity / API key to the client; the edit form only
// consumes channel/server passwords.
const { ts6ApiKey: _ts6ApiKey, identity: _identity, ...safe } = saved as unknown as Record<string, unknown>;
res.json(safe);
}); });
router.get("/:id/avatar", (req, res) => { router.get("/:id/avatar", requirePermission("bot.manage"), requireBotAccess("id"), (req, res) => {
const path = botDb.getCustomAvatarPath(req.params.id); const path = botDb.getCustomAvatarPath(req.params.id);
if (!path) { if (!path) {
res.status(404).end(); res.status(404).end();
@@ -62,7 +109,7 @@ export function createBotRouter(
res.send(buf); res.send(buf);
}); });
router.put("/:id/avatar", (req, res) => { router.put("/:id/avatar", requirePermission("bot.manage"), requireBotAccess("id"), (req, res) => {
const exists = const exists =
botManager.getBot(req.params.id) || botManager.getBot(req.params.id) ||
botDb.getBotInstances().some((b) => b.id === req.params.id); botDb.getBotInstances().some((b) => b.id === req.params.id);
@@ -96,7 +143,7 @@ export function createBotRouter(
res.json({ path: rel }); res.json({ path: rel });
}); });
router.delete("/:id/avatar", (req, res) => { router.delete("/:id/avatar", requirePermission("bot.manage"), requireBotAccess("id"), (req, res) => {
const path = botDb.getCustomAvatarPath(req.params.id); const path = botDb.getCustomAvatarPath(req.params.id);
if (path) avatarStore.remove(path); if (path) avatarStore.remove(path);
botDb.setCustomAvatarPath(req.params.id, null); botDb.setCustomAvatarPath(req.params.id, null);
@@ -104,7 +151,7 @@ export function createBotRouter(
res.status(204).end(); res.status(204).end();
}); });
router.post("/", async (req, res) => { router.post("/", requirePermission("bot.manage"), async (req, res) => {
try { try {
const { const {
name, name,
@@ -140,7 +187,7 @@ export function createBotRouter(
}); });
// Update bot config (must be stopped first to apply connection changes) // Update bot config (must be stopped first to apply connection changes)
router.put("/:id", async (req, res) => { router.put("/:id", requirePermission("bot.manage"), requireBotAccess("id"), async (req, res) => {
try { try {
const bot = botManager.getBot(req.params.id); const bot = botManager.getBot(req.params.id);
if (!bot) { if (!bot) {
@@ -159,7 +206,7 @@ export function createBotRouter(
} }
}); });
router.delete("/:id", async (req, res) => { router.delete("/:id", requirePermission("bot.manage"), requireBotAccess("id"), async (req, res) => {
try { try {
await botManager.removeBot(req.params.id); await botManager.removeBot(req.params.id);
res.json({ success: true }); res.json({ success: true });
@@ -168,7 +215,7 @@ export function createBotRouter(
} }
}); });
router.post("/:id/start", async (req, res) => { router.post("/:id/start", requirePermission("bot.manage"), requireBotAccess("id"), async (req, res) => {
try { try {
await botManager.startBot(req.params.id); await botManager.startBot(req.params.id);
res.json({ success: true }); res.json({ success: true });
@@ -177,7 +224,7 @@ export function createBotRouter(
} }
}); });
router.post("/:id/stop", (req, res) => { router.post("/:id/stop", requirePermission("bot.manage"), requireBotAccess("id"), (req, res) => {
try { try {
botManager.stopBot(req.params.id); botManager.stopBot(req.params.id);
res.json({ success: true }); res.json({ success: true });
@@ -185,27 +232,6 @@ export function createBotRouter(
res.status(500).json({ error: (err as Error).message }); res.status(500).json({ error: (err as Error).message });
} }
}); });
// GET /api/bot/settings — 读取全局 bot 行为设置
router.get("/settings", (_req, res) => {
res.json({ idleTimeoutMinutes: config.idleTimeoutMinutes ?? 0 });
});
// POST /api/bot/settings — 保存全局 bot 行为设置
router.post("/settings", (req, res) => {
const { idleTimeoutMinutes } = req.body;
if (typeof idleTimeoutMinutes !== "number" || idleTimeoutMinutes < 0) {
res.status(400).json({ error: "idleTimeoutMinutes must be a non-negative number" });
return;
}
config.idleTimeoutMinutes = idleTimeoutMinutes;
saveConfig(configPath, config);
// 通知所有 bot 实例更新定时器
for (const bot of botManager.getAllBots()) {
bot.updateIdleTimeout(idleTimeoutMinutes);
}
res.json({ ok: true });
});
return router; return router;
} }
+76
View File
@@ -0,0 +1,76 @@
import { Router } from "express";
import type { BotDatabase } from "../../data/database.js";
import type { Logger } from "../../logger.js";
export function createFavoritesRouter(database: BotDatabase, logger: Logger): Router {
const router = Router();
// GET /api/favorites — 获取当前用户的所有收藏
router.get("/", (req, res) => {
const userId = req.user!.id;
const favorites = database.getFavorites(userId);
res.json({ favorites });
});
// POST /api/favorites — 添加收藏
router.post("/", (req, res) => {
const userId = req.user!.id;
const { platform, playlistId, name, coverUrl, songCount } = req.body ?? {};
if (!platform || !playlistId || !name) {
res.status(400).json({ error: "platform, playlistId, name are required" });
return;
}
try {
database.addFavorite(userId, {
platform,
playlistId,
name,
coverUrl: coverUrl ?? "",
songCount: songCount ?? 0,
});
logger.info({ userId, platform, playlistId, name }, "Playlist favorited");
res.json({ success: true });
} catch (err: unknown) {
const e = err as { code?: string };
if (e?.code === "SQLITE_CONSTRAINT_UNIQUE") {
res.status(409).json({ error: "already favorited" });
return;
}
logger.error({ err }, "Failed to add favorite");
res.status(500).json({ error: "internal error" });
}
});
// DELETE /api/favorites/:id — 取消收藏(只允许删除自己的)
router.delete("/:id", (req, res) => {
const userId = req.user!.id;
const favId = parseInt(req.params.id, 10);
if (isNaN(favId)) {
res.status(400).json({ error: "invalid id" });
return;
}
const favorites = database.getFavorites(userId);
const fav = favorites.find((f) => f.id === favId);
if (!fav) {
res.status(404).json({ error: "favorite not found" });
return;
}
database.removeFavorite(userId, fav.playlistId, fav.platform);
logger.info({ userId, playlistId: fav.playlistId, platform: fav.platform }, "Playlist unfavorited");
res.json({ success: true });
});
// GET /api/favorites/check?platform=netease&playlistId=xxx — 检查是否已收藏
router.get("/check", (req, res) => {
const userId = req.user!.id;
const { platform, playlistId } = req.query;
if (typeof platform !== "string" || typeof playlistId !== "string") {
res.status(400).json({ error: "platform and playlistId required" });
return;
}
const favorited = database.isFavorited(userId, playlistId, platform);
res.json({ favorited });
});
return router;
}
+2 -1
View File
@@ -2,6 +2,7 @@ import { Router } from "express";
import type { MusicProvider } from "../../music/provider.js"; import type { MusicProvider } from "../../music/provider.js";
import { YouTubeProvider } from "../../music/youtube.js"; import { YouTubeProvider } from "../../music/youtube.js";
import type { Logger } from "../../logger.js"; import type { Logger } from "../../logger.js";
import { requirePermission } from "../middleware/requirePermission.js";
export function createMusicRouter( export function createMusicRouter(
neteaseProvider: MusicProvider, neteaseProvider: MusicProvider,
@@ -217,7 +218,7 @@ export function createMusicRouter(
}); });
// Set quality // Set quality
router.post("/quality", (req, res) => { router.post("/quality", requirePermission("quality"), (req, res) => {
const { quality, platform } = req.body; const { quality, platform } = req.body;
if (!quality) { if (!quality) {
res.status(400).json({ error: "quality is required" }); res.status(400).json({ error: "quality is required" });
+237
View File
@@ -0,0 +1,237 @@
import { describe, it, expect, beforeEach } from "vitest";
import express from "express";
import request from "supertest";
import pino from "pino";
import { createPlayerRouter } from "./player.js";
import { createBotRouter } from "./bot.js";
import { createAuthRouter } from "./auth.js";
import { createMusicRouter } from "./music.js";
const logger = pino({ level: "silent" });
// --- minimal stubs --------------------------------------------------------
const ALLOWED_BOT = "bot-allowed";
// A fake bot whose methods all no-op / return benign values so the real
// handlers run to completion without 500ing. We only assert that the
// permission/bot-access gate let the request THROUGH (status !== 403).
function makeFakeBot(id: string) {
return {
id,
executeCommand: async () => "ok",
getStatus: () => ({ id }),
getQueue: () => [],
getProfileManager: () => ({ getConfig: () => ({}), updateConfig: () => {}, setCustomAvatar: () => {} }),
};
}
function makeBotManager() {
const bot = makeFakeBot(ALLOWED_BOT);
return {
getBot: (id: string) => (id === ALLOWED_BOT ? bot : undefined),
getAllBots: () => [bot],
getBotConfig: () => undefined,
createBot: async () => bot,
updateBot: () => {},
removeBot: async () => {},
startBot: async () => {},
stopBot: () => {},
} as any;
}
function makeProvider() {
return {
platform: "netease",
getQuality: () => "high",
setQuality: () => {},
getAuthStatus: async () => ({ loggedIn: false }),
getQrCode: async () => ({ key: "k", url: "u" }),
getCookie: () => "c",
setCookie: () => {},
search: async () => ({ songs: [], albums: [], playlists: [] }),
} as any;
}
// Build one app mounting all four real routers, with req.user injected by a
// middleware placed BEFORE the routers (mimicking what requireAuth does).
function makeApp(user: any) {
const app = express();
app.use(express.json());
app.use((req, _res, next) => { (req as any).user = user; next(); });
const botManager = makeBotManager();
const provider = makeProvider();
app.use("/api/player", createPlayerRouter(botManager, logger));
app.use(
"/api/bot",
createBotRouter(
botManager,
{ idleTimeoutMinutes: 0 } as any,
"/tmp/config.json",
logger,
{ getBotInstances: () => [], getCustomAvatarPath: () => null, setCustomAvatarPath: () => {} } as any,
{ read: () => null, write: () => "x", remove: () => {} } as any,
),
);
app.use("/api/auth", createAuthRouter(provider, provider, provider, logger));
app.use("/api/music", createMusicRouter(provider, provider, provider, logger));
return app;
}
const member = (caps: string[], bots: "all" | string[]) => ({
id: "u1",
username: "alice",
role: "member" as const,
capabilities: new Set(caps),
bots: bots === "all" ? ("all" as const) : new Set(bots),
});
const admin = {
id: "a",
username: "admin",
role: "admin" as const,
capabilities: new Set<string>(),
bots: "all" as const,
};
describe("permission enforcement on action routes", () => {
describe("player.control", () => {
it("403 for member WITHOUT player.control", async () => {
const app = makeApp(member([], [ALLOWED_BOT]));
const res = await request(app).post(`/api/player/${ALLOWED_BOT}/pause`);
expect(res.status).toBe(403);
});
it("NOT 403 for member WITH player.control + bot in allow-list", async () => {
const app = makeApp(member(["player.control"], [ALLOWED_BOT]));
const res = await request(app).post(`/api/player/${ALLOWED_BOT}/pause`);
expect(res.status).not.toBe(403);
});
it("403 for member WITH player.control but bot NOT in allow-list", async () => {
const app = makeApp(member(["player.control"], ["other-bot"]));
const res = await request(app).post(`/api/player/${ALLOWED_BOT}/pause`);
expect(res.status).toBe(403);
});
});
describe("player.queue", () => {
it("403 for member WITHOUT player.queue", async () => {
const app = makeApp(member(["player.control"], [ALLOWED_BOT]));
const res = await request(app).post(`/api/player/${ALLOWED_BOT}/clear`);
expect(res.status).toBe(403);
});
it("NOT 403 for member WITH player.queue", async () => {
const app = makeApp(member(["player.queue"], [ALLOWED_BOT]));
const res = await request(app).post(`/api/player/${ALLOWED_BOT}/clear`);
expect(res.status).not.toBe(403);
});
});
describe("bot.manage", () => {
it("403 for member WITHOUT bot.manage on POST /api/bot", async () => {
const app = makeApp(member([], "all"));
const res = await request(app)
.post("/api/bot")
.send({ name: "n", serverAddress: "s", nickname: "nick" });
expect(res.status).toBe(403);
});
it("NOT 403 for member WITH bot.manage on POST /api/bot", async () => {
const app = makeApp(member(["bot.manage"], "all"));
const res = await request(app)
.post("/api/bot")
.send({ name: "n", serverAddress: "s", nickname: "nick" });
expect(res.status).not.toBe(403);
});
it("403 for member WITH bot.manage but bot NOT in allow-list on POST /api/bot/:id/start", async () => {
const app = makeApp(member(["bot.manage"], ["other-bot"]));
const res = await request(app).post(`/api/bot/${ALLOWED_BOT}/start`);
expect(res.status).toBe(403);
});
it("NOT 403 for member WITH bot.manage + bot in allow-list on POST /api/bot/:id/start", async () => {
const app = makeApp(member(["bot.manage"], [ALLOWED_BOT]));
const res = await request(app).post(`/api/bot/${ALLOWED_BOT}/start`);
expect(res.status).not.toBe(403);
});
});
describe("platform.auth", () => {
it("403 for member WITHOUT platform.auth on POST /api/auth/cookie", async () => {
const app = makeApp(member([], "all"));
const res = await request(app).post("/api/auth/cookie").send({ cookie: "c" });
expect(res.status).toBe(403);
});
it("NOT 403 for member WITH platform.auth on POST /api/auth/cookie", async () => {
const app = makeApp(member(["platform.auth"], "all"));
const res = await request(app).post("/api/auth/cookie").send({ cookie: "c" });
expect(res.status).not.toBe(403);
});
});
describe("quality", () => {
it("403 for member WITHOUT quality on POST /api/music/quality", async () => {
const app = makeApp(member([], "all"));
const res = await request(app).post("/api/music/quality").send({ quality: "high" });
expect(res.status).toBe(403);
});
it("NOT 403 for member WITH quality on POST /api/music/quality", async () => {
const app = makeApp(member(["quality"], "all"));
const res = await request(app).post("/api/music/quality").send({ quality: "high" });
expect(res.status).not.toBe(403);
});
});
describe("read-only routes stay open", () => {
it("GET /api/auth/status not gated", async () => {
const app = makeApp(member([], "all"));
const res = await request(app).get("/api/auth/status");
expect(res.status).not.toBe(403);
});
it("GET /api/music/quality not gated", async () => {
const app = makeApp(member([], "all"));
const res = await request(app).get("/api/music/quality");
expect(res.status).not.toBe(403);
});
it("GET /api/bot not gated", async () => {
const app = makeApp(member([], "all"));
const res = await request(app).get("/api/bot");
expect(res.status).not.toBe(403);
});
});
describe("admin bypasses every gate", () => {
let app: express.Express;
beforeEach(() => { app = makeApp(admin); });
it("player.control", async () => {
expect((await request(app).post(`/api/player/${ALLOWED_BOT}/pause`)).status).not.toBe(403);
});
it("player.queue", async () => {
expect((await request(app).post(`/api/player/${ALLOWED_BOT}/clear`)).status).not.toBe(403);
});
it("bot.manage POST /api/bot", async () => {
const res = await request(app).post("/api/bot").send({ name: "n", serverAddress: "s", nickname: "nick" });
expect(res.status).not.toBe(403);
});
it("bot.manage POST /api/bot/:id/start", async () => {
expect((await request(app).post(`/api/bot/${ALLOWED_BOT}/start`)).status).not.toBe(403);
});
it("platform.auth POST /api/auth/cookie", async () => {
expect((await request(app).post("/api/auth/cookie").send({ cookie: "c" })).status).not.toBe(403);
});
it("quality POST /api/music/quality", async () => {
expect((await request(app).post("/api/music/quality").send({ quality: "high" })).status).not.toBe(403);
});
});
});
+51 -21
View File
@@ -4,6 +4,7 @@ import type { BotDatabase } from "../../data/database.js";
import type { MusicProvider } from "../../music/provider.js"; import type { MusicProvider } from "../../music/provider.js";
import type { Logger } from "../../logger.js"; import type { Logger } from "../../logger.js";
import { parseCommand } from "../../bot/commands.js"; import { parseCommand } from "../../bot/commands.js";
import { requirePermission, requireBotAccess } from "../middleware/requirePermission.js";
export function createPlayerRouter( export function createPlayerRouter(
botManager: BotManager, botManager: BotManager,
@@ -15,6 +16,13 @@ export function createPlayerRouter(
): Router { ): Router {
const router = Router(); const router = Router();
// 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.
// requireBotAccess only needs req.params.botId and req.user (set by the
// global requireAuth mounted earlier), so it works before the resolver.
router.use("/:botId", requireBotAccess("botId"));
router.use("/:botId", (req, res, next) => { router.use("/:botId", (req, res, next) => {
const bot = botManager.getBot(req.params.botId); const bot = botManager.getBot(req.params.botId);
if (!bot) { if (!bot) {
@@ -33,7 +41,7 @@ export function createPlayerRouter(
return ""; return "";
}; };
router.post("/:botId/play", async (req, res) => { router.post("/:botId/play", requirePermission("player.control"), async (req, res) => {
try { try {
const bot = (req as any).bot; const bot = (req as any).bot;
const { query, platform } = req.body; const { query, platform } = req.body;
@@ -53,7 +61,7 @@ export function createPlayerRouter(
} }
}); });
router.post("/:botId/add", async (req, res) => { router.post("/:botId/add", requirePermission("player.queue"), async (req, res) => {
try { try {
const bot = (req as any).bot; const bot = (req as any).bot;
const { query, platform } = req.body; const { query, platform } = req.body;
@@ -80,14 +88,36 @@ export function createPlayerRouter(
} }
}; };
router.post("/:botId/pause", simpleCommand("!pause")); router.post("/:botId/pause", requirePermission("player.control"), simpleCommand("!pause"));
router.post("/:botId/resume", simpleCommand("!resume")); router.post("/:botId/resume", requirePermission("player.control"), simpleCommand("!resume"));
router.post("/:botId/next", simpleCommand("!next")); router.post("/:botId/next", requirePermission("player.control"), simpleCommand("!next"));
router.post("/:botId/prev", simpleCommand("!prev")); router.post("/:botId/prev", requirePermission("player.control"), simpleCommand("!prev"));
router.post("/:botId/stop", simpleCommand("!stop")); router.post("/:botId/stop", requirePermission("player.control"), simpleCommand("!stop"));
router.post("/:botId/clear", simpleCommand("!clear")); router.post("/:botId/clear", requirePermission("player.queue"), simpleCommand("!clear"));
router.post("/:botId/volume", async (req, res) => { router.post("/:botId/fm", requirePermission("player.control"), async (req, res) => {
try {
const bot = (req as any).bot;
const { platform } = req.body;
const provider = bot.getProviderFor(
platform === "bilibili" || platform === "qq" || platform === "youtube"
? platform
: "netease"
);
const message = await bot.startFm(provider);
res.json({
ok:
!message.startsWith("No FM songs") &&
!message.includes("not available") &&
!message.includes("not connected"),
message,
});
} catch (err) {
res.status(500).json({ error: (err as Error).message });
}
});
router.post("/:botId/volume", requirePermission("player.control"), async (req, res) => {
try { try {
const bot = (req as any).bot; const bot = (req as any).bot;
const { volume } = req.body; const { volume } = req.body;
@@ -115,7 +145,7 @@ export function createPlayerRouter(
const VALID_MODES = new Set(["seq", "loop", "random", "rloop"]); const VALID_MODES = new Set(["seq", "loop", "random", "rloop"]);
router.post("/:botId/mode", async (req, res) => { router.post("/:botId/mode", requirePermission("player.control"), async (req, res) => {
try { try {
const bot = (req as any).bot; const bot = (req as any).bot;
const { mode } = req.body; const { mode } = req.body;
@@ -140,7 +170,7 @@ export function createPlayerRouter(
}); });
// Seek to position // Seek to position
router.post("/:botId/seek", async (req, res) => { router.post("/:botId/seek", requirePermission("player.control"), async (req, res) => {
try { try {
const bot = (req as any).bot; const bot = (req as any).bot;
const { position } = req.body; // seconds const { position } = req.body; // seconds
@@ -164,7 +194,7 @@ export function createPlayerRouter(
res.json({ queue: bot.getQueue(), status: bot.getStatus() }); res.json({ queue: bot.getQueue(), status: bot.getStatus() });
}); });
router.delete("/:botId/queue/:index", async (req, res) => { router.delete("/:botId/queue/:index", requirePermission("player.queue"), async (req, res) => {
try { try {
const bot = (req as any).bot; const bot = (req as any).bot;
const cmd = parseCommand(`!remove ${req.params.index}`, "!")!; const cmd = parseCommand(`!remove ${req.params.index}`, "!")!;
@@ -176,7 +206,7 @@ export function createPlayerRouter(
}); });
// Jump to a specific index in the queue (without clearing it) // Jump to a specific index in the queue (without clearing it)
router.post("/:botId/play-at", async (req, res) => { router.post("/:botId/play-at", requirePermission("player.control"), async (req, res) => {
try { try {
const bot = (req as any).bot; const bot = (req as any).bot;
const { index } = req.body; const { index } = req.body;
@@ -210,7 +240,7 @@ export function createPlayerRouter(
} }
}); });
router.post("/:botId/playlist", async (req, res) => { router.post("/:botId/playlist", requirePermission("player.queue"), async (req, res) => {
try { try {
const bot = (req as any).bot; const bot = (req as any).bot;
const { playlistId, platform } = req.body; const { playlistId, platform } = req.body;
@@ -227,7 +257,7 @@ export function createPlayerRouter(
// Play a playlist by ID — stores metadata only, resolves URL for first song // Play a playlist by ID — stores metadata only, resolves URL for first song
// Respects current play mode (random = pick random first song) // Respects current play mode (random = pick random first song)
router.post("/:botId/play-playlist", async (req, res) => { router.post("/:botId/play-playlist", requirePermission("player.control"), async (req, res) => {
try { try {
const bot = (req as any).bot; const bot = (req as any).bot;
const { playlistId, platform } = req.body; const { playlistId, platform } = req.body;
@@ -314,7 +344,7 @@ export function createPlayerRouter(
}); });
// Play an album by ID — mirrors play-playlist but calls getAlbumSongs // Play an album by ID — mirrors play-playlist but calls getAlbumSongs
router.post("/:botId/play-album", async (req, res) => { router.post("/:botId/play-album", requirePermission("player.control"), async (req, res) => {
try { try {
const bot = (req as any).bot; const bot = (req as any).bot;
const { albumId, platform } = req.body; const { albumId, platform } = req.body;
@@ -386,7 +416,7 @@ export function createPlayerRouter(
}); });
// Play a single song by ID — resolves URL on demand // Play a single song by ID — resolves URL on demand
router.post("/:botId/play-song", async (req, res) => { router.post("/:botId/play-song", requirePermission("player.control"), async (req, res) => {
try { try {
const bot = (req as any).bot; const bot = (req as any).bot;
const { song } = req.body; const { song } = req.body;
@@ -414,7 +444,7 @@ export function createPlayerRouter(
// Insert a single song to play right after the current one. // Insert a single song to play right after the current one.
// If nothing is playing, behaves like /play-song (start immediately). // If nothing is playing, behaves like /play-song (start immediately).
router.post("/:botId/play-next-song", async (req, res) => { router.post("/:botId/play-next-song", requirePermission("player.control"), async (req, res) => {
try { try {
const bot = (req as any).bot; const bot = (req as any).bot;
const { song } = req.body; const { song } = req.body;
@@ -452,7 +482,7 @@ export function createPlayerRouter(
} }
}); });
router.post("/:botId/add-song", async (req, res) => { router.post("/:botId/add-song", requirePermission("player.queue"), async (req, res) => {
try { try {
const bot = (req as any).bot; const bot = (req as any).bot;
const { song } = req.body; const { song } = req.body;
@@ -480,7 +510,7 @@ export function createPlayerRouter(
}); });
// Add a song to queue by ID — metadata only // Add a song to queue by ID — metadata only
router.post("/:botId/add-by-id", async (req, res) => { router.post("/:botId/add-by-id", requirePermission("player.queue"), async (req, res) => {
try { try {
const bot = (req as any).bot; const bot = (req as any).bot;
const { songId, platform } = req.body; const { songId, platform } = req.body;
@@ -518,7 +548,7 @@ export function createPlayerRouter(
res.json(bot.getProfileManager().getConfig()); res.json(bot.getProfileManager().getConfig());
}); });
router.put("/:botId/profile", (req, res) => { router.put("/:botId/profile", requirePermission("bot.manage"), (req, res) => {
try { try {
const bot = (req as any).bot; const bot = (req as any).bot;
const pm = bot.getProfileManager(); const pm = bot.getProfileManager();
+9 -1
View File
@@ -7,6 +7,7 @@ import { createDatabase, type BotDatabase } from "../../data/database.js";
import { createUserStore, type UserStore } from "../../data/users.js"; import { createUserStore, type UserStore } from "../../data/users.js";
import { createSessionStore, type SessionStore } from "../../data/sessions.js"; import { createSessionStore, type SessionStore } from "../../data/sessions.js";
import { createAuditStore } from "../../data/audit.js"; import { createAuditStore } from "../../data/audit.js";
import { createPermissionStore } from "../../data/permissions.js";
import { createSessionRouter } from "./session.js"; import { createSessionRouter } from "./session.js";
import { SESSION_COOKIE_NAME } from "../auth/validateSession.js"; import { SESSION_COOKIE_NAME } from "../auth/validateSession.js";
@@ -15,7 +16,8 @@ function makeApp(botDb: BotDatabase, users: UserStore, sessions: SessionStore) {
app.use(express.json()); app.use(express.json());
app.use(cookieParser()); app.use(cookieParser());
const audit = createAuditStore(botDb.db); const audit = createAuditStore(botDb.db);
app.use("/api/session", createSessionRouter(users, sessions, audit, pino({ level: "silent" }))); const permissions = createPermissionStore(botDb.db);
app.use("/api/session", createSessionRouter(users, sessions, audit, pino({ level: "silent" }), permissions));
return app; return app;
} }
@@ -100,6 +102,12 @@ describe("session router", () => {
const me = await request(app).get("/api/session/me").set("Cookie", cookie); const me = await request(app).get("/api/session/me").set("Cookie", cookie);
expect(me.status).toBe(200); expect(me.status).toBe(200);
expect(me.body.username).toBe("alice"); expect(me.body.username).toBe("alice");
// alice is the first user (an admin), so /me exposes all capabilities and full bot access.
expect(Array.isArray(me.body.capabilities)).toBe(true);
expect(me.body.capabilities).toEqual(
expect.arrayContaining(["player.control", "player.queue", "bot.manage", "platform.auth", "quality"])
);
expect(me.body.bots).toBe("all");
const anon = await request(app).get("/api/session/me"); const anon = await request(app).get("/api/session/me");
expect(anon.status).toBe(401); expect(anon.status).toBe(401);
+12 -2
View File
@@ -4,6 +4,7 @@ import type { Logger } from "../../logger.js";
import type { UserStore } from "../../data/users.js"; import type { UserStore } from "../../data/users.js";
import type { SessionStore } from "../../data/sessions.js"; import type { SessionStore } from "../../data/sessions.js";
import type { AuditStore } from "../../data/audit.js"; import type { AuditStore } from "../../data/audit.js";
import { resolvePermissionContext, type PermissionStore } from "../../data/permissions.js";
import { SESSION_TTL_MS } from "../../data/sessions.js"; import { SESSION_TTL_MS } from "../../data/sessions.js";
import { SESSION_COOKIE_NAME, validateSessionFromHeaders, extractSessionToken } from "../auth/validateSession.js"; import { SESSION_COOKIE_NAME, validateSessionFromHeaders, extractSessionToken } from "../auth/validateSession.js";
@@ -49,7 +50,8 @@ export function createSessionRouter(
users: UserStore, users: UserStore,
sessions: SessionStore, sessions: SessionStore,
audit: AuditStore, audit: AuditStore,
logger: Logger logger: Logger,
permissions: PermissionStore
): Router { ): Router {
const router = Router(); const router = Router();
@@ -133,7 +135,15 @@ export function createSessionRouter(
}); });
router.get("/me", requireAuthInline, (req, res) => { router.get("/me", requireAuthInline, (req, res) => {
res.json(req.user); const user = req.user!;
const ctx = resolvePermissionContext(user.role, user.id, permissions);
res.json({
id: user.id,
username: user.username,
role: user.role,
capabilities: [...ctx.capabilities],
bots: ctx.bots === "all" ? "all" : [...ctx.bots],
});
}); });
router.post("/change-password", requireAuthInline, async (req, res) => { router.post("/change-password", requireAuthInline, async (req, res) => {
+94 -7
View File
@@ -6,7 +6,8 @@ import pino from "pino";
import { createDatabase, type BotDatabase } from "../../data/database.js"; import { createDatabase, type BotDatabase } from "../../data/database.js";
import { createUserStore, type UserStore } from "../../data/users.js"; import { createUserStore, type UserStore } from "../../data/users.js";
import { createSessionStore, type SessionStore } from "../../data/sessions.js"; import { createSessionStore, type SessionStore } from "../../data/sessions.js";
import { createAuditStore } from "../../data/audit.js"; import { createAuditStore, type AuditStore } from "../../data/audit.js";
import { createPermissionStore, type PermissionStore } from "../../data/permissions.js";
import { createRequireAuth } from "../middleware/requireAuth.js"; import { createRequireAuth } from "../middleware/requireAuth.js";
import { createUsersRouter } from "./users.js"; import { createUsersRouter } from "./users.js";
import { SESSION_COOKIE_NAME } from "../auth/validateSession.js"; import { SESSION_COOKIE_NAME } from "../auth/validateSession.js";
@@ -15,11 +16,12 @@ function makeApp(botDb: BotDatabase, users: UserStore, sessions: SessionStore) {
const app = express(); const app = express();
app.use(express.json()); app.use(express.json());
app.use(cookieParser()); app.use(cookieParser());
const requireAuth = createRequireAuth(sessions); const permissions = createPermissionStore(botDb.db);
const requireAuth = createRequireAuth(sessions, permissions);
const audit = createAuditStore(botDb.db); const audit = createAuditStore(botDb.db);
app.use("/api", requireAuth); app.use("/api", requireAuth);
app.use("/api/users", createUsersRouter(users, sessions, audit, pino({ level: "silent" }))); app.use("/api/users", createUsersRouter(users, sessions, audit, pino({ level: "silent" }), permissions));
return app; return { app, permissions, audit };
} }
describe("users router", () => { describe("users router", () => {
@@ -27,6 +29,8 @@ describe("users router", () => {
let users: UserStore; let users: UserStore;
let sessions: SessionStore; let sessions: SessionStore;
let app: express.Express; let app: express.Express;
let permissions: PermissionStore;
let audit: AuditStore;
let aliceId: string; let aliceId: string;
let aliceCookie: string; let aliceCookie: string;
let bobId: string; let bobId: string;
@@ -35,7 +39,7 @@ describe("users router", () => {
botDb = createDatabase(":memory:"); botDb = createDatabase(":memory:");
users = createUserStore(botDb.db); users = createUserStore(botDb.db);
sessions = createSessionStore(botDb.db); sessions = createSessionStore(botDb.db);
app = makeApp(botDb, users, sessions); ({ app, permissions, audit } = makeApp(botDb, users, sessions));
const alice = await users.createUser("alice", "pw-alice", "admin"); const alice = await users.createUser("alice", "pw-alice", "admin");
aliceId = alice.id; aliceId = alice.id;
aliceCookie = `${SESSION_COOKIE_NAME}=${sessions.createSession(alice.id).token}`; aliceCookie = `${SESSION_COOKIE_NAME}=${sessions.createSession(alice.id).token}`;
@@ -148,10 +152,10 @@ describe("users router", () => {
const localApp = express(); const localApp = express();
localApp.use(express.json()); localApp.use(express.json());
localApp.use(cookieParser()); localApp.use(cookieParser());
localApp.use("/api", createRequireAuth(sessions)); localApp.use("/api", createRequireAuth(sessions, createPermissionStore(botDb.db)));
localApp.use( localApp.use(
"/api/users", "/api/users",
createUsersRouter(users, sessions, brokenAudit, pino({ level: "silent" })) createUsersRouter(users, sessions, brokenAudit, pino({ level: "silent" }), createPermissionStore(botDb.db))
); );
const res = await request(localApp) const res = await request(localApp)
.post("/api/users") .post("/api/users")
@@ -254,4 +258,87 @@ describe("users router", () => {
.send({ role: "admin" }); .send({ role: "admin" });
expect(res.status).toBe(404); expect(res.status).toBe(404);
}); });
it("GET /:id/permissions returns empty arrays for a fresh member", async () => {
const res = await request(app)
.get(`/api/users/${bobId}/permissions`)
.set("Cookie", aliceCookie);
expect(res.status).toBe(200);
expect(res.body).toEqual({ capabilities: [], bots: [] });
});
it("GET /:id/permissions 404 on unknown user", async () => {
const res = await request(app)
.get(`/api/users/not-a-real-id/permissions`)
.set("Cookie", aliceCookie);
expect(res.status).toBe(404);
});
it("PUT /:id/permissions sets permissions, persists, and audits", async () => {
const before = audit.list(100, 0).filter((e) => e.action === "user.permissions_changed");
expect(before).toHaveLength(0);
const put = await request(app)
.put(`/api/users/${bobId}/permissions`)
.set("Cookie", aliceCookie)
.send({ capabilities: ["player.control"], bots: "all" });
expect(put.status).toBe(200);
const get = await request(app)
.get(`/api/users/${bobId}/permissions`)
.set("Cookie", aliceCookie);
expect(get.status).toBe(200);
expect(get.body).toEqual({ capabilities: ["player.control"], bots: "all" });
const rows = audit.list(100, 0).filter((e) => e.action === "user.permissions_changed");
expect(rows).toHaveLength(1);
expect(rows[0].actorId).toBe(aliceId);
expect(rows[0].targetUserId).toBe(bobId);
});
it("PUT /:id/permissions drops unknown capability tokens", async () => {
const put = await request(app)
.put(`/api/users/${bobId}/permissions`)
.set("Cookie", aliceCookie)
.send({ capabilities: ["player.control", "bogus"], bots: [] });
expect(put.status).toBe(200);
expect(permissions.getCapabilities(bobId)).toEqual(["player.control"]);
});
it("PUT /:id/permissions 404 on unknown user", async () => {
const res = await request(app)
.put(`/api/users/not-a-real-id/permissions`)
.set("Cookie", aliceCookie)
.send({ capabilities: ["player.control"], bots: "all" });
expect(res.status).toBe(404);
});
it("POST / seeds the basic tier for a new member", async () => {
const res = await request(app)
.post("/api/users")
.set("Cookie", aliceCookie)
.send({ username: "dave", password: "dave-pw-pw" });
expect(res.status).toBe(201);
const perms = await request(app)
.get(`/api/users/${res.body.id}/permissions`)
.set("Cookie", aliceCookie);
expect(perms.status).toBe(200);
expect(perms.body).toEqual({
capabilities: ["player.control", "player.queue"],
bots: "all",
});
});
it("POST / does NOT seed permissions for a new admin", async () => {
const res = await request(app)
.post("/api/users")
.set("Cookie", aliceCookie)
.send({ username: "erin", password: "erin-pw-pw", role: "admin" });
expect(res.status).toBe(201);
const perms = await request(app)
.get(`/api/users/${res.body.id}/permissions`)
.set("Cookie", aliceCookie);
expect(perms.status).toBe(200);
expect(perms.body).toEqual({ capabilities: [], bots: [] });
});
}); });
+44 -1
View File
@@ -4,6 +4,7 @@ import type { UserStore } from "../../data/users.js";
import { UsernameTakenError } from "../../data/users.js"; import { UsernameTakenError } from "../../data/users.js";
import type { SessionStore } from "../../data/sessions.js"; import type { SessionStore } from "../../data/sessions.js";
import type { AuditStore } from "../../data/audit.js"; import type { AuditStore } from "../../data/audit.js";
import { isCapability, BASIC_TIER_CAPABILITIES, type PermissionStore } from "../../data/permissions.js";
import { extractSessionToken } from "../auth/validateSession.js"; import { extractSessionToken } from "../auth/validateSession.js";
function isValidUsername(v: unknown): v is string { function isValidUsername(v: unknown): v is string {
@@ -18,7 +19,8 @@ export function createUsersRouter(
users: UserStore, users: UserStore,
sessions: SessionStore, sessions: SessionStore,
audit: AuditStore, audit: AuditStore,
logger: Logger logger: Logger,
permissions: PermissionStore
): Router { ): Router {
const router = Router(); const router = Router();
@@ -35,6 +37,9 @@ export function createUsersRouter(
const role: "admin" | "member" = roleInput === "admin" ? "admin" : "member"; const role: "admin" | "member" = roleInput === "admin" ? "admin" : "member";
try { try {
const u = await users.createUser(username, password, role); const u = await users.createUser(username, password, role);
if (u.role === "member") {
permissions.setPermissions(u.id, { capabilities: BASIC_TIER_CAPABILITIES, bots: "all" });
}
try { try {
audit.record({ audit.record({
actorId: req.user!.id, actorUsername: req.user!.username, actorId: req.user!.id, actorUsername: req.user!.username,
@@ -162,5 +167,43 @@ export function createUsersRouter(
res.status(204).end(); res.status(204).end();
}); });
router.get("/:id/permissions", (req, res) => {
const user = users.findById(req.params.id);
if (!user) {
res.status(404).json({ error: "not_found" });
return;
}
res.json({
capabilities: permissions.getCapabilities(user.id),
bots: permissions.getBotAccess(user.id),
});
});
router.put("/:id/permissions", (req, res) => {
const user = users.findById(req.params.id);
if (!user) {
res.status(404).json({ error: "not_found" });
return;
}
const body = req.body ?? {};
const caps: string[] = Array.isArray(body.capabilities)
? body.capabilities.filter(isCapability)
: [];
const bots: "all" | string[] =
body.bots === "all" ? "all" : Array.isArray(body.bots) ? body.bots.map(String) : [];
permissions.setPermissions(user.id, { capabilities: caps, bots });
try {
audit.record({
actorId: req.user!.id, actorUsername: req.user!.username,
targetUserId: user.id, targetUsername: user.username,
action: "user.permissions_changed",
});
} catch (auditErr) {
logger.warn({ err: auditErr, action: "user.permissions_changed" }, "audit insert failed");
}
logger.info({ actorId: req.user!.id, targetUserId: user.id }, "User permissions changed");
res.json({ success: true });
});
return router; return router;
} }
+15
View File
@@ -55,4 +55,19 @@ describe("csrfOriginCheck middleware", () => {
.set("Referer", "https://evil.com/some/path"); .set("Referer", "https://evil.com/some/path");
expect(res.status).toBe(403); expect(res.status).toBe(403);
}); });
// Documents the server side of the QR-login outage: a `no-referrer` document
// policy makes the browser send the literal `Origin: null` on same-origin
// POSTs, which this guard cannot parse a host from and therefore rejects.
// The fix lives in the frontend (referrer policy -> same-origin); this test
// pins the gate behavior so the interaction stays understood. See
// src/web/referrer-policy.test.ts.
it('rejects POST with the literal Origin: "null" (no-referrer downgrade)', async () => {
const res = await request(app)
.post("/")
.set("Host", "example.com")
.set("Origin", "null");
expect(res.status).toBe(403);
expect(res.body).toEqual({ error: "bad origin" });
});
}); });
+3 -1
View File
@@ -5,6 +5,7 @@ import request from "supertest";
import { createDatabase, type BotDatabase } from "../../data/database.js"; import { createDatabase, type BotDatabase } from "../../data/database.js";
import { createUserStore } from "../../data/users.js"; import { createUserStore } from "../../data/users.js";
import { createSessionStore } from "../../data/sessions.js"; import { createSessionStore } from "../../data/sessions.js";
import { createPermissionStore } from "../../data/permissions.js";
import { createRequireAuth } from "./requireAuth.js"; import { createRequireAuth } from "./requireAuth.js";
import { requireAdmin } from "./requireAdmin.js"; import { requireAdmin } from "./requireAdmin.js";
import { SESSION_COOKIE_NAME } from "../auth/validateSession.js"; import { SESSION_COOKIE_NAME } from "../auth/validateSession.js";
@@ -19,13 +20,14 @@ describe("requireAdmin middleware", () => {
botDb = createDatabase(":memory:"); botDb = createDatabase(":memory:");
const users = createUserStore(botDb.db); const users = createUserStore(botDb.db);
const sessions = createSessionStore(botDb.db); const sessions = createSessionStore(botDb.db);
const permissions = createPermissionStore(botDb.db);
const admin = await users.createUser("admin", "pw-admin-pw", "admin"); const admin = await users.createUser("admin", "pw-admin-pw", "admin");
const member = await users.createUser("member", "pw-member-pw", "member"); const member = await users.createUser("member", "pw-member-pw", "member");
adminCookie = `${SESSION_COOKIE_NAME}=${sessions.createSession(admin.id).token}`; adminCookie = `${SESSION_COOKIE_NAME}=${sessions.createSession(admin.id).token}`;
memberCookie = `${SESSION_COOKIE_NAME}=${sessions.createSession(member.id).token}`; memberCookie = `${SESSION_COOKIE_NAME}=${sessions.createSession(member.id).token}`;
app = express(); app = express();
app.use(cookieParser()); app.use(cookieParser());
app.use(createRequireAuth(sessions)); app.use(createRequireAuth(sessions, permissions));
app.use(requireAdmin); app.use(requireAdmin);
app.get("/admin-only", (_req, res) => res.json({ ok: true })); app.get("/admin-only", (_req, res) => res.json({ ok: true }));
}); });
+3 -1
View File
@@ -5,6 +5,7 @@ import request from "supertest";
import { createDatabase, type BotDatabase } from "../../data/database.js"; import { createDatabase, type BotDatabase } from "../../data/database.js";
import { createUserStore } from "../../data/users.js"; import { createUserStore } from "../../data/users.js";
import { createSessionStore } from "../../data/sessions.js"; import { createSessionStore } from "../../data/sessions.js";
import { createPermissionStore } from "../../data/permissions.js";
import { createRequireAuth } from "./requireAuth.js"; import { createRequireAuth } from "./requireAuth.js";
import { SESSION_COOKIE_NAME } from "../auth/validateSession.js"; import { SESSION_COOKIE_NAME } from "../auth/validateSession.js";
@@ -17,12 +18,13 @@ describe("requireAuth middleware", () => {
botDb = createDatabase(":memory:"); botDb = createDatabase(":memory:");
const users = createUserStore(botDb.db); const users = createUserStore(botDb.db);
const sessions = createSessionStore(botDb.db); const sessions = createSessionStore(botDb.db);
const permissions = createPermissionStore(botDb.db);
const u = await users.createUser("alice", "pw-alice", "admin"); const u = await users.createUser("alice", "pw-alice", "admin");
validToken = sessions.createSession(u.id).token; validToken = sessions.createSession(u.id).token;
app = express(); app = express();
app.use(cookieParser()); app.use(cookieParser());
app.use(createRequireAuth(sessions)); app.use(createRequireAuth(sessions, permissions));
app.get("/protected", (req, res) => { app.get("/protected", (req, res) => {
res.json({ ok: true, user: (req as any).user }); res.json({ ok: true, user: (req as any).user });
}); });
+17 -3
View File
@@ -1,6 +1,7 @@
import type { Request, Response, NextFunction, RequestHandler } from "express"; import type { Request, Response, NextFunction, RequestHandler } from "express";
import type { SessionStore } from "../../data/sessions.js"; import type { SessionStore } from "../../data/sessions.js";
import { SESSION_TTL_MS } from "../../data/sessions.js"; import { SESSION_TTL_MS } from "../../data/sessions.js";
import { resolvePermissionContext, type PermissionStore } from "../../data/permissions.js";
import { import {
validateSessionFromHeaders, validateSessionFromHeaders,
extractSessionToken, extractSessionToken,
@@ -9,11 +10,17 @@ import {
declare module "express-serve-static-core" { declare module "express-serve-static-core" {
interface Request { interface Request {
user?: { id: string; username: string; role: "admin" | "member" }; user?: {
id: string;
username: string;
role: "admin" | "member";
capabilities?: Set<string>;
bots?: "all" | Set<string>;
};
} }
} }
export function createRequireAuth(sessions: SessionStore): RequestHandler { export function createRequireAuth(sessions: SessionStore, permissions: PermissionStore): RequestHandler {
return function requireAuth(req: Request, res: Response, next: NextFunction) { return function requireAuth(req: Request, res: Response, next: NextFunction) {
const result = validateSessionFromHeaders(req.headers.cookie, sessions); const result = validateSessionFromHeaders(req.headers.cookie, sessions);
if (!result) { if (!result) {
@@ -21,7 +28,14 @@ export function createRequireAuth(sessions: SessionStore): RequestHandler {
res.status(401).json({ error: "unauthenticated" }); res.status(401).json({ error: "unauthenticated" });
return; return;
} }
req.user = { id: result.userId, username: result.username, role: result.role }; const ctx = resolvePermissionContext(result.role, result.userId, permissions);
req.user = {
id: result.userId,
username: result.username,
role: result.role,
capabilities: ctx.capabilities,
bots: ctx.bots,
};
const token = extractSessionToken(req.headers.cookie); const token = extractSessionToken(req.headers.cookie);
if (token) { if (token) {
res.cookie(SESSION_COOKIE_NAME, token, { res.cookie(SESSION_COOKIE_NAME, token, {
@@ -0,0 +1,61 @@
import { describe, it, expect } from "vitest";
import express from "express";
import request from "supertest";
import { requirePermission, requireBotAccess } from "./requirePermission.js";
function appWith(user: any) {
const app = express();
app.use((req, _res, next) => { (req as any).user = user; next(); });
app.post("/cap", requirePermission("quality"), (_req, res) => res.json({ ok: true }));
app.post("/bot/:botId", requireBotAccess("botId"), (_req, res) => res.json({ ok: true }));
return app;
}
const member = (caps: string[], bots: "all" | string[]) => ({
id: "u1", username: "a", role: "member",
capabilities: new Set(caps), bots: bots === "all" ? "all" : new Set(bots),
});
const admin = { id: "a", username: "admin", role: "admin", capabilities: new Set(), bots: "all" };
describe("requirePermission", () => {
it("401 when unauthenticated", async () => {
const app = express();
app.post("/cap", requirePermission("quality"), (_r, res) => res.json({ ok: true }));
expect((await request(app).post("/cap")).status).toBe(401);
});
it("403 when member lacks the capability", async () => {
expect((await request(appWith(member([], "all"))).post("/cap")).status).toBe(403);
});
it("200 when member has the capability", async () => {
expect((await request(appWith(member(["quality"], "all"))).post("/cap")).status).toBe(200);
});
it("200 for admin regardless of capabilities", async () => {
expect((await request(appWith(admin)).post("/cap")).status).toBe(200);
});
});
describe("requireBotAccess", () => {
it("200 when bots = all", async () => {
expect((await request(appWith(member([], "all"))).post("/bot/b1")).status).toBe(200);
});
it("200 when botId in allow-list", async () => {
expect((await request(appWith(member([], ["b1"]))).post("/bot/b1")).status).toBe(200);
});
it("403 when botId not in allow-list", async () => {
expect((await request(appWith(member([], ["b2"]))).post("/bot/b1")).status).toBe(403);
});
it("200 for admin", async () => {
expect((await request(appWith(admin)).post("/bot/b1")).status).toBe(200);
});
it("401 when unauthenticated", async () => {
const app = express();
app.post("/bot/:botId", requireBotAccess("botId"), (_r, res) => res.json({ ok: true }));
expect((await request(app).post("/bot/b1")).status).toBe(401);
});
it("403 when the route param is absent", async () => {
const app = express();
app.use((req, _res, next) => { (req as any).user = member([], ["b1"]); next(); });
app.post("/bot/:botId", requireBotAccess("nope"), (_r, res) => res.json({ ok: true }));
expect((await request(app).post("/bot/b1")).status).toBe(403);
});
});
+24
View File
@@ -0,0 +1,24 @@
import type { Request, Response, NextFunction, RequestHandler } from "express";
// Generic over the route-param shape (`P`) so Express can keep inferring
// `req.params` from the route string (e.g. `/:id` → `{ id: string }`) when
// these are passed as a per-route middleware argument. Pinning the default
// `ParamsDictionary` here would otherwise force the broad
// `string | string[]` param overload on every route they guard.
export function requirePermission<P = Record<string, string>>(capability: string): RequestHandler<P> {
return (req: Request<P>, res: Response, next: NextFunction) => {
if (!req.user) { res.status(401).json({ error: "unauthenticated" }); return; }
if (req.user.role === "admin" || req.user.capabilities?.has(capability)) { next(); return; }
res.status(403).json({ error: "forbidden" });
};
}
export function requireBotAccess<P = Record<string, string>>(paramName = "botId"): RequestHandler<P> {
return (req: Request<P>, res: Response, next: NextFunction) => {
if (!req.user) { res.status(401).json({ error: "unauthenticated" }); return; }
if (req.user.role === "admin" || req.user.bots === "all") { next(); return; }
const botId = (req.params as Record<string, string | undefined>)[paramName];
if (typeof botId === "string" && req.user.bots instanceof Set && req.user.bots.has(botId)) { next(); return; }
res.status(403).json({ error: "forbidden" });
};
}
+46
View File
@@ -0,0 +1,46 @@
import { describe, it, expect } from "vitest";
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
/**
* Regression guard for the QR-login / cookie-save outage (and in fact every
* mutating WebUI action). On 2026-05-27 the WebUI-auth feature added the
* same-origin CSRF gate `app.use("/api", csrfOriginCheck)` in server.ts, and
* the same day a `<meta name="referrer" content="no-referrer">` was added to
* web/index.html so cross-origin CDN cover thumbnails would load.
*
* Those two changes conflict: per the WHATWG Fetch "Append a request Origin
* header" algorithm, the `no-referrer` policy sets the Origin header to the
* literal string "null" on same-origin non-GET requests. csrfOriginCheck then
* fails to parse a host (`new URL("null")` throws) and returns 403 "bad
* origin", so POST /api/auth/qrcode (and every other POST/PUT/DELETE under
* /api/* except /api/session/*) never reaches its handler.
*
* `same-origin` is the correct policy: it keeps the real Origin on same-origin
* requests (CSRF passes) while still sending no Referer cross-origin (CDN
* thumbnails keep loading). Never switch this back to `no-referrer`.
*/
describe("frontend referrer policy (CSRF / Origin-header regression)", () => {
const indexHtmlPath = path.resolve(
path.dirname(fileURLToPath(import.meta.url)),
"../../web/index.html"
);
const html = fs.readFileSync(indexHtmlPath, "utf-8");
const referrerMeta = html.match(
/<meta\s+name=["']referrer["']\s+content=["']([^"']+)["']\s*\/?>/i
);
it("declares a referrer policy meta tag", () => {
expect(referrerMeta).not.toBeNull();
});
it("uses same-origin (NOT no-referrer, which sends Origin: null and 403s every POST)", () => {
expect(referrerMeta?.[1]).toBe("same-origin");
});
it("does not contain no-referrer anywhere in the document head", () => {
expect(html).not.toMatch(/content=["']no-referrer["']/i);
});
});
+8 -3
View File
@@ -18,9 +18,11 @@ import { createSessionRouter } from "./api/session.js";
import { createUsersRouter } from "./api/users.js"; import { createUsersRouter } from "./api/users.js";
import { createAuditStore } from "../data/audit.js"; import { createAuditStore } from "../data/audit.js";
import { createAuditRouter } from "./api/audit.js"; import { createAuditRouter } from "./api/audit.js";
import { createFavoritesRouter } from "./api/favorites.js";
import { setupWebSocket } from "./websocket.js"; import { setupWebSocket } from "./websocket.js";
import { createUserStore } from "../data/users.js"; import { createUserStore } from "../data/users.js";
import { createSessionStore } from "../data/sessions.js"; import { createSessionStore } from "../data/sessions.js";
import { createPermissionStore } from "../data/permissions.js";
import { createRequireAuth } from "./middleware/requireAuth.js"; import { createRequireAuth } from "./middleware/requireAuth.js";
import { requireAdmin } from "./middleware/requireAdmin.js"; import { requireAdmin } from "./middleware/requireAdmin.js";
import { csrfOriginCheck } from "./middleware/csrf.js"; import { csrfOriginCheck } from "./middleware/csrf.js";
@@ -73,6 +75,7 @@ export function createWebServer(options: WebServerOptions): WebServer {
const users = createUserStore(options.database.db); const users = createUserStore(options.database.db);
const sessions = createSessionStore(options.database.db); const sessions = createSessionStore(options.database.db);
const audit = createAuditStore(options.database.db); const audit = createAuditStore(options.database.db);
const permissions = createPermissionStore(options.database.db);
// ─── Public routes (no auth, no CSRF) ─────────────────────────────────── // ─── Public routes (no auth, no CSRF) ───────────────────────────────────
app.get("/api/health", (_req, res) => { app.get("/api/health", (_req, res) => {
@@ -92,10 +95,10 @@ export function createWebServer(options: WebServerOptions): WebServer {
app.use("/api/session/login", loginLimit); app.use("/api/session/login", loginLimit);
app.use("/api/session/setup", setupLimit); app.use("/api/session/setup", setupLimit);
app.use("/api/session", createSessionRouter(users, sessions, audit, logger)); app.use("/api/session", createSessionRouter(users, sessions, audit, logger, permissions));
// ─── Gates for everything else under /api ─────────────────────────────── // ─── Gates for everything else under /api ───────────────────────────────
const requireAuth = createRequireAuth(sessions); const requireAuth = createRequireAuth(sessions, permissions);
app.use("/api", csrfOriginCheck); app.use("/api", csrfOriginCheck);
app.use("/api", requireAuth); app.use("/api", requireAuth);
@@ -123,8 +126,10 @@ export function createWebServer(options: WebServerOptions): WebServer {
"/api/auth", "/api/auth",
createAuthRouter(options.neteaseProvider, options.qqProvider, options.bilibiliProvider, logger, options.cookieStore) createAuthRouter(options.neteaseProvider, options.qqProvider, options.bilibiliProvider, logger, options.cookieStore)
); );
app.use("/api/favorites", createFavoritesRouter(options.database, logger));
// admin-only routes // admin-only routes
app.use("/api/users", requireAdmin, createUsersRouter(users, sessions, audit, logger)); app.use("/api/users", requireAdmin, createUsersRouter(users, sessions, audit, logger, permissions));
app.use("/api/audit", requireAdmin, createAuditRouter(audit)); app.use("/api/audit", requireAdmin, createAuditRouter(audit));
// ─── Static SPA (public) ──────────────────────────────────────────────── // ─── Static SPA (public) ────────────────────────────────────────────────
+19
View File
@@ -0,0 +1,19 @@
@echo off
title TSMusicBot
:: Check node
where node >nul 2>&1
if errorlevel 1 (
echo Node.js not found. Run scripts\setup.bat first.
pause
exit /b 1
)
echo Starting TSMusicBot...
echo WebUI: http://localhost:3000
echo Press Ctrl+C to stop.
echo.
node dist\index.js
pause
+12 -4
View File
@@ -3,10 +3,18 @@
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Bilibili / NetEase / QQ image CDNs reject requests whose Referer is not on their whitelist. <!-- Bilibili / NetEase / QQ image CDNs reject requests whose Referer is not on
Setting no-referrer at the document level covers <img> tags AND CSS background-image fetches. their whitelist, so we must not leak a Referer cross-origin. "same-origin"
Our own /api/* CSRF check uses Origin (not Referer), so this doesn't break auth. --> does exactly that: full Referer for our own requests, none for cross-origin
<meta name="referrer" content="no-referrer"> ones — so cover thumbnails (<img> AND CSS background-image) still load.
Do NOT switch this back to "no-referrer": per the WHATWG Fetch spec
("Append a request Origin header") no-referrer downgrades the Origin header
to the literal string "null" on same-origin non-GET requests. The /api/*
CSRF guard (src/web/middleware/csrf.ts) then can't parse a host from it and
responds 403 "bad origin", silently breaking EVERY POST/PUT/DELETE — QR
login, cookie save, playback controls, bot management, user admin, etc.
"same-origin" keeps the real Origin on same-origin requests, so CSRF passes. -->
<meta name="referrer" content="same-origin">
<title>TSMusicBot</title> <title>TSMusicBot</title>
<link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Barlow:wght@400;500;600;700;800&display=swap" rel="stylesheet"> <link href="https://fonts.googleapis.com/css2?family=Barlow:wght@400;500;600;700;800&display=swap" rel="stylesheet">
+4
View File
@@ -143,6 +143,10 @@ function cycleMobileMode() {
onMounted(async () => { onMounted(async () => {
playerStore.loadTheme(); playerStore.loadTheme();
connect(); connect();
// Hydrate favorites once per session so deep-links / hard refreshes onto
// Search or Playlist render hearts correctly without first visiting Home.
// (fire-and-forget; fetchFavorites swallows the 401 when not yet logged in.)
playerStore.fetchFavorites();
syncTimer = setInterval(() => playerStore.syncElapsed(), 3000); syncTimer = setInterval(() => playerStore.syncElapsed(), 3000);
mobileRaf = requestAnimationFrame(updateMobileProgress); mobileRaf = requestAnimationFrame(updateMobileProgress);
// Reconcile the dedicated-link scope only after the bot list is known: the // Reconcile the dedicated-link scope only after the bot list is known: the
+15 -5
View File
@@ -22,8 +22,9 @@
<button class="scope-exit-btn" @click="exitScope" title="退出专属模式">退出</button> <button class="scope-exit-btn" @click="exitScope" title="退出专属模式">退出</button>
</div> </div>
<!-- Normal: full selector with switching (shown when at least one bot exists) --> <!-- Normal: full selector with switching (shown when at least one
<div v-else-if="store.bots.length > 0" class="bot-selector" ref="selectorRef"> controllable bot exists — scope ∩ permission via displayedBots) -->
<div v-else-if="displayedBots.length > 0" class="bot-selector" ref="selectorRef">
<button class="bot-selector-btn" @click="dropdownOpen = !dropdownOpen"> <button class="bot-selector-btn" @click="dropdownOpen = !dropdownOpen">
<span class="bot-dot" :class="{ online: activeBot?.connected }" /> <span class="bot-dot" :class="{ online: activeBot?.connected }" />
<span class="bot-selector-name">{{ activeBot?.name ?? '选择机器人' }}</span> <span class="bot-selector-name">{{ activeBot?.name ?? '选择机器人' }}</span>
@@ -143,17 +144,26 @@ import { useSession } from '../composables/useSession.js';
const store = usePlayerStore(); const store = usePlayerStore();
const session = useSession(); const session = useSession();
const { canControlBot } = session;
const navRouter = useRouter(); const navRouter = useRouter();
async function onLogout() { async function onLogout() {
await session.logout(); await session.logout();
navRouter.replace({ name: 'login' }); navRouter.replace({ name: 'login' });
} }
// Belt-and-suspenders: the backend already scopes store.bots to the allowed
// set for members, but filtering here keeps the UI correct if an admin (who
// sees all bots) is constrained, or if the list ever isn't pre-filtered.
const controllableBots = computed(() => store.bots.filter((b) => canControlBot(b.id)));
const activeBot = computed(() => store.activeBot); const activeBot = computed(() => store.activeBot);
// While scoped (dedicated link), the selector is locked to the single scoped // The bots shown in the selector are the INTERSECTION of the permission
// bot; otherwise the full list is shown and switching is allowed. // allow-list (controllableBots) and the dedicated-link scope: while scoped the
// selector is locked to the single scoped bot, otherwise the full controllable
// list is shown and switching is allowed.
const displayedBots = computed(() => const displayedBots = computed(() =>
store.isScoped ? store.bots.filter((b) => b.id === store.scopedBotId) : store.bots, store.isScoped
? controllableBots.value.filter((b) => b.id === store.scopedBotId)
: controllableBots.value,
); );
const dropdownOpen = ref(false); const dropdownOpen = ref(false);
const selectorRef = ref<HTMLElement | null>(null); const selectorRef = ref<HTMLElement | null>(null);
+43 -23
View File
@@ -3,9 +3,10 @@
<Queue :open="showQueue" @close="showQueue = false" /> <Queue :open="showQueue" @close="showQueue = false" />
<div class="player-bar frosted-glass"> <div class="player-bar frosted-glass">
<!-- Progress bar --> <!-- Progress bar (read-only display; seek interaction gated on player.control) -->
<div <div
class="progress-bar-container" class="progress-bar-container"
:class="{ 'no-seek': !canControl }"
ref="progressBarRef" ref="progressBarRef"
@click="onProgressClick" @click="onProgressClick"
@mousemove="onProgressHover" @mousemove="onProgressHover"
@@ -37,32 +38,38 @@
<div class="player-center"> <div class="player-center">
<span class="time-display time-current">{{ formatTime(currentElapsed) }}</span> <span class="time-display time-current">{{ formatTime(currentElapsed) }}</span>
<button class="control-btn" @click="store.prev()"> <!-- Transport controls require player.control -->
<Icon icon="mdi:skip-previous" /> <template v-if="canControl">
</button> <button class="control-btn" @click="store.prev()">
<button class="play-btn" @click="togglePlay"> <Icon icon="mdi:skip-previous" />
<Icon :icon="store.isPlaying ? 'mdi:pause' : 'mdi:play'" /> </button>
</button> <button class="play-btn" @click="togglePlay">
<button class="control-btn" @click="store.next()"> <Icon :icon="store.isPlaying ? 'mdi:pause' : 'mdi:play'" />
<Icon icon="mdi:skip-next" /> </button>
</button> <button class="control-btn" @click="store.next()">
<button class="control-btn mode-btn" @click="cycleMode" :title="modeLabel"> <Icon icon="mdi:skip-next" />
<Icon :icon="modeIcon" /> </button>
<span class="mode-label">{{ modeLabel }}</span> <button class="control-btn mode-btn" @click="cycleMode" :title="modeLabel">
</button> <Icon :icon="modeIcon" />
<span class="mode-label">{{ modeLabel }}</span>
</button>
</template>
<span class="time-display time-total">{{ formatTime(currentSong?.duration ?? 0) }}</span> <span class="time-display time-total">{{ formatTime(currentSong?.duration ?? 0) }}</span>
</div> </div>
<div class="player-right"> <div class="player-right">
<Icon icon="mdi:volume-high" class="volume-icon" /> <!-- Volume requires player.control -->
<input <template v-if="canControl">
type="range" <Icon icon="mdi:volume-high" class="volume-icon" />
min="0" <input
max="100" type="range"
:value="activeBot?.volume ?? 75" min="0"
@change="onVolumeChange" max="100"
class="volume-slider" :value="activeBot?.volume ?? 75"
/> @change="onVolumeChange"
class="volume-slider"
/>
</template>
<button class="control-btn" :class="{ active: showQueue }" @click="showQueue = !showQueue"> <button class="control-btn" :class="{ active: showQueue }" @click="showQueue = !showQueue">
<Icon icon="mdi:playlist-music" /> <Icon icon="mdi:playlist-music" />
</button> </button>
@@ -79,6 +86,7 @@ import { computed, ref, onMounted, onUnmounted } from 'vue';
import { Icon } from '@iconify/vue'; import { Icon } from '@iconify/vue';
import { useRoute, useRouter } from 'vue-router'; import { useRoute, useRouter } from 'vue-router';
import { usePlayerStore } from '../stores/player.js'; import { usePlayerStore } from '../stores/player.js';
import { useSession } from '../composables/useSession.js';
import CoverArt from './CoverArt.vue'; import CoverArt from './CoverArt.vue';
import Queue from './Queue.vue'; import Queue from './Queue.vue';
@@ -86,6 +94,9 @@ const route = useRoute();
const router = useRouter(); const router = useRouter();
const showQueue = ref(false); const showQueue = ref(false);
const { can } = useSession();
const canControl = computed(() => can('player.control'));
const store = usePlayerStore(); const store = usePlayerStore();
const activeBot = computed(() => store.activeBot); const activeBot = computed(() => store.activeBot);
const currentSong = computed(() => store.currentSong); const currentSong = computed(() => store.currentSong);
@@ -133,6 +144,7 @@ function updateProgress() {
} }
async function onProgressClick(e: MouseEvent) { async function onProgressClick(e: MouseEvent) {
if (!canControl.value) return; // seek requires player.control
const bar = progressBarRef.value; const bar = progressBarRef.value;
if (!bar) return; if (!bar) return;
const rect = bar.getBoundingClientRect(); const rect = bar.getBoundingClientRect();
@@ -237,6 +249,14 @@ function cycleMode() {
.progress-bar-bg { height: 4px; } .progress-bar-bg { height: 4px; }
.progress-bar-thumb { opacity: 1; transform: scale(1); } .progress-bar-thumb { opacity: 1; transform: scale(1); }
} }
&.no-seek {
cursor: default;
&:hover {
.progress-bar-bg { height: 2px; }
.progress-bar-thumb { opacity: 0; transform: scale(0); }
}
}
} }
.progress-bar-bg { .progress-bar-bg {
+8 -5
View File
@@ -3,10 +3,10 @@
<div class="queue-header"> <div class="queue-header">
<h3 class="queue-title">播放队列</h3> <h3 class="queue-title">播放队列</h3>
<span class="queue-count">{{ botQueue.length }} 首</span> <span class="queue-count">{{ botQueue.length }} 首</span>
<button <button
v-if="botQueue.length > 0" v-if="botQueue.length > 0 && can('player.control')"
class="clear-btn" class="clear-btn"
@click="clearAndStop" @click="clearAndStop"
title="清空队列并停止播放" title="清空队列并停止播放"
> >
<Icon icon="mdi:stop-circle-outline" /> <Icon icon="mdi:stop-circle-outline" />
@@ -33,7 +33,7 @@
<div class="queue-song-name">{{ song.name }}</div> <div class="queue-song-name">{{ song.name }}</div>
<div class="queue-song-artist">{{ song.artist }}</div> <div class="queue-song-artist">{{ song.artist }}</div>
</div> </div>
<button class="remove-btn" @click="removeSong(i)" title="移除"> <button v-if="can('player.queue')" class="remove-btn" @click="removeSong(i)" title="移除">
<Icon icon="mdi:close" /> <Icon icon="mdi:close" />
</button> </button>
</div> </div>
@@ -46,6 +46,7 @@ import { watch, computed } from 'vue';
import { Icon } from '@iconify/vue'; import { Icon } from '@iconify/vue';
import axios from 'axios'; import axios from 'axios';
import { usePlayerStore } from '../stores/player.js'; import { usePlayerStore } from '../stores/player.js';
import { useSession } from '../composables/useSession.js';
import CoverArt from './CoverArt.vue'; import CoverArt from './CoverArt.vue';
const props = defineProps<{ const props = defineProps<{
@@ -57,6 +58,7 @@ defineEmits<{
}>(); }>();
const store = usePlayerStore(); const store = usePlayerStore();
const { can } = useSession();
const botQueue = computed(() => store.queue); const botQueue = computed(() => store.queue);
// Fetch queue when panel opens // Fetch queue when panel opens
@@ -65,6 +67,7 @@ watch(() => props.open, (isOpen) => {
}); });
async function playAtIndex(index: number) { async function playAtIndex(index: number) {
if (!can('player.control')) return;
await store.playAtIndex(index); await store.playAtIndex(index);
await store.fetchQueue(); await store.fetchQueue();
} }
+20
View File
@@ -4,6 +4,8 @@ interface User {
id: string; id: string;
username: string; username: string;
role: 'admin' | 'member'; role: 'admin' | 'member';
capabilities?: string[];
bots?: "all" | string[];
} }
const currentUser = ref<User | null>(null); const currentUser = ref<User | null>(null);
@@ -70,6 +72,8 @@ async function login(username: string, password: string): Promise<void> {
throw new Error(body.error ?? `login failed (${res.status})`); throw new Error(body.error ?? `login failed (${res.status})`);
} }
currentUser.value = (await res.json()) as User; currentUser.value = (await res.json()) as User;
// Login response omits capabilities/bots; fetch the authoritative ones from /me.
await refreshMe();
} }
async function setup(username: string, password: string): Promise<void> { async function setup(username: string, password: string): Promise<void> {
@@ -85,6 +89,8 @@ async function setup(username: string, password: string): Promise<void> {
} }
currentUser.value = (await res.json()) as User; currentUser.value = (await res.json()) as User;
needsSetup.value = false; needsSetup.value = false;
// Setup response omits capabilities/bots; fetch the authoritative ones from /me.
await refreshMe();
} }
async function logout(): Promise<void> { async function logout(): Promise<void> {
@@ -93,6 +99,18 @@ async function logout(): Promise<void> {
currentUser.value = null; currentUser.value = null;
} }
function can(cap: string): boolean {
const u = currentUser.value;
return !!u && (u.role === "admin" || (u.capabilities ?? []).includes(cap));
}
function canControlBot(botId: string): boolean {
const u = currentUser.value;
if (!u) return false;
if (u.role === "admin" || u.bots === "all") return true;
return Array.isArray(u.bots) && u.bots.includes(botId);
}
export function useSession() { export function useSession() {
return { return {
currentUser: readonly(currentUser), currentUser: readonly(currentUser),
@@ -104,5 +122,7 @@ export function useSession() {
login, login,
logout, logout,
setup, setup,
can,
canControlBot,
}; };
} }
+77
View File
@@ -35,6 +35,17 @@ export interface PlaylistItem {
platform: string; platform: string;
} }
export interface FavoritePlaylist {
id: number;
userId: string;
platform: string;
playlistId: string;
name: string;
coverUrl: string;
songCount: number;
createdAt: string;
}
interface TimingState { interface TimingState {
serverElapsed: number; serverElapsed: number;
serverSyncTime: number; serverSyncTime: number;
@@ -68,6 +79,9 @@ export const usePlayerStore = defineStore('player', {
authStatus: { netease: false, qq: false }, authStatus: { netease: false, qq: false },
lastFetchTime: 0, lastFetchTime: 0,
// Favorited playlists (fetched from server, isolated per WebUI user)
favoritedPlaylists: [] as FavoritePlaylist[],
// Transient notification for surfacing failures (e.g., "song not playable") // Transient notification for surfacing failures (e.g., "song not playable")
// to a global Toast. Bumped `id` triggers re-render of the same message. // to a global Toast. Bumped `id` triggers re-render of the same message.
notification: null as { id: number; message: string; type: 'error' | 'info' } | null, notification: null as { id: number; message: string; type: 'error' | 'info' } | null,
@@ -202,6 +216,11 @@ export const usePlayerStore = defineStore('player', {
this.bots = this.bots.filter((b) => b.id !== botId); this.bots = this.bots.filter((b) => b.id !== botId);
delete this.queues[botId]; delete this.queues[botId];
delete this.timings[botId]; delete this.timings[botId];
// If the bot we were locked to is gone, drop the scope so the UI does not
// stay 'locked' onto a phantom (activeBot would silently fall back to bots[0]).
if (this.scopedBotId === botId) {
this.clearScope();
}
}, },
setQueue(botId: string, queue: Song[]) { setQueue(botId: string, queue: Song[]) {
@@ -433,6 +452,60 @@ export const usePlayerStore = defineStore('player', {
if (bot) bot.playMode = mode; if (bot) bot.playMode = mode;
}, },
async startFm(platform: Source = 'netease') {
if (!this.activeBotId) return;
const res = await axios.post(`/api/player/${this.activeBotId}/fm`, { platform });
if (res.data?.message) {
this.notify(res.data.message, res.data.ok === false ? 'error' : 'info');
}
this._setTiming(this.activeBotId, { serverElapsed: 0 });
this._syncAfterAction();
this.fetchQueue();
},
async fetchFavorites() {
try {
const res = await axios.get('/api/favorites');
this.favoritedPlaylists = res.data.favorites ?? [];
} catch {
// not critical
}
},
async addFavorite(playlist: { platform: string; playlistId: string; name: string; coverUrl: string; songCount: number }) {
try {
await axios.post('/api/favorites', playlist);
await this.fetchFavorites();
this.notify('已收藏', 'info');
} catch (err: any) {
// 409 = already favorited (e.g. stale heart); just resync so the UI converges.
if (err?.response?.status === 409) {
await this.fetchFavorites();
return;
}
this.notify('收藏失败', 'error');
}
},
async removeFavorite(id: number) {
try {
await axios.delete(`/api/favorites/${id}`);
await this.fetchFavorites();
this.notify('已取消收藏', 'info');
} catch (err: any) {
// 404 = already gone; resync. Otherwise report failure.
if (err?.response?.status === 404) {
await this.fetchFavorites();
return;
}
this.notify('取消收藏失败', 'error');
}
},
isFavorited(playlistId: string, platform: string): boolean {
return this.favoritedPlaylists.some((f) => f.playlistId === playlistId && f.platform === platform);
},
async fetchHomeData() { async fetchHomeData() {
// Always check auth status first — if it changed since the cached // Always check auth status first — if it changed since the cached
// fetch (e.g., user logged in/out as a different account), the // fetch (e.g., user logged in/out as a different account), the
@@ -450,6 +523,10 @@ export const usePlayerStore = defineStore('player', {
this.authStatus.netease = newAuth.netease; this.authStatus.netease = newAuth.netease;
this.authStatus.qq = newAuth.qq; this.authStatus.qq = newAuth.qq;
// Favorites are user-local and cheap; always refresh them, even on a
// home-data cache hit, so hearts stay correct across tabs/sessions.
this.fetchFavorites();
// Cache hit only if auth is unchanged AND within TTL. // Cache hit only if auth is unchanged AND within TTL.
if ( if (
!authChanged && !authChanged &&
+41 -16
View File
@@ -21,7 +21,7 @@
<!-- 私人FM --> <!-- 私人FM -->
<section class="section"> <section class="section">
<h2 class="section-title">私人FM</h2> <h2 class="section-title">私人FM</h2>
<div class="fm-card hover-scale" @click="playFm"> <div class="fm-card hover-scale" @click="playFm('netease')">
<div class="fm-icon-wrapper"> <div class="fm-icon-wrapper">
<Icon icon="mdi:radio" class="fm-icon" /> <Icon icon="mdi:radio" class="fm-icon" />
</div> </div>
@@ -31,6 +31,16 @@
</div> </div>
<Icon icon="mdi:play-circle" class="fm-play-icon" /> <Icon icon="mdi:play-circle" class="fm-play-icon" />
</div> </div>
<div v-if="store.authStatus.qq" class="fm-card hover-scale" @click="playFm('qq')">
<div class="fm-icon-wrapper qq">
<Icon icon="mdi:radar" class="fm-icon" />
</div>
<div class="fm-info">
<div class="fm-title">QQ音乐雷达</div>
<div class="fm-desc">猜你喜欢 / 雷达推荐歌曲流</div>
</div>
<Icon icon="mdi:play-circle" class="fm-play-icon" />
</div>
</section> </section>
<!-- 每日推荐 --> <!-- 每日推荐 -->
@@ -72,6 +82,27 @@
</div> </div>
</section> </section>
<!-- 我的收藏 -->
<section class="section" v-if="store.favoritedPlaylists.length > 0">
<h2 class="section-title">
<Icon icon="mdi:heart" style="color: var(--color-primary)" />
我的收藏
<span class="section-count">{{ store.favoritedPlaylists.length }}</span>
</h2>
<div class="playlist-grid">
<RouterLink
v-for="fav in store.favoritedPlaylists"
:key="fav.id"
:to="`/playlist/${fav.playlistId}?platform=${fav.platform}`"
class="playlist-card hover-scale"
>
<CoverArt :url="fav.coverUrl" :size="160" :radius="10" :show-shadow="true" />
<div class="playlist-name">{{ fav.name }}</div>
<div class="playlist-count">{{ fav.songCount }} 首</div>
</RouterLink>
</div>
</section>
<!-- 我的歌单 --> <!-- 我的歌单 -->
<section class="section" v-if="userAvailable.length > 0"> <section class="section" v-if="userAvailable.length > 0">
<h2 class="section-title"> <h2 class="section-title">
@@ -125,9 +156,9 @@
<script setup lang="ts"> <script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'; import { ref, computed, watch, onMounted } from 'vue';
import { RouterLink } from 'vue-router';
import { Icon } from '@iconify/vue'; import { Icon } from '@iconify/vue';
import axios from 'axios'; import { usePlayerStore, type Source } from '../stores/player.js';
import { usePlayerStore, type Song, type Source } from '../stores/player.js';
import { loadTabSource, saveTabSource } from '../stores/sourceTabs.js'; import { loadTabSource, saveTabSource } from '../stores/sourceTabs.js';
import CoverArt from '../components/CoverArt.vue'; import CoverArt from '../components/CoverArt.vue';
import SourceTabs from '../components/SourceTabs.vue'; import SourceTabs from '../components/SourceTabs.vue';
@@ -180,19 +211,8 @@ const visibleUserPlaylists = computed(() =>
: currentUserPlaylists.value.slice(0, USER_PLAYLIST_LIMIT) : currentUserPlaylists.value.slice(0, USER_PLAYLIST_LIMIT)
); );
async function playFm() { async function playFm(platform: Source) {
try { await store.startFm(platform);
const res = await axios.get('/api/music/personal/fm');
const songs: Song[] = res.data.songs;
if (songs.length > 0) {
await store.play(songs[0].name, songs[0].platform);
for (let i = 1; i < songs.length; i++) {
await store.addToQueue(songs[i].name, songs[i].platform);
}
}
} catch {
// Ignore
}
} }
onMounted(() => { onMounted(() => {
@@ -318,6 +338,7 @@ onMounted(() => {
border-radius: var(--radius-lg); border-radius: var(--radius-lg);
cursor: pointer; cursor: pointer;
transition: background var(--transition-fast); transition: background var(--transition-fast);
margin-bottom: 12px;
&:hover { &:hover {
background: var(--hover-bg); background: var(--hover-bg);
@@ -333,6 +354,10 @@ onMounted(() => {
align-items: center; align-items: center;
justify-content: center; justify-content: center;
flex-shrink: 0; flex-shrink: 0;
&.qq {
background: linear-gradient(135deg, var(--brand-qq), #17a2b8);
}
} }
.fm-icon { .fm-icon {
+22
View File
@@ -2,6 +2,27 @@
<div class="library-page"> <div class="library-page">
<h1 class="page-title">音乐库</h1> <h1 class="page-title">音乐库</h1>
<!-- 我的收藏 -->
<section class="section" v-if="store.favoritedPlaylists.length > 0">
<h2 class="section-title">
<Icon icon="mdi:heart" style="color: var(--color-primary)" />
我的收藏
<span class="section-count">{{ store.favoritedPlaylists.length }}</span>
</h2>
<div class="playlist-grid">
<RouterLink
v-for="fav in store.favoritedPlaylists"
:key="fav.id"
:to="`/playlist/${fav.playlistId}?platform=${fav.platform}`"
class="playlist-card hover-scale"
>
<CoverArt :url="fav.coverUrl" :size="160" :radius="10" :show-shadow="true" />
<div class="playlist-name">{{ fav.name }}</div>
<div class="playlist-count">{{ fav.songCount }} 首</div>
</RouterLink>
</div>
</section>
<!-- 我的歌单 --> <!-- 我的歌单 -->
<section class="section" v-if="userAvailable.length > 0"> <section class="section" v-if="userAvailable.length > 0">
<h2 class="section-title"> <h2 class="section-title">
@@ -51,6 +72,7 @@
<script setup lang="ts"> <script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'; import { ref, computed, watch, onMounted } from 'vue';
import { RouterLink } from 'vue-router';
import { Icon } from '@iconify/vue'; import { Icon } from '@iconify/vue';
import axios from 'axios'; import axios from 'axios';
import { usePlayerStore, type Song, type Source } from '../stores/player.js'; import { usePlayerStore, type Song, type Source } from '../stores/player.js';
+80 -4
View File
@@ -16,10 +16,21 @@
<div class="playlist-stats"> <div class="playlist-stats">
{{ songs.length }} 首歌曲 {{ songs.length }} 首歌曲
</div> </div>
<button class="play-all-btn" @click="playAll"> <div class="playlist-actions">
<Icon icon="mdi:play" /> <button class="play-all-btn" @click="playAll">
播放全部 <Icon icon="mdi:play" />
</button> 播放全部
</button>
<button
v-if="kind === 'playlist'"
class="fav-btn"
:class="{ favorited }"
@click="toggleFavorite"
>
<Icon :icon="favorited ? 'mdi:heart' : 'mdi:heart-outline'" />
{{ favorited ? '已收藏' : '收藏' }}
</button>
</div>
</div> </div>
</div> </div>
@@ -69,6 +80,7 @@ const kind = (route.meta.kind as string) ?? 'playlist'; // 'playlist' | 'album'
const playlist = ref<PlaylistDetail | null>(null); const playlist = ref<PlaylistDetail | null>(null);
const songs = ref<Song[]>([]); const songs = ref<Song[]>([]);
const loading = ref(true); const loading = ref(true);
const favorited = ref(false);
async function playAll() { async function playAll() {
const id = route.params.id as string; const id = route.params.id as string;
@@ -126,8 +138,35 @@ onMounted(async () => {
} }
} }
songs.value = songList; songs.value = songList;
// Check favorite status after songs are resolved
if (kind === 'playlist') {
favorited.value = store.isFavorited(id, platform);
}
loading.value = false; loading.value = false;
}); });
async function toggleFavorite() {
const id = route.params.id as string;
const platform = (route.query.platform as string) || 'netease';
if (favorited.value) {
const fav = store.favoritedPlaylists.find((f) => f.playlistId === id && f.platform === platform);
if (fav) {
await store.removeFavorite(fav.id);
favorited.value = false;
}
} else {
await store.addFavorite({
platform,
playlistId: id,
name: playlist.value?.name ?? '未知歌单',
coverUrl: playlist.value?.coverUrl ?? '',
songCount: songs.value.length,
});
favorited.value = true;
}
}
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>
@@ -193,6 +232,43 @@ onMounted(async () => {
&:active { transform: scale(0.96); } &:active { transform: scale(0.96); }
} }
.playlist-actions {
display: flex;
align-items: center;
gap: 12px;
}
.fav-btn {
display: flex;
align-items: center;
gap: 6px;
padding: 10px 20px;
background: transparent;
color: var(--text-secondary);
border: 1px solid var(--border-color);
border-radius: var(--radius-lg);
font-size: 14px;
font-weight: 500;
transition: all var(--transition-fast);
cursor: pointer;
&:hover {
color: var(--color-primary);
border-color: var(--color-primary);
background: var(--color-primary-8);
}
&.favorited {
color: #e74c3c;
border-color: #e74c3c;
background: rgba(231, 76, 60, 0.08);
&:hover {
background: rgba(231, 76, 60, 0.15);
}
}
}
.song-list { .song-list {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
+62
View File
@@ -92,6 +92,13 @@
class="card hover-scale" class="card hover-scale"
> >
<CoverArt :url="pl.coverUrl" :size="160" :radius="10" :show-shadow="true" /> <CoverArt :url="pl.coverUrl" :size="160" :radius="10" :show-shadow="true" />
<button
class="fav-badge"
:class="{ favorited: isFav(pl) }"
@click.prevent.stop="toggleFavPlaylist(pl)"
>
<Icon :icon="isFav(pl) ? 'mdi:heart' : 'mdi:heart-outline'" />
</button>
<div class="card-name"> <div class="card-name">
{{ pl.name }} {{ pl.name }}
<span class="platform-badge" :class="badgeClass(pl.platform)">{{ badgeLabel(pl.platform) }}</span> <span class="platform-badge" :class="badgeClass(pl.platform)">{{ badgeLabel(pl.platform) }}</span>
@@ -179,6 +186,25 @@ watch(selectedSource, (src) => {
} }
}); });
function isFav(pl: { id: string; platform: string }): boolean {
return store.isFavorited(pl.id, pl.platform);
}
async function toggleFavPlaylist(pl: { id: string; platform: string; name: string; coverUrl: string; songCount?: number }) {
if (isFav(pl)) {
const fav = store.favoritedPlaylists.find((f) => f.playlistId === pl.id && f.platform === pl.platform);
if (fav) await store.removeFavorite(fav.id);
} else {
await store.addFavorite({
platform: pl.platform,
playlistId: pl.id,
name: pl.name,
coverUrl: pl.coverUrl,
songCount: pl.songCount ?? 0,
});
}
}
async function doSearch() { async function doSearch() {
if (!query.value.trim()) return; if (!query.value.trim()) return;
loading.value = true; loading.value = true;
@@ -356,6 +382,7 @@ onMounted(() => {
gap: 16px 28px; gap: 16px 28px;
} }
.card { .card {
position: relative;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
gap: 6px; gap: 6px;
@@ -394,4 +421,39 @@ onMounted(() => {
background: var(--brand-youtube-12); background: var(--brand-youtube-12);
color: var(--brand-youtube); color: var(--brand-youtube);
} }
.fav-badge {
position: absolute;
top: 8px;
right: 8px;
width: 32px;
height: 32px;
display: flex;
align-items: center;
justify-content: center;
border: none;
border-radius: 50%;
background: rgba(0, 0, 0, 0.5);
backdrop-filter: blur(4px);
color: rgba(255, 255, 255, 0.7);
font-size: 16px;
cursor: pointer;
opacity: 0;
transition: opacity var(--transition-fast), color var(--transition-fast);
z-index: 2;
.card:hover & {
opacity: 1;
}
&.favorited {
color: #e74c3c;
opacity: 1;
}
&:hover {
color: #e74c3c;
background: rgba(0, 0, 0, 0.7);
}
}
</style> </style>
+231 -38
View File
@@ -50,8 +50,8 @@
<p v-if="ownPwSuccess" class="user-success">{{ ownPwSuccess }}</p> <p v-if="ownPwSuccess" class="user-success">{{ ownPwSuccess }}</p>
</section> </section>
<!-- Bot Management --> <!-- Bot Management (create/edit/delete/start-stop) requires bot.manage -->
<section class="settings-section"> <section v-if="can('bot.manage')" class="settings-section">
<h2 class="section-title">机器人管理</h2> <h2 class="section-title">机器人管理</h2>
<div class="bot-list"> <div class="bot-list">
<div v-for="bot in store.bots" :key="bot.id" class="bot-item"> <div v-for="bot in store.bots" :key="bot.id" class="bot-item">
@@ -157,8 +157,8 @@
</div> </div>
</section> </section>
<!-- Music Account - QR Code Login --> <!-- Music Account - QR Code Login (platform auth) requires platform.auth -->
<section class="settings-section"> <section v-if="can('platform.auth')" class="settings-section">
<h2 class="section-title">音乐账号</h2> <h2 class="section-title">音乐账号</h2>
<!-- NetEase --> <!-- NetEase -->
@@ -371,8 +371,8 @@
</div> </div>
</section> </section>
<!-- Audio Quality --> <!-- Audio Quality requires quality -->
<section class="settings-section"> <section v-if="can('quality')" class="settings-section">
<h2 class="section-title">音质设置</h2> <h2 class="section-title">音质设置</h2>
<div class="setting-row"> <div class="setting-row">
<div class="setting-label"> <div class="setting-label">
@@ -410,7 +410,7 @@
</section> </section>
<!-- Idle Timeout --> <!-- Idle Timeout -->
<section class="settings-section"> <section v-if="can('bot.manage')" class="settings-section">
<h2 class="section-title">行为设置</h2> <h2 class="section-title">行为设置</h2>
<div class="setting-row"> <div class="setting-row">
<div class="setting-label"> <div class="setting-label">
@@ -433,10 +433,22 @@
<button class="btn-primary" @click="saveIdleTimeout">保存</button> <button class="btn-primary" @click="saveIdleTimeout">保存</button>
</div> </div>
</div> </div>
<label class="profile-toggle behavior-toggle">
<div class="profile-toggle-text">
<div class="profile-toggle-label">频道无人时自动暂停播放</div>
<div class="profile-toggle-hint">机器人所在频道没有其他人时自动暂停,有人加入后可继续播放</div>
</div>
<input
v-model="autoPauseOnEmpty"
type="checkbox"
class="profile-toggle-switch"
@change="saveAutoPause"
/>
</label>
</section> </section>
<!-- Bot Profile (TeamSpeak Behavior) --> <!-- Bot Profile (TeamSpeak Behavior) -->
<section class="settings-section"> <section v-if="can('bot.manage')" class="settings-section">
<h2 class="section-title">机器人 Profile(TeamSpeak 行为)</h2> <h2 class="section-title">机器人 Profile(TeamSpeak 行为)</h2>
<p class="profile-section-hint">控制 bot 在 TeamSpeak 上自动同步歌曲信息的方式。⚠️ 标记的项会触发频道里所有人的提示音。</p> <p class="profile-section-hint">控制 bot 在 TeamSpeak 上自动同步歌曲信息的方式。⚠️ 标记的项会触发频道里所有人的提示音。</p>
<div v-if="store.bots.length === 0" class="empty-hint">还没有机器人,先在上面创建一个。</div> <div v-if="store.bots.length === 0" class="empty-hint">还没有机器人,先在上面创建一个。</div>
@@ -492,38 +504,96 @@
<section v-if="session.isAdmin.value" class="settings-section"> <section v-if="session.isAdmin.value" class="settings-section">
<h2 class="section-title">用户管理</h2> <h2 class="section-title">用户管理</h2>
<div class="user-list"> <div class="user-list">
<div v-for="u in userList" :key="u.id" class="user-item"> <div v-for="u in userList" :key="u.id" class="user-row-wrap">
<div class="user-info"> <div class="user-item">
<div class="user-name"> <div class="user-info">
{{ u.username }} <div class="user-name">
<span class="user-role-badge" :class="`role-${u.role}`"> {{ u.username }}
{{ u.role === 'admin' ? '管理员' : '成员' }} <span class="user-role-badge" :class="`role-${u.role}`">
</span> {{ u.role === 'admin' ? '管理员' : '成员' }}
<span v-if="session.currentUser.value && u.id === session.currentUser.value.id" class="user-self-badge">本人</span> </span>
<span v-if="session.currentUser.value && u.id === session.currentUser.value.id" class="user-self-badge">本人</span>
</div>
<div class="user-created">创建于 {{ formatDate(u.createdAt) }}</div>
</div>
<div class="user-actions">
<span v-if="u.role === 'admin'" class="perm-admin-label">全部权限(管理员)</span>
<button
v-else
class="btn-sm"
:class="{ 'btn-primary': permEditingId === u.id }"
@click="onTogglePermEditor(u)"
>
<Icon icon="mdi:shield-key" /> 权限
</button>
<button class="btn-sm" @click="openResetPassword(u)">
<Icon icon="mdi:lock-reset" /> 重置密码
</button>
<button
class="btn-sm"
:disabled="changingRoleId === u.id || isLastAdmin(u)"
:title="isLastAdmin(u) ? '不能降级唯一的管理员' : (u.role === 'admin' ? '降级为成员' : '提升为管理员')"
@click="onToggleRole(u)"
>
<Icon icon="mdi:account-cog" />
{{ u.role === 'admin' ? '降为成员' : '提升管理员' }}
</button>
<button
class="btn-sm btn-delete"
:disabled="!!(session.currentUser.value && u.id === session.currentUser.value.id) || isLastAdmin(u)"
:title="session.currentUser.value && u.id === session.currentUser.value.id ? '不能删除自己' : (isLastAdmin(u) ? '不能删除唯一的管理员' : '')"
@click="onDeleteUser(u)"
>
<Icon icon="mdi:delete" />
</button>
</div> </div>
<div class="user-created">创建于 {{ formatDate(u.createdAt) }}</div>
</div> </div>
<div class="user-actions">
<button class="btn-sm" @click="openResetPassword(u)"> <!-- Inline permission editor (members only) -->
<Icon icon="mdi:lock-reset" /> 重置密码 <div v-if="permEditingId === u.id" class="perm-editor">
</button> <div v-if="permLoading" class="user-empty">加载权限中…</div>
<button <template v-else>
class="btn-sm" <div class="perm-group">
:disabled="changingRoleId === u.id || isLastAdmin(u)" <div class="perm-group-title">能力</div>
:title="isLastAdmin(u) ? '不能降级唯一的管理员' : (u.role === 'admin' ? '降级为成员' : '提升为管理员')" <div class="perm-checks">
@click="onToggleRole(u)" <label v-for="cap in CAPABILITIES" :key="cap.token" class="perm-check">
> <input
<Icon icon="mdi:account-cog" /> type="checkbox"
{{ u.role === 'admin' ? '降为成员' : '提升管理员' }} :checked="permDraft.capabilities.includes(cap.token)"
</button> @change="toggleCapability(cap.token, ($event.target as HTMLInputElement).checked)"
<button />
class="btn-sm btn-delete" {{ cap.label }}
:disabled="!!(session.currentUser.value && u.id === session.currentUser.value.id) || isLastAdmin(u)" </label>
:title="session.currentUser.value && u.id === session.currentUser.value.id ? '不能删除自己' : (isLastAdmin(u) ? '不能删除唯一的管理员' : '')" </div>
@click="onDeleteUser(u)" </div>
>
<Icon icon="mdi:delete" /> <div class="perm-group">
</button> <div class="perm-group-title">机器人</div>
<label class="perm-check">
<input type="checkbox" v-model="permDraft.botsAll" />
全部机器人
</label>
<div v-if="!permDraft.botsAll" class="perm-checks perm-bots">
<label v-for="bot in store.bots" :key="bot.id" class="perm-check">
<input
type="checkbox"
:checked="permDraft.selectedBotIds.includes(bot.id)"
@change="toggleBotSelection(bot.id, ($event.target as HTMLInputElement).checked)"
/>
{{ bot.name }}
</label>
<span v-if="store.bots.length === 0" class="user-empty">还没有机器人。</span>
</div>
</div>
<p v-if="permError" class="user-error">{{ permError }}</p>
<div class="form-actions">
<button class="btn-sm" @click="permEditingId = null">取消</button>
<button class="btn-sm btn-primary" :disabled="permSaving" @click="onSavePermissions(u)">
{{ permSaving ? '保存中…' : '保存' }}
</button>
</div>
</template>
</div> </div>
</div> </div>
<div v-if="userList.length === 0 && !userLoadError" class="user-empty">加载中…</div> <div v-if="userList.length === 0 && !userLoadError" class="user-empty">加载中…</div>
@@ -885,11 +955,13 @@ async function savePrefix() {
// Idle timeout // Idle timeout
const idleTimeout = ref(0); const idleTimeout = ref(0);
const autoPauseOnEmpty = ref(true);
async function loadIdleTimeout() { async function loadIdleTimeout() {
try { try {
const res = await axios.get('/api/bot/settings'); const res = await axios.get('/api/bot/settings');
idleTimeout.value = res.data.idleTimeoutMinutes ?? 0; idleTimeout.value = res.data.idleTimeoutMinutes ?? 0;
autoPauseOnEmpty.value = res.data.autoPauseOnEmpty ?? true;
} catch { /* ignore */ } } catch { /* ignore */ }
} }
@@ -899,6 +971,12 @@ async function saveIdleTimeout() {
} catch { /* ignore */ } } catch { /* ignore */ }
} }
async function saveAutoPause() {
try {
await axios.post('/api/bot/settings', { autoPauseOnEmpty: autoPauseOnEmpty.value });
} catch { /* ignore */ }
}
// --- Bot Profile config --- // --- Bot Profile config ---
interface ProfileConfig { interface ProfileConfig {
avatarEnabled: boolean; avatarEnabled: boolean;
@@ -967,6 +1045,7 @@ async function updateProfile(botId: string, key: keyof ProfileConfig, value: boo
// --- User Management --- // --- User Management ---
const session = useSession(); const session = useSession();
const { can } = session;
// --- Own password change (available to all authenticated users) --- // --- Own password change (available to all authenticated users) ---
const ownPw = reactive({ old: '', new: '', confirm: '' }); const ownPw = reactive({ old: '', new: '', confirm: '' });
@@ -1132,6 +1211,91 @@ async function onConfirmReset() {
} }
} }
// --- Per-user permission editor (members only) ---
const CAPABILITIES: { token: string; label: string }[] = [
{ token: 'player.control', label: '播放控制' },
{ token: 'player.queue', label: '队列管理' },
{ token: 'bot.manage', label: '机器人管理' },
{ token: 'platform.auth', label: '平台登录凭据' },
{ token: 'quality', label: '音质设置' },
];
const permEditingId = ref<string | null>(null);
const permLoading = ref(false);
const permSaving = ref(false);
const permError = ref('');
const permDraft = reactive<{ capabilities: string[]; botsAll: boolean; selectedBotIds: string[] }>({
capabilities: [],
botsAll: true,
selectedBotIds: [],
});
async function onTogglePermEditor(u: UserListEntry) {
if (permEditingId.value === u.id) {
permEditingId.value = null;
return;
}
permEditingId.value = u.id;
permError.value = '';
permLoading.value = true;
permDraft.capabilities = [];
permDraft.botsAll = true;
permDraft.selectedBotIds = [];
try {
const res = await fetch(`/api/users/${u.id}/permissions`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const body = await res.json();
permDraft.capabilities = Array.isArray(body.capabilities) ? [...body.capabilities] : [];
if (body.bots === 'all') {
permDraft.botsAll = true;
permDraft.selectedBotIds = [];
} else {
permDraft.botsAll = false;
permDraft.selectedBotIds = Array.isArray(body.bots) ? [...body.bots] : [];
}
} catch (e) {
permError.value = (e as Error).message;
} finally {
permLoading.value = false;
}
}
function toggleCapability(token: string, checked: boolean) {
const has = permDraft.capabilities.includes(token);
if (checked && !has) permDraft.capabilities.push(token);
else if (!checked && has) permDraft.capabilities = permDraft.capabilities.filter((t) => t !== token);
}
function toggleBotSelection(id: string, checked: boolean) {
const has = permDraft.selectedBotIds.includes(id);
if (checked && !has) permDraft.selectedBotIds.push(id);
else if (!checked && has) permDraft.selectedBotIds = permDraft.selectedBotIds.filter((b) => b !== id);
}
async function onSavePermissions(u: UserListEntry) {
permSaving.value = true;
permError.value = '';
try {
const res = await fetch(`/api/users/${u.id}/permissions`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
capabilities: [...permDraft.capabilities],
bots: permDraft.botsAll ? 'all' : [...permDraft.selectedBotIds],
}),
});
if (!res.ok && res.status !== 204) {
const b = await res.json().catch(() => ({}));
throw new Error(b.error ?? `HTTP ${res.status}`);
}
permEditingId.value = null;
} catch (e) {
permError.value = (e as Error).message;
} finally {
permSaving.value = false;
}
}
function formatDate(ms: number): string { function formatDate(ms: number): string {
const d = new Date(ms); const d = new Date(ms);
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`; return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
@@ -1182,6 +1346,7 @@ function describeAction(e: AuditEntry): string {
case 'user.password_reset': return `重置 ${target} 的密码`; case 'user.password_reset': return `重置 ${target} 的密码`;
case 'user.password_changed': return `修改自己的密码`; case 'user.password_changed': return `修改自己的密码`;
case 'user.role_changed': return `变更 ${target} 的角色`; case 'user.role_changed': return `变更 ${target} 的角色`;
case 'user.permissions_changed': return `权限变更 → ${target}`;
default: return `${e.action} → ${target}`; default: return `${e.action} → ${target}`;
} }
} }
@@ -1794,6 +1959,12 @@ onUnmounted(() => {
align-items: flex-start; align-items: flex-start;
} }
// Standalone toggle inside 行为设置 (not part of a bordered list)
.behavior-toggle {
border-bottom: none;
padding-top: 4px;
}
@media (max-width: 768px) { @media (max-width: 768px) {
.profile-bot-header { .profile-bot-header {
padding: 14px 12px; padding: 14px 12px;
@@ -1904,6 +2075,28 @@ onUnmounted(() => {
.role-member { background: rgba(150, 150, 150, 0.18); color: var(--text-secondary); } .role-member { background: rgba(150, 150, 150, 0.18); color: var(--text-secondary); }
.user-role-select { flex: 0 0 110px; } .user-role-select { flex: 0 0 110px; }
.user-row-wrap { display: flex; flex-direction: column; gap: 0; }
.perm-admin-label { font-size: 12px; color: var(--text-secondary); align-self: center; }
.perm-editor {
margin-top: -2px;
padding: 12px;
background: var(--bg-secondary);
border-radius: var(--radius-sm);
border-top: 1px solid var(--border-color);
display: flex;
flex-direction: column;
gap: 12px;
}
.perm-group { display: flex; flex-direction: column; gap: 8px; }
.perm-group-title { font-size: 13px; font-weight: 500; color: var(--text-primary); }
.perm-checks { display: flex; flex-wrap: wrap; gap: 8px 16px; }
.perm-bots { padding-left: 16px; }
.perm-check {
display: inline-flex; align-items: center; gap: 6px;
font-size: 13px; color: var(--text-secondary); cursor: pointer;
}
.perm-check input { cursor: pointer; }
// --- Account section (own password change) --- // --- Account section (own password change) ---
.account-info-card { .account-info-card {
display: flex; flex-direction: column; gap: 8px; display: flex; flex-direction: column; gap: 8px;