inbound-link.ts 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701
  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. if (stream.security === 'reality') {
  416. const reality = stream.realitySettings;
  417. params.set('pbk', reality.settings.publicKey);
  418. params.set('fp', reality.settings.fingerprint);
  419. const sni =
  420. reality.settings.serverName || reality.serverNames?.[0] || reality.target?.split(':')[0];
  421. if (sni && sni.length > 0) params.set('sni', sni);
  422. if (reality.shortIds.length > 0) params.set('sid', reality.shortIds[0]);
  423. const spx = deriveSpiderX(reality.settings.spiderX, clientKey);
  424. if (spx.length > 0) params.set('spx', spx);
  425. if (reality.settings.mldsa65Verify.length > 0)
  426. params.set('pqv', reality.settings.mldsa65Verify);
  427. }
  428. } else {
  429. params.set('security', 'none');
  430. }
  431. // XTLS Vision flow: TCP over tls/reality (classic) or XHTTP+vlessenc (the
  432. // VLESS-level encryption stands in for transport TLS). Mirrors the backend's
  433. // vlessFlowAllowed and the form's flow-field gating so panel link, share
  434. // link and subscription agree.
  435. if (
  436. flow.length > 0 &&
  437. canEnableTlsFlow({
  438. protocol: inbound.protocol,
  439. settings: inbound.settings,
  440. streamSettings: stream,
  441. })
  442. ) {
  443. params.set('flow', flow);
  444. }
  445. const url = new URL(
  446. `vless://${applyVlessRoute(clientId, externalProxy?.vlessRoute)}@${formatUrlHost(address)}:${port}`,
  447. );
  448. for (const [key, value] of params) url.searchParams.set(key, value);
  449. url.hash = encodeURIComponent(remark);
  450. return url.toString();
  451. }
  452. // Shared network-branch writer used by trojan + shadowsocks links.
  453. // VLESS and VMess don't call this because they have minor per-protocol
  454. // quirks inline (vmess maps `multi` differently into obj.type; vless sets
  455. // encryption=none up-front).
  456. function writeNetworkParams(
  457. stream: NonNullable<Inbound['streamSettings']>,
  458. params: URLSearchParams,
  459. ): void {
  460. if (stream.network === 'tcp') {
  461. const tcp = stream.tcpSettings;
  462. if (tcp.header?.type === 'http') {
  463. const request = tcp.header.request;
  464. if (request) {
  465. params.set('path', request.path.join(','));
  466. const host =
  467. getHeaderValue(tcp.header.response?.headers, 'host') ||
  468. getHeaderValue(request.headers, 'host');
  469. if (host) params.set('host', host);
  470. params.set('headerType', 'http');
  471. }
  472. }
  473. } else if (stream.network === 'kcp') {
  474. const kcp = stream.kcpSettings;
  475. params.set('mtu', String(kcp.mtu));
  476. params.set('tti', String(kcp.tti));
  477. } else if (stream.network === 'ws') {
  478. const ws = stream.wsSettings;
  479. params.set('path', ws.path);
  480. params.set('host', ws.host.length > 0 ? ws.host : getHeaderValue(ws.headers, 'host'));
  481. } else if (stream.network === 'grpc') {
  482. const grpc = stream.grpcSettings;
  483. params.set('serviceName', grpc.serviceName);
  484. params.set('authority', grpc.authority);
  485. if (grpc.multiMode) params.set('mode', 'multi');
  486. } else if (stream.network === 'httpupgrade') {
  487. const hu = stream.httpupgradeSettings;
  488. params.set('path', hu.path);
  489. params.set('host', hu.host.length > 0 ? hu.host : getHeaderValue(hu.headers, 'host'));
  490. } else if (stream.network === 'xhttp') {
  491. applyXhttpExtraToParams(stream.xhttpSettings, params);
  492. }
  493. }
  494. function writeTlsParams(
  495. stream: NonNullable<Inbound['streamSettings']>,
  496. params: URLSearchParams,
  497. ): void {
  498. if (stream.security !== 'tls') return;
  499. const tls = stream.tlsSettings;
  500. if (tls.settings.fingerprint.length > 0) params.set('fp', tls.settings.fingerprint);
  501. params.set('alpn', tls.alpn.join(','));
  502. if (tls.settings.echConfigList.length > 0) params.set('ech', tls.settings.echConfigList);
  503. if (tls.serverName.length > 0) params.set('sni', tls.serverName);
  504. if (tls.settings.verifyPeerCertByName.length > 0) {
  505. params.set('vcn', tls.settings.verifyPeerCertByName);
  506. }
  507. if (tls.settings.pinnedPeerCertSha256.length > 0) {
  508. params.set('pcs', tls.settings.pinnedPeerCertSha256.join(','));
  509. }
  510. }
  511. // Reality query-string writer shared by VLESS and Trojan. Preserves the
  512. // legacy SNI-omission quirk (see genVlessLink for the full story).
  513. function writeRealityParams(
  514. stream: NonNullable<Inbound['streamSettings']>,
  515. params: URLSearchParams,
  516. clientKey: string,
  517. ): void {
  518. if (stream.security !== 'reality') return;
  519. const reality = stream.realitySettings;
  520. params.set('pbk', reality.settings.publicKey);
  521. params.set('fp', reality.settings.fingerprint);
  522. const sni =
  523. reality.settings.serverName || reality.serverNames?.[0] || reality.target?.split(':')[0];
  524. if (sni && sni.length > 0) params.set('sni', sni);
  525. if (reality.shortIds.length > 0) params.set('sid', reality.shortIds[0]);
  526. const spx = deriveSpiderX(reality.settings.spiderX, clientKey);
  527. if (spx.length > 0) params.set('spx', spx);
  528. if (reality.settings.mldsa65Verify.length > 0) params.set('pqv', reality.settings.mldsa65Verify);
  529. }
  530. export interface GenTrojanLinkInput {
  531. inbound: Inbound;
  532. address: string;
  533. port?: number;
  534. forceTls?: ForceTls;
  535. remark?: string;
  536. clientPassword: string;
  537. clientKey?: string;
  538. externalProxy?: ExternalProxyEntry | null;
  539. }
  540. // Trojan share link: trojan://<password>@<host>:<port>?<query>#<remark>.
  541. // Same query-string shape as VLESS minus the `encryption` and `flow`
  542. // fields. Returns '' if the inbound isn't trojan.
  543. export function genTrojanLink(input: GenTrojanLinkInput): string {
  544. const {
  545. inbound,
  546. address,
  547. port = inbound.port,
  548. forceTls = 'same',
  549. remark = '',
  550. clientPassword,
  551. clientKey = '',
  552. externalProxy = null,
  553. } = input;
  554. if (inbound.protocol !== 'trojan') return '';
  555. const stream = inbound.streamSettings;
  556. if (!stream) return '';
  557. const security = forceTls === 'same' ? stream.security : forceTls;
  558. const params = new URLSearchParams();
  559. params.set('type', stream.network ?? 'tcp');
  560. writeNetworkParams(stream, params);
  561. applyFinalMaskToParams(stream.finalmask, params);
  562. if (security === 'tls') {
  563. params.set('security', 'tls');
  564. writeTlsParams(stream, params);
  565. applyExternalProxyTLSParams(externalProxy, params, security);
  566. } else if (security === 'reality') {
  567. params.set('security', 'reality');
  568. writeRealityParams(stream, params, clientKey);
  569. } else {
  570. params.set('security', 'none');
  571. }
  572. const url = new URL(
  573. `trojan://${encodeURIComponent(clientPassword)}@${formatUrlHost(address)}:${port}`,
  574. );
  575. for (const [key, value] of params) url.searchParams.set(key, value);
  576. url.hash = encodeURIComponent(remark);
  577. return url.toString();
  578. }
  579. export interface GenShadowsocksLinkInput {
  580. inbound: Inbound;
  581. address: string;
  582. port?: number;
  583. forceTls?: ForceTls;
  584. remark?: string;
  585. clientPassword?: string;
  586. externalProxy?: ExternalProxyEntry | null;
  587. }
  588. // Shadowsocks 2022 share link. The userinfo portion is base64(method:pw)
  589. // for single-user and base64(method:settingsPw:clientPw) for multi-user
  590. // 2022-blake3. Legacy SS (non-2022) leaves the password out of the
  591. // userinfo entirely — matches the legacy class's password-array logic.
  592. // Note: legacy `isSSMultiUser` returns true for everything except
  593. // 2022-blake3-chacha20-poly1305 (a curious classification, but we
  594. // preserve it for byte-stable parity).
  595. export function genShadowsocksLink(input: GenShadowsocksLinkInput): string {
  596. const {
  597. inbound,
  598. address,
  599. port = inbound.port,
  600. forceTls = 'same',
  601. remark = '',
  602. clientPassword = '',
  603. externalProxy = null,
  604. } = input;
  605. if (inbound.protocol !== 'shadowsocks') return '';
  606. const stream = inbound.streamSettings;
  607. if (!stream) return '';
  608. const settings = inbound.settings;
  609. const security = forceTls === 'same' ? stream.security : forceTls;
  610. const params = new URLSearchParams();
  611. params.set('type', stream.network ?? 'tcp');
  612. writeNetworkParams(stream, params);
  613. applyFinalMaskToParams(stream.finalmask, params);
  614. if (security === 'tls') {
  615. params.set('security', 'tls');
  616. writeTlsParams(stream, params);
  617. applyExternalProxyTLSParams(externalProxy, params, security);
  618. }
  619. // SIP002 clients (v2rayN) ignore type/headerType/host/path and only read
  620. // `plugin`. Re-encode a TCP http header as obfs-local so they build a
  621. // matching tcp/http outbound (v2rayN forces request path "/").
  622. if ((stream.network ?? 'tcp') === 'tcp' && params.get('headerType') === 'http') {
  623. const host = params.get('host') ?? '';
  624. params.delete('type');
  625. params.delete('headerType');
  626. params.delete('host');
  627. params.delete('path');
  628. params.set('plugin', `obfs-local;obfs=http;obfs-host=${host}`);
  629. }
  630. const isSS2022 = settings.method.substring(0, 4) === '2022';
  631. const isSSMultiUser = settings.method !== '2022-blake3-chacha20-poly1305';
  632. const passwords: string[] = [];
  633. if (isSS2022) passwords.push(settings.password);
  634. if (isSSMultiUser) passwords.push(clientPassword);
  635. if (isSS2022) {
  636. // SIP022 (2022-blake3-*) forbids base64 userinfo: method and each key are
  637. // percent-encoded, joined by literal ':' separators. Built by hand because
  638. // `new URL` would re-encode the inner key separator to %3A.
  639. const userinfo = [settings.method, ...passwords].map(encodeURIComponent).join(':');
  640. let link = `ss://${userinfo}@${formatUrlHost(address)}:${port}`;
  641. const query = params.toString();
  642. if (query) link += `?${query}`;
  643. link += `#${encodeURIComponent(remark)}`;
  644. return link;
  645. }
  646. // SIP002 userinfo is base64(method:pw).
  647. const userinfo = Base64.encode(`${settings.method}:${passwords.join(':')}`, true);
  648. const url = new URL(`ss://${userinfo}@${formatUrlHost(address)}:${port}`);
  649. for (const [key, value] of params) url.searchParams.set(key, value);
  650. url.hash = encodeURIComponent(remark);
  651. return url.toString();
  652. }
  653. export interface GenHysteriaLinkInput {
  654. inbound: Inbound;
  655. address: string;
  656. port?: number;
  657. remark?: string;
  658. clientAuth: string;
  659. externalProxy?: ExternalProxyEntry | null;
  660. }
  661. // Hysteria2's pinSHA256 must be a 64-char lowercase hex string — Xray-core
  662. // clients hex-decode it and crash on a base64 value. The panel stores pins as
  663. // base64 (xray-core's native TLS format / the generate button) or hex, either
  664. // bare or colon-separated as `openssl x509 -fingerprint -sha256` emits it. Each
  665. // entry is coerced to bare hex. Values that are neither a 32-byte hex nor a
  666. // 32-byte base64 SHA-256 pass through unchanged.
  667. function hysteriaPinHex(pin: string): string {
  668. const stripped = pin.trim().replace(/:/g, '');
  669. if (/^[0-9a-fA-F]{64}$/.test(stripped)) return stripped.toLowerCase();
  670. try {
  671. const binary = atob(pin.trim().replace(/-/g, '+').replace(/_/g, '/'));
  672. if (binary.length !== 32) return pin;
  673. let hex = '';
  674. for (let i = 0; i < binary.length; i++) {
  675. hex += binary.charCodeAt(i).toString(16).padStart(2, '0');
  676. }
  677. return hex;
  678. } catch {
  679. return pin;
  680. }
  681. }
  682. // Hysteria2 hop range advertised as `mport`. xray-core 26.9.9 moved hopping
  683. // from finalmask.quicParams.udpHop to a 'udphop' UDP mask; inbounds stored
  684. // before the upgrade still carry the old key.
  685. function udpHopPorts(stream: NonNullable<Inbound['streamSettings']>): string {
  686. for (const mask of stream.finalmask?.udp ?? []) {
  687. if (mask.type !== 'udphop') continue;
  688. const ports = mask.settings?.remotePorts;
  689. if (typeof ports === 'string' && ports.trim().length > 0) return ports.trim();
  690. }
  691. return stream.finalmask?.quicParams?.udpHop?.ports?.trim() ?? '';
  692. }
  693. // Hysteria share link: hysteria2://<auth>@<host>:<port>?<query>#<remark>.
  694. // The scheme is always hysteria2 — xray-core builds version 2 only, so the
  695. // settings schema pins it there and the subscription server emits the same
  696. // scheme. Salamander obfuscation pulls its password from
  697. // finalmask.udp[type=salamander] when present; the broader finalmask payload
  698. // still rides under `fm` like the other links.
  699. //
  700. // Note: legacy genHysteriaLink reads stream.tls.settings.allowInsecure,
  701. // which isn't a field on TlsStreamSettings.Settings — the guard is always
  702. // false. We omit the `insecure` param here to stay byte-stable.
  703. export function genHysteriaLink(input: GenHysteriaLinkInput): string {
  704. const {
  705. inbound,
  706. address,
  707. port = inbound.port,
  708. remark = '',
  709. clientAuth,
  710. externalProxy = null,
  711. } = input;
  712. if (inbound.protocol !== 'hysteria') return '';
  713. const stream = inbound.streamSettings;
  714. if (!stream || stream.security !== 'tls') return '';
  715. const scheme = 'hysteria2';
  716. const params = new URLSearchParams();
  717. params.set('security', 'tls');
  718. const tls = stream.tlsSettings;
  719. if (tls.settings.fingerprint.length > 0) params.set('fp', tls.settings.fingerprint);
  720. if (tls.alpn.length > 0) params.set('alpn', tls.alpn.join(','));
  721. if (tls.settings.echConfigList.length > 0) params.set('ech', tls.settings.echConfigList);
  722. if (tls.serverName.length > 0) params.set('sni', tls.serverName);
  723. if (tls.settings.verifyPeerCertByName.length > 0) {
  724. params.set('vcn', tls.settings.verifyPeerCertByName);
  725. }
  726. if (tls.settings.pinnedPeerCertSha256.length > 0) {
  727. params.set('pinSHA256', tls.settings.pinnedPeerCertSha256.map(hysteriaPinHex).join(','));
  728. }
  729. // An external-proxy entry can pin a different endpoint's certificate.
  730. // Hysteria carries it as hex `pinSHA256` (not the `pcs` other protocols
  731. // use), so coerce each entry through hysteriaPinHex like the main pin.
  732. if (Array.isArray(externalProxy?.pinnedPeerCertSha256)) {
  733. const epPins = externalProxy.pinnedPeerCertSha256.filter(Boolean).map(hysteriaPinHex);
  734. if (epPins.length > 0) params.set('pinSHA256', epPins.join(','));
  735. }
  736. const udpMasks = stream.finalmask?.udp;
  737. if (Array.isArray(udpMasks)) {
  738. const salamander = udpMasks.find((m) => m?.type === 'salamander');
  739. const obfsPassword = salamander?.settings?.password;
  740. if (typeof obfsPassword === 'string' && obfsPassword.length > 0) {
  741. // packetSize (Gecko mode) exports via v2rayN's native fields; the
  742. // experimental fm=<json> dump breaks mihomo and other strict clients.
  743. const range = parseGeckoPacketSize(salamander?.settings?.packetSize);
  744. if (range) {
  745. params.set('obfs', 'gecko');
  746. params.set('minPacketSize', String(range.min));
  747. params.set('maxPacketSize', String(range.max));
  748. } else {
  749. params.set('obfs', 'salamander');
  750. }
  751. params.set('obfs-password', obfsPassword);
  752. }
  753. }
  754. const hopPorts = udpHopPorts(stream);
  755. if (hopPorts.length > 0) {
  756. params.set('mport', hopPorts);
  757. }
  758. const url = new URL(`${scheme}://${clientAuth}@${formatUrlHost(address)}:${port}`);
  759. for (const [key, value] of params) url.searchParams.set(key, value);
  760. url.hash = encodeURIComponent(remark);
  761. return url.toString();
  762. }
  763. export interface GenMtprotoLinkInput {
  764. inbound: Inbound;
  765. address: string;
  766. port?: number;
  767. clientSecret?: string;
  768. }
  769. // Builds a per-client Telegram proxy deep link for an mtproto inbound from the
  770. // client's own FakeTLS secret. No remark fragment is added: Telegram proxy deep
  771. // links have no name field, and a trailing "#remark" gets folded into the last
  772. // query value by lenient parsers, breaking the server address. The panel shows
  773. // the remark separately from the link.
  774. export function genMtprotoLink(input: GenMtprotoLinkInput): string {
  775. const { inbound, address, port = inbound.port, clientSecret = '' } = input;
  776. if (inbound.protocol !== 'mtproto') return '';
  777. if (clientSecret.length === 0) return '';
  778. const url = new URL('tg://proxy');
  779. url.searchParams.set('server', address);
  780. url.searchParams.set('port', String(port));
  781. url.searchParams.set('secret', clientSecret);
  782. return url.toString();
  783. }
  784. export interface GenTuicLinkInput {
  785. inbound: Inbound;
  786. address: string;
  787. port?: number;
  788. remark?: string;
  789. clientUuid?: string;
  790. clientPassword?: string;
  791. externalProxy?: ExternalProxyEntry | null;
  792. }
  793. export function genTuicLink(input: GenTuicLinkInput): string {
  794. const {
  795. inbound,
  796. address,
  797. port = inbound.port,
  798. remark = '',
  799. clientUuid = '',
  800. clientPassword = '',
  801. externalProxy = null,
  802. } = input;
  803. if (!clientUuid || !clientPassword) return '';
  804. const rawSettings = inbound.settings as Record<string, unknown>;
  805. const server = (rawSettings.server as Record<string, unknown>) ?? rawSettings;
  806. const host = formatUrlHost(externalProxy?.dest || address);
  807. const targetPort = externalProxy?.port || port;
  808. const url = new URL(
  809. `tuic://${encodeURIComponent(clientUuid)}:${encodeURIComponent(clientPassword)}@${host}:${targetPort}`,
  810. );
  811. const cc =
  812. (server.congestion_control as string) || (rawSettings.congestion_control as string) || 'bbr';
  813. url.searchParams.set('congestion_control', cc);
  814. const epAlpn = externalProxyAlpn(externalProxy?.alpn);
  815. const alpn =
  816. epAlpn ||
  817. (Array.isArray(server.alpn) && server.alpn.length > 0
  818. ? (server.alpn as string[]).join(',')
  819. : null) ||
  820. (Array.isArray(rawSettings.alpn) && rawSettings.alpn.length > 0
  821. ? (rawSettings.alpn as string[]).join(',')
  822. : null) ||
  823. 'h3,spdy/3.1';
  824. url.searchParams.set('alpn', alpn);
  825. const sni = externalProxy?.sni || (server.sni as string) || (rawSettings.sni as string);
  826. if (sni) {
  827. url.searchParams.set('sni', sni);
  828. }
  829. const udpRelay =
  830. (server.udp_relay_mode as string) || (rawSettings.udp_relay_mode as string) || 'native';
  831. url.searchParams.set('udp_relay_mode', udpRelay);
  832. const allowInsecure = externalProxy?.allowInsecure ? '1' : '0';
  833. url.searchParams.set('allow_insecure', allowInsecure);
  834. if (remark) {
  835. url.hash = encodeURIComponent(remark);
  836. }
  837. return url.toString();
  838. }
  839. export interface GenWireguardLinkInput {
  840. settings: WireguardInboundSettings;
  841. address: string;
  842. port: number;
  843. remark?: string;
  844. peerIndex: number;
  845. }
  846. // Wireguard share link: wireguard://<peerPrivKey>@<host>:<port>
  847. // ?publickey=<serverPub>&address=<peerAllowedIP>&mtu=<mtu>#<remark>
  848. // pubKey is derived from the server's secretKey via Wireguard.generateKeypair
  849. // at call time (Zod's schema stores secretKey only — pubKey isn't on the
  850. // wire). Returns '' when the peer index is out of bounds.
  851. export function genWireguardLink(input: GenWireguardLinkInput): string {
  852. const { settings, address, port, remark = '', peerIndex } = input;
  853. const peer = settings.peers[peerIndex];
  854. if (!peer) return '';
  855. const url = new URL(`wireguard://${formatUrlHost(address)}:${port}`);
  856. url.username = peer.privateKey ?? '';
  857. const pubKey =
  858. settings.secretKey.length > 0 ? Wireguard.generateKeypair(settings.secretKey).publicKey : '';
  859. if (pubKey.length > 0) url.searchParams.set('publickey', pubKey);
  860. if (peer.allowedIPs.length > 0) {
  861. url.searchParams.set('address', peer.allowedIPs.join(','));
  862. }
  863. if (typeof settings.mtu === 'number' && settings.mtu > 0) {
  864. url.searchParams.set('mtu', String(settings.mtu));
  865. }
  866. url.hash = encodeURIComponent(remark);
  867. return url.toString();
  868. }
  869. // Plain-text WireGuard client config (.conf format). Mirrors the legacy
  870. // getWireguardTxt — same DNS defaults (1.1.1.1, 1.0.0.1), MTU optional,
  871. // presharedKey + keepAlive only emitted when present on the peer. The
  872. // final newline structure follows the legacy: no newline after Endpoint,
  873. // optional preSharedKey appended with leading \n, keepAlive appended
  874. // with leading \n AND trailing \n.
  875. export function genWireguardConfig(input: GenWireguardLinkInput): string {
  876. const { settings, address, port, remark = '', peerIndex } = input;
  877. const peer = settings.peers[peerIndex];
  878. if (!peer) return '';
  879. const pubKey =
  880. settings.secretKey.length > 0 ? Wireguard.generateKeypair(settings.secretKey).publicKey : '';
  881. let txt = `[Interface]\n`;
  882. txt += `PrivateKey = ${peer.privateKey ?? ''}\n`;
  883. txt += `Address = ${peer.allowedIPs.join(', ')}\n`;
  884. txt += `DNS = ${settings.dns || '1.1.1.1, 1.0.0.1'}\n`;
  885. if (typeof settings.mtu === 'number' && settings.mtu > 0) {
  886. txt += `MTU = ${settings.mtu}\n`;
  887. }
  888. txt += `\n# ${remark}\n`;
  889. txt += `[Peer]\n`;
  890. txt += `PublicKey = ${pubKey}\n`;
  891. txt += `AllowedIPs = 0.0.0.0/0, ::/0\n`;
  892. txt += `Endpoint = ${address}:${port}`;
  893. if (peer.preSharedKey && peer.preSharedKey.length > 0) {
  894. txt += `\nPresharedKey = ${peer.preSharedKey}`;
  895. }
  896. if (typeof peer.keepAlive === 'number' && peer.keepAlive > 0) {
  897. txt += `\nPersistentKeepalive = ${peer.keepAlive}\n`;
  898. }
  899. return txt;
  900. }
  901. // Shared input shape for both the per-client vpn:// link and .conf
  902. // builders below — settings.clients (not a peers array; unlike WireGuard,
  903. // AmneziaWG was multi-client from day one, so there's no legacy format).
  904. export interface GenAmneziaWGLinkInput {
  905. settings: AmneziawgInboundSettings;
  906. address: string;
  907. port: number;
  908. remark?: string;
  909. peerIndex: number;
  910. }
  911. function amneziaWGHLine(key: string, value: string | undefined, fallback: string): string {
  912. return `${key} = ${value && value.trim() !== '' ? value : fallback}`;
  913. }
  914. // Base64url (RFC 4648 §5), no padding — matches the real AmneziaVPN app's
  915. // own Qt::Base64UrlEncoding | Qt::OmitTrailingEquals framing for vpn:// links.
  916. function toBase64Url(text: string): string {
  917. const bytes = new TextEncoder().encode(text);
  918. let binary = '';
  919. for (const b of bytes) binary += String.fromCharCode(b);
  920. return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
  921. }
  922. // AmneziaWG share link: vpn://<base64url .conf text>, matching the real
  923. // AmneziaVPN app's own share-link scheme. The app's import path base64url-
  924. // decodes, best-effort qUncompresses (falls back to the raw bytes when the
  925. // input isn't qCompress-framed, which plain text never is), then parses the
  926. // result as a flat bag of "Key = Value" lines regardless of which
  927. // [Interface]/[Peer] section they came from — so wrapping the same .conf
  928. // text genAmneziaWGConfig already produces is sufficient; no JSON schema or
  929. // compression needs replicating. Confirmed against the app's own source
  930. // (importController.cpp's checkConfigFormat/extractWireGuardConfig).
  931. export function genAmneziaWGLink(input: GenAmneziaWGLinkInput): string {
  932. const cfgText = genAmneziaWGConfig(input);
  933. if (!cfgText) return '';
  934. return `vpn://${toBase64Url(cfgText)}`;
  935. }
  936. // Plain-text AmneziaWG client config (.conf format). Mirrors
  937. // genWireguardConfig, plus the obfuscation lines every AmneziaWG client must
  938. // share with the server (see internal/amneziawg.writeObfuscation on the Go
  939. // side).
  940. export function genAmneziaWGConfig(input: GenAmneziaWGLinkInput): string {
  941. const { settings, address, port, remark = '', peerIndex } = input;
  942. const client = settings.clients[peerIndex];
  943. if (!client) return '';
  944. const server = settings.server;
  945. // These land unescaped in the .conf; a newline would inject a config line
  946. // (e.g. a rogue PostUp) — same guard as the panel's other two emitters.
  947. for (const v of [
  948. client.privateKey ?? '',
  949. server.primaryDns ?? '',
  950. server.secondaryDns ?? '',
  951. remark,
  952. ]) {
  953. if (/[\r\n]/.test(v)) return '';
  954. }
  955. let txt = `[Interface]\n`;
  956. txt += `PrivateKey = ${client.privateKey ?? ''}\n`;
  957. txt += `Address = ${(client.allowedIPs ?? []).join(', ')}\n`;
  958. const dns = [server.primaryDns, server.secondaryDns].filter((v) => !!v && v.trim() !== '');
  959. if (dns.length > 0) txt += `DNS = ${dns.join(', ')}\n`;
  960. txt += `MTU = ${effectiveMtu(server.mtu, server.s4)}\n`;
  961. txt += `Jc = ${server.jc}\n`;
  962. txt += `Jmin = ${server.jmin}\n`;
  963. txt += `Jmax = ${server.jmax}\n`;
  964. txt += `S1 = ${server.s1}\n`;
  965. txt += `S2 = ${server.s2}\n`;
  966. if (server.s3) txt += `S3 = ${server.s3}\n`;
  967. if (server.s4) txt += `S4 = ${server.s4}\n`;
  968. txt += `${amneziaWGHLine('H1', server.h1, '1')}\n`;
  969. txt += `${amneziaWGHLine('H2', server.h2, '2')}\n`;
  970. txt += `${amneziaWGHLine('H3', server.h3, '3')}\n`;
  971. txt += `${amneziaWGHLine('H4', server.h4, '4')}\n`;
  972. if (server.i1) txt += `I1 = ${server.i1}\n`;
  973. if (server.i2) txt += `I2 = ${server.i2}\n`;
  974. if (server.i3) txt += `I3 = ${server.i3}\n`;
  975. if (server.i4) txt += `I4 = ${server.i4}\n`;
  976. if (server.i5) txt += `I5 = ${server.i5}\n`;
  977. const optional31: Array<[string, string | undefined]> = [
  978. ['HeaderProtectionKey', server.headerProtectionKey],
  979. ['ContentPaddingAddition', server.contentPaddingAddition],
  980. ['RekeyAfterTime', server.rekeyAfterTime],
  981. ['RekeyTimeout', server.rekeyTimeout],
  982. ['RejectAfterTime', server.rejectAfterTime],
  983. ['KeepaliveTimeout', server.keepaliveTimeout],
  984. ['MaxHandshakeAttempts', server.maxHandshakeAttempts],
  985. ];
  986. for (const [key, value] of optional31) {
  987. if (value && value.trim() !== '') txt += `${key} = ${value}\n`;
  988. }
  989. if (server.randomTrailers) txt += `RandomTrailers = on\n`;
  990. if (server.disableCookies) txt += `DisableCookies = on\n`;
  991. // Peer field order follows wg-quick(8) and the panel's other two AmneziaWG
  992. // emitters (amneziaWGConfigText in Go, buildAmneziaWGClientConfig); all three
  993. // are independent implementations and must not drift apart.
  994. txt += `\n# ${remark}\n`;
  995. txt += `[Peer]\n`;
  996. txt += `PublicKey = ${server.publicKey ?? ''}\n`;
  997. if (client.preSharedKey && client.preSharedKey.length > 0) {
  998. txt += `PresharedKey = ${client.preSharedKey}\n`;
  999. }
  1000. txt += `AllowedIPs = 0.0.0.0/0, ::/0\n`;
  1001. txt += `Endpoint = ${address}:${port}`;
  1002. if (typeof client.keepAlive === 'number' && client.keepAlive > 0) {
  1003. txt += `\nPersistentKeepalive = ${client.keepAlive}`;
  1004. }
  1005. return txt;
  1006. }
  1007. export interface GenAmneziaWGFanoutInput {
  1008. inbound: Inbound;
  1009. remark?: string;
  1010. hostOverride?: string;
  1011. fallbackHostname: string;
  1012. }
  1013. function amneziaWGFanout(
  1014. input: GenAmneziaWGFanoutInput,
  1015. render: (input: GenAmneziaWGLinkInput) => string,
  1016. ): string[][] {
  1017. const { inbound, remark = '', hostOverride = '', fallbackHostname } = input;
  1018. if (inbound.protocol !== 'amneziawg') return [];
  1019. const endpoints = tunnelEndpoints(inbound, resolveAddr(inbound, hostOverride, fallbackHostname));
  1020. const settings = inbound.settings as AmneziawgInboundSettings;
  1021. const clients = settings.clients ?? [];
  1022. return clients.map((c, i) =>
  1023. endpoints.map((e) =>
  1024. render({
  1025. settings,
  1026. address: e.address,
  1027. port: e.port,
  1028. remark: tunnelPeerRemark(remark, e.remark, i, c),
  1029. peerIndex: i,
  1030. }),
  1031. ),
  1032. );
  1033. }
  1034. // Per-peer lists with one entry per advertised endpoint (Host), peer-major.
  1035. export function genAmneziaWGPeerLinks(input: GenAmneziaWGFanoutInput): string[][] {
  1036. return amneziaWGFanout(input, genAmneziaWGLink);
  1037. }
  1038. export function genAmneziaWGPeerConfigs(input: GenAmneziaWGFanoutInput): string[][] {
  1039. return amneziaWGFanout(input, genAmneziaWGConfig);
  1040. }
  1041. export function genAmneziaWGLinks(input: GenAmneziaWGFanoutInput): string {
  1042. return genAmneziaWGPeerLinks(input).flat().join('\r\n');
  1043. }
  1044. export function genAmneziaWGConfigs(input: GenAmneziaWGFanoutInput): string {
  1045. return genAmneziaWGPeerConfigs(input).flat().join('\r\n');
  1046. }
  1047. export function wireguardConfigFromLink(link: string, fallbackRemark = ''): string {
  1048. let url: URL;
  1049. try {
  1050. url = new URL(link);
  1051. } catch {
  1052. return '';
  1053. }
  1054. const scheme = url.protocol.replace(/:$/, '');
  1055. if (scheme !== 'wireguard' && scheme !== 'wg') return '';
  1056. const params = url.searchParams;
  1057. const pick = (...keys: string[]): string => {
  1058. for (const k of keys) {
  1059. const v = params.get(k);
  1060. if (v) return v;
  1061. }
  1062. return '';
  1063. };
  1064. let privateKey: string;
  1065. try {
  1066. privateKey = decodeURIComponent(url.username);
  1067. } catch {
  1068. privateKey = url.username;
  1069. }
  1070. const host = url.hostname;
  1071. const endpoint = host ? (url.port ? `${host}:${url.port}` : host) : '';
  1072. const address = pick('address', 'ip') || '10.0.0.2/32';
  1073. const publicKey = pick('publickey', 'publicKey', 'public_key', 'peerPublicKey');
  1074. const dns = pick('dns') || '1.1.1.1, 1.0.0.1';
  1075. const mtu = pick('mtu');
  1076. const psk = pick('presharedkey', 'preshared_key', 'pre-shared-key', 'psk');
  1077. const keepAlive = pick('keepalive', 'persistentkeepalive', 'persistent_keepalive');
  1078. const allowedIPs = pick('allowedips', 'allowed_ips') || '0.0.0.0/0, ::/0';
  1079. let remark = fallbackRemark;
  1080. try {
  1081. const decoded = decodeURIComponent(url.hash.replace(/^#/, ''));
  1082. if (decoded) remark = decoded;
  1083. } catch {
  1084. const raw = url.hash.replace(/^#/, '');
  1085. if (raw) remark = raw;
  1086. }
  1087. const lines = [
  1088. '[Interface]',
  1089. `PrivateKey = ${privateKey}`,
  1090. `Address = ${address}`,
  1091. `DNS = ${dns}`,
  1092. ];
  1093. if (mtu && Number(mtu) > 0) lines.push(`MTU = ${mtu}`);
  1094. lines.push('');
  1095. if (remark) lines.push(`# ${remark}`);
  1096. lines.push('[Peer]', `PublicKey = ${publicKey}`);
  1097. if (psk) lines.push(`PresharedKey = ${psk}`);
  1098. lines.push(`AllowedIPs = ${allowedIPs}`, `Endpoint = ${endpoint}`);
  1099. if (keepAlive && Number(keepAlive) > 0) lines.push(`PersistentKeepalive = ${keepAlive}`);
  1100. return lines.join('\n');
  1101. }
  1102. // Reverse of toBase64Url above -- recovers a vpn:// link's plain .conf
  1103. // payload for display/copy/download/QR, the AmneziaWG counterpart of
  1104. // wireguardConfigFromLink. Simpler than that function: a vpn:// link's
  1105. // payload already *is* the .conf text (see genAmneziaWGLink's own doc
  1106. // comment), so there's nothing to reconstruct from query params -- just
  1107. // decode. Mirrors link-label.tsx's own private fromBase64Url (used there
  1108. // only to pull the remark/port back out for the tag label); duplicated
  1109. // rather than imported since both are tiny, self-contained, and each
  1110. // file already owns the matching encode or decode half of this pair.
  1111. function fromBase64Url(value: string): string {
  1112. const b64 = value.replace(/-/g, '+').replace(/_/g, '/');
  1113. const padded = b64 + '='.repeat((4 - (b64.length % 4)) % 4);
  1114. const binary = atob(padded);
  1115. const bytes = new Uint8Array(binary.length);
  1116. for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
  1117. return new TextDecoder().decode(bytes);
  1118. }
  1119. export function amneziawgConfigFromLink(link: string): string {
  1120. const trimmed = link.trim();
  1121. if (!trimmed.startsWith('vpn://')) return '';
  1122. try {
  1123. return fromBase64Url(trimmed.slice('vpn://'.length));
  1124. } catch {
  1125. return '';
  1126. }
  1127. }
  1128. export type { WireguardInboundPeer };
  1129. function isUnixSocketListen(listen: string): boolean {
  1130. return listen.startsWith('/') || listen.startsWith('@');
  1131. }
  1132. function normalizeShareHost(host: string): string {
  1133. const h = host.trim();
  1134. if (h.length === 0 || h.includes('://') || h.startsWith('//') || /[/?#@]/.test(h)) {
  1135. return '';
  1136. }
  1137. if (h.startsWith('[')) {
  1138. if (!h.endsWith(']')) return '';
  1139. try {
  1140. return new URL(`http://${h}`).hostname;
  1141. } catch {
  1142. return '';
  1143. }
  1144. }
  1145. if (h.includes(':')) {
  1146. try {
  1147. return new URL(`http://[${h}]`).hostname;
  1148. } catch {
  1149. return '';
  1150. }
  1151. }
  1152. return SHARE_HOSTNAME_RE.test(h) ? h : '';
  1153. }
  1154. function isShareableHost(host: string): boolean {
  1155. const h = normalizeShareHost(host)
  1156. .replace(/^\[|\]$/g, '')
  1157. .toLowerCase();
  1158. if (h.length === 0) return false;
  1159. if (h === '0.0.0.0' || h === '::' || h === '::0') return false;
  1160. if (h === 'localhost' || h === '::1' || h.startsWith('127.')) return false;
  1161. return true;
  1162. }
  1163. function shareableListenFrom(listen: string): string {
  1164. const trimmed = listen.trim();
  1165. return trimmed.length > 0 && !isUnixSocketListen(trimmed) && isShareableHost(trimmed)
  1166. ? normalizeShareHost(trimmed)
  1167. : '';
  1168. }
  1169. type ShareAddrStrategy = 'node' | 'listen' | 'custom';
  1170. function normalizeShareAddrStrategy(strategy: string | undefined): ShareAddrStrategy {
  1171. return strategy === 'listen' || strategy === 'custom' ? strategy : 'node';
  1172. }
  1173. // ShareHostFields is the subset of an inbound resolveShareHost needs, so callers
  1174. // holding only a lightweight projection (e.g. the clients page InboundOption)
  1175. // can pick the same host as the full-inbound share/QR path.
  1176. export interface ShareHostFields {
  1177. listen?: string;
  1178. shareAddr?: string;
  1179. shareAddrStrategy?: string;
  1180. }
  1181. // resolveShareHost picks the host that goes into share/QR links, the browser-side
  1182. // analog of the backend resolveInboundAddress. hostOverride is the hosting node's
  1183. // address (empty for this panel's own inbounds); fallbackHostname is the
  1184. // already-resolved panel/public host used as the last resort — kept verbatim when
  1185. // it fails normalization (e.g. an underscore intranet hostname) so the last
  1186. // resort never degrades to an empty host.
  1187. export function resolveShareHost(
  1188. fields: ShareHostFields,
  1189. hostOverride: string,
  1190. fallbackHostname: string,
  1191. ): string {
  1192. const nodeAddr = normalizeShareHost(hostOverride);
  1193. const listenAddr = shareableListenFrom(fields.listen ?? '');
  1194. const customAddr = normalizeShareHost(fields.shareAddr ?? '');
  1195. const fallbackAddr = normalizeShareHost(fallbackHostname) || fallbackHostname.trim();
  1196. switch (normalizeShareAddrStrategy(fields.shareAddrStrategy)) {
  1197. case 'listen':
  1198. return listenAddr || nodeAddr || fallbackAddr;
  1199. case 'custom':
  1200. return customAddr || nodeAddr || listenAddr || fallbackAddr;
  1201. default:
  1202. return nodeAddr || listenAddr || fallbackAddr;
  1203. }
  1204. }
  1205. // Orchestrators.
  1206. // resolveAddr picks the host that goes into share/QR links. The default
  1207. // `node` strategy keeps the previous node-address-first behavior for
  1208. // node-managed inbounds; other strategies let a row prefer its listen address
  1209. // or a custom endpoint.
  1210. export function resolveAddr(
  1211. inbound: Inbound,
  1212. hostOverride: string,
  1213. fallbackHostname: string,
  1214. ): string {
  1215. return resolveShareHost(inbound, hostOverride, fallbackHostname);
  1216. }
  1217. // A loopback browser host means the panel was reached through a tunnel (e.g.
  1218. // SSH-forwarded 127.0.0.1/localhost), so it can never be a shareable link host.
  1219. function isLoopbackHost(host: string): boolean {
  1220. const h = host
  1221. .trim()
  1222. .replace(/^\[|\]$/g, '')
  1223. .toLowerCase();
  1224. return h === 'localhost' || h === '::1' || h.startsWith('127.');
  1225. }
  1226. // preferPublicHost is the browser-side analog of the backend's
  1227. // configuredPublicHost: when the panel is reached on a loopback host, prefer a
  1228. // configured public host (Sub/Web Domain) for share/QR links instead of leaking
  1229. // localhost. An explicit per-inbound listen or node override still wins, since
  1230. // resolveAddr only reaches the fallbackHostname after those.
  1231. export function preferPublicHost(browserHost: string, publicHost: string): string {
  1232. return publicHost && isLoopbackHost(browserHost) ? publicHost : browserHost;
  1233. }
  1234. // Returns the client array for protocols that have one. SS returns its
  1235. // clients only in 2022-blake3 multi-user mode (matches the legacy
  1236. // `this.clients` getter, which used isSSMultiUser to gate). Returns null
  1237. // for SS single-user, http, mixed, tunnel, wireguard, hysteria2-without-
  1238. // clients, and any protocol without a clients array.
  1239. type ClientShape = {
  1240. id?: string;
  1241. uuid?: string;
  1242. security?: VmessSecurity;
  1243. flow?: VlessClient['flow'];
  1244. password?: string;
  1245. auth?: string;
  1246. secret?: string;
  1247. email?: string;
  1248. subId?: string;
  1249. };
  1250. // Mirror of the Go subKey: the stable per-client identity spx derivation
  1251. // keys on — subscription id first, unique email as the fallback.
  1252. function clientSubKey(client: ClientShape): string {
  1253. return client.subId || client.email || '';
  1254. }
  1255. export function getInboundClients(inbound: Inbound): ClientShape[] | null {
  1256. switch (inbound.protocol) {
  1257. case 'vmess':
  1258. return (inbound.settings.clients ?? []) as ClientShape[];
  1259. case 'vless':
  1260. return (inbound.settings.clients ?? []) as ClientShape[];
  1261. case 'trojan':
  1262. return (inbound.settings.clients ?? []) as ClientShape[];
  1263. case 'hysteria':
  1264. return (inbound.settings.clients ?? []) as ClientShape[];
  1265. case 'mtproto':
  1266. return (inbound.settings.clients ?? []) as ClientShape[];
  1267. case 'tuic':
  1268. return (inbound.settings.clients ?? []) as ClientShape[];
  1269. case 'shadowsocks': {
  1270. const isMultiUser = inbound.settings.method !== '2022-blake3-chacha20-poly1305';
  1271. return isMultiUser ? ((inbound.settings.clients ?? []) as ClientShape[]) : null;
  1272. }
  1273. default:
  1274. return null;
  1275. }
  1276. }
  1277. export interface GenLinkInput {
  1278. inbound: Inbound;
  1279. address: string;
  1280. port?: number;
  1281. forceTls?: ForceTls;
  1282. remark?: string;
  1283. client: ClientShape;
  1284. externalProxy?: ExternalProxyEntry | null;
  1285. }
  1286. // Per-protocol dispatcher matching the legacy `genLink` switch. Returns
  1287. // '' for protocols that don't have client-based share links (wireguard
  1288. // goes through genWireguardLinks/Configs separately, http/mixed/tunnel
  1289. // don't have share URLs).
  1290. export function genLink(input: GenLinkInput): string {
  1291. const {
  1292. inbound,
  1293. address,
  1294. port = inbound.port,
  1295. forceTls = 'same',
  1296. remark = '',
  1297. client,
  1298. externalProxy = null,
  1299. } = input;
  1300. switch (inbound.protocol) {
  1301. case 'vmess':
  1302. return genVmessLink({
  1303. inbound,
  1304. address,
  1305. port,
  1306. forceTls,
  1307. remark,
  1308. clientId: client.id ?? '',
  1309. security: client.security,
  1310. externalProxy,
  1311. });
  1312. case 'vless':
  1313. return genVlessLink({
  1314. inbound,
  1315. address,
  1316. port,
  1317. forceTls,
  1318. remark,
  1319. clientId: client.id ?? '',
  1320. clientKey: clientSubKey(client),
  1321. flow: client.flow,
  1322. externalProxy,
  1323. });
  1324. case 'shadowsocks': {
  1325. const isMultiUser = inbound.settings.method !== '2022-blake3-chacha20-poly1305';
  1326. return genShadowsocksLink({
  1327. inbound,
  1328. address,
  1329. port,
  1330. forceTls,
  1331. remark,
  1332. clientPassword: isMultiUser ? (client.password ?? '') : '',
  1333. externalProxy,
  1334. });
  1335. }
  1336. case 'trojan':
  1337. return genTrojanLink({
  1338. inbound,
  1339. address,
  1340. port,
  1341. forceTls,
  1342. remark,
  1343. clientPassword: client.password ?? '',
  1344. clientKey: clientSubKey(client),
  1345. externalProxy,
  1346. });
  1347. case 'hysteria':
  1348. return genHysteriaLink({
  1349. inbound,
  1350. address,
  1351. port,
  1352. remark,
  1353. clientAuth: client.auth ?? '',
  1354. externalProxy,
  1355. });
  1356. case 'mtproto':
  1357. return genMtprotoLink({ inbound, address, port, clientSecret: client.secret ?? '' });
  1358. case 'tuic':
  1359. return genTuicLink({
  1360. inbound,
  1361. address,
  1362. port,
  1363. remark,
  1364. clientUuid: client.uuid ?? client.id ?? '',
  1365. clientPassword: client.password ?? '',
  1366. externalProxy,
  1367. });
  1368. default:
  1369. return '';
  1370. }
  1371. }
  1372. export interface GenAllLinksEntry {
  1373. remark: string;
  1374. link: string;
  1375. }
  1376. export interface GenAllLinksInput {
  1377. inbound: Inbound;
  1378. remark?: string;
  1379. client: ClientShape;
  1380. hostOverride?: string;
  1381. fallbackHostname: string;
  1382. }
  1383. // Fans out a single client's link per externalProxy entry, or just one link
  1384. // when there are no external proxies. The panel copy/QR remark is the inbound
  1385. // remark plus the externalProxy remark, dash-joined (the configurable
  1386. // subscription remark model was removed; subscription output uses the template).
  1387. export function genAllLinks(input: GenAllLinksInput): GenAllLinksEntry[] {
  1388. const { inbound, remark = '', client, hostOverride = '', fallbackHostname } = input;
  1389. const addr = resolveAddr(inbound, hostOverride, fallbackHostname);
  1390. const port = inbound.port;
  1391. const composeRemark = (proxyRemark: string): string =>
  1392. [remark, proxyRemark].filter((x) => x.length > 0).join('-');
  1393. const externals = inbound.streamSettings?.externalProxy;
  1394. if (!externals || externals.length === 0) {
  1395. const r = composeRemark('');
  1396. return [
  1397. {
  1398. remark: r,
  1399. link: genLink({ inbound, address: addr, port, forceTls: 'same', remark: r, client }),
  1400. },
  1401. ];
  1402. }
  1403. return externals.map((ep) => {
  1404. const r = composeRemark(ep.remark);
  1405. return {
  1406. remark: r,
  1407. link: genLink({
  1408. inbound,
  1409. address: ep.dest,
  1410. port: ep.port,
  1411. forceTls: ep.forceTls,
  1412. remark: r,
  1413. client,
  1414. externalProxy: ep,
  1415. }),
  1416. };
  1417. });
  1418. }
  1419. export interface GenInboundLinksInput {
  1420. inbound: Inbound;
  1421. remark?: string;
  1422. hostOverride?: string;
  1423. fallbackHostname: string;
  1424. }
  1425. // Top-level entrypoint that produces the full \r\n-joined block a user
  1426. // pastes into a client. Iterates per-client for protocols with clients,
  1427. // falls back to a single SS link for single-user 2022-blake3-chacha20,
  1428. // and emits per-peer .conf blocks for wireguard and amneziawg. Returns '' for the
  1429. // other clientless protocols (http, mixed, tunnel).
  1430. export function genInboundLinks(input: GenInboundLinksInput): string {
  1431. const { inbound, remark = '', hostOverride = '', fallbackHostname } = input;
  1432. const addr = resolveAddr(inbound, hostOverride, fallbackHostname);
  1433. const clients = getInboundClients(inbound);
  1434. if (clients) {
  1435. const links: string[] = [];
  1436. for (const client of clients) {
  1437. const entries = genAllLinks({ inbound, remark, client, hostOverride, fallbackHostname });
  1438. for (const e of entries) links.push(e.link);
  1439. }
  1440. return links.join('\r\n');
  1441. }
  1442. if (inbound.protocol === 'shadowsocks') {
  1443. return genShadowsocksLink({
  1444. inbound,
  1445. address: addr,
  1446. port: inbound.port,
  1447. forceTls: 'same',
  1448. remark,
  1449. });
  1450. }
  1451. if (inbound.protocol === 'wireguard') {
  1452. return genWireguardConfigs({ inbound, remark, hostOverride, fallbackHostname });
  1453. }
  1454. if (inbound.protocol === 'amneziawg') {
  1455. return genAmneziaWGConfigs({ inbound, remark, hostOverride, fallbackHostname });
  1456. }
  1457. return '';
  1458. }
  1459. // Per-peer wireguard fanout. Each peer gets its own link (or .conf
  1460. // block) with an index-suffixed remark, joined by \r\n. Matches the
  1461. // legacy genWireguardLinks / genWireguardConfigs exactly.
  1462. export interface GenWireguardFanoutInput {
  1463. inbound: Inbound;
  1464. remark?: string;
  1465. hostOverride?: string;
  1466. fallbackHostname: string;
  1467. }
  1468. // WireGuard is multi-client: each client is one accepted peer. The canonical
  1469. // store is settings.clients; legacy single-config inbounds (pre-migration) are
  1470. // still rendered from settings.peers. Both carry the privateKey/allowedIPs/
  1471. // preSharedKey/keepAlive the link and .conf need, so they project to the same
  1472. // peer shape and reuse genWireguardLink/genWireguardConfig unchanged.
  1473. function wgRenderPeers(settings: WireguardInboundSettings): WireguardInboundPeer[] {
  1474. const clients = settings.clients ?? [];
  1475. if (clients.length > 0) {
  1476. return clients.map((c) => ({ ...c, publicKey: c.publicKey ?? '' }));
  1477. }
  1478. return settings.peers;
  1479. }
  1480. // Hosts reach wireguard/amneziawg as externalProxy entries (withHostEndpoints);
  1481. // with none, every peer is advertised on the inbound's own address.
  1482. function tunnelEndpoints(
  1483. inbound: Inbound,
  1484. addr: string,
  1485. ): Array<{ address: string; port: number; remark: string }> {
  1486. const externals = inbound.streamSettings?.externalProxy;
  1487. if (Array.isArray(externals) && externals.length > 0) {
  1488. return externals.map((ep) => ({ address: ep.dest, port: ep.port, remark: ep.remark ?? '' }));
  1489. }
  1490. return [{ address: addr, port: inbound.port, remark: '' }];
  1491. }
  1492. function tunnelPeerRemark(
  1493. remark: string,
  1494. endpointRemark: string,
  1495. index: number,
  1496. peer: unknown,
  1497. ): string {
  1498. const base = [remark, endpointRemark].filter((x) => x.length > 0).join('-');
  1499. return `${base}-${index + 1}${wgPeerCommentSuffix(peer)}`;
  1500. }
  1501. function wireguardFanout(
  1502. input: GenWireguardFanoutInput,
  1503. render: (input: GenWireguardLinkInput) => string,
  1504. ): string[][] {
  1505. const { inbound, remark = '', hostOverride = '', fallbackHostname } = input;
  1506. if (inbound.protocol !== 'wireguard') return [];
  1507. const endpoints = tunnelEndpoints(inbound, resolveAddr(inbound, hostOverride, fallbackHostname));
  1508. const baseSettings = inbound.settings as WireguardInboundSettings;
  1509. const peers = wgRenderPeers(baseSettings);
  1510. const settings: WireguardInboundSettings = { ...baseSettings, peers };
  1511. return peers.map((p, i) =>
  1512. endpoints.map((e) =>
  1513. render({
  1514. settings,
  1515. address: e.address,
  1516. port: e.port,
  1517. remark: tunnelPeerRemark(remark, e.remark, i, p),
  1518. peerIndex: i,
  1519. }),
  1520. ),
  1521. );
  1522. }
  1523. // Per-peer lists with one entry per advertised endpoint (Host), peer-major.
  1524. export function genWireguardPeerLinks(input: GenWireguardFanoutInput): string[][] {
  1525. return wireguardFanout(input, genWireguardLink);
  1526. }
  1527. export function genWireguardPeerConfigs(input: GenWireguardFanoutInput): string[][] {
  1528. return wireguardFanout(input, genWireguardConfig);
  1529. }
  1530. export function genWireguardLinks(input: GenWireguardFanoutInput): string {
  1531. return genWireguardPeerLinks(input).flat().join('\r\n');
  1532. }
  1533. export function genWireguardConfigs(input: GenWireguardFanoutInput): string {
  1534. return genWireguardPeerConfigs(input).flat().join('\r\n');
  1535. }
  1536. // Peer comments (#5168) are panel-side annotations; when present they ride
  1537. // along in the share remark so the device is identifiable in client apps.
  1538. function wgPeerCommentSuffix(peer: unknown): string {
  1539. const comment = (peer as { comment?: unknown })?.comment;
  1540. return typeof comment === 'string' && comment.trim() !== '' ? ` (${comment.trim()})` : '';
  1541. }
  1542. export function isPostQuantumLink(link: string): boolean {
  1543. if (/[?&]pqv=/.test(link)) return true;
  1544. if (link.includes('mlkem768') || link.includes('mldsa65')) return true;
  1545. if (link.includes('ML-KEM-768')) return true;
  1546. return false;
  1547. }