The -460 documented in the previous commit has no code-level fix: NetEase
decides by IP, so a cloud-datacenter host gets refused regardless of account,
quality or retry budget. The only real remedy is to let the request leave from
somewhere else.
The sidecar already supports that, and nobody had noticed: `NeteaseCloudMusicApi`
reads a `proxy` REQUEST PARAMETER and tunnels through it itself
(`util/request.js`, via the `tunnel` package — `httpOverHttp`/`httpsOverHttp`).
So this needs **no new dependency, no global-agent patching, and no change to
how the sidecar is started**. It is one string carried on the calls we already
make.
What was added:
- `NeteaseProvider.setProxy()` / `getProxy()`. The value goes into
`requestParams`, a single getter that already existed for the cookie — which
is why all ~20 call sites (search, playlist, album, artist, lyric, playback)
pick it up without touching each one again.
- `config.musicProxy` (default `""` = direct, i.e. exactly the old behaviour).
Only `http(s)://host[:port]` is accepted; anything else falls back to direct
rather than silently breaking every music request.
- `index.ts` reads it, falls back to `HTTPS_PROXY`/`HTTP_PROXY` from the
environment, and logs `NetEase requests will go through a proxy` with the
credentials redacted.
Deliberate limits:
- Only HTTP proxies. The sidecar implements this with a CONNECT tunnel, so a
`socks5://` value would be parsed and then fail. Documented on the setter.
- Audio is NOT proxied. The player pulls the mp3 from NetEase's CDN with ffmpeg,
which knows nothing about this setting. If a deployment needs those requests
to share the API's egress IP, it needs a network-level route, not this option.
- Config wins over the environment: a container-wide `HTTPS_PROXY` set for
unrelated tools must not silently reroute music traffic.
6 new tests: no parameter by default, carried on every call once set, carried on
the playback call specifically, kept alongside the cookie, blank means direct,
values are trimmed.
This is additive and off by default — merging it changes nothing until someone
sets `musicProxy`.
The order was hardcoded: own account → assigned account → shared. That is the
right default (privacy first), but it leaves one common case stuck: a member's
own NetEase login is real but has no membership, while the admin's does. They
linked their account, so playback keeps using theirs, and every paid track
fails — with no way to say "just use the admin's for playback".
Two things now:
1. An explicit choice — `user_music_prefs` (userId + platform), exposed as
GET/PUT `/api/me/music/:platform/preference` and a radio in the account
card. `preferShared: true` outranks EVERYTHING, including `alwaysPersonal`
(someone who chose membership over their own recommendations wants the
shared login for FM too). It stores a flag, not a cookie — flipping it back
restores the personal account untouched.
2. An automatic fallback for people who never touch the switch. Only
`getSongUrl` is wrapped: if the personal account returns `url: null` or
throws, the same track is retried once on the shared login. Search,
playlists and FM stay on the member's own account — that is the point of
per-user logins, and widening the fallback would leak their library back to
the admin's.
Details:
- The fallback lives in `resolveProviderForRequest`, so every playback entry
point (web click, chat !play, auto-advance, playlists) gets it by
construction, and the shared instance is never mutated.
- `fallbackToShared: false` is available for callers that must stay strictly on
the member's account; the default is on, because "my account has no VIP" is
the complaint that produced this feature.
- The status payload now carries `preferShared` and `featureEnabled`, so the UI
can render the radio without a second round-trip and hide it when the admin
has the feature off (PUT answers 409 in that case).
13 new tests: preference overrides own + assigned + alwaysPersonal, feature-off
ignored, GET/PUT round-trip, per-platform isolation, stored cookie untouched,
non-boolean rejected, 409 when disabled; fallback on null, on throw, keeps the
personal result when it works, can be disabled, leaves the shared instance
untouched.
Two failure modes look identical to the user — 「无法播放(区域/版权限制)」 — but
need different handling, and both were hitting the same code path:
1. **Transient.** NetEase intermittently answers `url: null` for a song that
resolves fine a moment later. Repeating the SAME request fixes it, but the
user had to click play repeatedly to be that retry.
2. **Quality gap.** Measured against a real library: a track can be playable at
192k ("higher") while BOTH 320k ("exhigh") and 128k ("standard") return
`url: null`. So the ladder is not continuous and "just drop to the cheapest"
would still fail — every level below the current one has to be tried.
`resolveAndPlay` now resolves through `bot/url-retry.ts`:
- Phase 1: `1 + config.playUrlRetries` attempts (default 2, clamped 0..5) at the
configured quality, 250ms linear backoff between them.
- Phase 2: one attempt per lower level from `provider.getFallbackQualities()`
(NetEase: exhigh → higher → standard), 120ms apart — switching level is a
different request, not a re-poke of the same one.
- Cancel (stop / disconnect) is checked before every attempt, so the budget
never retries into a dead connection.
- A thrown error is retried exactly like an empty result: a sidecar timeout
looks identical to the user.
- Failure is logged once per track, not once per attempt.
Every queue path funnels into `resolveAndPlay` (web click, chat !play,
auto-advance, FM), so playlists and albums get the same budget for free — that
is where "click the playlist four times before it starts" came from.
`config.playUrlRetries` is exposed on GET/POST `/api/bot/settings`. A config
without the field falls back to 2 — retries are ON by default because the whole
point is to be invisible. Set it to 0 to restore the previous fail-fast path.
Every member saw the admin's library: the bot keeps one shared login per
platform (data/cookies/<platform>.json) and search, playlists and playback
URLs all read through it. #164 added a personal NetEase login, but only for
私人FM — the rest still came from the shared account.
On top of that, most members do not own a paid login, so "everyone links their
own" is not enough: the admin has to be able to hand out accounts.
What this adds, behind one admin switch (`perUserMusicAccounts`, default off):
- One login per request, resolved in this order: the caller's OWN linked
account, then an account an admin ASSIGNED, then the bot's shared login.
- An admin-owned pool (`music_accounts`) plus per-member assignments
(`music_account_grants`, PK userId+platform = one per platform). Assignments
are capacity-checked inside a transaction, so an exclusive account cannot be
handed to two members by two concurrent clicks. `enabled = 0` is an instant
rollback of every grant without deleting them.
- Own-beats-assigned, and the two live in separate tables: a member scanning
their own QR code never overwrites an admin's assignment, and unlinking on
the member side never revokes what the admin granted.
- QQ / Kugou / Bilibili now implement `withCookie`, so all four sources can be
isolated. Only NetEase exposes QR self-linking (it is the only one with
`pollQrLogin`); the rest accept an assigned account, which is the workflow
that actually matters for members without a paid login.
- `/api/music-accounts` is admin-only (`requireAdmin`, not `bot.manage`):
members must never see which account was handed to whom. Cookies are masked
in every response.
Switch off = no behaviour change at all, except 私人FM keeps the #164 behaviour
through `alwaysPersonal`.
With several people sharing one bot, personal FM always followed the one
account the bot was logged in with. Each signed-in (non-guest) web user
can now scan a QR code under Settings → 账户 to link their own NetEase
account; FM they start from the WebUI then comes from their account.
- user_music_cookies table (per user + platform, dropped with the user).
- NeteaseProvider.pollQrLogin returns the cookie without storing it, so
a personal login can never replace the bot's shared account;
checkQrCodeStatus is now built on it. withCookie gives a view bound to
another account.
- /api/me/music/netease: status / qrcode / qrcode/status / unlink, acting
only on req.user. The cookie never leaves the server.
- POST /api/player/:botId/fm uses the caller's linked account for
NetEase. Songs still resolve through the shared provider when played.
TeamSpeak chat !fm keeps using the shared account: chat users are not
tied to web accounts.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Add three default-off capabilities that stop the play queue from being lost,
all gated behind admin/independent toggles so existing behavior is unchanged
until an operator opts in:
- Named save/load of queues (Feature 1): new saved_queues table (per-user +
reserved __shared__ owner, capped at 50 queues / 1000 songs, JSON song blob
that degrades to empty on corruption); /api/saved-queues router (list/save/
load/delete with ownership 404s, inert 403 when disabled); chat commands
!save / !load [-a] / !queues; BotInstance.loadSavedQueue (replace/append).
- Auto-restore live queue across restart (Feature 2): PlayQueue.snapshot/restore,
queue_state table (one row per bot), a debounced snapshot writer driven off
stateChange, and restore+resume on connect. Cancels the pending snapshot on
disconnect so a stale write can't wipe the row a restart must restore.
- playKeepsQueue (Feature 3): BotInstance.playSingleSong funnels chat !play and
the web /play-song route through one place; when enabled a single-song play
inserts-after-current and jumps instead of clearing the queue.
Config gains savedQueuesEnabled + playKeepsQueue (both default false, strict-
coerced on load like spotify.enabled); the settings API round-trips them.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Runtime playback settings were kept only in memory (AudioPlayer.volume,
PlayQueue.mode, each provider's quality field), so restarting the bot reset
them to defaults and users had to re-tune volume and quality every time (#125).
Persist and restore them via the repo's existing storage:
- Volume and play mode are per-bot, stored on new bot_instances columns
(volume, play_mode) with a schema migration; restored when the instance is
(re)built, written by cmdVol / cmdMode which every entry point (chat command,
WebUI, REST) funnels through. Volume and mode are written independently so a
transient !fm/!artist mode switch never overwrites the user's saved !mode.
- Per-provider audio quality is global (shared providers), stored in a new
config.json `audioQuality` block; applied to the providers at startup and
re-snapshotted on POST /api/music/quality.
Queue, current song, progress and FM/artist sessions stay ephemeral.
Adds tests for config sanitize/round-trip, DB player-settings + migration,
cmdVol/cmdMode persistence + construction-time restore, and quality persistence
through the REST endpoint. Documents the behavior in the README.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Make the default playback source a user-configurable setting so servers
that mostly play e.g. Bilibili no longer need to type `-b` on every
`!play`. Previously defaultPlatform() always picked the first enabled
provider by a fixed priority order, with no way to override it.
- config: add optional `defaultPlatform: GateableProvider | null`.
loadConfig sanitizes it — kept only when it names a known provider that
is also currently enabled, else null. defaultPlatform() returns the
preference when enabled, otherwise falls back to the fixed priority order.
- POST /api/bot/settings accepts `defaultPlatform` (validated against the
possibly-updated enabledProviders; null/"" clears it), and reconciles a
stored default that a new enabledProviders list no longer allows. GET and
POST responses expose the field.
- WebUI: new "默认音源" section with a source picker; saving refreshes the
store's default source so it takes effect immediately without a restart.
- Tests: extend config defaultPlatform priority tests and add coverage for
the settings endpoint and /providers routing.
- README: document `defaultPlatform` in the enabledProviders section.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Revert the jellyfin-only default introduced by PR #123 so upgrading
users keep their online sources; Jellyfin becomes opt-in:
- default enabledProviders is now the online set (netease/qq/bilibili/
youtube/kugou); defaultPlatform() uses a fixed priority order
(netease -> qq -> kugou -> jellyfin -> bilibili -> youtube) instead
of jellyfin-first, so chat/REST/WebUI default to netease again
- Settings: Jellyfin card is always visible with a new enable toggle
(its enabled bit is enabledProviders membership); guards against
clobbering other providers before the list loads
- Setup wizard: saving the Jellyfin step auto-enables the source when
a server URL was entered
- Search/player store fallbacks flip from jellyfin to netease; !help
no longer hardcodes Jellyfin lines
- tests: update default-platform assertions, add coverage for the new
default set, legacy configs without enabledProviders, priority
order, and explicit jellyfin-only configs
- README: reframe Jellyfin as optional (badges, command table, quality
tiers, dedicated section, changelog), document the enabledProviders
default and the v1.10.0 jellyfin-only window fix, credit @ItsEricRao
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Merges feature/play-history-requester (@Fa1nttt) into main.
The PR records the WebUI/TeamSpeak requester on queued songs and persists it
to play history (schema migration for requestedBy), rendering it as a badge in
SongCard (gray for 游客/guest).
Conflicts (frontend platform union) resolved to keep both 'spotify' (from #118)
and the new requestedBy/playedAt fields.
Integration fix: the Spotify playback branch in resolveAndPlay (added by #118,
which did not exist on the PR's base) also records play history — added
`requestedBy: song.requestedBy` there so Spotify tracks carry attribution too,
matching the non-Spotify path.
Verified on the merged tree: tsc --noEmit clean, full suite 1309/1309, web build clean.
Co-Authored-By: Fa1nttt <noreply@github.com>
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Adds src/music/spotify/webapi.ts (client-credentials token, catalog
mappers, 429 retry) + tests, and threads the new "spotify" platform id
through the type unions in provider.ts and database.ts. Also widens the
downstream QueuedSong.platform union (audio/queue.ts) and the
getProviderFor parameter (bot/instance.ts) so tsc --noEmit stays clean;
these two are the necessary call-site fixes for the new union member.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Adds a self-contained Kugou provider (bilibili-style: direct API calls, no
embedded API server, no new npm dependency) plus full backend + WebUI wiring.
Provider (src/music/kugou.ts): search, song-url (with device registration),
lyrics (KRC decode), song detail, playlist, album, personal FM, QR login +
cookie persistence, and quality. Request signing / crypto / KRC decoding are
ported from the MIT-licensed MakcRe/KuGouMusicApi using Node's built-in
crypto and zlib (no third-party crypto packages).
Wiring: the "kugou" platform is threaded through the provider contract, queue,
play-history, bot instance/manager dispatch (getProviderFor + the -k command
flag), index/server composition, the music/player/auth routers (unified
/search/all, /quality, the platform coercions, QR login), the cookie store,
and the WebUI (search source tab + badge, SongCard badge, brand token, and a
Kugou QR/cookie login card in Settings).
Verified live during development: search, lyrics, and album playback resolve
correctly. NOT verifiable in CI (Kugou anti-bot blocks the build host's IP):
play-URL resolution, QR login, and VIP audio — these are built faithfully to
the reference and need end-to-end testing on a non-flagged IP / a Kugou
account. See the header comment in kugou.ts.
Includes src/music/kugou.test.ts (mappers + KRC→LRC). An adversarial review
pass fixed: pagination truncating on filtered counts, an ms/seconds duration
heuristic, dfid soft-fail caching, the /v5/url random-dfid fallback, the FM
body identity, and an unguarded nickname decode.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
- New guest flag playCollection (default OFF), gates play-playlist/play-album
- Keeps playNow's non-destructive semantics intact (Play All clears the queue)
- Admin-toggleable in Settings → 游客模式; default-off, backward-compatible
- Frontend: gate the 播放全部 button on the flag + surface 403 as a toast
instead of failing silently (the silent-failure half of the issue)
The sliding-refresh branch in validateAndTouch hardcoded SESSION_TTL_MS
(7d) for all roles, so a guest session created with GUEST_SESSION_TTL_MS
(1d) was wrongly bumped to 7d on the first touch after the touch
interval. Derive the touch TTL from row.role instead.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
loadConfig now sanitizes guestMode the same way the write path does: bots is
coerced to "all" | string[] (numbers/objects/missing fall back to the default
"all"), and permissions are rebuilt from defaults with each known flag
strict-coerced to a boolean so a hand-edited/legacy/corrupt config.json can no
longer crash the gate or leak garbage index keys. The authorize guest gate now
uses === true instead of a truthy check.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
The by-id user-management handlers use findById, which has no role
filter, so supplying the synthetic GUEST_USER_ID let an admin delete,
re-role, reset-password, and read/write permissions on the shared guest
principal (privilege-escalation / DoS / credential-login holes).
- web/api/users.ts: 404-guard every :id handler against GUEST_USER_ID
(DELETE, reset-password, role, GET/PUT permissions).
- data/users.ts: defense-in-depth — setRoleIfNotLastAdmin and
deleteUserIfNotLastAdmin return "not_found" for any role=guest row.
- web/api/session.ts: wrap POST /guest createSession in try/catch so a
missing guest row yields 503 instead of an unhandled 500.
- Tests: data-layer guest-protection + users-router 404 by-id guards.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Auto-pause within the first seconds of playback (and re-pause after a manual
play) whenever a listener is actually in the channel.
Root cause (confirmed live against a TS3 server): the full-client
`clientlist -uid -away -voice -groups` command TIMES OUT when other clients are
present in the bot's channel. `getClientsInChannel()` catches the error and
returns `[]`, so the occupancy callers computed `userCount = [].length - 1 = -1`,
which `decideOccupancyAction` reads as `-1 <= 0` → "channel empty" → pause. With
the bot alone, clientlist succeeds (returns just the bot), so the bug only
surfaced when someone was listening — exactly the report.
Fix: a connected bot is always a member of its own channel, so a valid query
returns >= 1 (itself). A length of 0 therefore means the query FAILED, not that
the channel is empty. New pure helper `occupancyFromClientList()` maps a
0-length result to `null` ("occupancy unknown"); `refreshOccupancy()` and the
30s idle poller skip the auto-pause / idle-disconnect decision when the count is
unknown instead of mis-reading it as empty. This also removes a latent
false-positive idle-disconnect on the same failed query.
Also default `autoPauseOnEmpty` to OFF (occupancy detection is unreliable on
some servers); users can opt in from Settings.
Verified live with two clients in one channel: clientlist returns 0 → helper
returns null → no false pause (control: bot alone returns 1 → 0 others, normal).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
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>
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).