inbound-link.ts 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702
  1. import { Base64, Wireguard } from '@/utils';
  2. import { effectiveMtu } from '@/lib/xray/amneziawg-obfuscation';
  3. import type { Inbound } from '@/schemas/api/inbound';
  4. import type { AmneziawgInboundSettings } from '@/schemas/protocols/inbound/amneziawg';
  5. import type { VlessClient } from '@/schemas/protocols/inbound/vless';
  6. import type { VmessSecurity } from '@/schemas/protocols/shared/vmess';
  7. import type {
  8. WireguardInboundPeer,
  9. WireguardInboundSettings,
  10. } from '@/schemas/protocols/inbound/wireguard';
  11. import type { ExternalProxyEntry } from '@/schemas/protocols/stream/external-proxy';
  12. import type { FinalMaskStreamSettings } from '@/schemas/protocols/stream/finalmask';
  13. import type { XHttpStreamSettings } from '@/schemas/protocols/stream/xhttp';
  14. import { parseGeckoPacketSize } from '@/lib/xray/forms/transport/FinalMaskForm';
  15. import { getHeaderValue } from './headers';
  16. import { canEnableTlsFlow } from './protocol-capabilities';
  17. import { deriveSpiderX } from './spider-x';
  18. // Share-link generators. Each per-protocol fn takes a typed inbound plus
  19. // client overrides and returns a URL (or '' when the protocol doesn't
  20. // support shareable links). The helpers below were previously static
  21. // methods on the Inbound class; extracting them removes the
  22. // XrayCommonClass dependency and lets these run against Zod-parsed data
  23. // directly.
  24. type ForceTls = 'same' | 'tls' | 'none';
  25. const SHARE_HOSTNAME_RE =
  26. /^[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?)*$/;
  27. // Format a host for interpolation into a URL authority. IPv6 literals are
  28. // wrapped in square brackets per RFC 3986; IPv4 and hostnames are left as-is.
  29. // Any brackets already present are first stripped so the helper is idempotent.
  30. function formatUrlHost(address: string): string {
  31. const bare = address.replace(/^\[|\]$/g, '');
  32. return bare.includes(':') ? `[${bare}]` : bare;
  33. }
  34. // xHTTP headers ship as Record<string, string> on the wire (Zod schema)
  35. // rather than the legacy class's HeaderEntry[]. Lookup by case-folded key.
  36. function xhttpHostFallback(xhttp: XHttpStreamSettings | undefined): string {
  37. return getHeaderValue(xhttp?.headers, 'host');
  38. }
  39. // Pull the bidirectional SplitHTTPConfig fields out of xhttp into a
  40. // compact extra payload. Server-only fields (noSSEHeader, scMaxBufferedPosts,
  41. // scStreamUpServerSecs, serverMaxHeaderBytes) are excluded — the client
  42. // reading the share link wouldn't honor them.
  43. function buildXhttpExtra(xhttp: XHttpStreamSettings | undefined): Record<string, unknown> | null {
  44. if (!xhttp) return null;
  45. const extra: Record<string, unknown> = {};
  46. if (typeof xhttp.mode === 'string' && xhttp.mode.length > 0) {
  47. extra.mode = xhttp.mode;
  48. }
  49. if (typeof xhttp.xPaddingBytes === 'string' && xhttp.xPaddingBytes.length > 0) {
  50. extra.xPaddingBytes = xhttp.xPaddingBytes;
  51. }
  52. if (xhttp.xPaddingObfsMode === true) {
  53. extra.xPaddingObfsMode = true;
  54. for (const k of [
  55. 'xPaddingKey',
  56. 'xPaddingHeader',
  57. 'xPaddingPlacement',
  58. 'xPaddingMethod',
  59. ] as const) {
  60. const v = xhttp[k];
  61. if (typeof v === 'string' && v.length > 0) extra[k] = v;
  62. }
  63. }
  64. const stringFields = [
  65. 'uplinkHTTPMethod',
  66. 'sessionIDPlacement',
  67. 'sessionIDKey',
  68. 'sessionIDTable',
  69. 'sessionIDLength',
  70. 'seqPlacement',
  71. 'seqKey',
  72. 'uplinkDataPlacement',
  73. 'uplinkDataKey',
  74. 'scMaxEachPostBytes',
  75. ] as const;
  76. // Values matching xray-core's own defaults stay off the wire — old panels
  77. // seeded them into every config and the literal values are a DPI
  78. // fingerprint (#5141). Mirrors the sub service's filter.
  79. const coreDefaults: Partial<Record<(typeof stringFields)[number], string>> = {
  80. scMaxEachPostBytes: '1000000',
  81. };
  82. for (const k of stringFields) {
  83. const v = xhttp[k];
  84. if (typeof v === 'string' && v.length > 0 && v !== coreDefaults[k]) extra[k] = v;
  85. }
  86. // xray-core #6258 renamed these fields, but older clients still read the
  87. // legacy names from share-link extra. Emit both names so one link works
  88. // across old and new clients while the stored panel config stays canonical.
  89. if (typeof extra.sessionIDPlacement === 'string') {
  90. extra.sessionPlacement = extra.sessionIDPlacement;
  91. }
  92. if (typeof extra.sessionIDKey === 'string') {
  93. extra.sessionKey = extra.sessionIDKey;
  94. }
  95. // Headers on the wire are a record; emit them as a map upstream's
  96. // SplitHTTPConfig.headers expects, dropping Host (already on the URL).
  97. if (xhttp.headers && Object.keys(xhttp.headers).length > 0) {
  98. const headersMap: Record<string, string> = {};
  99. for (const [name, value] of Object.entries(xhttp.headers)) {
  100. if (name.toLowerCase() === 'host') continue;
  101. headersMap[name] = value;
  102. }
  103. if (Object.keys(headersMap).length > 0) extra.headers = headersMap;
  104. }
  105. return Object.keys(extra).length > 0 ? extra : null;
  106. }
  107. function applyXhttpExtraToObj(
  108. xhttp: XHttpStreamSettings | undefined,
  109. obj: Record<string, unknown>,
  110. ): void {
  111. if (!xhttp) return;
  112. if (typeof xhttp.xPaddingBytes === 'string' && xhttp.xPaddingBytes.length > 0) {
  113. obj.x_padding_bytes = xhttp.xPaddingBytes;
  114. }
  115. const extra = buildXhttpExtra(xhttp);
  116. if (!extra) return;
  117. for (const [k, v] of Object.entries(extra)) obj[k] = v;
  118. }
  119. // Recursively checks whether a finalmask payload has any non-empty
  120. // content. Empty arrays / empty objects / empty strings all return false;
  121. // any truthy primitive returns true. Used to decide whether the link
  122. // should carry an `fm` blob at all.
  123. function hasShareableFinalMaskValue(value: unknown): boolean {
  124. if (value == null) return false;
  125. if (Array.isArray(value)) return value.some(hasShareableFinalMaskValue);
  126. if (typeof value === 'object') {
  127. return Object.values(value as Record<string, unknown>).some(hasShareableFinalMaskValue);
  128. }
  129. if (typeof value === 'string') return value.length > 0;
  130. return true;
  131. }
  132. function serializeFinalMask(finalmask: FinalMaskStreamSettings | undefined): string {
  133. if (!finalmask) return '';
  134. return hasShareableFinalMaskValue(finalmask) ? JSON.stringify(finalmask) : '';
  135. }
  136. function applyFinalMaskToObj(
  137. finalmask: FinalMaskStreamSettings | undefined,
  138. obj: Record<string, unknown>,
  139. ): void {
  140. const payload = serializeFinalMask(finalmask);
  141. if (payload.length > 0) obj.fm = payload;
  142. }
  143. function externalProxyAlpn(value: ExternalProxyEntry['alpn']): string {
  144. if (Array.isArray(value)) return value.filter(Boolean).join(',');
  145. return '';
  146. }
  147. function externalProxyPins(value: ExternalProxyEntry['pinnedPeerCertSha256']): string {
  148. if (Array.isArray(value)) return value.filter(Boolean).join(',');
  149. return '';
  150. }
  151. function applyExternalProxyTLSObj(
  152. externalProxy: ExternalProxyEntry | null | undefined,
  153. obj: Record<string, unknown>,
  154. security: string,
  155. ): void {
  156. if (!externalProxy || security !== 'tls') return;
  157. const sni =
  158. externalProxy.sni && externalProxy.sni.length > 0 ? externalProxy.sni : externalProxy.dest;
  159. if (sni && sni.length > 0) obj.sni = sni;
  160. if (externalProxy.fingerprint && externalProxy.fingerprint.length > 0)
  161. obj.fp = externalProxy.fingerprint;
  162. const alpn = externalProxyAlpn(externalProxy.alpn);
  163. if (alpn.length > 0) obj.alpn = alpn;
  164. const pins = externalProxyPins(externalProxy.pinnedPeerCertSha256);
  165. if (pins.length > 0) obj.pcs = pins;
  166. if (externalProxy.verifyPeerCertByName && externalProxy.verifyPeerCertByName.length > 0) {
  167. obj.vcn = externalProxy.verifyPeerCertByName;
  168. }
  169. if (externalProxy.echConfigList && externalProxy.echConfigList.length > 0)
  170. obj.ech = externalProxy.echConfigList;
  171. }
  172. export interface GenVmessLinkInput {
  173. inbound: Inbound;
  174. address: string;
  175. port?: number;
  176. forceTls?: ForceTls;
  177. remark?: string;
  178. clientId: string;
  179. security?: VmessSecurity;
  180. externalProxy?: ExternalProxyEntry | null;
  181. }
  182. // VMess share link: `vmess://` followed by base64-encoded JSON. The JSON
  183. // schema is the v2rayN-compatible "v2" shape. Returns '' if the inbound
  184. // is not vmess so dispatcher code can fall through cleanly.
  185. export function genVmessLink(input: GenVmessLinkInput): string {
  186. const {
  187. inbound,
  188. address,
  189. port = inbound.port,
  190. forceTls = 'same',
  191. remark = '',
  192. clientId,
  193. security,
  194. externalProxy = null,
  195. } = input;
  196. if (inbound.protocol !== 'vmess') return '';
  197. const stream = inbound.streamSettings;
  198. if (!stream) return '';
  199. const tls = forceTls === 'same' ? (stream.security ?? 'none') : forceTls;
  200. const obj: Record<string, unknown> = {
  201. v: '2',
  202. ps: remark,
  203. add: address,
  204. port,
  205. id: clientId,
  206. scy: security,
  207. net: stream.network,
  208. tls,
  209. };
  210. if (stream.network === 'tcp') {
  211. const tcp = stream.tcpSettings;
  212. const header = tcp.header;
  213. if (header) {
  214. obj.type = header.type;
  215. if (header.type === 'http') {
  216. const request = header.request;
  217. if (request) {
  218. obj.path = request.path.join(',');
  219. const host =
  220. getHeaderValue(header.response?.headers, 'host') ||
  221. getHeaderValue(request.headers, 'host');
  222. if (host) obj.host = host;
  223. }
  224. }
  225. } else {
  226. obj.type = 'none';
  227. }
  228. } else if (stream.network === 'kcp') {
  229. const kcp = stream.kcpSettings;
  230. obj.mtu = kcp.mtu;
  231. obj.tti = kcp.tti;
  232. } else if (stream.network === 'ws') {
  233. const ws = stream.wsSettings;
  234. obj.path = ws.path;
  235. obj.host = ws.host.length > 0 ? ws.host : getHeaderValue(ws.headers, 'host');
  236. } else if (stream.network === 'grpc') {
  237. const grpc = stream.grpcSettings;
  238. obj.path = grpc.serviceName;
  239. obj.authority = grpc.authority;
  240. if (grpc.multiMode) obj.type = 'multi';
  241. } else if (stream.network === 'httpupgrade') {
  242. const hu = stream.httpupgradeSettings;
  243. obj.path = hu.path;
  244. obj.host = hu.host.length > 0 ? hu.host : getHeaderValue(hu.headers, 'host');
  245. } else if (stream.network === 'xhttp') {
  246. const xhttp = stream.xhttpSettings;
  247. obj.path = xhttp.path;
  248. obj.host = xhttp.host.length > 0 ? xhttp.host : xhttpHostFallback(xhttp);
  249. obj.type = xhttp.mode;
  250. applyXhttpExtraToObj(xhttp, obj);
  251. }
  252. applyFinalMaskToObj(stream.finalmask, obj);
  253. if (tls === 'tls' && stream.security === 'tls') {
  254. const tlsSettings = stream.tlsSettings;
  255. if (tlsSettings.serverName.length > 0) obj.sni = tlsSettings.serverName;
  256. if (tlsSettings.settings.fingerprint.length > 0) obj.fp = tlsSettings.settings.fingerprint;
  257. if (tlsSettings.alpn.length > 0) obj.alpn = tlsSettings.alpn.join(',');
  258. if (tlsSettings.settings.echConfigList.length > 0) obj.ech = tlsSettings.settings.echConfigList;
  259. if (tlsSettings.settings.verifyPeerCertByName.length > 0) {
  260. obj.vcn = tlsSettings.settings.verifyPeerCertByName;
  261. }
  262. if (tlsSettings.settings.pinnedPeerCertSha256.length > 0) {
  263. obj.pcs = tlsSettings.settings.pinnedPeerCertSha256.join(',');
  264. }
  265. }
  266. applyExternalProxyTLSObj(externalProxy, obj, tls);
  267. return 'vmess://' + Base64.encode(JSON.stringify(obj, null, 2));
  268. }
  269. // Param-style helpers (vless/trojan/ss/hysteria links). These mirror the
  270. // legacy applyXhttpExtraToParams / applyFinalMaskToParams /
  271. // applyExternalProxyTLSParams but write to a URLSearchParams instance
  272. // directly. Number values get coerced via .toString() on set — same as
  273. // what URLSearchParams does internally so the resulting URL bytes match.
  274. function applyXhttpExtraToParams(
  275. xhttp: XHttpStreamSettings | undefined,
  276. params: URLSearchParams,
  277. ): void {
  278. if (!xhttp) return;
  279. params.set('path', xhttp.path);
  280. const host = xhttp.host.length > 0 ? xhttp.host : xhttpHostFallback(xhttp);
  281. params.set('host', host);
  282. params.set('mode', xhttp.mode);
  283. if (typeof xhttp.xPaddingBytes === 'string' && xhttp.xPaddingBytes.length > 0) {
  284. params.set('x_padding_bytes', xhttp.xPaddingBytes);
  285. }
  286. const extra = buildXhttpExtra(xhttp);
  287. if (extra) params.set('extra', JSON.stringify(extra));
  288. }
  289. function applyFinalMaskToParams(
  290. finalmask: FinalMaskStreamSettings | undefined,
  291. params: URLSearchParams,
  292. ): void {
  293. const payload = serializeFinalMask(finalmask);
  294. if (payload.length > 0) params.set('fm', payload);
  295. }
  296. function applyExternalProxyTLSParams(
  297. externalProxy: ExternalProxyEntry | null | undefined,
  298. params: URLSearchParams,
  299. security: string,
  300. ): void {
  301. if (!externalProxy || security !== 'tls') return;
  302. const sni =
  303. externalProxy.sni && externalProxy.sni.length > 0 ? externalProxy.sni : externalProxy.dest;
  304. if (sni && sni.length > 0) params.set('sni', sni);
  305. if (externalProxy.fingerprint && externalProxy.fingerprint.length > 0)
  306. params.set('fp', externalProxy.fingerprint);
  307. const alpn = externalProxyAlpn(externalProxy.alpn);
  308. if (alpn.length > 0) params.set('alpn', alpn);
  309. const pins = externalProxyPins(externalProxy.pinnedPeerCertSha256);
  310. if (pins.length > 0) params.set('pcs', pins);
  311. if (externalProxy.verifyPeerCertByName && externalProxy.verifyPeerCertByName.length > 0) {
  312. params.set('vcn', externalProxy.verifyPeerCertByName);
  313. }
  314. if (externalProxy.echConfigList && externalProxy.echConfigList.length > 0)
  315. params.set('ech', externalProxy.echConfigList);
  316. }
  317. export interface GenVlessLinkInput {
  318. inbound: Inbound;
  319. address: string;
  320. port?: number;
  321. forceTls?: ForceTls;
  322. remark?: string;
  323. clientId: string;
  324. clientKey?: string;
  325. flow?: VlessClient['flow'];
  326. externalProxy?: ExternalProxyEntry | null;
  327. }
  328. // Mirror of the Go applyVlessRoute: bake a single 0-65535 value into the UUID's
  329. // 3rd group (bytes 6-7), which xray reads as the vless route. Empty/invalid/non-
  330. // UUID input is returned unchanged.
  331. export function applyVlessRoute(id: string, route: string | undefined): string {
  332. const r = (route ?? '').trim();
  333. if (r === '' || !/^\d{1,5}$/.test(r)) return id;
  334. const n = Number(r);
  335. if (n > 65535) return id;
  336. 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))
  337. return id;
  338. return id.slice(0, 14) + n.toString(16).padStart(4, '0') + id.slice(18);
  339. }
  340. // VLESS share link: vless://<uuid>@<host>:<port>?<query>#<remark>. The
  341. // query carries network type, encryption, network-specific knobs, and
  342. // security-specific knobs (TLS fingerprint/alpn/sni or Reality
  343. // pbk/sid/spx). Returns '' if the inbound isn't vless.
  344. export function genVlessLink(input: GenVlessLinkInput): string {
  345. const {
  346. inbound,
  347. address,
  348. port = inbound.port,
  349. forceTls = 'same',
  350. remark = '',
  351. clientId,
  352. clientKey = '',
  353. flow = '',
  354. externalProxy = null,
  355. } = input;
  356. if (inbound.protocol !== 'vless') return '';
  357. const stream = inbound.streamSettings;
  358. if (!stream) return '';
  359. const security = forceTls === 'same' ? stream.security : forceTls;
  360. const params = new URLSearchParams();
  361. params.set('type', stream.network ?? 'tcp');
  362. params.set('encryption', inbound.settings.encryption);
  363. if (stream.network === 'tcp') {
  364. const tcp = stream.tcpSettings;
  365. if (tcp.header?.type === 'http') {
  366. const request = tcp.header.request;
  367. if (request) {
  368. params.set('path', request.path.join(','));
  369. const host =
  370. getHeaderValue(tcp.header.response?.headers, 'host') ||
  371. getHeaderValue(request.headers, 'host');
  372. if (host) params.set('host', host);
  373. params.set('headerType', 'http');
  374. }
  375. }
  376. } else if (stream.network === 'kcp') {
  377. const kcp = stream.kcpSettings;
  378. params.set('mtu', String(kcp.mtu));
  379. params.set('tti', String(kcp.tti));
  380. } else if (stream.network === 'ws') {
  381. const ws = stream.wsSettings;
  382. params.set('path', ws.path);
  383. params.set('host', ws.host.length > 0 ? ws.host : getHeaderValue(ws.headers, 'host'));
  384. } else if (stream.network === 'grpc') {
  385. const grpc = stream.grpcSettings;
  386. params.set('serviceName', grpc.serviceName);
  387. params.set('authority', grpc.authority);
  388. if (grpc.multiMode) params.set('mode', 'multi');
  389. } else if (stream.network === 'httpupgrade') {
  390. const hu = stream.httpupgradeSettings;
  391. params.set('path', hu.path);
  392. params.set('host', hu.host.length > 0 ? hu.host : getHeaderValue(hu.headers, 'host'));
  393. } else if (stream.network === 'xhttp') {
  394. applyXhttpExtraToParams(stream.xhttpSettings, params);
  395. }
  396. applyFinalMaskToParams(stream.finalmask, params);
  397. if (security === 'tls') {
  398. params.set('security', 'tls');
  399. if (stream.security === 'tls') {
  400. const tls = stream.tlsSettings;
  401. if (tls.settings.fingerprint.length > 0) params.set('fp', tls.settings.fingerprint);
  402. params.set('alpn', tls.alpn.join(','));
  403. if (tls.serverName.length > 0) params.set('sni', tls.serverName);
  404. if (tls.settings.echConfigList.length > 0) params.set('ech', tls.settings.echConfigList);
  405. if (tls.settings.verifyPeerCertByName.length > 0) {
  406. params.set('vcn', tls.settings.verifyPeerCertByName);
  407. }
  408. if (tls.settings.pinnedPeerCertSha256.length > 0) {
  409. params.set('pcs', tls.settings.pinnedPeerCertSha256.join(','));
  410. }
  411. }
  412. applyExternalProxyTLSParams(externalProxy, params, security);
  413. } else if (security === 'reality') {
  414. params.set('security', 'reality');
  415. params.set('support-x25519mlkem768', 'true');
  416. if (stream.security === 'reality') {
  417. const reality = stream.realitySettings;
  418. params.set('pbk', reality.settings.publicKey);
  419. params.set('fp', reality.settings.fingerprint);
  420. const sni =
  421. reality.settings.serverName || reality.serverNames?.[0] || reality.target?.split(':')[0];
  422. if (sni && sni.length > 0) params.set('sni', sni);
  423. if (reality.shortIds.length > 0) params.set('sid', reality.shortIds[0]);
  424. const spx = deriveSpiderX(reality.settings.spiderX, clientKey);
  425. if (spx.length > 0) params.set('spx', spx);
  426. if (reality.settings.mldsa65Verify.length > 0)
  427. params.set('pqv', reality.settings.mldsa65Verify);
  428. }
  429. } else {
  430. params.set('security', 'none');
  431. }
  432. // XTLS Vision flow: TCP over tls/reality (classic) or XHTTP+vlessenc (the
  433. // VLESS-level encryption stands in for transport TLS). Mirrors the backend's
  434. // vlessFlowAllowed and the form's flow-field gating so panel link, share
  435. // link and subscription agree.
  436. if (
  437. flow.length > 0 &&
  438. canEnableTlsFlow({
  439. protocol: inbound.protocol,
  440. settings: inbound.settings,
  441. streamSettings: stream,
  442. })
  443. ) {
  444. params.set('flow', flow);
  445. }
  446. const url = new URL(
  447. `vless://${applyVlessRoute(clientId, externalProxy?.vlessRoute)}@${formatUrlHost(address)}:${port}`,
  448. );
  449. for (const [key, value] of params) url.searchParams.set(key, value);
  450. url.hash = encodeURIComponent(remark);
  451. return url.toString();
  452. }
  453. // Shared network-branch writer used by trojan + shadowsocks links.
  454. // VLESS and VMess don't call this because they have minor per-protocol
  455. // quirks inline (vmess maps `multi` differently into obj.type; vless sets
  456. // encryption=none up-front).
  457. function writeNetworkParams(
  458. stream: NonNullable<Inbound['streamSettings']>,
  459. params: URLSearchParams,
  460. ): void {
  461. if (stream.network === 'tcp') {
  462. const tcp = stream.tcpSettings;
  463. if (tcp.header?.type === 'http') {
  464. const request = tcp.header.request;
  465. if (request) {
  466. params.set('path', request.path.join(','));
  467. const host =
  468. getHeaderValue(tcp.header.response?.headers, 'host') ||
  469. getHeaderValue(request.headers, 'host');
  470. if (host) params.set('host', host);
  471. params.set('headerType', 'http');
  472. }
  473. }
  474. } else if (stream.network === 'kcp') {
  475. const kcp = stream.kcpSettings;
  476. params.set('mtu', String(kcp.mtu));
  477. params.set('tti', String(kcp.tti));
  478. } else if (stream.network === 'ws') {
  479. const ws = stream.wsSettings;
  480. params.set('path', ws.path);
  481. params.set('host', ws.host.length > 0 ? ws.host : getHeaderValue(ws.headers, 'host'));
  482. } else if (stream.network === 'grpc') {
  483. const grpc = stream.grpcSettings;
  484. params.set('serviceName', grpc.serviceName);
  485. params.set('authority', grpc.authority);
  486. if (grpc.multiMode) params.set('mode', 'multi');
  487. } else if (stream.network === 'httpupgrade') {
  488. const hu = stream.httpupgradeSettings;
  489. params.set('path', hu.path);
  490. params.set('host', hu.host.length > 0 ? hu.host : getHeaderValue(hu.headers, 'host'));
  491. } else if (stream.network === 'xhttp') {
  492. applyXhttpExtraToParams(stream.xhttpSettings, params);
  493. }
  494. }
  495. function writeTlsParams(
  496. stream: NonNullable<Inbound['streamSettings']>,
  497. params: URLSearchParams,
  498. ): void {
  499. if (stream.security !== 'tls') return;
  500. const tls = stream.tlsSettings;
  501. if (tls.settings.fingerprint.length > 0) params.set('fp', tls.settings.fingerprint);
  502. params.set('alpn', tls.alpn.join(','));
  503. if (tls.settings.echConfigList.length > 0) params.set('ech', tls.settings.echConfigList);
  504. if (tls.serverName.length > 0) params.set('sni', tls.serverName);
  505. if (tls.settings.verifyPeerCertByName.length > 0) {
  506. params.set('vcn', tls.settings.verifyPeerCertByName);
  507. }
  508. if (tls.settings.pinnedPeerCertSha256.length > 0) {
  509. params.set('pcs', tls.settings.pinnedPeerCertSha256.join(','));
  510. }
  511. }
  512. // Reality query-string writer shared by VLESS and Trojan. Preserves the
  513. // legacy SNI-omission quirk (see genVlessLink for the full story).
  514. function writeRealityParams(
  515. stream: NonNullable<Inbound['streamSettings']>,
  516. params: URLSearchParams,
  517. clientKey: string,
  518. ): void {
  519. if (stream.security !== 'reality') return;
  520. const reality = stream.realitySettings;
  521. params.set('pbk', reality.settings.publicKey);
  522. params.set('fp', reality.settings.fingerprint);
  523. const sni =
  524. reality.settings.serverName || reality.serverNames?.[0] || reality.target?.split(':')[0];
  525. if (sni && sni.length > 0) params.set('sni', sni);
  526. if (reality.shortIds.length > 0) params.set('sid', reality.shortIds[0]);
  527. const spx = deriveSpiderX(reality.settings.spiderX, clientKey);
  528. if (spx.length > 0) params.set('spx', spx);
  529. if (reality.settings.mldsa65Verify.length > 0) params.set('pqv', reality.settings.mldsa65Verify);
  530. }
  531. export interface GenTrojanLinkInput {
  532. inbound: Inbound;
  533. address: string;
  534. port?: number;
  535. forceTls?: ForceTls;
  536. remark?: string;
  537. clientPassword: string;
  538. clientKey?: string;
  539. externalProxy?: ExternalProxyEntry | null;
  540. }
  541. // Trojan share link: trojan://<password>@<host>:<port>?<query>#<remark>.
  542. // Same query-string shape as VLESS minus the `encryption` and `flow`
  543. // fields. Returns '' if the inbound isn't trojan.
  544. export function genTrojanLink(input: GenTrojanLinkInput): string {
  545. const {
  546. inbound,
  547. address,
  548. port = inbound.port,
  549. forceTls = 'same',
  550. remark = '',
  551. clientPassword,
  552. clientKey = '',
  553. externalProxy = null,
  554. } = input;
  555. if (inbound.protocol !== 'trojan') return '';
  556. const stream = inbound.streamSettings;
  557. if (!stream) return '';
  558. const security = forceTls === 'same' ? stream.security : forceTls;
  559. const params = new URLSearchParams();
  560. params.set('type', stream.network ?? 'tcp');
  561. writeNetworkParams(stream, params);
  562. applyFinalMaskToParams(stream.finalmask, params);
  563. if (security === 'tls') {
  564. params.set('security', 'tls');
  565. writeTlsParams(stream, params);
  566. applyExternalProxyTLSParams(externalProxy, params, security);
  567. } else if (security === 'reality') {
  568. params.set('security', 'reality');
  569. writeRealityParams(stream, params, clientKey);
  570. } else {
  571. params.set('security', 'none');
  572. }
  573. const url = new URL(
  574. `trojan://${encodeURIComponent(clientPassword)}@${formatUrlHost(address)}:${port}`,
  575. );
  576. for (const [key, value] of params) url.searchParams.set(key, value);
  577. url.hash = encodeURIComponent(remark);
  578. return url.toString();
  579. }
  580. export interface GenShadowsocksLinkInput {
  581. inbound: Inbound;
  582. address: string;
  583. port?: number;
  584. forceTls?: ForceTls;
  585. remark?: string;
  586. clientPassword?: string;
  587. externalProxy?: ExternalProxyEntry | null;
  588. }
  589. // Shadowsocks 2022 share link. The userinfo portion is base64(method:pw)
  590. // for single-user and base64(method:settingsPw:clientPw) for multi-user
  591. // 2022-blake3. Legacy SS (non-2022) leaves the password out of the
  592. // userinfo entirely — matches the legacy class's password-array logic.
  593. // Note: legacy `isSSMultiUser` returns true for everything except
  594. // 2022-blake3-chacha20-poly1305 (a curious classification, but we
  595. // preserve it for byte-stable parity).
  596. export function genShadowsocksLink(input: GenShadowsocksLinkInput): string {
  597. const {
  598. inbound,
  599. address,
  600. port = inbound.port,
  601. forceTls = 'same',
  602. remark = '',
  603. clientPassword = '',
  604. externalProxy = null,
  605. } = input;
  606. if (inbound.protocol !== 'shadowsocks') return '';
  607. const stream = inbound.streamSettings;
  608. if (!stream) return '';
  609. const settings = inbound.settings;
  610. const security = forceTls === 'same' ? stream.security : forceTls;
  611. const params = new URLSearchParams();
  612. params.set('type', stream.network ?? 'tcp');
  613. writeNetworkParams(stream, params);
  614. applyFinalMaskToParams(stream.finalmask, params);
  615. if (security === 'tls') {
  616. params.set('security', 'tls');
  617. writeTlsParams(stream, params);
  618. applyExternalProxyTLSParams(externalProxy, params, security);
  619. }
  620. // SIP002 clients (v2rayN) ignore type/headerType/host/path and only read
  621. // `plugin`. Re-encode a TCP http header as obfs-local so they build a
  622. // matching tcp/http outbound (v2rayN forces request path "/").
  623. if ((stream.network ?? 'tcp') === 'tcp' && params.get('headerType') === 'http') {
  624. const host = params.get('host') ?? '';
  625. params.delete('type');
  626. params.delete('headerType');
  627. params.delete('host');
  628. params.delete('path');
  629. params.set('plugin', `obfs-local;obfs=http;obfs-host=${host}`);
  630. }
  631. const isSS2022 = settings.method.substring(0, 4) === '2022';
  632. const isSSMultiUser = settings.method !== '2022-blake3-chacha20-poly1305';
  633. const passwords: string[] = [];
  634. if (isSS2022) passwords.push(settings.password);
  635. if (isSSMultiUser) passwords.push(clientPassword);
  636. if (isSS2022) {
  637. // SIP022 (2022-blake3-*) forbids base64 userinfo: method and each key are
  638. // percent-encoded, joined by literal ':' separators. Built by hand because
  639. // `new URL` would re-encode the inner key separator to %3A.
  640. const userinfo = [settings.method, ...passwords].map(encodeURIComponent).join(':');
  641. let link = `ss://${userinfo}@${formatUrlHost(address)}:${port}`;
  642. const query = params.toString();
  643. if (query) link += `?${query}`;
  644. link += `#${encodeURIComponent(remark)}`;
  645. return link;
  646. }
  647. // SIP002 userinfo is base64(method:pw).
  648. const userinfo = Base64.encode(`${settings.method}:${passwords.join(':')}`, true);
  649. const url = new URL(`ss://${userinfo}@${formatUrlHost(address)}:${port}`);
  650. for (const [key, value] of params) url.searchParams.set(key, value);
  651. url.hash = encodeURIComponent(remark);
  652. return url.toString();
  653. }
  654. export interface GenHysteriaLinkInput {
  655. inbound: Inbound;
  656. address: string;
  657. port?: number;
  658. remark?: string;
  659. clientAuth: string;
  660. externalProxy?: ExternalProxyEntry | null;
  661. }
  662. // Hysteria2's pinSHA256 must be a 64-char lowercase hex string — Xray-core
  663. // clients hex-decode it and crash on a base64 value. The panel stores pins as
  664. // base64 (xray-core's native TLS format / the generate button) or hex, either
  665. // bare or colon-separated as `openssl x509 -fingerprint -sha256` emits it. Each
  666. // entry is coerced to bare hex. Values that are neither a 32-byte hex nor a
  667. // 32-byte base64 SHA-256 pass through unchanged.
  668. function hysteriaPinHex(pin: string): string {
  669. const stripped = pin.trim().replace(/:/g, '');
  670. if (/^[0-9a-fA-F]{64}$/.test(stripped)) return stripped.toLowerCase();
  671. try {
  672. const binary = atob(pin.trim().replace(/-/g, '+').replace(/_/g, '/'));
  673. if (binary.length !== 32) return pin;
  674. let hex = '';
  675. for (let i = 0; i < binary.length; i++) {
  676. hex += binary.charCodeAt(i).toString(16).padStart(2, '0');
  677. }
  678. return hex;
  679. } catch {
  680. return pin;
  681. }
  682. }
  683. // Hysteria2 hop range advertised as `mport`. xray-core 26.9.9 moved hopping
  684. // from finalmask.quicParams.udpHop to a 'udphop' UDP mask; inbounds stored
  685. // before the upgrade still carry the old key.
  686. function udpHopPorts(stream: NonNullable<Inbound['streamSettings']>): string {
  687. for (const mask of stream.finalmask?.udp ?? []) {
  688. if (mask.type !== 'udphop') continue;
  689. const ports = mask.settings?.remotePorts;
  690. if (typeof ports === 'string' && ports.trim().length > 0) return ports.trim();
  691. }
  692. return stream.finalmask?.quicParams?.udpHop?.ports?.trim() ?? '';
  693. }
  694. // Hysteria share link: hysteria2://<auth>@<host>:<port>?<query>#<remark>.
  695. // The scheme is always hysteria2 — xray-core builds version 2 only, so the
  696. // settings schema pins it there and the subscription server emits the same
  697. // scheme. Salamander obfuscation pulls its password from
  698. // finalmask.udp[type=salamander] when present; the broader finalmask payload
  699. // still rides under `fm` like the other links.
  700. //
  701. // Note: legacy genHysteriaLink reads stream.tls.settings.allowInsecure,
  702. // which isn't a field on TlsStreamSettings.Settings — the guard is always
  703. // false. We omit the `insecure` param here to stay byte-stable.
  704. export function genHysteriaLink(input: GenHysteriaLinkInput): string {
  705. const {
  706. inbound,
  707. address,
  708. port = inbound.port,
  709. remark = '',
  710. clientAuth,
  711. externalProxy = null,
  712. } = input;
  713. if (inbound.protocol !== 'hysteria') return '';
  714. const stream = inbound.streamSettings;
  715. if (!stream || stream.security !== 'tls') return '';
  716. const scheme = 'hysteria2';
  717. const params = new URLSearchParams();
  718. params.set('security', 'tls');
  719. const tls = stream.tlsSettings;
  720. if (tls.settings.fingerprint.length > 0) params.set('fp', tls.settings.fingerprint);
  721. if (tls.alpn.length > 0) params.set('alpn', tls.alpn.join(','));
  722. if (tls.settings.echConfigList.length > 0) params.set('ech', tls.settings.echConfigList);
  723. if (tls.serverName.length > 0) params.set('sni', tls.serverName);
  724. if (tls.settings.verifyPeerCertByName.length > 0) {
  725. params.set('vcn', tls.settings.verifyPeerCertByName);
  726. }
  727. if (tls.settings.pinnedPeerCertSha256.length > 0) {
  728. params.set('pinSHA256', tls.settings.pinnedPeerCertSha256.map(hysteriaPinHex).join(','));
  729. }
  730. // An external-proxy entry can pin a different endpoint's certificate.
  731. // Hysteria carries it as hex `pinSHA256` (not the `pcs` other protocols
  732. // use), so coerce each entry through hysteriaPinHex like the main pin.
  733. if (Array.isArray(externalProxy?.pinnedPeerCertSha256)) {
  734. const epPins = externalProxy.pinnedPeerCertSha256.filter(Boolean).map(hysteriaPinHex);
  735. if (epPins.length > 0) params.set('pinSHA256', epPins.join(','));
  736. }
  737. const udpMasks = stream.finalmask?.udp;
  738. if (Array.isArray(udpMasks)) {
  739. const salamander = udpMasks.find((m) => m?.type === 'salamander');
  740. const obfsPassword = salamander?.settings?.password;
  741. if (typeof obfsPassword === 'string' && obfsPassword.length > 0) {
  742. // packetSize (Gecko mode) exports via v2rayN's native fields; the
  743. // experimental fm=<json> dump breaks mihomo and other strict clients.
  744. const range = parseGeckoPacketSize(salamander?.settings?.packetSize);
  745. if (range) {
  746. params.set('obfs', 'gecko');
  747. params.set('minPacketSize', String(range.min));
  748. params.set('maxPacketSize', String(range.max));
  749. } else {
  750. params.set('obfs', 'salamander');
  751. }
  752. params.set('obfs-password', obfsPassword);
  753. }
  754. }
  755. const hopPorts = udpHopPorts(stream);
  756. if (hopPorts.length > 0) {
  757. params.set('mport', hopPorts);
  758. }
  759. const url = new URL(`${scheme}://${clientAuth}@${formatUrlHost(address)}:${port}`);
  760. for (const [key, value] of params) url.searchParams.set(key, value);
  761. url.hash = encodeURIComponent(remark);
  762. return url.toString();
  763. }
  764. export interface GenMtprotoLinkInput {
  765. inbound: Inbound;
  766. address: string;
  767. port?: number;
  768. clientSecret?: string;
  769. }
  770. // Builds a per-client Telegram proxy deep link for an mtproto inbound from the
  771. // client's own FakeTLS secret. No remark fragment is added: Telegram proxy deep
  772. // links have no name field, and a trailing "#remark" gets folded into the last
  773. // query value by lenient parsers, breaking the server address. The panel shows
  774. // the remark separately from the link.
  775. export function genMtprotoLink(input: GenMtprotoLinkInput): string {
  776. const { inbound, address, port = inbound.port, clientSecret = '' } = input;
  777. if (inbound.protocol !== 'mtproto') return '';
  778. if (clientSecret.length === 0) return '';
  779. const url = new URL('tg://proxy');
  780. url.searchParams.set('server', address);
  781. url.searchParams.set('port', String(port));
  782. url.searchParams.set('secret', clientSecret);
  783. return url.toString();
  784. }
  785. export interface GenTuicLinkInput {
  786. inbound: Inbound;
  787. address: string;
  788. port?: number;
  789. remark?: string;
  790. clientUuid?: string;
  791. clientPassword?: string;
  792. externalProxy?: ExternalProxyEntry | null;
  793. }
  794. export function genTuicLink(input: GenTuicLinkInput): string {
  795. const {
  796. inbound,
  797. address,
  798. port = inbound.port,
  799. remark = '',
  800. clientUuid = '',
  801. clientPassword = '',
  802. externalProxy = null,
  803. } = input;
  804. if (!clientUuid || !clientPassword) return '';
  805. const rawSettings = inbound.settings as Record<string, unknown>;
  806. const server = (rawSettings.server as Record<string, unknown>) ?? rawSettings;
  807. const host = formatUrlHost(externalProxy?.dest || address);
  808. const targetPort = externalProxy?.port || port;
  809. const url = new URL(
  810. `tuic://${encodeURIComponent(clientUuid)}:${encodeURIComponent(clientPassword)}@${host}:${targetPort}`,
  811. );
  812. const cc =
  813. (server.congestion_control as string) || (rawSettings.congestion_control as string) || 'bbr';
  814. url.searchParams.set('congestion_control', cc);
  815. const epAlpn = externalProxyAlpn(externalProxy?.alpn);
  816. const alpn =
  817. epAlpn ||
  818. (Array.isArray(server.alpn) && server.alpn.length > 0
  819. ? (server.alpn as string[]).join(',')
  820. : null) ||
  821. (Array.isArray(rawSettings.alpn) && rawSettings.alpn.length > 0
  822. ? (rawSettings.alpn as string[]).join(',')
  823. : null) ||
  824. 'h3,spdy/3.1';
  825. url.searchParams.set('alpn', alpn);
  826. const sni = externalProxy?.sni || (server.sni as string) || (rawSettings.sni as string);
  827. if (sni) {
  828. url.searchParams.set('sni', sni);
  829. }
  830. const udpRelay =
  831. (server.udp_relay_mode as string) || (rawSettings.udp_relay_mode as string) || 'native';
  832. url.searchParams.set('udp_relay_mode', udpRelay);
  833. const allowInsecure = externalProxy?.allowInsecure ? '1' : '0';
  834. url.searchParams.set('allow_insecure', allowInsecure);
  835. if (remark) {
  836. url.hash = encodeURIComponent(remark);
  837. }
  838. return url.toString();
  839. }
  840. export interface GenWireguardLinkInput {
  841. settings: WireguardInboundSettings;
  842. address: string;
  843. port: number;
  844. remark?: string;
  845. peerIndex: number;
  846. }
  847. // Wireguard share link: wireguard://<peerPrivKey>@<host>:<port>
  848. // ?publickey=<serverPub>&address=<peerAllowedIP>&mtu=<mtu>#<remark>
  849. // pubKey is derived from the server's secretKey via Wireguard.generateKeypair
  850. // at call time (Zod's schema stores secretKey only — pubKey isn't on the
  851. // wire). Returns '' when the peer index is out of bounds.
  852. export function genWireguardLink(input: GenWireguardLinkInput): string {
  853. const { settings, address, port, remark = '', peerIndex } = input;
  854. const peer = settings.peers[peerIndex];
  855. if (!peer) return '';
  856. const url = new URL(`wireguard://${formatUrlHost(address)}:${port}`);
  857. url.username = peer.privateKey ?? '';
  858. const pubKey =
  859. settings.secretKey.length > 0 ? Wireguard.generateKeypair(settings.secretKey).publicKey : '';
  860. if (pubKey.length > 0) url.searchParams.set('publickey', pubKey);
  861. if (peer.allowedIPs.length > 0) {
  862. url.searchParams.set('address', peer.allowedIPs.join(','));
  863. }
  864. if (typeof settings.mtu === 'number' && settings.mtu > 0) {
  865. url.searchParams.set('mtu', String(settings.mtu));
  866. }
  867. url.hash = encodeURIComponent(remark);
  868. return url.toString();
  869. }
  870. // Plain-text WireGuard client config (.conf format). Mirrors the legacy
  871. // getWireguardTxt — same DNS defaults (1.1.1.1, 1.0.0.1), MTU optional,
  872. // presharedKey + keepAlive only emitted when present on the peer. The
  873. // final newline structure follows the legacy: no newline after Endpoint,
  874. // optional preSharedKey appended with leading \n, keepAlive appended
  875. // with leading \n AND trailing \n.
  876. export function genWireguardConfig(input: GenWireguardLinkInput): string {
  877. const { settings, address, port, remark = '', peerIndex } = input;
  878. const peer = settings.peers[peerIndex];
  879. if (!peer) return '';
  880. const pubKey =
  881. settings.secretKey.length > 0 ? Wireguard.generateKeypair(settings.secretKey).publicKey : '';
  882. let txt = `[Interface]\n`;
  883. txt += `PrivateKey = ${peer.privateKey ?? ''}\n`;
  884. txt += `Address = ${peer.allowedIPs.join(', ')}\n`;
  885. txt += `DNS = ${settings.dns || '1.1.1.1, 1.0.0.1'}\n`;
  886. if (typeof settings.mtu === 'number' && settings.mtu > 0) {
  887. txt += `MTU = ${settings.mtu}\n`;
  888. }
  889. txt += `\n# ${remark}\n`;
  890. txt += `[Peer]\n`;
  891. txt += `PublicKey = ${pubKey}\n`;
  892. txt += `AllowedIPs = 0.0.0.0/0, ::/0\n`;
  893. txt += `Endpoint = ${address}:${port}`;
  894. if (peer.preSharedKey && peer.preSharedKey.length > 0) {
  895. txt += `\nPresharedKey = ${peer.preSharedKey}`;
  896. }
  897. if (typeof peer.keepAlive === 'number' && peer.keepAlive > 0) {
  898. txt += `\nPersistentKeepalive = ${peer.keepAlive}\n`;
  899. }
  900. return txt;
  901. }
  902. // Shared input shape for both the per-client vpn:// link and .conf
  903. // builders below — settings.clients (not a peers array; unlike WireGuard,
  904. // AmneziaWG was multi-client from day one, so there's no legacy format).
  905. export interface GenAmneziaWGLinkInput {
  906. settings: AmneziawgInboundSettings;
  907. address: string;
  908. port: number;
  909. remark?: string;
  910. peerIndex: number;
  911. }
  912. function amneziaWGHLine(key: string, value: string | undefined, fallback: string): string {
  913. return `${key} = ${value && value.trim() !== '' ? value : fallback}`;
  914. }
  915. // Base64url (RFC 4648 §5), no padding — matches the real AmneziaVPN app's
  916. // own Qt::Base64UrlEncoding | Qt::OmitTrailingEquals framing for vpn:// links.
  917. function toBase64Url(text: string): string {
  918. const bytes = new TextEncoder().encode(text);
  919. let binary = '';
  920. for (const b of bytes) binary += String.fromCharCode(b);
  921. return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
  922. }
  923. // AmneziaWG share link: vpn://<base64url .conf text>, matching the real
  924. // AmneziaVPN app's own share-link scheme. The app's import path base64url-
  925. // decodes, best-effort qUncompresses (falls back to the raw bytes when the
  926. // input isn't qCompress-framed, which plain text never is), then parses the
  927. // result as a flat bag of "Key = Value" lines regardless of which
  928. // [Interface]/[Peer] section they came from — so wrapping the same .conf
  929. // text genAmneziaWGConfig already produces is sufficient; no JSON schema or
  930. // compression needs replicating. Confirmed against the app's own source
  931. // (importController.cpp's checkConfigFormat/extractWireGuardConfig).
  932. export function genAmneziaWGLink(input: GenAmneziaWGLinkInput): string {
  933. const cfgText = genAmneziaWGConfig(input);
  934. if (!cfgText) return '';
  935. return `vpn://${toBase64Url(cfgText)}`;
  936. }
  937. // Plain-text AmneziaWG client config (.conf format). Mirrors
  938. // genWireguardConfig, plus the obfuscation lines every AmneziaWG client must
  939. // share with the server (see internal/amneziawg.writeObfuscation on the Go
  940. // side).
  941. export function genAmneziaWGConfig(input: GenAmneziaWGLinkInput): string {
  942. const { settings, address, port, remark = '', peerIndex } = input;
  943. const client = settings.clients[peerIndex];
  944. if (!client) return '';
  945. const server = settings.server;
  946. // These land unescaped in the .conf; a newline would inject a config line
  947. // (e.g. a rogue PostUp) — same guard as the panel's other two emitters.
  948. for (const v of [
  949. client.privateKey ?? '',
  950. server.primaryDns ?? '',
  951. server.secondaryDns ?? '',
  952. remark,
  953. ]) {
  954. if (/[\r\n]/.test(v)) return '';
  955. }
  956. let txt = `[Interface]\n`;
  957. txt += `PrivateKey = ${client.privateKey ?? ''}\n`;
  958. txt += `Address = ${(client.allowedIPs ?? []).join(', ')}\n`;
  959. const dns = [server.primaryDns, server.secondaryDns].filter((v) => !!v && v.trim() !== '');
  960. if (dns.length > 0) txt += `DNS = ${dns.join(', ')}\n`;
  961. txt += `MTU = ${effectiveMtu(server.mtu, server.s4)}\n`;
  962. txt += `Jc = ${server.jc}\n`;
  963. txt += `Jmin = ${server.jmin}\n`;
  964. txt += `Jmax = ${server.jmax}\n`;
  965. txt += `S1 = ${server.s1}\n`;
  966. txt += `S2 = ${server.s2}\n`;
  967. if (server.s3) txt += `S3 = ${server.s3}\n`;
  968. if (server.s4) txt += `S4 = ${server.s4}\n`;
  969. txt += `${amneziaWGHLine('H1', server.h1, '1')}\n`;
  970. txt += `${amneziaWGHLine('H2', server.h2, '2')}\n`;
  971. txt += `${amneziaWGHLine('H3', server.h3, '3')}\n`;
  972. txt += `${amneziaWGHLine('H4', server.h4, '4')}\n`;
  973. if (server.i1) txt += `I1 = ${server.i1}\n`;
  974. if (server.i2) txt += `I2 = ${server.i2}\n`;
  975. if (server.i3) txt += `I3 = ${server.i3}\n`;
  976. if (server.i4) txt += `I4 = ${server.i4}\n`;
  977. if (server.i5) txt += `I5 = ${server.i5}\n`;
  978. const optional31: Array<[string, string | undefined]> = [
  979. ['HeaderProtectionKey', server.headerProtectionKey],
  980. ['ContentPaddingAddition', server.contentPaddingAddition],
  981. ['RekeyAfterTime', server.rekeyAfterTime],
  982. ['RekeyTimeout', server.rekeyTimeout],
  983. ['RejectAfterTime', server.rejectAfterTime],
  984. ['KeepaliveTimeout', server.keepaliveTimeout],
  985. ['MaxHandshakeAttempts', server.maxHandshakeAttempts],
  986. ];
  987. for (const [key, value] of optional31) {
  988. if (value && value.trim() !== '') txt += `${key} = ${value}\n`;
  989. }
  990. if (server.randomTrailers) txt += `RandomTrailers = on\n`;
  991. if (server.disableCookies) txt += `DisableCookies = on\n`;
  992. // Peer field order follows wg-quick(8) and the panel's other two AmneziaWG
  993. // emitters (amneziaWGConfigText in Go, buildAmneziaWGClientConfig); all three
  994. // are independent implementations and must not drift apart.
  995. txt += `\n# ${remark}\n`;
  996. txt += `[Peer]\n`;
  997. txt += `PublicKey = ${server.publicKey ?? ''}\n`;
  998. if (client.preSharedKey && client.preSharedKey.length > 0) {
  999. txt += `PresharedKey = ${client.preSharedKey}\n`;
  1000. }
  1001. txt += `AllowedIPs = 0.0.0.0/0, ::/0\n`;
  1002. txt += `Endpoint = ${address}:${port}`;
  1003. if (typeof client.keepAlive === 'number' && client.keepAlive > 0) {
  1004. txt += `\nPersistentKeepalive = ${client.keepAlive}`;
  1005. }
  1006. return txt;
  1007. }
  1008. export interface GenAmneziaWGFanoutInput {
  1009. inbound: Inbound;
  1010. remark?: string;
  1011. hostOverride?: string;
  1012. fallbackHostname: string;
  1013. }
  1014. function amneziaWGFanout(
  1015. input: GenAmneziaWGFanoutInput,
  1016. render: (input: GenAmneziaWGLinkInput) => string,
  1017. ): string[][] {
  1018. const { inbound, remark = '', hostOverride = '', fallbackHostname } = input;
  1019. if (inbound.protocol !== 'amneziawg') return [];
  1020. const endpoints = tunnelEndpoints(inbound, resolveAddr(inbound, hostOverride, fallbackHostname));
  1021. const settings = inbound.settings as AmneziawgInboundSettings;
  1022. const clients = settings.clients ?? [];
  1023. return clients.map((c, i) =>
  1024. endpoints.map((e) =>
  1025. render({
  1026. settings,
  1027. address: e.address,
  1028. port: e.port,
  1029. remark: tunnelPeerRemark(remark, e.remark, i, c),
  1030. peerIndex: i,
  1031. }),
  1032. ),
  1033. );
  1034. }
  1035. // Per-peer lists with one entry per advertised endpoint (Host), peer-major.
  1036. export function genAmneziaWGPeerLinks(input: GenAmneziaWGFanoutInput): string[][] {
  1037. return amneziaWGFanout(input, genAmneziaWGLink);
  1038. }
  1039. export function genAmneziaWGPeerConfigs(input: GenAmneziaWGFanoutInput): string[][] {
  1040. return amneziaWGFanout(input, genAmneziaWGConfig);
  1041. }
  1042. export function genAmneziaWGLinks(input: GenAmneziaWGFanoutInput): string {
  1043. return genAmneziaWGPeerLinks(input).flat().join('\r\n');
  1044. }
  1045. export function genAmneziaWGConfigs(input: GenAmneziaWGFanoutInput): string {
  1046. return genAmneziaWGPeerConfigs(input).flat().join('\r\n');
  1047. }
  1048. export function wireguardConfigFromLink(link: string, fallbackRemark = ''): string {
  1049. let url: URL;
  1050. try {
  1051. url = new URL(link);
  1052. } catch {
  1053. return '';
  1054. }
  1055. const scheme = url.protocol.replace(/:$/, '');
  1056. if (scheme !== 'wireguard' && scheme !== 'wg') return '';
  1057. const params = url.searchParams;
  1058. const pick = (...keys: string[]): string => {
  1059. for (const k of keys) {
  1060. const v = params.get(k);
  1061. if (v) return v;
  1062. }
  1063. return '';
  1064. };
  1065. let privateKey: string;
  1066. try {
  1067. privateKey = decodeURIComponent(url.username);
  1068. } catch {
  1069. privateKey = url.username;
  1070. }
  1071. const host = url.hostname;
  1072. const endpoint = host ? (url.port ? `${host}:${url.port}` : host) : '';
  1073. const address = pick('address', 'ip') || '10.0.0.2/32';
  1074. const publicKey = pick('publickey', 'publicKey', 'public_key', 'peerPublicKey');
  1075. const dns = pick('dns') || '1.1.1.1, 1.0.0.1';
  1076. const mtu = pick('mtu');
  1077. const psk = pick('presharedkey', 'preshared_key', 'pre-shared-key', 'psk');
  1078. const keepAlive = pick('keepalive', 'persistentkeepalive', 'persistent_keepalive');
  1079. const allowedIPs = pick('allowedips', 'allowed_ips') || '0.0.0.0/0, ::/0';
  1080. let remark = fallbackRemark;
  1081. try {
  1082. const decoded = decodeURIComponent(url.hash.replace(/^#/, ''));
  1083. if (decoded) remark = decoded;
  1084. } catch {
  1085. const raw = url.hash.replace(/^#/, '');
  1086. if (raw) remark = raw;
  1087. }
  1088. const lines = [
  1089. '[Interface]',
  1090. `PrivateKey = ${privateKey}`,
  1091. `Address = ${address}`,
  1092. `DNS = ${dns}`,
  1093. ];
  1094. if (mtu && Number(mtu) > 0) lines.push(`MTU = ${mtu}`);
  1095. lines.push('');
  1096. if (remark) lines.push(`# ${remark}`);
  1097. lines.push('[Peer]', `PublicKey = ${publicKey}`);
  1098. if (psk) lines.push(`PresharedKey = ${psk}`);
  1099. lines.push(`AllowedIPs = ${allowedIPs}`, `Endpoint = ${endpoint}`);
  1100. if (keepAlive && Number(keepAlive) > 0) lines.push(`PersistentKeepalive = ${keepAlive}`);
  1101. return lines.join('\n');
  1102. }
  1103. // Reverse of toBase64Url above -- recovers a vpn:// link's plain .conf
  1104. // payload for display/copy/download/QR, the AmneziaWG counterpart of
  1105. // wireguardConfigFromLink. Simpler than that function: a vpn:// link's
  1106. // payload already *is* the .conf text (see genAmneziaWGLink's own doc
  1107. // comment), so there's nothing to reconstruct from query params -- just
  1108. // decode. Mirrors link-label.tsx's own private fromBase64Url (used there
  1109. // only to pull the remark/port back out for the tag label); duplicated
  1110. // rather than imported since both are tiny, self-contained, and each
  1111. // file already owns the matching encode or decode half of this pair.
  1112. function fromBase64Url(value: string): string {
  1113. const b64 = value.replace(/-/g, '+').replace(/_/g, '/');
  1114. const padded = b64 + '='.repeat((4 - (b64.length % 4)) % 4);
  1115. const binary = atob(padded);
  1116. const bytes = new Uint8Array(binary.length);
  1117. for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
  1118. return new TextDecoder().decode(bytes);
  1119. }
  1120. export function amneziawgConfigFromLink(link: string): string {
  1121. const trimmed = link.trim();
  1122. if (!trimmed.startsWith('vpn://')) return '';
  1123. try {
  1124. return fromBase64Url(trimmed.slice('vpn://'.length));
  1125. } catch {
  1126. return '';
  1127. }
  1128. }
  1129. export type { WireguardInboundPeer };
  1130. function isUnixSocketListen(listen: string): boolean {
  1131. return listen.startsWith('/') || listen.startsWith('@');
  1132. }
  1133. function normalizeShareHost(host: string): string {
  1134. const h = host.trim();
  1135. if (h.length === 0 || h.includes('://') || h.startsWith('//') || /[/?#@]/.test(h)) {
  1136. return '';
  1137. }
  1138. if (h.startsWith('[')) {
  1139. if (!h.endsWith(']')) return '';
  1140. try {
  1141. return new URL(`http://${h}`).hostname;
  1142. } catch {
  1143. return '';
  1144. }
  1145. }
  1146. if (h.includes(':')) {
  1147. try {
  1148. return new URL(`http://[${h}]`).hostname;
  1149. } catch {
  1150. return '';
  1151. }
  1152. }
  1153. return SHARE_HOSTNAME_RE.test(h) ? h : '';
  1154. }
  1155. function isShareableHost(host: string): boolean {
  1156. const h = normalizeShareHost(host)
  1157. .replace(/^\[|\]$/g, '')
  1158. .toLowerCase();
  1159. if (h.length === 0) return false;
  1160. if (h === '0.0.0.0' || h === '::' || h === '::0') return false;
  1161. if (h === 'localhost' || h === '::1' || h.startsWith('127.')) return false;
  1162. return true;
  1163. }
  1164. function shareableListenFrom(listen: string): string {
  1165. const trimmed = listen.trim();
  1166. return trimmed.length > 0 && !isUnixSocketListen(trimmed) && isShareableHost(trimmed)
  1167. ? normalizeShareHost(trimmed)
  1168. : '';
  1169. }
  1170. type ShareAddrStrategy = 'node' | 'listen' | 'custom';
  1171. function normalizeShareAddrStrategy(strategy: string | undefined): ShareAddrStrategy {
  1172. return strategy === 'listen' || strategy === 'custom' ? strategy : 'node';
  1173. }
  1174. // ShareHostFields is the subset of an inbound resolveShareHost needs, so callers
  1175. // holding only a lightweight projection (e.g. the clients page InboundOption)
  1176. // can pick the same host as the full-inbound share/QR path.
  1177. export interface ShareHostFields {
  1178. listen?: string;
  1179. shareAddr?: string;
  1180. shareAddrStrategy?: string;
  1181. }
  1182. // resolveShareHost picks the host that goes into share/QR links, the browser-side
  1183. // analog of the backend resolveInboundAddress. hostOverride is the hosting node's
  1184. // address (empty for this panel's own inbounds); fallbackHostname is the
  1185. // already-resolved panel/public host used as the last resort — kept verbatim when
  1186. // it fails normalization (e.g. an underscore intranet hostname) so the last
  1187. // resort never degrades to an empty host.
  1188. export function resolveShareHost(
  1189. fields: ShareHostFields,
  1190. hostOverride: string,
  1191. fallbackHostname: string,
  1192. ): string {
  1193. const nodeAddr = normalizeShareHost(hostOverride);
  1194. const listenAddr = shareableListenFrom(fields.listen ?? '');
  1195. const customAddr = normalizeShareHost(fields.shareAddr ?? '');
  1196. const fallbackAddr = normalizeShareHost(fallbackHostname) || fallbackHostname.trim();
  1197. switch (normalizeShareAddrStrategy(fields.shareAddrStrategy)) {
  1198. case 'listen':
  1199. return listenAddr || nodeAddr || fallbackAddr;
  1200. case 'custom':
  1201. return customAddr || nodeAddr || listenAddr || fallbackAddr;
  1202. default:
  1203. return nodeAddr || listenAddr || fallbackAddr;
  1204. }
  1205. }
  1206. // Orchestrators.
  1207. // resolveAddr picks the host that goes into share/QR links. The default
  1208. // `node` strategy keeps the previous node-address-first behavior for
  1209. // node-managed inbounds; other strategies let a row prefer its listen address
  1210. // or a custom endpoint.
  1211. export function resolveAddr(
  1212. inbound: Inbound,
  1213. hostOverride: string,
  1214. fallbackHostname: string,
  1215. ): string {
  1216. return resolveShareHost(inbound, hostOverride, fallbackHostname);
  1217. }
  1218. // A loopback browser host means the panel was reached through a tunnel (e.g.
  1219. // SSH-forwarded 127.0.0.1/localhost), so it can never be a shareable link host.
  1220. function isLoopbackHost(host: string): boolean {
  1221. const h = host
  1222. .trim()
  1223. .replace(/^\[|\]$/g, '')
  1224. .toLowerCase();
  1225. return h === 'localhost' || h === '::1' || h.startsWith('127.');
  1226. }
  1227. // preferPublicHost is the browser-side analog of the backend's
  1228. // configuredPublicHost: when the panel is reached on a loopback host, prefer a
  1229. // configured public host (Sub/Web Domain) for share/QR links instead of leaking
  1230. // localhost. An explicit per-inbound listen or node override still wins, since
  1231. // resolveAddr only reaches the fallbackHostname after those.
  1232. export function preferPublicHost(browserHost: string, publicHost: string): string {
  1233. return publicHost && isLoopbackHost(browserHost) ? publicHost : browserHost;
  1234. }
  1235. // Returns the client array for protocols that have one. SS returns its
  1236. // clients only in 2022-blake3 multi-user mode (matches the legacy
  1237. // `this.clients` getter, which used isSSMultiUser to gate). Returns null
  1238. // for SS single-user, http, mixed, tunnel, wireguard, hysteria2-without-
  1239. // clients, and any protocol without a clients array.
  1240. type ClientShape = {
  1241. id?: string;
  1242. uuid?: string;
  1243. security?: VmessSecurity;
  1244. flow?: VlessClient['flow'];
  1245. password?: string;
  1246. auth?: string;
  1247. secret?: string;
  1248. email?: string;
  1249. subId?: string;
  1250. };
  1251. // Mirror of the Go subKey: the stable per-client identity spx derivation
  1252. // keys on — subscription id first, unique email as the fallback.
  1253. function clientSubKey(client: ClientShape): string {
  1254. return client.subId || client.email || '';
  1255. }
  1256. export function getInboundClients(inbound: Inbound): ClientShape[] | null {
  1257. switch (inbound.protocol) {
  1258. case 'vmess':
  1259. return (inbound.settings.clients ?? []) as ClientShape[];
  1260. case 'vless':
  1261. return (inbound.settings.clients ?? []) as ClientShape[];
  1262. case 'trojan':
  1263. return (inbound.settings.clients ?? []) as ClientShape[];
  1264. case 'hysteria':
  1265. return (inbound.settings.clients ?? []) as ClientShape[];
  1266. case 'mtproto':
  1267. return (inbound.settings.clients ?? []) as ClientShape[];
  1268. case 'tuic':
  1269. return (inbound.settings.clients ?? []) as ClientShape[];
  1270. case 'shadowsocks': {
  1271. const isMultiUser = inbound.settings.method !== '2022-blake3-chacha20-poly1305';
  1272. return isMultiUser ? ((inbound.settings.clients ?? []) as ClientShape[]) : null;
  1273. }
  1274. default:
  1275. return null;
  1276. }
  1277. }
  1278. export interface GenLinkInput {
  1279. inbound: Inbound;
  1280. address: string;
  1281. port?: number;
  1282. forceTls?: ForceTls;
  1283. remark?: string;
  1284. client: ClientShape;
  1285. externalProxy?: ExternalProxyEntry | null;
  1286. }
  1287. // Per-protocol dispatcher matching the legacy `genLink` switch. Returns
  1288. // '' for protocols that don't have client-based share links (wireguard
  1289. // goes through genWireguardLinks/Configs separately, http/mixed/tunnel
  1290. // don't have share URLs).
  1291. export function genLink(input: GenLinkInput): string {
  1292. const {
  1293. inbound,
  1294. address,
  1295. port = inbound.port,
  1296. forceTls = 'same',
  1297. remark = '',
  1298. client,
  1299. externalProxy = null,
  1300. } = input;
  1301. switch (inbound.protocol) {
  1302. case 'vmess':
  1303. return genVmessLink({
  1304. inbound,
  1305. address,
  1306. port,
  1307. forceTls,
  1308. remark,
  1309. clientId: client.id ?? '',
  1310. security: client.security,
  1311. externalProxy,
  1312. });
  1313. case 'vless':
  1314. return genVlessLink({
  1315. inbound,
  1316. address,
  1317. port,
  1318. forceTls,
  1319. remark,
  1320. clientId: client.id ?? '',
  1321. clientKey: clientSubKey(client),
  1322. flow: client.flow,
  1323. externalProxy,
  1324. });
  1325. case 'shadowsocks': {
  1326. const isMultiUser = inbound.settings.method !== '2022-blake3-chacha20-poly1305';
  1327. return genShadowsocksLink({
  1328. inbound,
  1329. address,
  1330. port,
  1331. forceTls,
  1332. remark,
  1333. clientPassword: isMultiUser ? (client.password ?? '') : '',
  1334. externalProxy,
  1335. });
  1336. }
  1337. case 'trojan':
  1338. return genTrojanLink({
  1339. inbound,
  1340. address,
  1341. port,
  1342. forceTls,
  1343. remark,
  1344. clientPassword: client.password ?? '',
  1345. clientKey: clientSubKey(client),
  1346. externalProxy,
  1347. });
  1348. case 'hysteria':
  1349. return genHysteriaLink({
  1350. inbound,
  1351. address,
  1352. port,
  1353. remark,
  1354. clientAuth: client.auth ?? '',
  1355. externalProxy,
  1356. });
  1357. case 'mtproto':
  1358. return genMtprotoLink({ inbound, address, port, clientSecret: client.secret ?? '' });
  1359. case 'tuic':
  1360. return genTuicLink({
  1361. inbound,
  1362. address,
  1363. port,
  1364. remark,
  1365. clientUuid: client.uuid ?? client.id ?? '',
  1366. clientPassword: client.password ?? '',
  1367. externalProxy,
  1368. });
  1369. default:
  1370. return '';
  1371. }
  1372. }
  1373. export interface GenAllLinksEntry {
  1374. remark: string;
  1375. link: string;
  1376. }
  1377. export interface GenAllLinksInput {
  1378. inbound: Inbound;
  1379. remark?: string;
  1380. client: ClientShape;
  1381. hostOverride?: string;
  1382. fallbackHostname: string;
  1383. }
  1384. // Fans out a single client's link per externalProxy entry, or just one link
  1385. // when there are no external proxies. The panel copy/QR remark is the inbound
  1386. // remark plus the externalProxy remark, dash-joined (the configurable
  1387. // subscription remark model was removed; subscription output uses the template).
  1388. export function genAllLinks(input: GenAllLinksInput): GenAllLinksEntry[] {
  1389. const { inbound, remark = '', client, hostOverride = '', fallbackHostname } = input;
  1390. const addr = resolveAddr(inbound, hostOverride, fallbackHostname);
  1391. const port = inbound.port;
  1392. const composeRemark = (proxyRemark: string): string =>
  1393. [remark, proxyRemark].filter((x) => x.length > 0).join('-');
  1394. const externals = inbound.streamSettings?.externalProxy;
  1395. if (!externals || externals.length === 0) {
  1396. const r = composeRemark('');
  1397. return [
  1398. {
  1399. remark: r,
  1400. link: genLink({ inbound, address: addr, port, forceTls: 'same', remark: r, client }),
  1401. },
  1402. ];
  1403. }
  1404. return externals.map((ep) => {
  1405. const r = composeRemark(ep.remark);
  1406. return {
  1407. remark: r,
  1408. link: genLink({
  1409. inbound,
  1410. address: ep.dest,
  1411. port: ep.port,
  1412. forceTls: ep.forceTls,
  1413. remark: r,
  1414. client,
  1415. externalProxy: ep,
  1416. }),
  1417. };
  1418. });
  1419. }
  1420. export interface GenInboundLinksInput {
  1421. inbound: Inbound;
  1422. remark?: string;
  1423. hostOverride?: string;
  1424. fallbackHostname: string;
  1425. }
  1426. // Top-level entrypoint that produces the full \r\n-joined block a user
  1427. // pastes into a client. Iterates per-client for protocols with clients,
  1428. // falls back to a single SS link for single-user 2022-blake3-chacha20,
  1429. // and emits per-peer .conf blocks for wireguard and amneziawg. Returns '' for the
  1430. // other clientless protocols (http, mixed, tunnel).
  1431. export function genInboundLinks(input: GenInboundLinksInput): string {
  1432. const { inbound, remark = '', hostOverride = '', fallbackHostname } = input;
  1433. const addr = resolveAddr(inbound, hostOverride, fallbackHostname);
  1434. const clients = getInboundClients(inbound);
  1435. if (clients) {
  1436. const links: string[] = [];
  1437. for (const client of clients) {
  1438. const entries = genAllLinks({ inbound, remark, client, hostOverride, fallbackHostname });
  1439. for (const e of entries) links.push(e.link);
  1440. }
  1441. return links.join('\r\n');
  1442. }
  1443. if (inbound.protocol === 'shadowsocks') {
  1444. return genShadowsocksLink({
  1445. inbound,
  1446. address: addr,
  1447. port: inbound.port,
  1448. forceTls: 'same',
  1449. remark,
  1450. });
  1451. }
  1452. if (inbound.protocol === 'wireguard') {
  1453. return genWireguardConfigs({ inbound, remark, hostOverride, fallbackHostname });
  1454. }
  1455. if (inbound.protocol === 'amneziawg') {
  1456. return genAmneziaWGConfigs({ inbound, remark, hostOverride, fallbackHostname });
  1457. }
  1458. return '';
  1459. }
  1460. // Per-peer wireguard fanout. Each peer gets its own link (or .conf
  1461. // block) with an index-suffixed remark, joined by \r\n. Matches the
  1462. // legacy genWireguardLinks / genWireguardConfigs exactly.
  1463. export interface GenWireguardFanoutInput {
  1464. inbound: Inbound;
  1465. remark?: string;
  1466. hostOverride?: string;
  1467. fallbackHostname: string;
  1468. }
  1469. // WireGuard is multi-client: each client is one accepted peer. The canonical
  1470. // store is settings.clients; legacy single-config inbounds (pre-migration) are
  1471. // still rendered from settings.peers. Both carry the privateKey/allowedIPs/
  1472. // preSharedKey/keepAlive the link and .conf need, so they project to the same
  1473. // peer shape and reuse genWireguardLink/genWireguardConfig unchanged.
  1474. function wgRenderPeers(settings: WireguardInboundSettings): WireguardInboundPeer[] {
  1475. const clients = settings.clients ?? [];
  1476. if (clients.length > 0) {
  1477. return clients.map((c) => ({ ...c, publicKey: c.publicKey ?? '' }));
  1478. }
  1479. return settings.peers;
  1480. }
  1481. // Hosts reach wireguard/amneziawg as externalProxy entries (withHostEndpoints);
  1482. // with none, every peer is advertised on the inbound's own address.
  1483. function tunnelEndpoints(
  1484. inbound: Inbound,
  1485. addr: string,
  1486. ): Array<{ address: string; port: number; remark: string }> {
  1487. const externals = inbound.streamSettings?.externalProxy;
  1488. if (Array.isArray(externals) && externals.length > 0) {
  1489. return externals.map((ep) => ({ address: ep.dest, port: ep.port, remark: ep.remark ?? '' }));
  1490. }
  1491. return [{ address: addr, port: inbound.port, remark: '' }];
  1492. }
  1493. function tunnelPeerRemark(
  1494. remark: string,
  1495. endpointRemark: string,
  1496. index: number,
  1497. peer: unknown,
  1498. ): string {
  1499. const base = [remark, endpointRemark].filter((x) => x.length > 0).join('-');
  1500. return `${base}-${index + 1}${wgPeerCommentSuffix(peer)}`;
  1501. }
  1502. function wireguardFanout(
  1503. input: GenWireguardFanoutInput,
  1504. render: (input: GenWireguardLinkInput) => string,
  1505. ): string[][] {
  1506. const { inbound, remark = '', hostOverride = '', fallbackHostname } = input;
  1507. if (inbound.protocol !== 'wireguard') return [];
  1508. const endpoints = tunnelEndpoints(inbound, resolveAddr(inbound, hostOverride, fallbackHostname));
  1509. const baseSettings = inbound.settings as WireguardInboundSettings;
  1510. const peers = wgRenderPeers(baseSettings);
  1511. const settings: WireguardInboundSettings = { ...baseSettings, peers };
  1512. return peers.map((p, i) =>
  1513. endpoints.map((e) =>
  1514. render({
  1515. settings,
  1516. address: e.address,
  1517. port: e.port,
  1518. remark: tunnelPeerRemark(remark, e.remark, i, p),
  1519. peerIndex: i,
  1520. }),
  1521. ),
  1522. );
  1523. }
  1524. // Per-peer lists with one entry per advertised endpoint (Host), peer-major.
  1525. export function genWireguardPeerLinks(input: GenWireguardFanoutInput): string[][] {
  1526. return wireguardFanout(input, genWireguardLink);
  1527. }
  1528. export function genWireguardPeerConfigs(input: GenWireguardFanoutInput): string[][] {
  1529. return wireguardFanout(input, genWireguardConfig);
  1530. }
  1531. export function genWireguardLinks(input: GenWireguardFanoutInput): string {
  1532. return genWireguardPeerLinks(input).flat().join('\r\n');
  1533. }
  1534. export function genWireguardConfigs(input: GenWireguardFanoutInput): string {
  1535. return genWireguardPeerConfigs(input).flat().join('\r\n');
  1536. }
  1537. // Peer comments (#5168) are panel-side annotations; when present they ride
  1538. // along in the share remark so the device is identifiable in client apps.
  1539. function wgPeerCommentSuffix(peer: unknown): string {
  1540. const comment = (peer as { comment?: unknown })?.comment;
  1541. return typeof comment === 'string' && comment.trim() !== '' ? ` (${comment.trim()})` : '';
  1542. }
  1543. export function isPostQuantumLink(link: string): boolean {
  1544. if (/[?&]pqv=/.test(link)) return true;
  1545. if (link.includes('mlkem768') || link.includes('mldsa65')) return true;
  1546. if (link.includes('ML-KEM-768')) return true;
  1547. return false;
  1548. }