inbound-link.ts 63 KB

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