inbound-link.ts 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924
  1. import { Base64, Wireguard } from '@/utils';
  2. import type { Inbound } from '@/schemas/api/inbound';
  3. import type { VlessClient } from '@/schemas/protocols/inbound/vless';
  4. import type { VmessSecurity } from '@/schemas/protocols/inbound/vmess';
  5. import type {
  6. WireguardInboundPeer,
  7. WireguardInboundSettings,
  8. } from '@/schemas/protocols/inbound/wireguard';
  9. import type { ExternalProxyEntry } from '@/schemas/protocols/stream/external-proxy';
  10. import type { FinalMaskStreamSettings } from '@/schemas/protocols/stream/finalmask';
  11. import type { XHttpStreamSettings } from '@/schemas/protocols/stream/xhttp';
  12. import { getHeaderValue } from './headers';
  13. // Share-link generators. Each per-protocol fn takes a typed inbound plus
  14. // client overrides and returns a URL (or '' when the protocol doesn't
  15. // support shareable links). The helpers below were previously static
  16. // methods on the Inbound class; extracting them removes the
  17. // XrayCommonClass dependency and lets these run against Zod-parsed data
  18. // directly.
  19. type ForceTls = 'same' | 'tls' | 'none';
  20. // xHTTP headers ship as Record<string, string> on the wire (Zod schema)
  21. // rather than the legacy class's HeaderEntry[]. Lookup by case-folded key.
  22. function xhttpHostFallback(xhttp: XHttpStreamSettings | undefined): string {
  23. return getHeaderValue(xhttp?.headers, 'host');
  24. }
  25. // Pull the bidirectional SplitHTTPConfig fields out of xhttp into a
  26. // compact extra payload. Server-only fields (noSSEHeader, scMaxBufferedPosts,
  27. // scStreamUpServerSecs, serverMaxHeaderBytes) are excluded — the client
  28. // reading the share link wouldn't honor them. Mirrors the legacy
  29. // Inbound.buildXhttpExtra exactly so the shadow link snapshots line up.
  30. function buildXhttpExtra(xhttp: XHttpStreamSettings | undefined): Record<string, unknown> | null {
  31. if (!xhttp) return null;
  32. const extra: Record<string, unknown> = {};
  33. if (typeof xhttp.xPaddingBytes === 'string' && xhttp.xPaddingBytes.length > 0) {
  34. extra.xPaddingBytes = xhttp.xPaddingBytes;
  35. }
  36. if (xhttp.xPaddingObfsMode === true) {
  37. extra.xPaddingObfsMode = true;
  38. for (const k of ['xPaddingKey', 'xPaddingHeader', 'xPaddingPlacement', 'xPaddingMethod'] as const) {
  39. const v = xhttp[k];
  40. if (typeof v === 'string' && v.length > 0) extra[k] = v;
  41. }
  42. }
  43. const stringFields = [
  44. 'uplinkHTTPMethod',
  45. 'sessionPlacement',
  46. 'sessionKey',
  47. 'seqPlacement',
  48. 'seqKey',
  49. 'uplinkDataPlacement',
  50. 'uplinkDataKey',
  51. 'scMaxEachPostBytes',
  52. ] as const;
  53. for (const k of stringFields) {
  54. const v = xhttp[k];
  55. if (typeof v === 'string' && v.length > 0) extra[k] = v;
  56. }
  57. // Headers on the wire are a record; emit them as a map upstream's
  58. // SplitHTTPConfig.headers expects, dropping Host (already on the URL).
  59. if (xhttp.headers && Object.keys(xhttp.headers).length > 0) {
  60. const headersMap: Record<string, string> = {};
  61. for (const [name, value] of Object.entries(xhttp.headers)) {
  62. if (name.toLowerCase() === 'host') continue;
  63. headersMap[name] = value;
  64. }
  65. if (Object.keys(headersMap).length > 0) extra.headers = headersMap;
  66. }
  67. return Object.keys(extra).length > 0 ? extra : null;
  68. }
  69. function applyXhttpExtraToObj(xhttp: XHttpStreamSettings | undefined, obj: Record<string, unknown>): void {
  70. if (!xhttp) return;
  71. if (typeof xhttp.xPaddingBytes === 'string' && xhttp.xPaddingBytes.length > 0) {
  72. obj.x_padding_bytes = xhttp.xPaddingBytes;
  73. }
  74. const extra = buildXhttpExtra(xhttp);
  75. if (!extra) return;
  76. for (const [k, v] of Object.entries(extra)) obj[k] = v;
  77. }
  78. // Recursively checks whether a finalmask payload has any non-empty
  79. // content. Empty arrays / empty objects / empty strings all return false;
  80. // any truthy primitive returns true. Used to decide whether the link
  81. // should carry an `fm` blob at all.
  82. function hasShareableFinalMaskValue(value: unknown): boolean {
  83. if (value == null) return false;
  84. if (Array.isArray(value)) return value.some(hasShareableFinalMaskValue);
  85. if (typeof value === 'object') {
  86. return Object.values(value as Record<string, unknown>).some(hasShareableFinalMaskValue);
  87. }
  88. if (typeof value === 'string') return value.length > 0;
  89. return true;
  90. }
  91. function serializeFinalMask(finalmask: FinalMaskStreamSettings | undefined): string {
  92. if (!finalmask) return '';
  93. return hasShareableFinalMaskValue(finalmask) ? JSON.stringify(finalmask) : '';
  94. }
  95. function applyFinalMaskToObj(
  96. finalmask: FinalMaskStreamSettings | undefined,
  97. obj: Record<string, unknown>,
  98. ): void {
  99. const payload = serializeFinalMask(finalmask);
  100. if (payload.length > 0) obj.fm = payload;
  101. }
  102. function externalProxyAlpn(value: ExternalProxyEntry['alpn']): string {
  103. if (Array.isArray(value)) return value.filter(Boolean).join(',');
  104. return '';
  105. }
  106. function applyExternalProxyTLSObj(
  107. externalProxy: ExternalProxyEntry | null | undefined,
  108. obj: Record<string, unknown>,
  109. security: string,
  110. ): void {
  111. if (!externalProxy || security !== 'tls') return;
  112. const sni = externalProxy.sni && externalProxy.sni.length > 0 ? externalProxy.sni : externalProxy.dest;
  113. if (sni && sni.length > 0) obj.sni = sni;
  114. if (externalProxy.fingerprint && externalProxy.fingerprint.length > 0) obj.fp = externalProxy.fingerprint;
  115. const alpn = externalProxyAlpn(externalProxy.alpn);
  116. if (alpn.length > 0) obj.alpn = alpn;
  117. }
  118. export interface GenVmessLinkInput {
  119. inbound: Inbound;
  120. address: string;
  121. port?: number;
  122. forceTls?: ForceTls;
  123. remark?: string;
  124. clientId: string;
  125. security?: VmessSecurity;
  126. externalProxy?: ExternalProxyEntry | null;
  127. }
  128. // VMess share link: `vmess://` followed by base64-encoded JSON. The JSON
  129. // schema is the v2rayN-compatible "v2" shape. Returns '' if the inbound
  130. // is not vmess so dispatcher code can fall through cleanly.
  131. export function genVmessLink(input: GenVmessLinkInput): string {
  132. const {
  133. inbound,
  134. address,
  135. port = inbound.port,
  136. forceTls = 'same',
  137. remark = '',
  138. clientId,
  139. security,
  140. externalProxy = null,
  141. } = input;
  142. if (inbound.protocol !== 'vmess') return '';
  143. const stream = inbound.streamSettings;
  144. if (!stream) return '';
  145. const tls = forceTls === 'same' ? stream.security : forceTls;
  146. const obj: Record<string, unknown> = {
  147. v: '2',
  148. ps: remark,
  149. add: address,
  150. port,
  151. id: clientId,
  152. scy: security,
  153. net: stream.network,
  154. tls,
  155. };
  156. if (stream.network === 'tcp') {
  157. const tcp = stream.tcpSettings;
  158. const header = tcp.header;
  159. if (header) {
  160. obj.type = header.type;
  161. if (header.type === 'http') {
  162. const request = header.request;
  163. if (request) {
  164. obj.path = request.path.join(',');
  165. const host = getHeaderValue(request.headers, 'host');
  166. if (host) obj.host = host;
  167. }
  168. }
  169. } else {
  170. obj.type = 'none';
  171. }
  172. } else if (stream.network === 'kcp') {
  173. const kcp = stream.kcpSettings;
  174. obj.mtu = kcp.mtu;
  175. obj.tti = kcp.tti;
  176. } else if (stream.network === 'ws') {
  177. const ws = stream.wsSettings;
  178. obj.path = ws.path;
  179. obj.host = ws.host.length > 0 ? ws.host : getHeaderValue(ws.headers, 'host');
  180. } else if (stream.network === 'grpc') {
  181. const grpc = stream.grpcSettings;
  182. obj.path = grpc.serviceName;
  183. obj.authority = grpc.authority;
  184. if (grpc.multiMode) obj.type = 'multi';
  185. } else if (stream.network === 'httpupgrade') {
  186. const hu = stream.httpupgradeSettings;
  187. obj.path = hu.path;
  188. obj.host = hu.host.length > 0 ? hu.host : getHeaderValue(hu.headers, 'host');
  189. } else if (stream.network === 'xhttp') {
  190. const xhttp = stream.xhttpSettings;
  191. obj.path = xhttp.path;
  192. obj.host = xhttp.host.length > 0 ? xhttp.host : xhttpHostFallback(xhttp);
  193. obj.type = xhttp.mode;
  194. applyXhttpExtraToObj(xhttp, obj);
  195. }
  196. applyFinalMaskToObj(stream.finalmask, obj);
  197. if (tls === 'tls' && stream.security === 'tls') {
  198. const tlsSettings = stream.tlsSettings;
  199. if (tlsSettings.serverName.length > 0) obj.sni = tlsSettings.serverName;
  200. if (tlsSettings.settings.fingerprint.length > 0) obj.fp = tlsSettings.settings.fingerprint;
  201. if (tlsSettings.alpn.length > 0) obj.alpn = tlsSettings.alpn.join(',');
  202. }
  203. applyExternalProxyTLSObj(externalProxy, obj, tls);
  204. return 'vmess://' + Base64.encode(JSON.stringify(obj, null, 2));
  205. }
  206. // Param-style helpers (vless/trojan/ss/hysteria links). These mirror the
  207. // legacy applyXhttpExtraToParams / applyFinalMaskToParams /
  208. // applyExternalProxyTLSParams but write to a URLSearchParams instance
  209. // directly. Number values get coerced via .toString() on set — same as
  210. // what URLSearchParams does internally so the resulting URL bytes match.
  211. function applyXhttpExtraToParams(xhttp: XHttpStreamSettings | undefined, params: URLSearchParams): void {
  212. if (!xhttp) return;
  213. params.set('path', xhttp.path);
  214. const host = xhttp.host.length > 0 ? xhttp.host : xhttpHostFallback(xhttp);
  215. params.set('host', host);
  216. params.set('mode', xhttp.mode);
  217. if (typeof xhttp.xPaddingBytes === 'string' && xhttp.xPaddingBytes.length > 0) {
  218. params.set('x_padding_bytes', xhttp.xPaddingBytes);
  219. }
  220. const extra = buildXhttpExtra(xhttp);
  221. if (extra) params.set('extra', JSON.stringify(extra));
  222. }
  223. function applyFinalMaskToParams(finalmask: FinalMaskStreamSettings | undefined, params: URLSearchParams): void {
  224. const payload = serializeFinalMask(finalmask);
  225. if (payload.length > 0) params.set('fm', payload);
  226. }
  227. function applyExternalProxyTLSParams(
  228. externalProxy: ExternalProxyEntry | null | undefined,
  229. params: URLSearchParams,
  230. security: string,
  231. ): void {
  232. if (!externalProxy || security !== 'tls') return;
  233. const sni = externalProxy.sni && externalProxy.sni.length > 0 ? externalProxy.sni : externalProxy.dest;
  234. if (sni && sni.length > 0) params.set('sni', sni);
  235. if (externalProxy.fingerprint && externalProxy.fingerprint.length > 0) params.set('fp', externalProxy.fingerprint);
  236. const alpn = externalProxyAlpn(externalProxy.alpn);
  237. if (alpn.length > 0) params.set('alpn', alpn);
  238. }
  239. export interface GenVlessLinkInput {
  240. inbound: Inbound;
  241. address: string;
  242. port?: number;
  243. forceTls?: ForceTls;
  244. remark?: string;
  245. clientId: string;
  246. flow?: VlessClient['flow'];
  247. externalProxy?: ExternalProxyEntry | null;
  248. }
  249. // VLESS share link: vless://<uuid>@<host>:<port>?<query>#<remark>. The
  250. // query carries network type, encryption, network-specific knobs, and
  251. // security-specific knobs (TLS fingerprint/alpn/sni or Reality
  252. // pbk/sid/spx). Returns '' if the inbound isn't vless.
  253. export function genVlessLink(input: GenVlessLinkInput): string {
  254. const {
  255. inbound,
  256. address,
  257. port = inbound.port,
  258. forceTls = 'same',
  259. remark = '',
  260. clientId,
  261. flow = '',
  262. externalProxy = null,
  263. } = input;
  264. if (inbound.protocol !== 'vless') return '';
  265. const stream = inbound.streamSettings;
  266. if (!stream) return '';
  267. const security = forceTls === 'same' ? stream.security : forceTls;
  268. const params = new URLSearchParams();
  269. params.set('type', stream.network);
  270. params.set('encryption', inbound.settings.encryption);
  271. if (stream.network === 'tcp') {
  272. const tcp = stream.tcpSettings;
  273. if (tcp.header?.type === 'http') {
  274. const request = tcp.header.request;
  275. if (request) {
  276. params.set('path', request.path.join(','));
  277. const host = getHeaderValue(request.headers, 'host');
  278. if (host) params.set('host', host);
  279. params.set('headerType', 'http');
  280. }
  281. }
  282. } else if (stream.network === 'kcp') {
  283. const kcp = stream.kcpSettings;
  284. params.set('mtu', String(kcp.mtu));
  285. params.set('tti', String(kcp.tti));
  286. } else if (stream.network === 'ws') {
  287. const ws = stream.wsSettings;
  288. params.set('path', ws.path);
  289. params.set('host', ws.host.length > 0 ? ws.host : getHeaderValue(ws.headers, 'host'));
  290. } else if (stream.network === 'grpc') {
  291. const grpc = stream.grpcSettings;
  292. params.set('serviceName', grpc.serviceName);
  293. params.set('authority', grpc.authority);
  294. if (grpc.multiMode) params.set('mode', 'multi');
  295. } else if (stream.network === 'httpupgrade') {
  296. const hu = stream.httpupgradeSettings;
  297. params.set('path', hu.path);
  298. params.set('host', hu.host.length > 0 ? hu.host : getHeaderValue(hu.headers, 'host'));
  299. } else if (stream.network === 'xhttp') {
  300. applyXhttpExtraToParams(stream.xhttpSettings, params);
  301. }
  302. applyFinalMaskToParams(stream.finalmask, params);
  303. if (security === 'tls') {
  304. params.set('security', 'tls');
  305. if (stream.security === 'tls') {
  306. const tls = stream.tlsSettings;
  307. params.set('fp', tls.settings.fingerprint);
  308. params.set('alpn', tls.alpn.join(','));
  309. if (tls.serverName.length > 0) params.set('sni', tls.serverName);
  310. if (tls.settings.echConfigList.length > 0) params.set('ech', tls.settings.echConfigList);
  311. if (stream.network === 'tcp' && flow.length > 0) params.set('flow', flow);
  312. }
  313. applyExternalProxyTLSParams(externalProxy, params, security);
  314. } else if (security === 'reality') {
  315. params.set('security', 'reality');
  316. if (stream.security === 'reality') {
  317. const reality = stream.realitySettings;
  318. params.set('pbk', reality.settings.publicKey);
  319. params.set('fp', reality.settings.fingerprint);
  320. // Legacy parity quirk: the old class stored realitySettings.serverNames
  321. // as a comma-joined string and gated SNI on `!ObjectUtil.isArrEmpty(s)`
  322. // — which returns true for any string, so SNI was never written into
  323. // Reality share links. Existing deployed clients rely on receiving
  324. // the SNI from realitySettings.target instead; we keep the omission
  325. // here so this extraction stays byte-stable with the legacy URL.
  326. // Fixing the bug is a separate intentional commit.
  327. if (reality.shortIds.length > 0) params.set('sid', reality.shortIds[0]);
  328. if (reality.settings.spiderX.length > 0) params.set('spx', reality.settings.spiderX);
  329. if (reality.settings.mldsa65Verify.length > 0) params.set('pqv', reality.settings.mldsa65Verify);
  330. if (stream.network === 'tcp' && flow.length > 0) params.set('flow', flow);
  331. }
  332. } else {
  333. params.set('security', 'none');
  334. }
  335. const url = new URL(`vless://${clientId}@${address}:${port}`);
  336. for (const [key, value] of params) url.searchParams.set(key, value);
  337. url.hash = encodeURIComponent(remark);
  338. return url.toString();
  339. }
  340. // Shared network-branch writer used by trojan + shadowsocks links.
  341. // VLESS and VMess don't call this because they have minor per-protocol
  342. // quirks inline (vmess maps `multi` differently into obj.type; vless sets
  343. // encryption=none up-front).
  344. function writeNetworkParams(stream: NonNullable<Inbound['streamSettings']>, params: URLSearchParams): void {
  345. if (stream.network === 'tcp') {
  346. const tcp = stream.tcpSettings;
  347. if (tcp.header?.type === 'http') {
  348. const request = tcp.header.request;
  349. if (request) {
  350. params.set('path', request.path.join(','));
  351. const host = getHeaderValue(request.headers, 'host');
  352. if (host) params.set('host', host);
  353. params.set('headerType', 'http');
  354. }
  355. }
  356. } else if (stream.network === 'kcp') {
  357. const kcp = stream.kcpSettings;
  358. params.set('mtu', String(kcp.mtu));
  359. params.set('tti', String(kcp.tti));
  360. } else if (stream.network === 'ws') {
  361. const ws = stream.wsSettings;
  362. params.set('path', ws.path);
  363. params.set('host', ws.host.length > 0 ? ws.host : getHeaderValue(ws.headers, 'host'));
  364. } else if (stream.network === 'grpc') {
  365. const grpc = stream.grpcSettings;
  366. params.set('serviceName', grpc.serviceName);
  367. params.set('authority', grpc.authority);
  368. if (grpc.multiMode) params.set('mode', 'multi');
  369. } else if (stream.network === 'httpupgrade') {
  370. const hu = stream.httpupgradeSettings;
  371. params.set('path', hu.path);
  372. params.set('host', hu.host.length > 0 ? hu.host : getHeaderValue(hu.headers, 'host'));
  373. } else if (stream.network === 'xhttp') {
  374. applyXhttpExtraToParams(stream.xhttpSettings, params);
  375. }
  376. }
  377. function writeTlsParams(stream: NonNullable<Inbound['streamSettings']>, params: URLSearchParams): void {
  378. if (stream.security !== 'tls') return;
  379. const tls = stream.tlsSettings;
  380. params.set('fp', tls.settings.fingerprint);
  381. params.set('alpn', tls.alpn.join(','));
  382. if (tls.settings.echConfigList.length > 0) params.set('ech', tls.settings.echConfigList);
  383. if (tls.serverName.length > 0) params.set('sni', tls.serverName);
  384. }
  385. // Reality query-string writer shared by VLESS and Trojan. Preserves the
  386. // legacy SNI-omission quirk (see genVlessLink for the full story).
  387. function writeRealityParams(stream: NonNullable<Inbound['streamSettings']>, params: URLSearchParams): void {
  388. if (stream.security !== 'reality') return;
  389. const reality = stream.realitySettings;
  390. params.set('pbk', reality.settings.publicKey);
  391. params.set('fp', reality.settings.fingerprint);
  392. if (reality.shortIds.length > 0) params.set('sid', reality.shortIds[0]);
  393. if (reality.settings.spiderX.length > 0) params.set('spx', reality.settings.spiderX);
  394. if (reality.settings.mldsa65Verify.length > 0) params.set('pqv', reality.settings.mldsa65Verify);
  395. }
  396. export interface GenTrojanLinkInput {
  397. inbound: Inbound;
  398. address: string;
  399. port?: number;
  400. forceTls?: ForceTls;
  401. remark?: string;
  402. clientPassword: string;
  403. externalProxy?: ExternalProxyEntry | null;
  404. }
  405. // Trojan share link: trojan://<password>@<host>:<port>?<query>#<remark>.
  406. // Same query-string shape as VLESS minus the `encryption` and `flow`
  407. // fields. Returns '' if the inbound isn't trojan.
  408. export function genTrojanLink(input: GenTrojanLinkInput): string {
  409. const {
  410. inbound,
  411. address,
  412. port = inbound.port,
  413. forceTls = 'same',
  414. remark = '',
  415. clientPassword,
  416. externalProxy = null,
  417. } = input;
  418. if (inbound.protocol !== 'trojan') return '';
  419. const stream = inbound.streamSettings;
  420. if (!stream) return '';
  421. const security = forceTls === 'same' ? stream.security : forceTls;
  422. const params = new URLSearchParams();
  423. params.set('type', stream.network);
  424. writeNetworkParams(stream, params);
  425. applyFinalMaskToParams(stream.finalmask, params);
  426. if (security === 'tls') {
  427. params.set('security', 'tls');
  428. writeTlsParams(stream, params);
  429. applyExternalProxyTLSParams(externalProxy, params, security);
  430. } else if (security === 'reality') {
  431. params.set('security', 'reality');
  432. writeRealityParams(stream, params);
  433. } else {
  434. params.set('security', 'none');
  435. }
  436. const url = new URL(`trojan://${clientPassword}@${address}:${port}`);
  437. for (const [key, value] of params) url.searchParams.set(key, value);
  438. url.hash = encodeURIComponent(remark);
  439. return url.toString();
  440. }
  441. export interface GenShadowsocksLinkInput {
  442. inbound: Inbound;
  443. address: string;
  444. port?: number;
  445. forceTls?: ForceTls;
  446. remark?: string;
  447. clientPassword?: string;
  448. externalProxy?: ExternalProxyEntry | null;
  449. }
  450. // Shadowsocks 2022 share link. The userinfo portion is base64(method:pw)
  451. // for single-user and base64(method:settingsPw:clientPw) for multi-user
  452. // 2022-blake3. Legacy SS (non-2022) leaves the password out of the
  453. // userinfo entirely — matches the legacy class's password-array logic.
  454. // Note: legacy `isSSMultiUser` returns true for everything except
  455. // 2022-blake3-chacha20-poly1305 (a curious classification, but we
  456. // preserve it for byte-stable parity).
  457. export function genShadowsocksLink(input: GenShadowsocksLinkInput): string {
  458. const {
  459. inbound,
  460. address,
  461. port = inbound.port,
  462. forceTls = 'same',
  463. remark = '',
  464. clientPassword = '',
  465. externalProxy = null,
  466. } = input;
  467. if (inbound.protocol !== 'shadowsocks') return '';
  468. const stream = inbound.streamSettings;
  469. if (!stream) return '';
  470. const settings = inbound.settings;
  471. const security = forceTls === 'same' ? stream.security : forceTls;
  472. const params = new URLSearchParams();
  473. params.set('type', stream.network);
  474. writeNetworkParams(stream, params);
  475. applyFinalMaskToParams(stream.finalmask, params);
  476. if (security === 'tls') {
  477. params.set('security', 'tls');
  478. writeTlsParams(stream, params);
  479. applyExternalProxyTLSParams(externalProxy, params, security);
  480. }
  481. const isSS2022 = settings.method.substring(0, 4) === '2022';
  482. const isSSMultiUser = settings.method !== '2022-blake3-chacha20-poly1305';
  483. const passwords: string[] = [];
  484. if (isSS2022) passwords.push(settings.password);
  485. if (isSSMultiUser) passwords.push(clientPassword);
  486. const userinfo = Base64.encode(`${settings.method}:${passwords.join(':')}`, true);
  487. const url = new URL(`ss://${userinfo}@${address}:${port}`);
  488. for (const [key, value] of params) url.searchParams.set(key, value);
  489. url.hash = encodeURIComponent(remark);
  490. return url.toString();
  491. }
  492. export interface GenHysteriaLinkInput {
  493. inbound: Inbound;
  494. address: string;
  495. port?: number;
  496. remark?: string;
  497. clientAuth: string;
  498. }
  499. // Hysteria share link: hysteria://<auth>@<host>:<port>?<query>#<remark>.
  500. // The URL scheme is "hysteria2" when settings.version === 2 (hysteria v2
  501. // AKA hysteria2), "hysteria" otherwise. Salamander obfuscation pulls its
  502. // password from finalmask.udp[type=salamander] when present; the broader
  503. // finalmask payload still rides under `fm` like the other links.
  504. //
  505. // Note: legacy genHysteriaLink reads stream.tls.settings.allowInsecure,
  506. // which isn't a field on TlsStreamSettings.Settings — the guard is always
  507. // false. We omit the `insecure` param here to stay byte-stable.
  508. export function genHysteriaLink(input: GenHysteriaLinkInput): string {
  509. const {
  510. inbound,
  511. address,
  512. port = inbound.port,
  513. remark = '',
  514. clientAuth,
  515. } = input;
  516. if (inbound.protocol !== 'hysteria' && inbound.protocol !== 'hysteria2') return '';
  517. const stream = inbound.streamSettings;
  518. if (!stream || stream.security !== 'tls') return '';
  519. const settings = inbound.settings;
  520. const scheme = settings.version === 2 ? 'hysteria2' : 'hysteria';
  521. const params = new URLSearchParams();
  522. params.set('security', 'tls');
  523. const tls = stream.tlsSettings;
  524. if (tls.settings.fingerprint.length > 0) params.set('fp', tls.settings.fingerprint);
  525. if (tls.alpn.length > 0) params.set('alpn', tls.alpn.join(','));
  526. if (tls.settings.echConfigList.length > 0) params.set('ech', tls.settings.echConfigList);
  527. if (tls.serverName.length > 0) params.set('sni', tls.serverName);
  528. const udpMasks = stream.finalmask?.udp;
  529. if (Array.isArray(udpMasks)) {
  530. const salamander = udpMasks.find((m) => m?.type === 'salamander');
  531. const obfsPassword = salamander?.settings?.password;
  532. if (typeof obfsPassword === 'string' && obfsPassword.length > 0) {
  533. params.set('obfs', 'salamander');
  534. params.set('obfs-password', obfsPassword);
  535. }
  536. }
  537. applyFinalMaskToParams(stream.finalmask, params);
  538. const url = new URL(`${scheme}://${clientAuth}@${address}:${port}`);
  539. for (const [key, value] of params) url.searchParams.set(key, value);
  540. url.hash = encodeURIComponent(remark);
  541. return url.toString();
  542. }
  543. export interface GenWireguardLinkInput {
  544. settings: WireguardInboundSettings;
  545. address: string;
  546. port: number;
  547. remark?: string;
  548. peerIndex: number;
  549. }
  550. // Wireguard share link: wireguard://<peerPrivKey>@<host>:<port>
  551. // ?publickey=<serverPub>&address=<peerAllowedIP>&mtu=<mtu>#<remark>
  552. // pubKey is derived from the server's secretKey via Wireguard.generateKeypair
  553. // at call time (Zod's schema stores secretKey only — pubKey isn't on the
  554. // wire). Returns '' when the peer index is out of bounds.
  555. export function genWireguardLink(input: GenWireguardLinkInput): string {
  556. const { settings, address, port, remark = '', peerIndex } = input;
  557. const peer = settings.peers[peerIndex];
  558. if (!peer) return '';
  559. const url = new URL(`wireguard://${address}:${port}`);
  560. url.username = peer.privateKey ?? '';
  561. const pubKey = settings.secretKey.length > 0
  562. ? Wireguard.generateKeypair(settings.secretKey).publicKey
  563. : '';
  564. if (pubKey.length > 0) url.searchParams.set('publickey', pubKey);
  565. if (peer.allowedIPs.length > 0 && peer.allowedIPs[0]) {
  566. url.searchParams.set('address', peer.allowedIPs[0]);
  567. }
  568. if (typeof settings.mtu === 'number' && settings.mtu > 0) {
  569. url.searchParams.set('mtu', String(settings.mtu));
  570. }
  571. url.hash = encodeURIComponent(remark);
  572. return url.toString();
  573. }
  574. // Plain-text WireGuard client config (.conf format). Mirrors the legacy
  575. // getWireguardTxt — same DNS defaults (1.1.1.1, 1.0.0.1), MTU optional,
  576. // presharedKey + keepAlive only emitted when present on the peer. The
  577. // final newline structure follows the legacy: no newline after Endpoint,
  578. // optional preSharedKey appended with leading \n, keepAlive appended
  579. // with leading \n AND trailing \n.
  580. export function genWireguardConfig(input: GenWireguardLinkInput): string {
  581. const { settings, address, port, remark = '', peerIndex } = input;
  582. const peer = settings.peers[peerIndex];
  583. if (!peer) return '';
  584. const pubKey = settings.secretKey.length > 0
  585. ? Wireguard.generateKeypair(settings.secretKey).publicKey
  586. : '';
  587. let txt = `[Interface]\n`;
  588. txt += `PrivateKey = ${peer.privateKey ?? ''}\n`;
  589. txt += `Address = ${peer.allowedIPs[0] ?? ''}\n`;
  590. txt += `DNS = 1.1.1.1, 1.0.0.1\n`;
  591. if (typeof settings.mtu === 'number' && settings.mtu > 0) {
  592. txt += `MTU = ${settings.mtu}\n`;
  593. }
  594. txt += `\n# ${remark}\n`;
  595. txt += `[Peer]\n`;
  596. txt += `PublicKey = ${pubKey}\n`;
  597. txt += `AllowedIPs = 0.0.0.0/0, ::/0\n`;
  598. txt += `Endpoint = ${address}:${port}`;
  599. if (peer.preSharedKey && peer.preSharedKey.length > 0) {
  600. txt += `\nPresharedKey = ${peer.preSharedKey}`;
  601. }
  602. if (typeof peer.keepAlive === 'number' && peer.keepAlive > 0) {
  603. txt += `\nPersistentKeepalive = ${peer.keepAlive}\n`;
  604. }
  605. return txt;
  606. }
  607. export type { WireguardInboundPeer };
  608. // Orchestrators.
  609. // resolveAddr picks the host that goes into share/sub links. Order:
  610. // 1. hostOverride (caller supplies node address for node-managed inbounds)
  611. // 2. inbound's bind listen (when explicit, not 0.0.0.0)
  612. // 3. fallbackHostname (caller-supplied — typically window.location.hostname
  613. // in the browser; tests pass a fixed value)
  614. export function resolveAddr(inbound: Inbound, hostOverride: string, fallbackHostname: string): string {
  615. if (hostOverride.length > 0) return hostOverride;
  616. if (inbound.listen.length > 0 && inbound.listen !== '0.0.0.0') return inbound.listen;
  617. return fallbackHostname;
  618. }
  619. // Returns the client array for protocols that have one. SS returns its
  620. // clients only in 2022-blake3 multi-user mode (matches the legacy
  621. // `this.clients` getter, which used isSSMultiUser to gate). Returns null
  622. // for SS single-user, http, mixed, tunnel, wireguard, hysteria2-without-
  623. // clients, and any protocol without a clients array.
  624. type ClientShape = { id?: string; security?: VmessSecurity; flow?: VlessClient['flow']; password?: string; auth?: string; email?: string };
  625. export function getInboundClients(inbound: Inbound): ClientShape[] | null {
  626. switch (inbound.protocol) {
  627. case 'vmess':
  628. return (inbound.settings.clients ?? []) as ClientShape[];
  629. case 'vless':
  630. return (inbound.settings.clients ?? []) as ClientShape[];
  631. case 'trojan':
  632. return (inbound.settings.clients ?? []) as ClientShape[];
  633. case 'hysteria':
  634. case 'hysteria2':
  635. return (inbound.settings.clients ?? []) as ClientShape[];
  636. case 'shadowsocks': {
  637. const isMultiUser = inbound.settings.method !== '2022-blake3-chacha20-poly1305';
  638. return isMultiUser ? ((inbound.settings.clients ?? []) as ClientShape[]) : null;
  639. }
  640. default:
  641. return null;
  642. }
  643. }
  644. export interface GenLinkInput {
  645. inbound: Inbound;
  646. address: string;
  647. port?: number;
  648. forceTls?: ForceTls;
  649. remark?: string;
  650. client: ClientShape;
  651. externalProxy?: ExternalProxyEntry | null;
  652. }
  653. // Per-protocol dispatcher matching the legacy `genLink` switch. Returns
  654. // '' for protocols that don't have client-based share links (wireguard
  655. // goes through genWireguardLinks/Configs separately, http/mixed/tunnel
  656. // don't have share URLs).
  657. export function genLink(input: GenLinkInput): string {
  658. const { inbound, address, port = inbound.port, forceTls = 'same', remark = '', client, externalProxy = null } = input;
  659. switch (inbound.protocol) {
  660. case 'vmess':
  661. return genVmessLink({
  662. inbound, address, port, forceTls, remark,
  663. clientId: client.id ?? '',
  664. security: client.security,
  665. externalProxy,
  666. });
  667. case 'vless':
  668. return genVlessLink({
  669. inbound, address, port, forceTls, remark,
  670. clientId: client.id ?? '',
  671. flow: client.flow,
  672. externalProxy,
  673. });
  674. case 'shadowsocks': {
  675. const isMultiUser = inbound.settings.method !== '2022-blake3-chacha20-poly1305';
  676. return genShadowsocksLink({
  677. inbound, address, port, forceTls, remark,
  678. clientPassword: isMultiUser ? (client.password ?? '') : '',
  679. externalProxy,
  680. });
  681. }
  682. case 'trojan':
  683. return genTrojanLink({
  684. inbound, address, port, forceTls, remark,
  685. clientPassword: client.password ?? '',
  686. externalProxy,
  687. });
  688. case 'hysteria':
  689. case 'hysteria2':
  690. return genHysteriaLink({
  691. inbound, address, port, remark,
  692. clientAuth: client.auth ?? '',
  693. });
  694. default:
  695. return '';
  696. }
  697. }
  698. export interface GenAllLinksEntry {
  699. remark: string;
  700. link: string;
  701. }
  702. export interface GenAllLinksInput {
  703. inbound: Inbound;
  704. remark?: string;
  705. remarkModel?: string;
  706. client: ClientShape;
  707. hostOverride?: string;
  708. fallbackHostname: string;
  709. }
  710. // Fans out a single client's link per externalProxy entry, or just one
  711. // link when there are no external proxies. remarkModel is a 4-char
  712. // string: first char is the separator, remaining chars pick which
  713. // pieces to compose into the per-link remark — 'i' = inbound remark,
  714. // 'e' = client email, 'o' = externalProxy remark. Defaults to '-ieo'
  715. // (dash-separated, inbound + email + proxy).
  716. export function genAllLinks(input: GenAllLinksInput): GenAllLinksEntry[] {
  717. const {
  718. inbound,
  719. remark = '',
  720. remarkModel = '-ieo',
  721. client,
  722. hostOverride = '',
  723. fallbackHostname,
  724. } = input;
  725. const addr = resolveAddr(inbound, hostOverride, fallbackHostname);
  726. const port = inbound.port;
  727. const separationChar = remarkModel.charAt(0);
  728. const orderChars = remarkModel.slice(1);
  729. const email = client.email ?? '';
  730. const composeRemark = (proxyRemark: string): string => {
  731. const orders: Record<string, string> = { i: remark, e: email, o: proxyRemark };
  732. return orderChars.split('')
  733. .map((c) => orders[c] ?? '')
  734. .filter((x) => x.length > 0)
  735. .join(separationChar);
  736. };
  737. const externals = inbound.streamSettings?.externalProxy;
  738. if (!externals || externals.length === 0) {
  739. const r = composeRemark('');
  740. return [{ remark: r, link: genLink({ inbound, address: addr, port, forceTls: 'same', remark: r, client }) }];
  741. }
  742. return externals.map((ep) => {
  743. const r = composeRemark(ep.remark);
  744. return {
  745. remark: r,
  746. link: genLink({
  747. inbound,
  748. address: ep.dest,
  749. port: ep.port,
  750. forceTls: ep.forceTls,
  751. remark: r,
  752. client,
  753. externalProxy: ep,
  754. }),
  755. };
  756. });
  757. }
  758. export interface GenInboundLinksInput {
  759. inbound: Inbound;
  760. remark?: string;
  761. remarkModel?: string;
  762. hostOverride?: string;
  763. fallbackHostname: string;
  764. }
  765. // Top-level entrypoint that produces the full \r\n-joined block a user
  766. // pastes into a client. Iterates per-client for protocols with clients,
  767. // falls back to a single SS link for single-user 2022-blake3-chacha20,
  768. // and emits per-peer .conf blocks for wireguard. Returns '' for the
  769. // other clientless protocols (http, mixed, tunnel).
  770. export function genInboundLinks(input: GenInboundLinksInput): string {
  771. const {
  772. inbound,
  773. remark = '',
  774. remarkModel = '-ieo',
  775. hostOverride = '',
  776. fallbackHostname,
  777. } = input;
  778. const addr = resolveAddr(inbound, hostOverride, fallbackHostname);
  779. const clients = getInboundClients(inbound);
  780. if (clients) {
  781. const links: string[] = [];
  782. for (const client of clients) {
  783. const entries = genAllLinks({ inbound, remark, remarkModel, client, hostOverride, fallbackHostname });
  784. for (const e of entries) links.push(e.link);
  785. }
  786. return links.join('\r\n');
  787. }
  788. if (inbound.protocol === 'shadowsocks') {
  789. return genShadowsocksLink({ inbound, address: addr, port: inbound.port, forceTls: 'same', remark });
  790. }
  791. if (inbound.protocol === 'wireguard') {
  792. return genWireguardConfigs({ inbound, remark, remarkModel, hostOverride, fallbackHostname });
  793. }
  794. return '';
  795. }
  796. // Per-peer wireguard fanout. Each peer gets its own link (or .conf
  797. // block) with an index-suffixed remark, joined by \r\n. Matches the
  798. // legacy genWireguardLinks / genWireguardConfigs exactly.
  799. export interface GenWireguardFanoutInput {
  800. inbound: Inbound;
  801. remark?: string;
  802. remarkModel?: string;
  803. hostOverride?: string;
  804. fallbackHostname: string;
  805. }
  806. export function genWireguardLinks(input: GenWireguardFanoutInput): string {
  807. const { inbound, remark = '', remarkModel = '-ieo', hostOverride = '', fallbackHostname } = input;
  808. if (inbound.protocol !== 'wireguard') return '';
  809. const addr = resolveAddr(inbound, hostOverride, fallbackHostname);
  810. const sep = remarkModel.charAt(0);
  811. return inbound.settings.peers
  812. .map((_p, i) => genWireguardLink({
  813. settings: inbound.settings as WireguardInboundSettings,
  814. address: addr,
  815. port: inbound.port,
  816. remark: `${remark}${sep}${i + 1}`,
  817. peerIndex: i,
  818. }))
  819. .join('\r\n');
  820. }
  821. export function genWireguardConfigs(input: GenWireguardFanoutInput): string {
  822. const { inbound, remark = '', remarkModel = '-ieo', hostOverride = '', fallbackHostname } = input;
  823. if (inbound.protocol !== 'wireguard') return '';
  824. const addr = resolveAddr(inbound, hostOverride, fallbackHostname);
  825. const sep = remarkModel.charAt(0);
  826. return inbound.settings.peers
  827. .map((_p, i) => genWireguardConfig({
  828. settings: inbound.settings as WireguardInboundSettings,
  829. address: addr,
  830. port: inbound.port,
  831. remark: `${remark}${sep}${i + 1}`,
  832. peerIndex: i,
  833. }))
  834. .join('\r\n');
  835. }