inbound-link.ts 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305
  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/shared/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. import { canEnableTlsFlow } from './protocol-capabilities';
  14. import { deriveSpiderX } from './spider-x';
  15. // Share-link generators. Each per-protocol fn takes a typed inbound plus
  16. // client overrides and returns a URL (or '' when the protocol doesn't
  17. // support shareable links). The helpers below were previously static
  18. // methods on the Inbound class; extracting them removes the
  19. // XrayCommonClass dependency and lets these run against Zod-parsed data
  20. // directly.
  21. type ForceTls = 'same' | 'tls' | 'none';
  22. const SHARE_HOSTNAME_RE = /^[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?)*$/;
  23. // Format a host for interpolation into a URL authority. IPv6 literals are
  24. // wrapped in square brackets per RFC 3986; IPv4 and hostnames are left as-is.
  25. // Any brackets already present are first stripped so the helper is idempotent.
  26. function formatUrlHost(address: string): string {
  27. const bare = address.replace(/^\[|\]$/g, '');
  28. return bare.includes(':') ? `[${bare}]` : bare;
  29. }
  30. // xHTTP headers ship as Record<string, string> on the wire (Zod schema)
  31. // rather than the legacy class's HeaderEntry[]. Lookup by case-folded key.
  32. function xhttpHostFallback(xhttp: XHttpStreamSettings | undefined): string {
  33. return getHeaderValue(xhttp?.headers, 'host');
  34. }
  35. // Pull the bidirectional SplitHTTPConfig fields out of xhttp into a
  36. // compact extra payload. Server-only fields (noSSEHeader, scMaxBufferedPosts,
  37. // scStreamUpServerSecs, serverMaxHeaderBytes) are excluded — the client
  38. // reading the share link wouldn't honor them. Mirrors the legacy
  39. // Inbound.buildXhttpExtra exactly so the shadow link snapshots line up.
  40. function buildXhttpExtra(xhttp: XHttpStreamSettings | undefined): Record<string, unknown> | null {
  41. if (!xhttp) return null;
  42. const extra: Record<string, unknown> = {};
  43. if (typeof xhttp.mode === 'string' && xhttp.mode.length > 0) {
  44. extra.mode = xhttp.mode;
  45. }
  46. if (typeof xhttp.xPaddingBytes === 'string' && xhttp.xPaddingBytes.length > 0) {
  47. extra.xPaddingBytes = xhttp.xPaddingBytes;
  48. }
  49. if (xhttp.xPaddingObfsMode === true) {
  50. extra.xPaddingObfsMode = true;
  51. for (const k of ['xPaddingKey', 'xPaddingHeader', 'xPaddingPlacement', 'xPaddingMethod'] as const) {
  52. const v = xhttp[k];
  53. if (typeof v === 'string' && v.length > 0) extra[k] = v;
  54. }
  55. }
  56. const stringFields = [
  57. 'uplinkHTTPMethod',
  58. 'sessionIDPlacement',
  59. 'sessionIDKey',
  60. 'sessionIDTable',
  61. 'sessionIDLength',
  62. 'seqPlacement',
  63. 'seqKey',
  64. 'uplinkDataPlacement',
  65. 'uplinkDataKey',
  66. 'scMaxEachPostBytes',
  67. ] as const;
  68. // Values matching xray-core's own defaults stay off the wire — old panels
  69. // seeded them into every config and the literal values are a DPI
  70. // fingerprint (#5141). Mirrors the sub service's filter.
  71. const coreDefaults: Partial<Record<(typeof stringFields)[number], string>> = {
  72. scMaxEachPostBytes: '1000000',
  73. };
  74. for (const k of stringFields) {
  75. const v = xhttp[k];
  76. if (typeof v === 'string' && v.length > 0 && v !== coreDefaults[k]) extra[k] = v;
  77. }
  78. // Headers on the wire are a record; emit them as a map upstream's
  79. // SplitHTTPConfig.headers expects, dropping Host (already on the URL).
  80. if (xhttp.headers && Object.keys(xhttp.headers).length > 0) {
  81. const headersMap: Record<string, string> = {};
  82. for (const [name, value] of Object.entries(xhttp.headers)) {
  83. if (name.toLowerCase() === 'host') continue;
  84. headersMap[name] = value;
  85. }
  86. if (Object.keys(headersMap).length > 0) extra.headers = headersMap;
  87. }
  88. return Object.keys(extra).length > 0 ? extra : null;
  89. }
  90. function applyXhttpExtraToObj(xhttp: XHttpStreamSettings | undefined, obj: Record<string, unknown>): void {
  91. if (!xhttp) return;
  92. if (typeof xhttp.xPaddingBytes === 'string' && xhttp.xPaddingBytes.length > 0) {
  93. obj.x_padding_bytes = xhttp.xPaddingBytes;
  94. }
  95. const extra = buildXhttpExtra(xhttp);
  96. if (!extra) return;
  97. for (const [k, v] of Object.entries(extra)) obj[k] = v;
  98. }
  99. // Recursively checks whether a finalmask payload has any non-empty
  100. // content. Empty arrays / empty objects / empty strings all return false;
  101. // any truthy primitive returns true. Used to decide whether the link
  102. // should carry an `fm` blob at all.
  103. function hasShareableFinalMaskValue(value: unknown): boolean {
  104. if (value == null) return false;
  105. if (Array.isArray(value)) return value.some(hasShareableFinalMaskValue);
  106. if (typeof value === 'object') {
  107. return Object.values(value as Record<string, unknown>).some(hasShareableFinalMaskValue);
  108. }
  109. if (typeof value === 'string') return value.length > 0;
  110. return true;
  111. }
  112. function serializeFinalMask(finalmask: FinalMaskStreamSettings | undefined): string {
  113. if (!finalmask) return '';
  114. return hasShareableFinalMaskValue(finalmask) ? JSON.stringify(finalmask) : '';
  115. }
  116. function applyFinalMaskToObj(
  117. finalmask: FinalMaskStreamSettings | undefined,
  118. obj: Record<string, unknown>,
  119. ): void {
  120. const payload = serializeFinalMask(finalmask);
  121. if (payload.length > 0) obj.fm = payload;
  122. }
  123. function externalProxyAlpn(value: ExternalProxyEntry['alpn']): string {
  124. if (Array.isArray(value)) return value.filter(Boolean).join(',');
  125. return '';
  126. }
  127. function externalProxyPins(value: ExternalProxyEntry['pinnedPeerCertSha256']): string {
  128. if (Array.isArray(value)) return value.filter(Boolean).join(',');
  129. return '';
  130. }
  131. function applyExternalProxyTLSObj(
  132. externalProxy: ExternalProxyEntry | null | undefined,
  133. obj: Record<string, unknown>,
  134. security: string,
  135. ): void {
  136. if (!externalProxy || security !== 'tls') return;
  137. const sni = externalProxy.sni && externalProxy.sni.length > 0 ? externalProxy.sni : externalProxy.dest;
  138. if (sni && sni.length > 0) obj.sni = sni;
  139. if (externalProxy.fingerprint && externalProxy.fingerprint.length > 0) obj.fp = externalProxy.fingerprint;
  140. const alpn = externalProxyAlpn(externalProxy.alpn);
  141. if (alpn.length > 0) obj.alpn = alpn;
  142. const pins = externalProxyPins(externalProxy.pinnedPeerCertSha256);
  143. if (pins.length > 0) obj.pcs = pins;
  144. if (externalProxy.verifyPeerCertByName && externalProxy.verifyPeerCertByName.length > 0) {
  145. obj.vcn = externalProxy.verifyPeerCertByName;
  146. }
  147. if (externalProxy.echConfigList && externalProxy.echConfigList.length > 0) obj.ech = externalProxy.echConfigList;
  148. }
  149. export interface GenVmessLinkInput {
  150. inbound: Inbound;
  151. address: string;
  152. port?: number;
  153. forceTls?: ForceTls;
  154. remark?: string;
  155. clientId: string;
  156. security?: VmessSecurity;
  157. externalProxy?: ExternalProxyEntry | null;
  158. }
  159. // VMess share link: `vmess://` followed by base64-encoded JSON. The JSON
  160. // schema is the v2rayN-compatible "v2" shape. Returns '' if the inbound
  161. // is not vmess so dispatcher code can fall through cleanly.
  162. export function genVmessLink(input: GenVmessLinkInput): string {
  163. const {
  164. inbound,
  165. address,
  166. port = inbound.port,
  167. forceTls = 'same',
  168. remark = '',
  169. clientId,
  170. security,
  171. externalProxy = null,
  172. } = input;
  173. if (inbound.protocol !== 'vmess') return '';
  174. const stream = inbound.streamSettings;
  175. if (!stream) return '';
  176. const tls = forceTls === 'same' ? (stream.security ?? 'none') : forceTls;
  177. const obj: Record<string, unknown> = {
  178. v: '2',
  179. ps: remark,
  180. add: address,
  181. port,
  182. id: clientId,
  183. scy: security,
  184. net: stream.network,
  185. tls,
  186. };
  187. if (stream.network === 'tcp') {
  188. const tcp = stream.tcpSettings;
  189. const header = tcp.header;
  190. if (header) {
  191. obj.type = header.type;
  192. if (header.type === 'http') {
  193. const request = header.request;
  194. if (request) {
  195. obj.path = request.path.join(',');
  196. const host =
  197. getHeaderValue(header.response?.headers, 'host')
  198. || getHeaderValue(request.headers, 'host');
  199. if (host) obj.host = host;
  200. }
  201. }
  202. } else {
  203. obj.type = 'none';
  204. }
  205. } else if (stream.network === 'kcp') {
  206. const kcp = stream.kcpSettings;
  207. obj.mtu = kcp.mtu;
  208. obj.tti = kcp.tti;
  209. } else if (stream.network === 'ws') {
  210. const ws = stream.wsSettings;
  211. obj.path = ws.path;
  212. obj.host = ws.host.length > 0 ? ws.host : getHeaderValue(ws.headers, 'host');
  213. } else if (stream.network === 'grpc') {
  214. const grpc = stream.grpcSettings;
  215. obj.path = grpc.serviceName;
  216. obj.authority = grpc.authority;
  217. if (grpc.multiMode) obj.type = 'multi';
  218. } else if (stream.network === 'httpupgrade') {
  219. const hu = stream.httpupgradeSettings;
  220. obj.path = hu.path;
  221. obj.host = hu.host.length > 0 ? hu.host : getHeaderValue(hu.headers, 'host');
  222. } else if (stream.network === 'xhttp') {
  223. const xhttp = stream.xhttpSettings;
  224. obj.path = xhttp.path;
  225. obj.host = xhttp.host.length > 0 ? xhttp.host : xhttpHostFallback(xhttp);
  226. obj.type = xhttp.mode;
  227. applyXhttpExtraToObj(xhttp, obj);
  228. }
  229. applyFinalMaskToObj(stream.finalmask, obj);
  230. if (tls === 'tls' && stream.security === 'tls') {
  231. const tlsSettings = stream.tlsSettings;
  232. if (tlsSettings.serverName.length > 0) obj.sni = tlsSettings.serverName;
  233. if (tlsSettings.settings.fingerprint.length > 0) obj.fp = tlsSettings.settings.fingerprint;
  234. if (tlsSettings.alpn.length > 0) obj.alpn = tlsSettings.alpn.join(',');
  235. if (tlsSettings.settings.echConfigList.length > 0) obj.ech = tlsSettings.settings.echConfigList;
  236. if (tlsSettings.settings.verifyPeerCertByName.length > 0) {
  237. obj.vcn = tlsSettings.settings.verifyPeerCertByName;
  238. }
  239. if (tlsSettings.settings.pinnedPeerCertSha256.length > 0) {
  240. obj.pcs = tlsSettings.settings.pinnedPeerCertSha256.join(',');
  241. }
  242. }
  243. applyExternalProxyTLSObj(externalProxy, obj, tls);
  244. return 'vmess://' + Base64.encode(JSON.stringify(obj, null, 2));
  245. }
  246. // Param-style helpers (vless/trojan/ss/hysteria links). These mirror the
  247. // legacy applyXhttpExtraToParams / applyFinalMaskToParams /
  248. // applyExternalProxyTLSParams but write to a URLSearchParams instance
  249. // directly. Number values get coerced via .toString() on set — same as
  250. // what URLSearchParams does internally so the resulting URL bytes match.
  251. function applyXhttpExtraToParams(xhttp: XHttpStreamSettings | undefined, params: URLSearchParams): void {
  252. if (!xhttp) return;
  253. params.set('path', xhttp.path);
  254. const host = xhttp.host.length > 0 ? xhttp.host : xhttpHostFallback(xhttp);
  255. params.set('host', host);
  256. params.set('mode', xhttp.mode);
  257. if (typeof xhttp.xPaddingBytes === 'string' && xhttp.xPaddingBytes.length > 0) {
  258. params.set('x_padding_bytes', xhttp.xPaddingBytes);
  259. }
  260. const extra = buildXhttpExtra(xhttp);
  261. if (extra) params.set('extra', JSON.stringify(extra));
  262. }
  263. function applyFinalMaskToParams(finalmask: FinalMaskStreamSettings | undefined, params: URLSearchParams): void {
  264. const payload = serializeFinalMask(finalmask);
  265. if (payload.length > 0) params.set('fm', payload);
  266. }
  267. function applyExternalProxyTLSParams(
  268. externalProxy: ExternalProxyEntry | null | undefined,
  269. params: URLSearchParams,
  270. security: string,
  271. ): void {
  272. if (!externalProxy || security !== 'tls') return;
  273. const sni = externalProxy.sni && externalProxy.sni.length > 0 ? externalProxy.sni : externalProxy.dest;
  274. if (sni && sni.length > 0) params.set('sni', sni);
  275. if (externalProxy.fingerprint && externalProxy.fingerprint.length > 0) params.set('fp', externalProxy.fingerprint);
  276. const alpn = externalProxyAlpn(externalProxy.alpn);
  277. if (alpn.length > 0) params.set('alpn', alpn);
  278. const pins = externalProxyPins(externalProxy.pinnedPeerCertSha256);
  279. if (pins.length > 0) params.set('pcs', pins);
  280. if (externalProxy.verifyPeerCertByName && externalProxy.verifyPeerCertByName.length > 0) {
  281. params.set('vcn', externalProxy.verifyPeerCertByName);
  282. }
  283. if (externalProxy.echConfigList && externalProxy.echConfigList.length > 0) params.set('ech', externalProxy.echConfigList);
  284. }
  285. export interface GenVlessLinkInput {
  286. inbound: Inbound;
  287. address: string;
  288. port?: number;
  289. forceTls?: ForceTls;
  290. remark?: string;
  291. clientId: string;
  292. clientKey?: string;
  293. flow?: VlessClient['flow'];
  294. externalProxy?: ExternalProxyEntry | null;
  295. }
  296. // Mirror of the Go applyVlessRoute: bake a single 0-65535 value into the UUID's
  297. // 3rd group (bytes 6-7), which xray reads as the vless route. Empty/invalid/non-
  298. // UUID input is returned unchanged.
  299. export function applyVlessRoute(id: string, route: string | undefined): string {
  300. const r = (route ?? '').trim();
  301. if (r === '' || !/^\d{1,5}$/.test(r)) return id;
  302. const n = Number(r);
  303. if (n > 65535) return id;
  304. if (!/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/.test(id)) return id;
  305. return id.slice(0, 14) + n.toString(16).padStart(4, '0') + id.slice(18);
  306. }
  307. // VLESS share link: vless://<uuid>@<host>:<port>?<query>#<remark>. The
  308. // query carries network type, encryption, network-specific knobs, and
  309. // security-specific knobs (TLS fingerprint/alpn/sni or Reality
  310. // pbk/sid/spx). Returns '' if the inbound isn't vless.
  311. export function genVlessLink(input: GenVlessLinkInput): string {
  312. const {
  313. inbound,
  314. address,
  315. port = inbound.port,
  316. forceTls = 'same',
  317. remark = '',
  318. clientId,
  319. clientKey = '',
  320. flow = '',
  321. externalProxy = null,
  322. } = input;
  323. if (inbound.protocol !== 'vless') return '';
  324. const stream = inbound.streamSettings;
  325. if (!stream) return '';
  326. const security = forceTls === 'same' ? stream.security : forceTls;
  327. const params = new URLSearchParams();
  328. params.set('type', stream.network ?? 'tcp');
  329. params.set('encryption', inbound.settings.encryption);
  330. if (stream.network === 'tcp') {
  331. const tcp = stream.tcpSettings;
  332. if (tcp.header?.type === 'http') {
  333. const request = tcp.header.request;
  334. if (request) {
  335. params.set('path', request.path.join(','));
  336. const host =
  337. getHeaderValue(tcp.header.response?.headers, 'host')
  338. || getHeaderValue(request.headers, 'host');
  339. if (host) params.set('host', host);
  340. params.set('headerType', 'http');
  341. }
  342. }
  343. } else if (stream.network === 'kcp') {
  344. const kcp = stream.kcpSettings;
  345. params.set('mtu', String(kcp.mtu));
  346. params.set('tti', String(kcp.tti));
  347. } else if (stream.network === 'ws') {
  348. const ws = stream.wsSettings;
  349. params.set('path', ws.path);
  350. params.set('host', ws.host.length > 0 ? ws.host : getHeaderValue(ws.headers, 'host'));
  351. } else if (stream.network === 'grpc') {
  352. const grpc = stream.grpcSettings;
  353. params.set('serviceName', grpc.serviceName);
  354. params.set('authority', grpc.authority);
  355. if (grpc.multiMode) params.set('mode', 'multi');
  356. } else if (stream.network === 'httpupgrade') {
  357. const hu = stream.httpupgradeSettings;
  358. params.set('path', hu.path);
  359. params.set('host', hu.host.length > 0 ? hu.host : getHeaderValue(hu.headers, 'host'));
  360. } else if (stream.network === 'xhttp') {
  361. applyXhttpExtraToParams(stream.xhttpSettings, params);
  362. }
  363. applyFinalMaskToParams(stream.finalmask, params);
  364. if (security === 'tls') {
  365. params.set('security', 'tls');
  366. if (stream.security === 'tls') {
  367. const tls = stream.tlsSettings;
  368. params.set('fp', tls.settings.fingerprint);
  369. params.set('alpn', tls.alpn.join(','));
  370. if (tls.serverName.length > 0) params.set('sni', tls.serverName);
  371. if (tls.settings.echConfigList.length > 0) params.set('ech', tls.settings.echConfigList);
  372. if (tls.settings.verifyPeerCertByName.length > 0) {
  373. params.set('vcn', tls.settings.verifyPeerCertByName);
  374. }
  375. if (tls.settings.pinnedPeerCertSha256.length > 0) {
  376. params.set('pcs', tls.settings.pinnedPeerCertSha256.join(','));
  377. }
  378. }
  379. applyExternalProxyTLSParams(externalProxy, params, security);
  380. } else if (security === 'reality') {
  381. params.set('security', 'reality');
  382. if (stream.security === 'reality') {
  383. const reality = stream.realitySettings;
  384. params.set('pbk', reality.settings.publicKey);
  385. params.set('fp', reality.settings.fingerprint);
  386. const sni =
  387. reality.settings.serverName ||
  388. reality.serverNames?.[0] ||
  389. reality.target?.split(':')[0];
  390. if (sni && sni.length > 0) params.set('sni', sni);
  391. if (reality.shortIds.length > 0) params.set('sid', reality.shortIds[0]);
  392. const spx = deriveSpiderX(reality.settings.spiderX, clientKey);
  393. if (spx.length > 0) params.set('spx', spx);
  394. if (reality.settings.mldsa65Verify.length > 0) params.set('pqv', reality.settings.mldsa65Verify);
  395. }
  396. } else {
  397. params.set('security', 'none');
  398. }
  399. // XTLS Vision flow: TCP over tls/reality (classic) or XHTTP+vlessenc (the
  400. // VLESS-level encryption stands in for transport TLS). Mirrors the backend's
  401. // vlessFlowAllowed and the form's flow-field gating so panel link, share
  402. // link and subscription agree.
  403. if (flow.length > 0 && canEnableTlsFlow({
  404. protocol: inbound.protocol,
  405. settings: inbound.settings,
  406. streamSettings: stream,
  407. })) {
  408. params.set('flow', flow);
  409. }
  410. const url = new URL(`vless://${applyVlessRoute(clientId, externalProxy?.vlessRoute)}@${formatUrlHost(address)}:${port}`);
  411. for (const [key, value] of params) url.searchParams.set(key, value);
  412. url.hash = encodeURIComponent(remark);
  413. return url.toString();
  414. }
  415. // Shared network-branch writer used by trojan + shadowsocks links.
  416. // VLESS and VMess don't call this because they have minor per-protocol
  417. // quirks inline (vmess maps `multi` differently into obj.type; vless sets
  418. // encryption=none up-front).
  419. function writeNetworkParams(stream: NonNullable<Inbound['streamSettings']>, params: URLSearchParams): void {
  420. if (stream.network === 'tcp') {
  421. const tcp = stream.tcpSettings;
  422. if (tcp.header?.type === 'http') {
  423. const request = tcp.header.request;
  424. if (request) {
  425. params.set('path', request.path.join(','));
  426. const host =
  427. getHeaderValue(tcp.header.response?.headers, 'host')
  428. || getHeaderValue(request.headers, 'host');
  429. if (host) params.set('host', host);
  430. params.set('headerType', 'http');
  431. }
  432. }
  433. } else if (stream.network === 'kcp') {
  434. const kcp = stream.kcpSettings;
  435. params.set('mtu', String(kcp.mtu));
  436. params.set('tti', String(kcp.tti));
  437. } else if (stream.network === 'ws') {
  438. const ws = stream.wsSettings;
  439. params.set('path', ws.path);
  440. params.set('host', ws.host.length > 0 ? ws.host : getHeaderValue(ws.headers, 'host'));
  441. } else if (stream.network === 'grpc') {
  442. const grpc = stream.grpcSettings;
  443. params.set('serviceName', grpc.serviceName);
  444. params.set('authority', grpc.authority);
  445. if (grpc.multiMode) params.set('mode', 'multi');
  446. } else if (stream.network === 'httpupgrade') {
  447. const hu = stream.httpupgradeSettings;
  448. params.set('path', hu.path);
  449. params.set('host', hu.host.length > 0 ? hu.host : getHeaderValue(hu.headers, 'host'));
  450. } else if (stream.network === 'xhttp') {
  451. applyXhttpExtraToParams(stream.xhttpSettings, params);
  452. }
  453. }
  454. function writeTlsParams(stream: NonNullable<Inbound['streamSettings']>, params: URLSearchParams): void {
  455. if (stream.security !== 'tls') return;
  456. const tls = stream.tlsSettings;
  457. params.set('fp', tls.settings.fingerprint);
  458. params.set('alpn', tls.alpn.join(','));
  459. if (tls.settings.echConfigList.length > 0) params.set('ech', tls.settings.echConfigList);
  460. if (tls.serverName.length > 0) params.set('sni', tls.serverName);
  461. if (tls.settings.verifyPeerCertByName.length > 0) {
  462. params.set('vcn', tls.settings.verifyPeerCertByName);
  463. }
  464. if (tls.settings.pinnedPeerCertSha256.length > 0) {
  465. params.set('pcs', tls.settings.pinnedPeerCertSha256.join(','));
  466. }
  467. }
  468. // Reality query-string writer shared by VLESS and Trojan. Preserves the
  469. // legacy SNI-omission quirk (see genVlessLink for the full story).
  470. function writeRealityParams(stream: NonNullable<Inbound['streamSettings']>, params: URLSearchParams, clientKey: string): void {
  471. if (stream.security !== 'reality') return;
  472. const reality = stream.realitySettings;
  473. params.set('pbk', reality.settings.publicKey);
  474. params.set('fp', reality.settings.fingerprint);
  475. const sni =
  476. reality.settings.serverName ||
  477. reality.serverNames?.[0] ||
  478. reality.target?.split(':')[0];
  479. if (sni && sni.length > 0) params.set('sni', sni);
  480. if (reality.shortIds.length > 0) params.set('sid', reality.shortIds[0]);
  481. const spx = deriveSpiderX(reality.settings.spiderX, clientKey);
  482. if (spx.length > 0) params.set('spx', spx);
  483. if (reality.settings.mldsa65Verify.length > 0) params.set('pqv', reality.settings.mldsa65Verify);
  484. }
  485. export interface GenTrojanLinkInput {
  486. inbound: Inbound;
  487. address: string;
  488. port?: number;
  489. forceTls?: ForceTls;
  490. remark?: string;
  491. clientPassword: string;
  492. clientKey?: string;
  493. externalProxy?: ExternalProxyEntry | null;
  494. }
  495. // Trojan share link: trojan://<password>@<host>:<port>?<query>#<remark>.
  496. // Same query-string shape as VLESS minus the `encryption` and `flow`
  497. // fields. Returns '' if the inbound isn't trojan.
  498. export function genTrojanLink(input: GenTrojanLinkInput): string {
  499. const {
  500. inbound,
  501. address,
  502. port = inbound.port,
  503. forceTls = 'same',
  504. remark = '',
  505. clientPassword,
  506. clientKey = '',
  507. externalProxy = null,
  508. } = input;
  509. if (inbound.protocol !== 'trojan') return '';
  510. const stream = inbound.streamSettings;
  511. if (!stream) return '';
  512. const security = forceTls === 'same' ? stream.security : forceTls;
  513. const params = new URLSearchParams();
  514. params.set('type', stream.network ?? 'tcp');
  515. writeNetworkParams(stream, params);
  516. applyFinalMaskToParams(stream.finalmask, params);
  517. if (security === 'tls') {
  518. params.set('security', 'tls');
  519. writeTlsParams(stream, params);
  520. applyExternalProxyTLSParams(externalProxy, params, security);
  521. } else if (security === 'reality') {
  522. params.set('security', 'reality');
  523. writeRealityParams(stream, params, clientKey);
  524. } else {
  525. params.set('security', 'none');
  526. }
  527. const url = new URL(`trojan://${encodeURIComponent(clientPassword)}@${formatUrlHost(address)}:${port}`);
  528. for (const [key, value] of params) url.searchParams.set(key, value);
  529. url.hash = encodeURIComponent(remark);
  530. return url.toString();
  531. }
  532. export interface GenShadowsocksLinkInput {
  533. inbound: Inbound;
  534. address: string;
  535. port?: number;
  536. forceTls?: ForceTls;
  537. remark?: string;
  538. clientPassword?: string;
  539. externalProxy?: ExternalProxyEntry | null;
  540. }
  541. // Shadowsocks 2022 share link. The userinfo portion is base64(method:pw)
  542. // for single-user and base64(method:settingsPw:clientPw) for multi-user
  543. // 2022-blake3. Legacy SS (non-2022) leaves the password out of the
  544. // userinfo entirely — matches the legacy class's password-array logic.
  545. // Note: legacy `isSSMultiUser` returns true for everything except
  546. // 2022-blake3-chacha20-poly1305 (a curious classification, but we
  547. // preserve it for byte-stable parity).
  548. export function genShadowsocksLink(input: GenShadowsocksLinkInput): string {
  549. const {
  550. inbound,
  551. address,
  552. port = inbound.port,
  553. forceTls = 'same',
  554. remark = '',
  555. clientPassword = '',
  556. externalProxy = null,
  557. } = input;
  558. if (inbound.protocol !== 'shadowsocks') return '';
  559. const stream = inbound.streamSettings;
  560. if (!stream) return '';
  561. const settings = inbound.settings;
  562. const security = forceTls === 'same' ? stream.security : forceTls;
  563. const params = new URLSearchParams();
  564. params.set('type', stream.network ?? 'tcp');
  565. writeNetworkParams(stream, params);
  566. applyFinalMaskToParams(stream.finalmask, params);
  567. if (security === 'tls') {
  568. params.set('security', 'tls');
  569. writeTlsParams(stream, params);
  570. applyExternalProxyTLSParams(externalProxy, params, security);
  571. }
  572. // SIP002 clients (v2rayN) ignore type/headerType/host/path and only read
  573. // `plugin`. Re-encode a TCP http header as obfs-local so they build a
  574. // matching tcp/http outbound (v2rayN forces request path "/").
  575. if ((stream.network ?? 'tcp') === 'tcp' && params.get('headerType') === 'http') {
  576. const host = params.get('host') ?? '';
  577. params.delete('type');
  578. params.delete('headerType');
  579. params.delete('host');
  580. params.delete('path');
  581. params.set('plugin', `obfs-local;obfs=http;obfs-host=${host}`);
  582. }
  583. const isSS2022 = settings.method.substring(0, 4) === '2022';
  584. const isSSMultiUser = settings.method !== '2022-blake3-chacha20-poly1305';
  585. const passwords: string[] = [];
  586. if (isSS2022) passwords.push(settings.password);
  587. if (isSSMultiUser) passwords.push(clientPassword);
  588. if (isSS2022) {
  589. // SIP022 (2022-blake3-*) forbids base64 userinfo: method and each key are
  590. // percent-encoded, joined by literal ':' separators. Built by hand because
  591. // `new URL` would re-encode the inner key separator to %3A.
  592. const userinfo = [settings.method, ...passwords].map(encodeURIComponent).join(':');
  593. let link = `ss://${userinfo}@${formatUrlHost(address)}:${port}`;
  594. const query = params.toString();
  595. if (query) link += `?${query}`;
  596. link += `#${encodeURIComponent(remark)}`;
  597. return link;
  598. }
  599. // SIP002 userinfo is base64(method:pw).
  600. const userinfo = Base64.encode(`${settings.method}:${passwords.join(':')}`, true);
  601. const url = new URL(`ss://${userinfo}@${formatUrlHost(address)}:${port}`);
  602. for (const [key, value] of params) url.searchParams.set(key, value);
  603. url.hash = encodeURIComponent(remark);
  604. return url.toString();
  605. }
  606. export interface GenHysteriaLinkInput {
  607. inbound: Inbound;
  608. address: string;
  609. port?: number;
  610. remark?: string;
  611. clientAuth: string;
  612. externalProxy?: ExternalProxyEntry | null;
  613. }
  614. // Hysteria2's pinSHA256 must be a 64-char lowercase hex string — Xray-core
  615. // clients hex-decode it and crash on a base64 value. The panel stores pins as
  616. // base64 (xray-core's native TLS format / the generate button) or hex, either
  617. // bare or colon-separated as `openssl x509 -fingerprint -sha256` emits it. Each
  618. // entry is coerced to bare hex. Values that are neither a 32-byte hex nor a
  619. // 32-byte base64 SHA-256 pass through unchanged.
  620. function hysteriaPinHex(pin: string): string {
  621. const stripped = pin.trim().replace(/:/g, '');
  622. if (/^[0-9a-fA-F]{64}$/.test(stripped)) return stripped.toLowerCase();
  623. try {
  624. const binary = atob(pin.trim().replace(/-/g, '+').replace(/_/g, '/'));
  625. if (binary.length !== 32) return pin;
  626. let hex = '';
  627. for (let i = 0; i < binary.length; i++) {
  628. hex += binary.charCodeAt(i).toString(16).padStart(2, '0');
  629. }
  630. return hex;
  631. } catch {
  632. return pin;
  633. }
  634. }
  635. // Hysteria share link: hysteria://<auth>@<host>:<port>?<query>#<remark>.
  636. // The URL scheme is "hysteria2" when settings.version === 2 (hysteria v2
  637. // AKA hysteria2), "hysteria" otherwise. Salamander obfuscation pulls its
  638. // password from finalmask.udp[type=salamander] when present; the broader
  639. // finalmask payload still rides under `fm` like the other links.
  640. //
  641. // Note: legacy genHysteriaLink reads stream.tls.settings.allowInsecure,
  642. // which isn't a field on TlsStreamSettings.Settings — the guard is always
  643. // false. We omit the `insecure` param here to stay byte-stable.
  644. export function genHysteriaLink(input: GenHysteriaLinkInput): string {
  645. const {
  646. inbound,
  647. address,
  648. port = inbound.port,
  649. remark = '',
  650. clientAuth,
  651. externalProxy = null,
  652. } = input;
  653. if (inbound.protocol !== 'hysteria') return '';
  654. const stream = inbound.streamSettings;
  655. if (!stream || stream.security !== 'tls') return '';
  656. const settings = inbound.settings;
  657. const scheme = settings.version === 2 ? 'hysteria2' : 'hysteria';
  658. const params = new URLSearchParams();
  659. params.set('security', 'tls');
  660. const tls = stream.tlsSettings;
  661. if (tls.settings.fingerprint.length > 0) params.set('fp', tls.settings.fingerprint);
  662. if (tls.alpn.length > 0) params.set('alpn', tls.alpn.join(','));
  663. if (tls.settings.echConfigList.length > 0) params.set('ech', tls.settings.echConfigList);
  664. if (tls.serverName.length > 0) params.set('sni', tls.serverName);
  665. if (tls.settings.verifyPeerCertByName.length > 0) {
  666. params.set('vcn', tls.settings.verifyPeerCertByName);
  667. }
  668. if (tls.settings.pinnedPeerCertSha256.length > 0) {
  669. params.set('pinSHA256', tls.settings.pinnedPeerCertSha256.map(hysteriaPinHex).join(','));
  670. }
  671. // An external-proxy entry can pin a different endpoint's certificate.
  672. // Hysteria carries it as hex `pinSHA256` (not the `pcs` other protocols
  673. // use), so coerce each entry through hysteriaPinHex like the main pin.
  674. if (Array.isArray(externalProxy?.pinnedPeerCertSha256)) {
  675. const epPins = externalProxy.pinnedPeerCertSha256.filter(Boolean).map(hysteriaPinHex);
  676. if (epPins.length > 0) params.set('pinSHA256', epPins.join(','));
  677. }
  678. const udpMasks = stream.finalmask?.udp;
  679. if (Array.isArray(udpMasks)) {
  680. const salamander = udpMasks.find((m) => m?.type === 'salamander');
  681. const obfsPassword = salamander?.settings?.password;
  682. if (typeof obfsPassword === 'string' && obfsPassword.length > 0) {
  683. params.set('obfs', 'salamander');
  684. params.set('obfs-password', obfsPassword);
  685. }
  686. }
  687. applyFinalMaskToParams(stream.finalmask, params);
  688. const hopPorts = stream.finalmask?.quicParams?.udpHop?.ports?.trim() ?? '';
  689. if (hopPorts.length > 0) {
  690. params.set('mport', hopPorts);
  691. }
  692. const url = new URL(`${scheme}://${clientAuth}@${formatUrlHost(address)}:${port}`);
  693. for (const [key, value] of params) url.searchParams.set(key, value);
  694. url.hash = encodeURIComponent(remark);
  695. return url.toString();
  696. }
  697. export interface GenMtprotoLinkInput {
  698. inbound: Inbound;
  699. address: string;
  700. port?: number;
  701. clientSecret?: string;
  702. }
  703. // Builds a per-client Telegram proxy deep link for an mtproto inbound from the
  704. // client's own FakeTLS secret. No remark fragment is added: Telegram proxy deep
  705. // links have no name field, and a trailing "#remark" gets folded into the last
  706. // query value by lenient parsers, breaking the server address. The panel shows
  707. // the remark separately from the link.
  708. export function genMtprotoLink(input: GenMtprotoLinkInput): string {
  709. const { inbound, address, port = inbound.port, clientSecret = '' } = input;
  710. if (inbound.protocol !== 'mtproto') return '';
  711. if (clientSecret.length === 0) return '';
  712. const url = new URL('tg://proxy');
  713. url.searchParams.set('server', address);
  714. url.searchParams.set('port', String(port));
  715. url.searchParams.set('secret', clientSecret);
  716. return url.toString();
  717. }
  718. export interface GenWireguardLinkInput {
  719. settings: WireguardInboundSettings;
  720. address: string;
  721. port: number;
  722. remark?: string;
  723. peerIndex: number;
  724. }
  725. // Wireguard share link: wireguard://<peerPrivKey>@<host>:<port>
  726. // ?publickey=<serverPub>&address=<peerAllowedIP>&mtu=<mtu>#<remark>
  727. // pubKey is derived from the server's secretKey via Wireguard.generateKeypair
  728. // at call time (Zod's schema stores secretKey only — pubKey isn't on the
  729. // wire). Returns '' when the peer index is out of bounds.
  730. export function genWireguardLink(input: GenWireguardLinkInput): string {
  731. const { settings, address, port, remark = '', peerIndex } = input;
  732. const peer = settings.peers[peerIndex];
  733. if (!peer) return '';
  734. const url = new URL(`wireguard://${formatUrlHost(address)}:${port}`);
  735. url.username = peer.privateKey ?? '';
  736. const pubKey = settings.secretKey.length > 0
  737. ? Wireguard.generateKeypair(settings.secretKey).publicKey
  738. : '';
  739. if (pubKey.length > 0) url.searchParams.set('publickey', pubKey);
  740. if (peer.allowedIPs.length > 0 && peer.allowedIPs[0]) {
  741. url.searchParams.set('address', peer.allowedIPs[0]);
  742. }
  743. if (typeof settings.mtu === 'number' && settings.mtu > 0) {
  744. url.searchParams.set('mtu', String(settings.mtu));
  745. }
  746. url.hash = encodeURIComponent(remark);
  747. return url.toString();
  748. }
  749. // Plain-text WireGuard client config (.conf format). Mirrors the legacy
  750. // getWireguardTxt — same DNS defaults (1.1.1.1, 1.0.0.1), MTU optional,
  751. // presharedKey + keepAlive only emitted when present on the peer. The
  752. // final newline structure follows the legacy: no newline after Endpoint,
  753. // optional preSharedKey appended with leading \n, keepAlive appended
  754. // with leading \n AND trailing \n.
  755. export function genWireguardConfig(input: GenWireguardLinkInput): string {
  756. const { settings, address, port, remark = '', peerIndex } = input;
  757. const peer = settings.peers[peerIndex];
  758. if (!peer) return '';
  759. const pubKey = settings.secretKey.length > 0
  760. ? Wireguard.generateKeypair(settings.secretKey).publicKey
  761. : '';
  762. let txt = `[Interface]\n`;
  763. txt += `PrivateKey = ${peer.privateKey ?? ''}\n`;
  764. txt += `Address = ${peer.allowedIPs[0] ?? ''}\n`;
  765. txt += `DNS = ${settings.dns || '1.1.1.1, 1.0.0.1'}\n`;
  766. if (typeof settings.mtu === 'number' && settings.mtu > 0) {
  767. txt += `MTU = ${settings.mtu}\n`;
  768. }
  769. txt += `\n# ${remark}\n`;
  770. txt += `[Peer]\n`;
  771. txt += `PublicKey = ${pubKey}\n`;
  772. txt += `AllowedIPs = 0.0.0.0/0, ::/0\n`;
  773. txt += `Endpoint = ${address}:${port}`;
  774. if (peer.preSharedKey && peer.preSharedKey.length > 0) {
  775. txt += `\nPresharedKey = ${peer.preSharedKey}`;
  776. }
  777. if (typeof peer.keepAlive === 'number' && peer.keepAlive > 0) {
  778. txt += `\nPersistentKeepalive = ${peer.keepAlive}\n`;
  779. }
  780. return txt;
  781. }
  782. export function wireguardConfigFromLink(link: string, fallbackRemark = ''): string {
  783. let url: URL;
  784. try {
  785. url = new URL(link);
  786. } catch {
  787. return '';
  788. }
  789. const scheme = url.protocol.replace(/:$/, '');
  790. if (scheme !== 'wireguard' && scheme !== 'wg') return '';
  791. const params = url.searchParams;
  792. const pick = (...keys: string[]): string => {
  793. for (const k of keys) {
  794. const v = params.get(k);
  795. if (v) return v;
  796. }
  797. return '';
  798. };
  799. let privateKey: string;
  800. try {
  801. privateKey = decodeURIComponent(url.username);
  802. } catch {
  803. privateKey = url.username;
  804. }
  805. const host = url.hostname;
  806. const endpoint = host ? (url.port ? `${host}:${url.port}` : host) : '';
  807. const address = pick('address', 'ip') || '10.0.0.2/32';
  808. const publicKey = pick('publickey', 'publicKey', 'public_key', 'peerPublicKey');
  809. const dns = pick('dns') || '1.1.1.1, 1.0.0.1';
  810. const mtu = pick('mtu');
  811. const psk = pick('presharedkey', 'preshared_key', 'pre-shared-key', 'psk');
  812. const keepAlive = pick('keepalive', 'persistentkeepalive', 'persistent_keepalive');
  813. const allowedIPs = pick('allowedips', 'allowed_ips') || '0.0.0.0/0, ::/0';
  814. let remark = fallbackRemark;
  815. try {
  816. const decoded = decodeURIComponent(url.hash.replace(/^#/, ''));
  817. if (decoded) remark = decoded;
  818. } catch {
  819. const raw = url.hash.replace(/^#/, '');
  820. if (raw) remark = raw;
  821. }
  822. const lines = [
  823. '[Interface]',
  824. `PrivateKey = ${privateKey}`,
  825. `Address = ${address}`,
  826. `DNS = ${dns}`,
  827. ];
  828. if (mtu && Number(mtu) > 0) lines.push(`MTU = ${mtu}`);
  829. lines.push('');
  830. if (remark) lines.push(`# ${remark}`);
  831. lines.push('[Peer]', `PublicKey = ${publicKey}`);
  832. if (psk) lines.push(`PresharedKey = ${psk}`);
  833. lines.push(`AllowedIPs = ${allowedIPs}`, `Endpoint = ${endpoint}`);
  834. if (keepAlive && Number(keepAlive) > 0) lines.push(`PersistentKeepalive = ${keepAlive}`);
  835. return lines.join('\n');
  836. }
  837. export type { WireguardInboundPeer };
  838. function isUnixSocketListen(listen: string): boolean {
  839. return listen.startsWith('/') || listen.startsWith('@');
  840. }
  841. function normalizeShareHost(host: string): string {
  842. const h = host.trim();
  843. if (
  844. h.length === 0
  845. || h.includes('://')
  846. || h.startsWith('//')
  847. || /[/?#@]/.test(h)
  848. ) {
  849. return '';
  850. }
  851. if (h.startsWith('[')) {
  852. if (!h.endsWith(']')) return '';
  853. try {
  854. return new URL(`http://${h}`).hostname;
  855. } catch {
  856. return '';
  857. }
  858. }
  859. if (h.includes(':')) {
  860. try {
  861. return new URL(`http://[${h}]`).hostname;
  862. } catch {
  863. return '';
  864. }
  865. }
  866. return SHARE_HOSTNAME_RE.test(h) ? h : '';
  867. }
  868. function isShareableHost(host: string): boolean {
  869. const h = normalizeShareHost(host).replace(/^\[|\]$/g, '').toLowerCase();
  870. if (h.length === 0) return false;
  871. if (h === '0.0.0.0' || h === '::' || h === '::0') return false;
  872. if (h === 'localhost' || h === '::1' || h.startsWith('127.')) return false;
  873. return true;
  874. }
  875. function shareableListenFrom(listen: string): string {
  876. const trimmed = listen.trim();
  877. return trimmed.length > 0 && !isUnixSocketListen(trimmed) && isShareableHost(trimmed)
  878. ? normalizeShareHost(trimmed)
  879. : '';
  880. }
  881. type ShareAddrStrategy = 'node' | 'listen' | 'custom';
  882. function normalizeShareAddrStrategy(strategy: string | undefined): ShareAddrStrategy {
  883. return strategy === 'listen' || strategy === 'custom' ? strategy : 'node';
  884. }
  885. // ShareHostFields is the subset of an inbound resolveShareHost needs, so callers
  886. // holding only a lightweight projection (e.g. the clients page InboundOption)
  887. // can pick the same host as the full-inbound share/QR path.
  888. export interface ShareHostFields {
  889. listen?: string;
  890. shareAddr?: string;
  891. shareAddrStrategy?: string;
  892. }
  893. // resolveShareHost picks the host that goes into share/QR links, the browser-side
  894. // analog of the backend resolveInboundAddress. hostOverride is the hosting node's
  895. // address (empty for this panel's own inbounds); fallbackHostname is the
  896. // already-resolved panel/public host used as the last resort — kept verbatim when
  897. // it fails normalization (e.g. an underscore intranet hostname) so the last
  898. // resort never degrades to an empty host.
  899. export function resolveShareHost(
  900. fields: ShareHostFields,
  901. hostOverride: string,
  902. fallbackHostname: string,
  903. ): string {
  904. const nodeAddr = normalizeShareHost(hostOverride);
  905. const listenAddr = shareableListenFrom(fields.listen ?? '');
  906. const customAddr = normalizeShareHost(fields.shareAddr ?? '');
  907. const fallbackAddr = normalizeShareHost(fallbackHostname) || fallbackHostname.trim();
  908. switch (normalizeShareAddrStrategy(fields.shareAddrStrategy)) {
  909. case 'listen':
  910. return listenAddr || nodeAddr || fallbackAddr;
  911. case 'custom':
  912. return customAddr || nodeAddr || listenAddr || fallbackAddr;
  913. default:
  914. return nodeAddr || listenAddr || fallbackAddr;
  915. }
  916. }
  917. // Orchestrators.
  918. // resolveAddr picks the host that goes into share/QR links. The default
  919. // `node` strategy keeps the previous node-address-first behavior for
  920. // node-managed inbounds; other strategies let a row prefer its listen address
  921. // or a custom endpoint.
  922. export function resolveAddr(inbound: Inbound, hostOverride: string, fallbackHostname: string): string {
  923. return resolveShareHost(inbound, hostOverride, fallbackHostname);
  924. }
  925. // A loopback browser host means the panel was reached through a tunnel (e.g.
  926. // SSH-forwarded 127.0.0.1/localhost), so it can never be a shareable link host.
  927. function isLoopbackHost(host: string): boolean {
  928. const h = host.trim().replace(/^\[|\]$/g, '').toLowerCase();
  929. return h === 'localhost' || h === '::1' || h.startsWith('127.');
  930. }
  931. // preferPublicHost is the browser-side analog of the backend's
  932. // configuredPublicHost: when the panel is reached on a loopback host, prefer a
  933. // configured public host (Sub/Web Domain) for share/QR links instead of leaking
  934. // localhost. An explicit per-inbound listen or node override still wins, since
  935. // resolveAddr only reaches the fallbackHostname after those.
  936. export function preferPublicHost(browserHost: string, publicHost: string): string {
  937. return publicHost && isLoopbackHost(browserHost) ? publicHost : browserHost;
  938. }
  939. // Returns the client array for protocols that have one. SS returns its
  940. // clients only in 2022-blake3 multi-user mode (matches the legacy
  941. // `this.clients` getter, which used isSSMultiUser to gate). Returns null
  942. // for SS single-user, http, mixed, tunnel, wireguard, hysteria2-without-
  943. // clients, and any protocol without a clients array.
  944. type ClientShape = { id?: string; security?: VmessSecurity; flow?: VlessClient['flow']; password?: string; auth?: string; secret?: string; email?: string; subId?: string };
  945. // Mirror of the Go subKey: the stable per-client identity spx derivation
  946. // keys on — subscription id first, unique email as the fallback.
  947. function clientSubKey(client: ClientShape): string {
  948. return client.subId || client.email || '';
  949. }
  950. export function getInboundClients(inbound: Inbound): ClientShape[] | null {
  951. switch (inbound.protocol) {
  952. case 'vmess':
  953. return (inbound.settings.clients ?? []) as ClientShape[];
  954. case 'vless':
  955. return (inbound.settings.clients ?? []) as ClientShape[];
  956. case 'trojan':
  957. return (inbound.settings.clients ?? []) as ClientShape[];
  958. case 'hysteria':
  959. return (inbound.settings.clients ?? []) as ClientShape[];
  960. case 'mtproto':
  961. return (inbound.settings.clients ?? []) as ClientShape[];
  962. case 'shadowsocks': {
  963. const isMultiUser = inbound.settings.method !== '2022-blake3-chacha20-poly1305';
  964. return isMultiUser ? ((inbound.settings.clients ?? []) as ClientShape[]) : null;
  965. }
  966. default:
  967. return null;
  968. }
  969. }
  970. export interface GenLinkInput {
  971. inbound: Inbound;
  972. address: string;
  973. port?: number;
  974. forceTls?: ForceTls;
  975. remark?: string;
  976. client: ClientShape;
  977. externalProxy?: ExternalProxyEntry | null;
  978. }
  979. // Per-protocol dispatcher matching the legacy `genLink` switch. Returns
  980. // '' for protocols that don't have client-based share links (wireguard
  981. // goes through genWireguardLinks/Configs separately, http/mixed/tunnel
  982. // don't have share URLs).
  983. export function genLink(input: GenLinkInput): string {
  984. const { inbound, address, port = inbound.port, forceTls = 'same', remark = '', client, externalProxy = null } = input;
  985. switch (inbound.protocol) {
  986. case 'vmess':
  987. return genVmessLink({
  988. inbound, address, port, forceTls, remark,
  989. clientId: client.id ?? '',
  990. security: client.security,
  991. externalProxy,
  992. });
  993. case 'vless':
  994. return genVlessLink({
  995. inbound, address, port, forceTls, remark,
  996. clientId: client.id ?? '',
  997. clientKey: clientSubKey(client),
  998. flow: client.flow,
  999. externalProxy,
  1000. });
  1001. case 'shadowsocks': {
  1002. const isMultiUser = inbound.settings.method !== '2022-blake3-chacha20-poly1305';
  1003. return genShadowsocksLink({
  1004. inbound, address, port, forceTls, remark,
  1005. clientPassword: isMultiUser ? (client.password ?? '') : '',
  1006. externalProxy,
  1007. });
  1008. }
  1009. case 'trojan':
  1010. return genTrojanLink({
  1011. inbound, address, port, forceTls, remark,
  1012. clientPassword: client.password ?? '',
  1013. clientKey: clientSubKey(client),
  1014. externalProxy,
  1015. });
  1016. case 'hysteria':
  1017. return genHysteriaLink({
  1018. inbound, address, port, remark,
  1019. clientAuth: client.auth ?? '',
  1020. externalProxy,
  1021. });
  1022. case 'mtproto':
  1023. return genMtprotoLink({ inbound, address, port, clientSecret: client.secret ?? '' });
  1024. default:
  1025. return '';
  1026. }
  1027. }
  1028. export interface GenAllLinksEntry {
  1029. remark: string;
  1030. link: string;
  1031. }
  1032. export interface GenAllLinksInput {
  1033. inbound: Inbound;
  1034. remark?: string;
  1035. client: ClientShape;
  1036. hostOverride?: string;
  1037. fallbackHostname: string;
  1038. }
  1039. // Fans out a single client's link per externalProxy entry, or just one link
  1040. // when there are no external proxies. The panel copy/QR remark is the inbound
  1041. // remark plus the externalProxy remark, dash-joined (the configurable
  1042. // subscription remark model was removed; subscription output uses the template).
  1043. export function genAllLinks(input: GenAllLinksInput): GenAllLinksEntry[] {
  1044. const {
  1045. inbound,
  1046. remark = '',
  1047. client,
  1048. hostOverride = '',
  1049. fallbackHostname,
  1050. } = input;
  1051. const addr = resolveAddr(inbound, hostOverride, fallbackHostname);
  1052. const port = inbound.port;
  1053. const composeRemark = (proxyRemark: string): string =>
  1054. [remark, proxyRemark].filter((x) => x.length > 0).join('-');
  1055. const externals = inbound.streamSettings?.externalProxy;
  1056. if (!externals || externals.length === 0) {
  1057. const r = composeRemark('');
  1058. return [{ remark: r, link: genLink({ inbound, address: addr, port, forceTls: 'same', remark: r, client }) }];
  1059. }
  1060. return externals.map((ep) => {
  1061. const r = composeRemark(ep.remark);
  1062. return {
  1063. remark: r,
  1064. link: genLink({
  1065. inbound,
  1066. address: ep.dest,
  1067. port: ep.port,
  1068. forceTls: ep.forceTls,
  1069. remark: r,
  1070. client,
  1071. externalProxy: ep,
  1072. }),
  1073. };
  1074. });
  1075. }
  1076. export interface GenInboundLinksInput {
  1077. inbound: Inbound;
  1078. remark?: string;
  1079. hostOverride?: string;
  1080. fallbackHostname: string;
  1081. }
  1082. // Top-level entrypoint that produces the full \r\n-joined block a user
  1083. // pastes into a client. Iterates per-client for protocols with clients,
  1084. // falls back to a single SS link for single-user 2022-blake3-chacha20,
  1085. // and emits per-peer .conf blocks for wireguard. Returns '' for the
  1086. // other clientless protocols (http, mixed, tunnel).
  1087. export function genInboundLinks(input: GenInboundLinksInput): string {
  1088. const {
  1089. inbound,
  1090. remark = '',
  1091. hostOverride = '',
  1092. fallbackHostname,
  1093. } = input;
  1094. const addr = resolveAddr(inbound, hostOverride, fallbackHostname);
  1095. const clients = getInboundClients(inbound);
  1096. if (clients) {
  1097. const links: string[] = [];
  1098. for (const client of clients) {
  1099. const entries = genAllLinks({ inbound, remark, client, hostOverride, fallbackHostname });
  1100. for (const e of entries) links.push(e.link);
  1101. }
  1102. return links.join('\r\n');
  1103. }
  1104. if (inbound.protocol === 'shadowsocks') {
  1105. return genShadowsocksLink({ inbound, address: addr, port: inbound.port, forceTls: 'same', remark });
  1106. }
  1107. if (inbound.protocol === 'wireguard') {
  1108. return genWireguardConfigs({ inbound, remark, hostOverride, fallbackHostname });
  1109. }
  1110. return '';
  1111. }
  1112. // Per-peer wireguard fanout. Each peer gets its own link (or .conf
  1113. // block) with an index-suffixed remark, joined by \r\n. Matches the
  1114. // legacy genWireguardLinks / genWireguardConfigs exactly.
  1115. export interface GenWireguardFanoutInput {
  1116. inbound: Inbound;
  1117. remark?: string;
  1118. hostOverride?: string;
  1119. fallbackHostname: string;
  1120. }
  1121. // WireGuard is multi-client: each client is one accepted peer. The canonical
  1122. // store is settings.clients; legacy single-config inbounds (pre-migration) are
  1123. // still rendered from settings.peers. Both carry the privateKey/allowedIPs/
  1124. // preSharedKey/keepAlive the link and .conf need, so they project to the same
  1125. // peer shape and reuse genWireguardLink/genWireguardConfig unchanged.
  1126. function wgRenderPeers(settings: WireguardInboundSettings): WireguardInboundPeer[] {
  1127. const clients = settings.clients ?? [];
  1128. if (clients.length > 0) {
  1129. return clients.map((c) => ({ ...c, publicKey: c.publicKey ?? '' }));
  1130. }
  1131. return settings.peers;
  1132. }
  1133. export function genWireguardLinks(input: GenWireguardFanoutInput): string {
  1134. const { inbound, remark = '', hostOverride = '', fallbackHostname } = input;
  1135. if (inbound.protocol !== 'wireguard') return '';
  1136. const addr = resolveAddr(inbound, hostOverride, fallbackHostname);
  1137. const sep = '-';
  1138. const baseSettings = inbound.settings as WireguardInboundSettings;
  1139. const peers = wgRenderPeers(baseSettings);
  1140. const settings: WireguardInboundSettings = { ...baseSettings, peers };
  1141. return peers
  1142. .map((p, i) => genWireguardLink({
  1143. settings,
  1144. address: addr,
  1145. port: inbound.port,
  1146. remark: `${remark}${sep}${i + 1}${wgPeerCommentSuffix(p)}`,
  1147. peerIndex: i,
  1148. }))
  1149. .join('\r\n');
  1150. }
  1151. export function genWireguardConfigs(input: GenWireguardFanoutInput): string {
  1152. const { inbound, remark = '', hostOverride = '', fallbackHostname } = input;
  1153. if (inbound.protocol !== 'wireguard') return '';
  1154. const addr = resolveAddr(inbound, hostOverride, fallbackHostname);
  1155. const sep = '-';
  1156. const baseSettings = inbound.settings as WireguardInboundSettings;
  1157. const peers = wgRenderPeers(baseSettings);
  1158. const settings: WireguardInboundSettings = { ...baseSettings, peers };
  1159. return peers
  1160. .map((p, i) => genWireguardConfig({
  1161. settings,
  1162. address: addr,
  1163. port: inbound.port,
  1164. remark: `${remark}${sep}${i + 1}${wgPeerCommentSuffix(p)}`,
  1165. peerIndex: i,
  1166. }))
  1167. .join('\r\n');
  1168. }
  1169. // Peer comments (#5168) are panel-side annotations; when present they ride
  1170. // along in the share remark so the device is identifiable in client apps.
  1171. function wgPeerCommentSuffix(peer: unknown): string {
  1172. const comment = (peer as { comment?: unknown })?.comment;
  1173. return typeof comment === 'string' && comment.trim() !== '' ? ` (${comment.trim()})` : '';
  1174. }
  1175. export function isPostQuantumLink(link: string): boolean {
  1176. if (/[?&]pqv=/.test(link)) return true;
  1177. if (link.includes('mlkem768') || link.includes('mldsa65')) return true;
  1178. if (link.includes('ML-KEM-768')) return true;
  1179. return false;
  1180. }