Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,16 @@ PASSWORD=change-me
REQUEST_TIMEOUT=8000
MAX_RETRIES=1

# 可选:出网代理(HTTP/HTTPS 代理地址,如 http://127.0.0.1:7897)。
# 采集站被 Cloudflare 拦截、或目标站在本地网络不可达时可用;不设置则直连。
# 注意:系统代理设置(macOS/Windows 的系统代理)不会被 Node 继承,必须在此显式配置。
# HTTPS_PROXY=http://127.0.0.1:7897
# HTTP_PROXY=http://127.0.0.1:7897

# 可选:NO_PROXY 例外列表(逗号分隔),命中的目标直连不走代理。
# 建议把视频 CDN 域名加进来,避免播放流量绕行代理导致卡顿。
# NO_PROXY=127.0.0.1,localhost,::1,cdn.example.com

# 可选:影视榜单推荐源(60s API)实例地址,默认官方公共实例 https://60s.viki.moe。
# 官方实例有限流(本项目每小时仅请求 6 次榜单,通常够用);高频使用可自部署:docker run -d -p 4399:4399 vikiboss/60s:latest
# 60S_API_BASE=https://60s.viki.moe
Expand Down
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,8 @@ PASSWORD=your-password npm start # 监听 8080
| `DEFAULT_SUBSCRIPTIONS` | 否 | 预置数据源订阅(LibreTV-SourceList JSON 链接,也接受 TVBOX 配置与接口目录地址),JSON 数组:`["https://.../sources.json", {"url":"https://.../list.json","name":"名称","refreshDays":10}]`。首次访问自动导入点播源与直播源,之后按 `refreshDays`(1-365,缺省 1 天)静默刷新;用户删除后不再自动加回。`refreshDays` 只是初始值,用户在源管理面板改过之后以面板设置为准 |
| `DEFAULT_RECOMMEND_SOURCE` | 否 | 首页推荐数据源的默认值(`douban` / `bangumi` / `hot-list`,出厂默认 `hot-list`);仅对未在设置中主动选择过的用户生效,用户的选择始终优先 |
| `LIVE_ALLOW_PRIVATE` | 否 | 设为 `1` 时允许直播流代理访问内网/保留地址(自建 IPTV 场景),默认关闭以维持 SSRF 防护 |
| `HTTPS_PROXY` / `HTTP_PROXY` | 否 | 出网代理地址(如 `http://127.0.0.1:7897`)。采集站被 Cloudflare 拦截、或目标站在本地网络不可达时使用;不设置则直连。**系统代理设置(macOS/Windows 系统代理)不会被 Node 继承,必须在此显式配置**,否则表现为「浏览器能访问、服务端请求却 403/超时」 |
| `NO_PROXY` / `no_proxy` | 否 | 例外列表(逗号分隔),命中的目标直连不走代理。建议把视频 CDN 域名加进来,避免播放流量绕行代理导致卡顿 |

## 使用说明

Expand Down
91 changes: 90 additions & 1 deletion src/lib/ssrf.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
import { describe, expect, it } from 'vitest';
import http from 'node:http';
import { isPrivateIP, isValidProxyUrl, runWithSSRFProtection } from './ssrf';
import {
createUpstreamDispatcher,
getUpstreamProxyUrl,
isNoProxyHost,
isPrivateIP,
isValidProxyUrl,
runWithSSRFProtection,
} from './ssrf';

describe('isPrivateIP', () => {
it.each([
Expand Down Expand Up @@ -225,3 +232,85 @@ describe('DNS Rebinding & Connection SSRF Protection (#941)', () => {
}
});
});


describe('出网代理支持(#P1)', () => {
const PROXY_ENV_KEYS = ['HTTPS_PROXY', 'https_proxy', 'HTTP_PROXY', 'http_proxy'] as const;
const NO_PROXY_ENV_KEYS = ['NO_PROXY', 'no_proxy'] as const;

function withEnv<T>(patch: Record<string, string | undefined>, fn: () => T): T {
const saved: Record<string, string | undefined> = {};
for (const key of [...PROXY_ENV_KEYS, ...NO_PROXY_ENV_KEYS]) {
saved[key] = process.env[key];
if (patch[key] === undefined) delete process.env[key];
else process.env[key] = patch[key];
}
try {
return fn();
} finally {
for (const [key, value] of Object.entries(saved)) {
if (value === undefined) delete process.env[key];
else process.env[key] = value;
}
}
}

it('未配置代理时返回 null', () => {
withEnv(
{ HTTPS_PROXY: undefined, https_proxy: undefined, HTTP_PROXY: undefined, http_proxy: undefined },
() => {
expect(getUpstreamProxyUrl()).toBeNull();
}
);
});

it('读取 HTTPS_PROXY / http_proxy(小写)并忽略非法协议', () => {
withEnv(
{ HTTPS_PROXY: undefined, https_proxy: undefined, HTTP_PROXY: undefined, http_proxy: undefined },
() => {
process.env.HTTPS_PROXY = 'http://127.0.0.1:7897';
expect(getUpstreamProxyUrl()).toBe('http://127.0.0.1:7897/');
delete process.env.HTTPS_PROXY;
process.env.http_proxy = 'http://127.0.0.1:7898';
expect(getUpstreamProxyUrl()).toBe('http://127.0.0.1:7898/');
delete process.env.http_proxy;
process.env.HTTPS_PROXY = 'socks5://127.0.0.1:1080';
expect(getUpstreamProxyUrl()).toBeNull();
}
);
});

it('NO_PROXY 命中时判定为直连', () => {
withEnv({ NO_PROXY: undefined, no_proxy: undefined }, () => {
process.env.NO_PROXY = 'localhost,127.0.0.1,.example.com';
expect(isNoProxyHost('localhost')).toBe(true);
expect(isNoProxyHost('127.0.0.1')).toBe(true);
expect(isNoProxyHost('api.example.com')).toBe(true);
expect(isNoProxyHost('example.com')).toBe(true);
expect(isNoProxyHost('notexample.com')).toBe(false);
expect(isNoProxyHost('api.other.com')).toBe(false);
delete process.env.NO_PROXY;
process.env.no_proxy = '*';
expect(isNoProxyHost('anything.com')).toBe(true);
});
});

it('配置代理后 dispatcher 走代理,未配置时走连接级 SSRF Agent', () => {
withEnv(
{ HTTPS_PROXY: undefined, https_proxy: undefined, HTTP_PROXY: undefined, http_proxy: undefined, NO_PROXY: undefined, no_proxy: undefined },
() => {
const direct = createUpstreamDispatcher({ url: 'https://example.com/x' });
expect(direct.constructor.name).toBe('Agent');

process.env.HTTPS_PROXY = 'http://127.0.0.1:7897';
const proxied = createUpstreamDispatcher({ url: 'https://example.com/x' });
expect(proxied.constructor.name).toBe('ProxyAgent');

// 命中 NO_PROXY 的目标仍然直连
process.env.NO_PROXY = 'example.com';
const bypassed = createUpstreamDispatcher({ url: 'https://example.com/x' });
expect(bypassed.constructor.name).toBe('Agent');
}
);
});
});
80 changes: 78 additions & 2 deletions src/lib/ssrf.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ import { AsyncLocalStorage } from 'node:async_hooks';
import type { LookupAddress } from 'node:dns';
import { lookup as callbackLookup } from 'node:dns';
import dns from 'node:dns/promises';
import { Agent, buildConnector, fetch as undiciFetch } from 'undici';
import { Agent, buildConnector, fetch as undiciFetch, ProxyAgent } from 'undici';
import type { Dispatcher } from 'undici';

/** 去掉 URL.hostname 对 IPv6 附加的方括号("[::1]" → "::1") */
function stripBrackets(host: string): string {
Expand Down Expand Up @@ -206,6 +207,78 @@ export function createSSRFAgent(options: { allowPrivate?: boolean } = {}): Agent
});
}

/**
* 读取部署者显式配置的出网代理地址;未配置返回 null。
*
* 只认 HTTPS_PROXY / https_proxy / HTTP_PROXY / http_proxy。macOS 的系统代理
* 设置(networksetup)不会被 Node/undici 继承,必须通过环境变量显式告知应用,
* 否则应用仍然直连,表现为「curl 走代理能通、应用里 403/超时」。
*/
export function getUpstreamProxyUrl(): string | null {
const raw =
process.env.HTTPS_PROXY ??
process.env.https_proxy ??
process.env.HTTP_PROXY ??
process.env.http_proxy;
if (!raw) return null;
let parsed: URL;
try {
parsed = new URL(raw);
} catch {
return null;
}
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return null;
return parsed.href;
}

/** 目标主机是否命中 NO_PROXY / no_proxy(命中则直连,不走代理) */
export function isNoProxyHost(hostname: string): boolean {
const raw = process.env.NO_PROXY ?? process.env.no_proxy;
if (!raw) return false;
const host = stripBrackets(hostname).toLowerCase();
for (const entry of raw.split(/[,\s]+/)) {
const item = entry.trim().toLowerCase();
if (!item) continue;
if (item === '*') return true;
const bare = item.startsWith('.') ? item.slice(1) : item;
if (host === bare || host.endsWith(`.${bare}`)) return true;
}
return false;
}

/** 从 fetch 入参里取出目标 URL(string / URL / Request 三种形态) */
function requestTargetUrl(input: RequestInfo | URL): string {
if (typeof input === 'string') return input;
if (input instanceof URL) return input.href;
return (input as Request).url ?? '';
}

/**
* 创建出网 dispatcher:配置了代理且目标未命中 NO_PROXY 时走 ProxyAgent,
* 否则走连接级 SSRF Agent。
*
* 走代理时连接层 SSRF 校验(safeLookup / ssrfConnect)不再生效——TCP 连接由
* 代理建立、目标域名也由代理解析。应用层校验(isValidProxyUrl + isBlockedByDNS)
* 在每次请求前仍然执行,内网/保留地址目标依旧会被拦下。
*/
export function createUpstreamDispatcher(
options: { allowPrivate?: boolean; url?: string } = {}
): Dispatcher {
const proxyUrl = getUpstreamProxyUrl();
if (proxyUrl) {
let targetHost = '';
try {
targetHost = new URL(options.url ?? '').hostname;
} catch {
targetHost = '';
}
if (!targetHost || !isNoProxyHost(targetHost)) {
return new ProxyAgent({ uri: proxyUrl });
}
}
return createSSRFAgent({ allowPrivate: options.allowPrivate });
}

const GLOBAL_FETCH_WRAPPED = Symbol.for('libretv.ssrf.fetch.wrapped');

/**
Expand Down Expand Up @@ -241,7 +314,10 @@ export function installFetchSSRFProtection(): void {
}

// 在受保护作用域内,如果未提供专属 dispatcher,自动注入安全专用的 Agent
const agent = createSSRFAgent({ allowPrivate: ctx.allowPrivate });
const agent = createUpstreamDispatcher({
allowPrivate: ctx.allowPrivate,
url: requestTargetUrl(input),
});
try {
// input/init 走 undici 自己的重载签名:DOM 的 Request 类型与 undici 的
// Request 类型在 duplex 上要求不同,直接传会报类型不兼容,这里只是同族对象互转
Expand Down
Loading