From 2daae590149029b3c30b9f0cb43c38bedc87c81c Mon Sep 17 00:00:00 2001 From: jiayuLian Date: Sun, 8 Nov 2026 11:21:37 +0000 Subject: [PATCH] feat(music): optional outbound proxy for the NetEase sidecar MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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`. --- src/data/config.ts | 23 ++++++++++++ src/index.ts | 21 +++++++++++ src/music/netease.test.ts | 70 +++++++++++++++++++++++++++++++++++ src/music/netease.ts | 78 +++++++++++++++++++++++++++++---------- 4 files changed, 172 insertions(+), 20 deletions(-) mode change 100755 => 100644 src/data/config.ts mode change 100755 => 100644 src/index.ts diff --git a/src/data/config.ts b/src/data/config.ts old mode 100755 new mode 100644 index ff0623c..ca58ad1 --- a/src/data/config.ts +++ b/src/data/config.ts @@ -150,6 +150,18 @@ export interface BotConfig { * a hand-edited config cannot turn every failed track into a long stall. */ playUrlRetries: number; + /** + * Outbound HTTP proxy for the NetEase sidecar, e.g. `http://192.168.1.2:8118`. + * + * NetEase rejects cloud-datacenter IPs with `-460` ("网络环境存在风险") no matter + * which account is used, so on a VPS the only fix is to send the request out + * through somewhere else. Empty (the default) = direct, i.e. unchanged. + * + * Only `http://` proxies are supported — the sidecar implements this with a + * CONNECT tunnel. When left empty, `HTTPS_PROXY`/`HTTP_PROXY` from the + * environment is used as a fallback (see index.ts). + */ + musicProxy: string; // Public base URL used when generating share links (e.g. the bot专属链接). // Leave empty to use the browser's current origin. Example: // "https://music.example.com" or "http://1.2.3.4:3000" @@ -208,6 +220,7 @@ export function getDefaultConfig(): BotConfig { // Two extra attempts: enough to ride out a transient NetEase hiccup without // making a genuinely unlicensed track feel stuck (~1s of backoff total). playUrlRetries: 2, + musicProxy: "", publicUrl: "", trustProxy: false, guestMode: { @@ -421,6 +434,15 @@ export function loadConfig(path: string): BotConfig { ? Math.min(5, Math.max(0, Math.trunc(rawRetries))) : defaults.playUrlRetries; + // Outbound proxy for the NetEase sidecar. Only http(s) URLs are kept: a + // stray value here would silently break every music request, so anything + // unparseable is dropped back to "direct" instead of being passed through. + const rawMusicProxy = partial.musicProxy; + const musicProxy = + typeof rawMusicProxy === "string" && /^https?:\/\/[^\s]+$/i.test(rawMusicProxy.trim()) + ? rawMusicProxy.trim() + : defaults.musicProxy; + // Voice ducking is opt-in and the retained-volume percentage is consumed // directly by the audio path. Only a plain-object block with correctly // typed, finite and in-range fields may override the safe defaults. @@ -484,6 +506,7 @@ export function loadConfig(path: string): BotConfig { savedQueuesEnabled, playKeepsQueue, playUrlRetries, + musicProxy, voiceDucking, defaultPlatform: defaultPlatformPref, }; diff --git a/src/index.ts b/src/index.ts old mode 100755 new mode 100644 index d7d14d1..5dda266 --- a/src/index.ts +++ b/src/index.ts @@ -81,6 +81,27 @@ async function main() { const cookieStore = createCookieStore(COOKIE_DIR); const avatarStore = createAvatarStore(AVATAR_DIR); + + // Outbound proxy for the NetEase sidecar. On a cloud host NetEase answers + // -460 ("网络环境存在风险") by IP, so the request has to leave through somewhere + // else. Config wins over the environment: a container-wide HTTPS_PROXY set + // for unrelated tools must not silently reroute music traffic. + const musicProxy = + config.musicProxy || + process.env.HTTPS_PROXY || + process.env.https_proxy || + process.env.HTTP_PROXY || + process.env.http_proxy || + ""; + if (musicProxy) { + neteaseProvider.setProxy(musicProxy); + // Credentials in a proxy URL are common; never put them in the log. + logger.info( + { proxy: musicProxy.replace(/\/\/[^@/]+@/, "//***@") }, + "NetEase requests will go through a proxy", + ); + } + const neteaseCookie = cookieStore.load("netease"); if (neteaseCookie) neteaseProvider.setCookie(neteaseCookie); const qqCookie = cookieStore.load("qq"); diff --git a/src/music/netease.test.ts b/src/music/netease.test.ts index 0eb39f9..f5793d5 100644 --- a/src/music/netease.test.ts +++ b/src/music/netease.test.ts @@ -485,3 +485,73 @@ describe("NetEase — why a track has no URL", () => { expect(err.failure.upstream).toMatchObject({ fee: 8, payed: 0, level: "higher", br: 192000 }); }); }); + +// --------------------------------------------------------------------------- +// Outbound proxy +// +// On a cloud host NetEase answers -460 by IP, so the request has to leave from +// somewhere else. The sidecar (NeteaseCloudMusicApi) supports this natively via +// a `proxy` request parameter — no new dependency, no global-agent patching. +// These tests pin that it is carried on EVERY call and that the default stays +// exactly as before. +// --------------------------------------------------------------------------- +describe("NetEase — outbound proxy", () => { + function capture() { + const seen: Array> = []; + const p = new NeteaseProvider("http://127.0.0.1:3001"); + (p as unknown as { api: { get: (u: string, c: any) => Promise } }).api = { + get: async (_url: string, cfg: any) => { + seen.push({ ...cfg?.params }); + return { data: { result: {}, data: [{ url: null, code: 200, fee: 8, level: "exhigh" }] } }; + }, + }; + return { p, seen }; + } + + it("sends no proxy parameter by default — behaviour is unchanged", async () => { + const { p, seen } = capture(); + await p.search("x").catch(() => {}); + expect(seen.length).toBeGreaterThan(0); + for (const params of seen) expect(params.proxy).toBeUndefined(); + }); + + it("carries the proxy on every call once configured", async () => { + const { p, seen } = capture(); + p.setProxy("http://192.168.1.9:8118"); + await p.search("x").catch(() => {}); + expect(seen.length).toBeGreaterThan(0); + for (const params of seen) expect(params.proxy).toBe("http://192.168.1.9:8118"); + }); + + it("carries it on the playback call too — that is the one that gets -460", async () => { + const { p, seen } = capture(); + p.setProxy("http://192.168.1.9:8118"); + await p.getSongUrl("1", "standard").catch(() => {}); + expect(seen).toHaveLength(1); + expect(seen[0]).toMatchObject({ id: "1", level: "standard", proxy: "http://192.168.1.9:8118" }); + }); + + it("keeps the cookie alongside the proxy", async () => { + const { p, seen } = capture(); + p.setCookie("MUSIC_U=abc"); + p.setProxy("http://h:1"); + await p.getSongUrl("1").catch(() => {}); + // cookie is normalised on the way in, so compare loosely. + expect(String(seen[0].cookie)).toContain("MUSIC_U=abc"); + expect(seen[0].proxy).toBe("http://h:1"); + }); + + it("treats a blank value as direct service", async () => { + const { p, seen } = capture(); + p.setProxy(" "); + await p.search("x").catch(() => {}); + for (const params of seen) expect(params.proxy).toBeUndefined(); + expect(p.getProxy()).toBe(""); + }); + + it("trims the value it is given", () => { + const p = new NeteaseProvider("http://x"); + p.setProxy(" http://h:1 "); + expect(p.getProxy()).toBe("http://h:1"); + }); +}); diff --git a/src/music/netease.ts b/src/music/netease.ts index 1e8a3ad..41b484e 100644 --- a/src/music/netease.ts +++ b/src/music/netease.ts @@ -209,6 +209,8 @@ export class NeteaseProvider implements MusicProvider { private api: AxiosInstance; private cookie = ""; private quality = "exhigh"; + /** Outbound HTTP proxy for the sidecar's own requests. "" = direct. */ + private proxy = ""; private readonly baseUrl: string; constructor(baseUrl: string) { @@ -231,13 +233,49 @@ export class NeteaseProvider implements MusicProvider { return this.cookie ? { cookie: this.cookie } : {}; } + /** + * Outbound proxy for every sidecar call. + * + * NetEase limits by IP: a cloud-datacenter address answers `-460` + * ("检测到您的网络环境存在风险") on most requests no matter which account asks, + * while the same account from a residential IP works. There is no code-level + * fix — the request has to originate somewhere else. + * + * The sidecar already knows how: `NeteaseCloudMusicApi` reads a `proxy` + * request parameter and tunnels through it itself (`util/request.js`, via the + * `tunnel` package). So this needs no new dependency and no global-agent + * patching — just carry the value. + * + * Only `http://` proxies work (the sidecar implements this with CONNECT). + * Empty means direct, i.e. exactly the previous behaviour. + */ + setProxy(proxy: string): void { + this.proxy = (proxy ?? "").trim(); + } + + getProxy(): string { + return this.proxy; + } + + private get proxyParams(): Record { + return this.proxy ? { proxy: this.proxy } : {}; + } + + /** + * Everything every call needs. One getter so a field added here cannot be + * forgotten on any of the ~20 call sites. + */ + private get requestParams(): Record { + return { ...this.cookieParams, ...this.proxyParams }; + } + async search(query: string, limit = 20, offset = 0): Promise { // /cloudsearch supports offset for every type. Songs, playlists (type 1000) // and albums (type 10) are all limit/offset-driven so the web can page past // the first page (playlists/albums were previously hardcoded to limit: 10). const [songRes, playlistRes, albumRes, artistRes] = await Promise.all([ this.api.get("/cloudsearch", { - params: { keywords: query, type: 1, limit, offset, ...this.cookieParams }, + params: { keywords: query, type: 1, limit, offset, ...this.requestParams }, }), this.api.get("/cloudsearch", { params: { @@ -245,14 +283,14 @@ export class NeteaseProvider implements MusicProvider { type: 1000, limit, offset, - ...this.cookieParams, + ...this.requestParams, }, }), this.api.get("/cloudsearch", { - params: { keywords: query, type: 10, limit, offset, ...this.cookieParams }, + params: { keywords: query, type: 10, limit, offset, ...this.requestParams }, }), this.api.get("/cloudsearch", { - params: { keywords: query, type: 100, limit, offset, ...this.cookieParams }, + params: { keywords: query, type: 100, limit, offset, ...this.requestParams }, }), ]); @@ -280,7 +318,7 @@ export class NeteaseProvider implements MusicProvider { let res; try { res = await this.api.get("/song/url/v1", { - params: { id: songId, level, ...this.cookieParams }, + params: { id: songId, level, ...this.requestParams }, }); } catch (err) { // -460 arrives as HTTP 400, and left as-is it looks like "this track is @@ -321,21 +359,21 @@ export class NeteaseProvider implements MusicProvider { async getSongDetail(songId: string): Promise { const res = await this.api.get("/song/detail", { - params: { ids: songId, ...this.cookieParams }, + params: { ids: songId, ...this.requestParams }, }); return mapNeteaseSongs(res.data?.songs)[0] ?? null; } async getPlaylistSongs(playlistId: string): Promise { const res = await this.api.get("/playlist/track/all", { - params: { id: playlistId, ...this.cookieParams }, + params: { id: playlistId, ...this.requestParams }, }); return mapNeteaseSongs(res.data?.songs); } async getRecommendPlaylists(): Promise { const res = await this.api.get("/personalized", { - params: { limit: 10, ...this.cookieParams }, + params: { limit: 10, ...this.requestParams }, }); return (res.data?.result ?? []).map((p: any) => ({ id: String(p.id), @@ -348,7 +386,7 @@ export class NeteaseProvider implements MusicProvider { async getAlbumSongs(albumId: string): Promise { const res = await this.api.get("/album", { - params: { id: albumId, ...this.cookieParams }, + params: { id: albumId, ...this.requestParams }, }); return mapNeteaseSongs(res.data?.songs); } @@ -358,7 +396,7 @@ export class NeteaseProvider implements MusicProvider { // separately via /artist/songs (order=hot) so the artist page's three // upstream calls stay independent of each other. const res = await this.api.get("/artists", { - params: { id: artistId, ...this.cookieParams }, + params: { id: artistId, ...this.requestParams }, }); const a = res.data?.artist; if (!a) return null; @@ -375,7 +413,7 @@ export class NeteaseProvider implements MusicProvider { limit, offset: 0, order: "hot", - ...this.cookieParams, + ...this.requestParams, }, }); return mapNeteaseSongs(res.data?.songs); @@ -383,7 +421,7 @@ export class NeteaseProvider implements MusicProvider { async getArtistAlbums(artistId: string, limit = 20): Promise { const res = await this.api.get("/artist/album", { - params: { id: artistId, limit, offset: 0, ...this.cookieParams }, + params: { id: artistId, limit, offset: 0, ...this.requestParams }, }); return mapNeteaseAlbums(res.data?.hotAlbums); } @@ -404,7 +442,7 @@ export class NeteaseProvider implements MusicProvider { limit: safeLimit, offset: safeOffset, order: "hot", - ...this.cookieParams, + ...this.requestParams, }, }); const songs = mapNeteaseSongs(res.data?.songs); @@ -418,7 +456,7 @@ export class NeteaseProvider implements MusicProvider { async getLyrics(songId: string): Promise { const res = await this.api.get("/lyric", { - params: { id: songId, ...this.cookieParams }, + params: { id: songId, ...this.requestParams }, }); return parseLyrics( res.data?.lrc?.lyric ?? "", @@ -514,7 +552,7 @@ export class NeteaseProvider implements MusicProvider { if (!this.cookie) return { loggedIn: false }; try { const res = await this.api.get("/login/status", { - params: { ...this.cookieParams }, + params: { ...this.requestParams }, }); const profile = res.data?.data?.profile; if (profile) { @@ -532,21 +570,21 @@ export class NeteaseProvider implements MusicProvider { async getPersonalFm(): Promise { const res = await this.api.get("/personal_fm", { - params: { ...this.cookieParams }, + params: { ...this.requestParams }, }); return mapNeteaseSongs(res.data?.data); } async getDailyRecommendSongs(): Promise { const res = await this.api.get("/recommend/songs", { - params: { ...this.cookieParams }, + params: { ...this.requestParams }, }); return mapNeteaseSongs(res.data?.data?.dailySongs); } async getPlaylistDetail(playlistId: string): Promise { const res = await this.api.get("/playlist/detail", { - params: { id: playlistId, ...this.cookieParams }, + params: { id: playlistId, ...this.requestParams }, }); const p = res.data?.playlist; if (!p) return null; @@ -562,13 +600,13 @@ export class NeteaseProvider implements MusicProvider { async getUserPlaylists(): Promise { // First get user ID from login status const statusRes = await this.api.get("/login/status", { - params: { ...this.cookieParams }, + params: { ...this.requestParams }, }); const uid = statusRes.data?.data?.profile?.userId; if (!uid) return []; const res = await this.api.get("/user/playlist", { - params: { uid, ...this.cookieParams }, + params: { uid, ...this.requestParams }, }); return (res.data?.playlist ?? []).map((p: any) => ({ id: String(p.id),