Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
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
11 changes: 7 additions & 4 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co

## 项目概览

Sublink Worker 是多平台代理订阅转换器:将各类协议(ShadowSocks/VMess/VLESS/Hysteria2/Trojan/TUIC)转为客户端配置(Sing-Box/Clash/Xray/Surge)。同一份代码跑在 Cloudflare Workers / Node.js / Vercel / Docker 上。技术栈:Hono(Web/JSX SSR)+ Vitest + Wrangler + esbuild + ioredis。
Sublink Worker 是多平台代理订阅转换器:将各类协议(ShadowSocks/VMess/VLESS/Hysteria2/Trojan/TUIC)转为客户端配置(Sing-Box/Clash/Xray/Surge/Quantumult X)。同一份代码跑在 Cloudflare Workers / Node.js / Vercel / Docker 上。技术栈:Hono(Web/JSX SSR)+ Vitest + Wrangler + esbuild + ioredis。

## 常用命令

Expand Down Expand Up @@ -47,18 +47,21 @@ Sublink Worker 是多平台代理订阅转换器:将各类协议(ShadowSocks

## 协议解析与配置构建

**ProxyParser**(`src/parsers/ProxyParser.js`)按 URL scheme 分发到 `src/parsers/protocols/<protocol>Parser.js`。HTTP(S) 订阅走 `httpSubscriptionFetcher` → `subscriptionContentParser`,自动识别 Sing-Box JSON / Clash YAML / Surge INI / Base64 列表。
**ProxyParser**(`src/parsers/ProxyParser.js`)按 URL scheme 分发到 `src/parsers/protocols/<protocol>Parser.js`。HTTP(S) 订阅走 `httpSubscriptionFetcher` → `subscriptionContentParser`,自动识别 Sing-Box JSON / Clash YAML / Surge INI / Quantumult X 节点行 / Base64 列表。

返回值约定:
- 协议 parser:`{ tag, type, ...protocolFields }`
- 订阅级 parser:`{ type: 'yamlConfig'|'singboxConfig'|'surgeConfig', config, proxies }`
- 订阅级 parser:`{ type: 'yamlConfig'|'singboxConfig'|'surgeConfig'|'quanxConfig', config, proxies }`(类型集合见 `BaseConfigBuilder` 的 `CONFIG_RESULT_TYPES`)
- 解析不出节点的输入行/订阅记入 builder 的 `inputDiagnostics`(QuanX 无节点时的 400 会列出)

**新增协议**:在 `src/parsers/protocols/` 加 parser,并在 `ProxyParser.js` 的 `protocolParsers` map 注册。

**Builder 模式**:`SingboxConfigBuilder` / `ClashConfigBuilder` / `SurgeConfigBuilder` 都继承 `BaseConfigBuilder`。子类必须实现:`getProxies()`、`getProxyName(proxy)`、`convertProxy(proxy)`、`addProxyToConfig(proxy)`、`addAutoSelectGroup(list)`、`addNodeSelectGroup(list)`、`addOutboundGroups(outbounds, list)`、`addCustomRuleGroups(list)`、`addFallBackGroup(list)`、`addCountryGroups()`、`formatConfig()`。
**Builder 模式**:`SingboxConfigBuilder` / `ClashConfigBuilder` / `SurgeConfigBuilder` / `QuanxConfigBuilder` 都继承 `BaseConfigBuilder`。子类必须实现:`getProxies()`、`getProxyName(proxy)`、`convertProxy(proxy)`、`addProxyToConfig(proxy)`、`addAutoSelectGroup(list)`、`addNodeSelectGroup(list)`、`addOutboundGroups(outbounds, list)`、`addCustomRuleGroups(list)`、`addFallBackGroup(list)`、`addCountryGroups()`、`formatConfig()`。

**Config Override**:订阅含完整配置时,`applyConfigOverrides()` 合并非代理字段到 base config;blacklist(proxies、rules、rule-providers)永远不被覆盖;Clash `proxy-groups` 可被订阅覆盖以保留用户分组结构。

QuanX(`/quanx`,短链前缀 `q`):不支持 hysteria2/tuic/grpc/xhttp/httpupgrade 等,节点输出为注释;一个可用节点都没有时返回 400 并列出跳过原因(不生成全 direct 配置);远程规则复用 Surge 规则源,依赖 `resource_parser_url` + `opt-parser=true` 在设备端转换;不接受订阅的 config override;拉上游订阅默认用 `clash.meta` UA(不转发 QuanX UA,也不用 curl)。基础配置(`configId` 前缀 `quanx_`)由服务端解析 INI 存为 `{ sections: { name: [lines] } }`,`[general]` 按 key 合并,`policy/server_local/filter_*` 永远由生成逻辑决定。`list=true` 只输出节点行(用作 QX 节点资源);TLS SNI 统一写 `tls-host`,`obfs-host` 只承载 ws/http Host(对齐 Sub-Store)。

国家分组逻辑在 `src/utils.js#groupProxiesByCountry`。

## 测试
Expand Down
56 changes: 54 additions & 2 deletions src/app/createApp.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { UpdateChecker } from '../components/UpdateChecker.jsx';
import { SingboxConfigBuilder } from '../builders/SingboxConfigBuilder.js';
import { ClashConfigBuilder } from '../builders/ClashConfigBuilder.js';
import { SurgeConfigBuilder } from '../builders/SurgeConfigBuilder.js';
import { QuanxConfigBuilder } from '../builders/QuanxConfigBuilder.js';
import { createTranslator, resolveLanguage } from '../i18n/index.js';
import { encodeBase64, tryDecodeSubscriptionLines } from '../utils.js';
import { APP_NAME, APP_SUBTITLE } from '../constants.js';
Expand All @@ -19,6 +20,7 @@ import { normalizeRuntime } from '../runtime/runtimeConfig.js';
import { PREDEFINED_RULE_SETS, SING_BOX_CONFIG, SING_BOX_CONFIG_V1_11, generateSubconverterConfig } from '../config/index.js';

const DEFAULT_USER_AGENT = 'curl/7.74.0';
const QUANX_UPSTREAM_USER_AGENT = 'clash.meta';

export function createApp(bindings = {}) {
const runtime = normalizeRuntime(bindings);
Expand Down Expand Up @@ -217,6 +219,55 @@ export function createApp(bindings = {}) {
}
});

app.get('/quanx', async (c) => {
try {
const config = c.req.query('config');
if (!config) {
return c.text('Missing config parameter', 400);
}

const selectedRules = parseSelectedRules(c.req.query('selectedRules'));
const customRules = parseJsonArray(c.req.query('customRules'));
// Panels pick the response format from the UA; curl often gets an empty/HTML answer and
// the QX app's own UA gets QX lines. A Clash UA yields the most widely served and most
// completely parsed format (Clash YAML); UA-agnostic sources (e.g. 3x-ui) are unaffected.
const ua = c.req.query('ua') || QUANX_UPSTREAM_USER_AGENT;
const groupByCountry = parseBooleanFlag(c.req.query('group_by_country'));
const includeAutoSelect = c.req.query('include_auto_select') !== 'false';
const configId = c.req.query('configId');
const lang = c.get('lang');

let baseConfig;
if (configId?.startsWith('quanx_')) {
const storage = requireConfigStorage(services.configStorage);
baseConfig = await storage.getConfigById(configId);
}

const builder = new QuanxConfigBuilder(
config,
selectedRules,
customRules,
baseConfig,
lang,
ua,
groupByCountry,
includeAutoSelect
);
// list=true serves only node lines, for use as a QX node resource ([server_remote])
const output = parseBooleanFlag(c.req.query('list'))
? await builder.buildNodeList()
: await builder.build();

const userinfo = builder.getSubscriptionUserinfo();
if (userinfo) {
c.header('subscription-userinfo', userinfo);
}
return c.text(output);
} catch (error) {
return handleError(c, error, runtime.logger);
}
});

app.get('/subconverter', (c) => {
try {
const rawSelectedRules = c.req.query('selectedRules');
Expand Down Expand Up @@ -350,6 +401,7 @@ export function createApp(bindings = {}) {
app.get('/b/:code', redirectHandler('singbox'));
app.get('/c/:code', redirectHandler('clash'));
app.get('/x/:code', redirectHandler('xray'));
app.get('/q/:code', redirectHandler('quanx'));

app.post('/config', async (c) => {
try {
Expand Down Expand Up @@ -382,13 +434,13 @@ export function createApp(bindings = {}) {

const prefix = pathParts[1];
const shortCode = pathParts[2];
if (!['b', 'c', 'x', 's'].includes(prefix)) return c.text(t('invalidShortUrl'), 400);
if (!['b', 'c', 'x', 's', 'q'].includes(prefix)) return c.text(t('invalidShortUrl'), 400);

const shortLinks = requireShortLinkService(services.shortLinks);
const originalParam = await shortLinks.resolveShortCode(shortCode);
if (!originalParam) return c.text(t('shortUrlNotFound'), 404);

const mapping = { b: 'singbox', c: 'clash', x: 'xray', s: 'surge' };
const mapping = { b: 'singbox', c: 'clash', x: 'xray', s: 'surge', q: 'quanx' };
const originalUrl = `${urlObj.origin}/${mapping[prefix]}${originalParam}`;
return c.json({ originalUrl });
} catch (error) {
Expand Down
38 changes: 32 additions & 6 deletions src/builders/BaseConfigBuilder.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,18 @@
import { ProxyParser } from '../parsers/index.js';
import { createStableProviderName, deepCopy, tryDecodeSubscriptionLines, decodeBase64 } from '../utils.js';
import { createStableProviderName, deepCopy, tryDecodeSubscriptionLines, decodeBase64, stripInvisibleChars, previewInput } from '../utils.js';
import { createTranslator } from '../i18n/index.js';
import { generateRules, getOutbounds, PREDEFINED_RULE_SETS } from '../config/index.js';

// Share links without a `#name` fragment parse with an empty tag and were silently dropped;
// name them after their endpoint so they still reach the output.
function withFallbackTag(item) {
if (item?.tag || !item?.type || !item?.server) return item;
return { ...item, tag: `${item.type} ${item.server}:${item.server_port}` };
}

// Subscription-level parser results that carry a proxies array (see subscriptionContentParser)
const CONFIG_RESULT_TYPES = new Set(['yamlConfig', 'singboxConfig', 'surgeConfig', 'quanxConfig']);

export class BaseConfigBuilder {
constructor(inputString, baseConfig, lang, userAgent, groupByCountry = false, includeAutoSelect = true) {
this.inputString = inputString;
Expand All @@ -18,6 +28,8 @@ export class BaseConfigBuilder {
this.providerNodeNames = []; // node names from provider subscriptions, for country enumeration only
this.autoProviderDescriptors = undefined;
this.subscriptionUserinfo = undefined;
// Input lines that yielded no proxy, kept so callers can explain an empty result
this.inputDiagnostics = [];
}

async build() {
Expand All @@ -28,7 +40,7 @@ export class BaseConfigBuilder {
}

async parseCustomItems() {
const input = this.inputString || '';
const input = stripInvisibleChars(this.inputString || '');
const parsedItems = [];

// Import the content parser for direct input parsing
Expand Down Expand Up @@ -93,8 +105,18 @@ export class BaseConfigBuilder {

try {
const fetchResult = await fetchSubscriptionWithFormat(trimmedUrl, this.userAgent);
if (!fetchResult) {
this.inputDiagnostics.push(`failed to fetch subscription: ${previewInput(trimmedUrl)}`);
}
if (fetchResult) {
const { content, format, url: originalUrl, subscriptionUserinfo } = fetchResult;
const parsedBefore = parsedItems.length;
// A fetched-but-unusable subscription is otherwise indistinguishable from empty input
const noteIfEmpty = () => {
if (parsedItems.length === parsedBefore) {
this.inputDiagnostics.push(`subscription returned no usable nodes: ${previewInput(trimmedUrl)} (content starts with: ${previewInput(content, 40)})`);
}
};

if (subscriptionUserinfo && !this.subscriptionUserinfo) {
this.subscriptionUserinfo = subscriptionUserinfo;
Expand All @@ -111,7 +133,7 @@ export class BaseConfigBuilder {

// Otherwise parse the content as usual
const result = parseSubscriptionContent(content);
if (result && typeof result === 'object' && (result.type === 'yamlConfig' || result.type === 'singboxConfig' || result.type === 'surgeConfig')) {
if (result && typeof result === 'object' && CONFIG_RESULT_TYPES.has(result.type)) {
if (result.config) {
this.applyConfigOverrides(result.config);
}
Expand All @@ -122,6 +144,7 @@ export class BaseConfigBuilder {
}
});
}
noteIfEmpty();
continue;
}
// Handle array of URIs or other formats
Expand All @@ -137,17 +160,18 @@ export class BaseConfigBuilder {
}
}
}
noteIfEmpty();
}
} catch (error) {
console.error('Error processing HTTP subscription:', error);
this.inputDiagnostics.push(`error processing subscription: ${previewInput(trimmedUrl)} (${previewInput(error?.message, 80)})`);
}
continue;
}

// Non-HTTP URLs (protocol URIs like ss://, vmess://, etc.)
const result = await ProxyParser.parse(processedUrl, this.userAgent);
// Handle yamlConfig, singboxConfig, and surgeConfig types (they have the same structure)
if (result && typeof result === 'object' && (result.type === 'yamlConfig' || result.type === 'singboxConfig' || result.type === 'surgeConfig')) {
if (result && typeof result === 'object' && CONFIG_RESULT_TYPES.has(result.type)) {
if (result.config) {
this.applyConfigOverrides(result.config);
}
Expand All @@ -173,6 +197,8 @@ export class BaseConfigBuilder {
}
} else if (result) {
parsedItems.push(result);
} else if (trimmedUrl) {
this.inputDiagnostics.push(`unrecognized input: ${previewInput(processedUrl)}`);
}
}
}
Expand Down Expand Up @@ -381,7 +407,7 @@ export class BaseConfigBuilder {
}

addCustomItems(customItems) {
const validItems = customItems.filter(item => item != null);
const validItems = customItems.filter(item => item != null).map(withFallbackTag);
validItems.forEach(item => {
if (item?.tag) {
const convertedProxy = this.convertProxy(item);
Expand Down
Loading