inbound-link.ts 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592
  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. // Hysteria share link: hysteria2://<auth>@<host>:<port>?<query>#<remark>.
  683. // The scheme is always hysteria2 — xray-core builds version 2 only, so the
  684. // settings schema pins it there and the subscription server emits the same
  685. // scheme. Salamander obfuscation pulls its password from
  686. // finalmask.udp[type=salamander] when present; the broader finalmask payload
  687. // still rides under `fm` like the other links.
  688. //
  689. // Note: legacy genHysteriaLink reads stream.tls.settings.allowInsecure,
  690. // which isn't a field on TlsStreamSettings.Settings — the guard is always
  691. // false. We omit the `insecure` param here to stay byte-stable.
  692. export function genHysteriaLink(input: GenHysteriaLinkInput): string {
  693. const {
  694. inbound,
  695. address,
  696. port = inbound.port,
  697. remark = '',
  698. clientAuth,
  699. externalProxy = null,
  700. } = input;
  701. if (inbound.protocol !== 'hysteria') return '';
  702. const stream = inbound.streamSettings;
  703. if (!stream || stream.security !== 'tls') return '';
  704. const scheme = 'hysteria2';
  705. const params = new URLSearchParams();
  706. params.set('security', 'tls');
  707. const tls = stream.tlsSettings;
  708. if (tls.settings.fingerprint.length > 0) params.set('fp', tls.settings.fingerprint);
  709. if (tls.alpn.length > 0) params.set('alpn', tls.alpn.join(','));
  710. if (tls.settings.echConfigList.length > 0) params.set('ech', tls.settings.echConfigList);
  711. if (tls.serverName.length > 0) params.set('sni', tls.serverName);
  712. if (tls.settings.verifyPeerCertByName.length > 0) {
  713. params.set('vcn', tls.settings.verifyPeerCertByName);
  714. }
  715. if (tls.settings.pinnedPeerCertSha256.length > 0) {
  716. params.set('pinSHA256', tls.settings.pinnedPeerCertSha256.map(hysteriaPinHex).join(','));
  717. }
  718. // An external-proxy entry can pin a different endpoint's certificate.
  719. // Hysteria carries it as hex `pinSHA256` (not the `pcs` other protocols
  720. // use), so coerce each entry through hysteriaPinHex like the main pin.
  721. if (Array.isArray(externalProxy?.pinnedPeerCertSha256)) {
  722. const epPins = externalProxy.pinnedPeerCertSha256.filter(Boolean).map(hysteriaPinHex);
  723. if (epPins.length > 0) params.set('pinSHA256', epPins.join(','));
  724. }
  725. const udpMasks = stream.finalmask?.udp;
  726. if (Array.isArray(udpMasks)) {
  727. const salamander = udpMasks.find((m) => m?.type === 'salamander');
  728. const obfsPassword = salamander?.settings?.password;
  729. if (typeof obfsPassword === 'string' && obfsPassword.length > 0) {
  730. // packetSize (Gecko mode) exports via v2rayN's native fields; the
  731. // experimental fm=<json> dump breaks mihomo and other strict clients.
  732. const range = parseGeckoPacketSize(salamander?.settings?.packetSize);
  733. if (range) {
  734. params.set('obfs', 'gecko');
  735. params.set('minPacketSize', String(range.min));
  736. params.set('maxPacketSize', String(range.max));
  737. } else {
  738. params.set('obfs', 'salamander');
  739. }
  740. params.set('obfs-password', obfsPassword);
  741. }
  742. }
  743. const hopPorts = stream.finalmask?.quicParams?.udpHop?.ports?.trim() ?? '';
  744. if (hopPorts.length > 0) {
  745. params.set('mport', hopPorts);
  746. }
  747. const url = new URL(`${scheme}://${clientAuth}@${formatUrlHost(address)}:${port}`);
  748. for (const [key, value] of params) url.searchParams.set(key, value);
  749. url.hash = encodeURIComponent(remark);
  750. return url.toString();
  751. }
  752. export interface GenMtprotoLinkInput {
  753. inbound: Inbound;
  754. address: string;
  755. port?: number;
  756. clientSecret?: string;
  757. }
  758. // Builds a per-client Telegram proxy deep link for an mtproto inbound from the
  759. // client's own FakeTLS secret. No remark fragment is added: Telegram proxy deep
  760. // links have no name field, and a trailing "#remark" gets folded into the last
  761. // query value by lenient parsers, breaking the server address. The panel shows
  762. // the remark separately from the link.
  763. export function genMtprotoLink(input: GenMtprotoLinkInput): string {
  764. const { inbound, address, port = inbound.port, clientSecret = '' } = input;
  765. if (inbound.protocol !== 'mtproto') return '';
  766. if (clientSecret.length === 0) return '';
  767. const url = new URL('tg://proxy');
  768. url.searchParams.set('server', address);
  769. url.searchParams.set('port', String(port));
  770. url.searchParams.set('secret', clientSecret);
  771. return url.toString();
  772. }
  773. export interface GenWireguardLinkInput {
  774. settings: WireguardInboundSettings;
  775. address: string;
  776. port: number;
  777. remark?: string;
  778. peerIndex: number;
  779. }
  780. // Wireguard share link: wireguard://<peerPrivKey>@<host>:<port>
  781. // ?publickey=<serverPub>&address=<peerAllowedIP>&mtu=<mtu>#<remark>
  782. // pubKey is derived from the server's secretKey via Wireguard.generateKeypair
  783. // at call time (Zod's schema stores secretKey only — pubKey isn't on the
  784. // wire). Returns '' when the peer index is out of bounds.
  785. export function genWireguardLink(input: GenWireguardLinkInput): string {
  786. const { settings, address, port, remark = '', peerIndex } = input;
  787. const peer = settings.peers[peerIndex];
  788. if (!peer) return '';
  789. const url = new URL(`wireguard://${formatUrlHost(address)}:${port}`);
  790. url.username = peer.privateKey ?? '';
  791. const pubKey =
  792. settings.secretKey.length > 0 ? Wireguard.generateKeypair(settings.secretKey).publicKey : '';
  793. if (pubKey.length > 0) url.searchParams.set('publickey', pubKey);
  794. if (peer.allowedIPs.length > 0) {
  795. url.searchParams.set('address', peer.allowedIPs.join(','));
  796. }
  797. if (typeof settings.mtu === 'number' && settings.mtu > 0) {
  798. url.searchParams.set('mtu', String(settings.mtu));
  799. }
  800. url.hash = encodeURIComponent(remark);
  801. return url.toString();
  802. }
  803. // Plain-text WireGuard client config (.conf format). Mirrors the legacy
  804. // getWireguardTxt — same DNS defaults (1.1.1.1, 1.0.0.1), MTU optional,
  805. // presharedKey + keepAlive only emitted when present on the peer. The
  806. // final newline structure follows the legacy: no newline after Endpoint,
  807. // optional preSharedKey appended with leading \n, keepAlive appended
  808. // with leading \n AND trailing \n.
  809. export function genWireguardConfig(input: GenWireguardLinkInput): string {
  810. const { settings, address, port, remark = '', peerIndex } = input;
  811. const peer = settings.peers[peerIndex];
  812. if (!peer) return '';
  813. const pubKey =
  814. settings.secretKey.length > 0 ? Wireguard.generateKeypair(settings.secretKey).publicKey : '';
  815. let txt = `[Interface]\n`;
  816. txt += `PrivateKey = ${peer.privateKey ?? ''}\n`;
  817. txt += `Address = ${peer.allowedIPs.join(', ')}\n`;
  818. txt += `DNS = ${settings.dns || '1.1.1.1, 1.0.0.1'}\n`;
  819. if (typeof settings.mtu === 'number' && settings.mtu > 0) {
  820. txt += `MTU = ${settings.mtu}\n`;
  821. }
  822. txt += `\n# ${remark}\n`;
  823. txt += `[Peer]\n`;
  824. txt += `PublicKey = ${pubKey}\n`;
  825. txt += `AllowedIPs = 0.0.0.0/0, ::/0\n`;
  826. txt += `Endpoint = ${address}:${port}`;
  827. if (peer.preSharedKey && peer.preSharedKey.length > 0) {
  828. txt += `\nPresharedKey = ${peer.preSharedKey}`;
  829. }
  830. if (typeof peer.keepAlive === 'number' && peer.keepAlive > 0) {
  831. txt += `\nPersistentKeepalive = ${peer.keepAlive}\n`;
  832. }
  833. return txt;
  834. }
  835. // Shared input shape for both the per-client vpn:// link and .conf
  836. // builders below — settings.clients (not a peers array; unlike WireGuard,
  837. // AmneziaWG was multi-client from day one, so there's no legacy format).
  838. export interface GenAmneziaWGLinkInput {
  839. settings: AmneziawgInboundSettings;
  840. address: string;
  841. port: number;
  842. remark?: string;
  843. peerIndex: number;
  844. }
  845. function amneziaWGHLine(key: string, value: string | undefined, fallback: string): string {
  846. return `${key} = ${value && value.trim() !== '' ? value : fallback}`;
  847. }
  848. // Base64url (RFC 4648 §5), no padding — matches the real AmneziaVPN app's
  849. // own Qt::Base64UrlEncoding | Qt::OmitTrailingEquals framing for vpn:// links.
  850. function toBase64Url(text: string): string {
  851. const bytes = new TextEncoder().encode(text);
  852. let binary = '';
  853. for (const b of bytes) binary += String.fromCharCode(b);
  854. return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
  855. }
  856. // AmneziaWG share link: vpn://<base64url .conf text>, matching the real
  857. // AmneziaVPN app's own share-link scheme. The app's import path base64url-
  858. // decodes, best-effort qUncompresses (falls back to the raw bytes when the
  859. // input isn't qCompress-framed, which plain text never is), then parses the
  860. // result as a flat bag of "Key = Value" lines regardless of which
  861. // [Interface]/[Peer] section they came from — so wrapping the same .conf
  862. // text genAmneziaWGConfig already produces is sufficient; no JSON schema or
  863. // compression needs replicating. Confirmed against the app's own source
  864. // (importController.cpp's checkConfigFormat/extractWireGuardConfig).
  865. export function genAmneziaWGLink(input: GenAmneziaWGLinkInput): string {
  866. const cfgText = genAmneziaWGConfig(input);
  867. if (!cfgText) return '';
  868. return `vpn://${toBase64Url(cfgText)}`;
  869. }
  870. // Plain-text AmneziaWG client config (.conf format). Mirrors
  871. // genWireguardConfig, plus the obfuscation lines every AmneziaWG client must
  872. // share with the server (see internal/amneziawg.writeObfuscation on the Go
  873. // side).
  874. export function genAmneziaWGConfig(input: GenAmneziaWGLinkInput): string {
  875. const { settings, address, port, remark = '', peerIndex } = input;
  876. const client = settings.clients[peerIndex];
  877. if (!client) return '';
  878. const server = settings.server;
  879. // These land unescaped in the .conf; a newline would inject a config line
  880. // (e.g. a rogue PostUp) — same guard as the panel's other two emitters.
  881. for (const v of [
  882. client.privateKey ?? '',
  883. server.primaryDns ?? '',
  884. server.secondaryDns ?? '',
  885. remark,
  886. ]) {
  887. if (/[\r\n]/.test(v)) return '';
  888. }
  889. let txt = `[Interface]\n`;
  890. txt += `PrivateKey = ${client.privateKey ?? ''}\n`;
  891. txt += `Address = ${(client.allowedIPs ?? []).join(', ')}\n`;
  892. const dns = [server.primaryDns, server.secondaryDns].filter((v) => !!v && v.trim() !== '');
  893. if (dns.length > 0) txt += `DNS = ${dns.join(', ')}\n`;
  894. txt += `MTU = ${effectiveMtu(server.mtu, server.s4)}\n`;
  895. txt += `Jc = ${server.jc}\n`;
  896. txt += `Jmin = ${server.jmin}\n`;
  897. txt += `Jmax = ${server.jmax}\n`;
  898. txt += `S1 = ${server.s1}\n`;
  899. txt += `S2 = ${server.s2}\n`;
  900. if (server.s3) txt += `S3 = ${server.s3}\n`;
  901. if (server.s4) txt += `S4 = ${server.s4}\n`;
  902. txt += `${amneziaWGHLine('H1', server.h1, '1')}\n`;
  903. txt += `${amneziaWGHLine('H2', server.h2, '2')}\n`;
  904. txt += `${amneziaWGHLine('H3', server.h3, '3')}\n`;
  905. txt += `${amneziaWGHLine('H4', server.h4, '4')}\n`;
  906. if (server.i1) txt += `I1 = ${server.i1}\n`;
  907. if (server.i2) txt += `I2 = ${server.i2}\n`;
  908. if (server.i3) txt += `I3 = ${server.i3}\n`;
  909. if (server.i4) txt += `I4 = ${server.i4}\n`;
  910. if (server.i5) txt += `I5 = ${server.i5}\n`;
  911. const optional31: Array<[string, string | undefined]> = [
  912. ['HeaderProtectionKey', server.headerProtectionKey],
  913. ['ContentPaddingAddition', server.contentPaddingAddition],
  914. ['RekeyAfterTime', server.rekeyAfterTime],
  915. ['RekeyTimeout', server.rekeyTimeout],
  916. ['RejectAfterTime', server.rejectAfterTime],
  917. ['KeepaliveTimeout', server.keepaliveTimeout],
  918. ['MaxHandshakeAttempts', server.maxHandshakeAttempts],
  919. ];
  920. for (const [key, value] of optional31) {
  921. if (value && value.trim() !== '') txt += `${key} = ${value}\n`;
  922. }
  923. if (server.randomTrailers) txt += `RandomTrailers = on\n`;
  924. if (server.disableCookies) txt += `DisableCookies = on\n`;
  925. // Peer field order follows wg-quick(8) and the panel's other two AmneziaWG
  926. // emitters (amneziaWGConfigText in Go, buildAmneziaWGClientConfig); all three
  927. // are independent implementations and must not drift apart.
  928. txt += `\n# ${remark}\n`;
  929. txt += `[Peer]\n`;
  930. txt += `PublicKey = ${server.publicKey ?? ''}\n`;
  931. if (client.preSharedKey && client.preSharedKey.length > 0) {
  932. txt += `PresharedKey = ${client.preSharedKey}\n`;
  933. }
  934. txt += `AllowedIPs = 0.0.0.0/0, ::/0\n`;
  935. txt += `Endpoint = ${address}:${port}`;
  936. if (typeof client.keepAlive === 'number' && client.keepAlive > 0) {
  937. txt += `\nPersistentKeepalive = ${client.keepAlive}`;
  938. }
  939. return txt;
  940. }
  941. export interface GenAmneziaWGFanoutInput {
  942. inbound: Inbound;
  943. remark?: string;
  944. hostOverride?: string;
  945. fallbackHostname: string;
  946. }
  947. export function genAmneziaWGLinks(input: GenAmneziaWGFanoutInput): string {
  948. const { inbound, remark = '', hostOverride = '', fallbackHostname } = input;
  949. if (inbound.protocol !== 'amneziawg') return '';
  950. const addr = resolveAddr(inbound, hostOverride, fallbackHostname);
  951. const sep = '-';
  952. const settings = inbound.settings as AmneziawgInboundSettings;
  953. const clients = settings.clients ?? [];
  954. return clients
  955. .map((c, i) =>
  956. genAmneziaWGLink({
  957. settings,
  958. address: addr,
  959. port: inbound.port,
  960. remark: `${remark}${sep}${i + 1}${wgPeerCommentSuffix(c)}`,
  961. peerIndex: i,
  962. }),
  963. )
  964. .join('\r\n');
  965. }
  966. export function genAmneziaWGConfigs(input: GenAmneziaWGFanoutInput): string {
  967. const { inbound, remark = '', hostOverride = '', fallbackHostname } = input;
  968. if (inbound.protocol !== 'amneziawg') return '';
  969. const addr = resolveAddr(inbound, hostOverride, fallbackHostname);
  970. const sep = '-';
  971. const settings = inbound.settings as AmneziawgInboundSettings;
  972. const clients = settings.clients ?? [];
  973. return clients
  974. .map((c, i) =>
  975. genAmneziaWGConfig({
  976. settings,
  977. address: addr,
  978. port: inbound.port,
  979. remark: `${remark}${sep}${i + 1}${wgPeerCommentSuffix(c)}`,
  980. peerIndex: i,
  981. }),
  982. )
  983. .join('\r\n');
  984. }
  985. export function wireguardConfigFromLink(link: string, fallbackRemark = ''): string {
  986. let url: URL;
  987. try {
  988. url = new URL(link);
  989. } catch {
  990. return '';
  991. }
  992. const scheme = url.protocol.replace(/:$/, '');
  993. if (scheme !== 'wireguard' && scheme !== 'wg') return '';
  994. const params = url.searchParams;
  995. const pick = (...keys: string[]): string => {
  996. for (const k of keys) {
  997. const v = params.get(k);
  998. if (v) return v;
  999. }
  1000. return '';
  1001. };
  1002. let privateKey: string;
  1003. try {
  1004. privateKey = decodeURIComponent(url.username);
  1005. } catch {
  1006. privateKey = url.username;
  1007. }
  1008. const host = url.hostname;
  1009. const endpoint = host ? (url.port ? `${host}:${url.port}` : host) : '';
  1010. const address = pick('address', 'ip') || '10.0.0.2/32';
  1011. const publicKey = pick('publickey', 'publicKey', 'public_key', 'peerPublicKey');
  1012. const dns = pick('dns') || '1.1.1.1, 1.0.0.1';
  1013. const mtu = pick('mtu');
  1014. const psk = pick('presharedkey', 'preshared_key', 'pre-shared-key', 'psk');
  1015. const keepAlive = pick('keepalive', 'persistentkeepalive', 'persistent_keepalive');
  1016. const allowedIPs = pick('allowedips', 'allowed_ips') || '0.0.0.0/0, ::/0';
  1017. let remark = fallbackRemark;
  1018. try {
  1019. const decoded = decodeURIComponent(url.hash.replace(/^#/, ''));
  1020. if (decoded) remark = decoded;
  1021. } catch {
  1022. const raw = url.hash.replace(/^#/, '');
  1023. if (raw) remark = raw;
  1024. }
  1025. const lines = [
  1026. '[Interface]',
  1027. `PrivateKey = ${privateKey}`,
  1028. `Address = ${address}`,
  1029. `DNS = ${dns}`,
  1030. ];
  1031. if (mtu && Number(mtu) > 0) lines.push(`MTU = ${mtu}`);
  1032. lines.push('');
  1033. if (remark) lines.push(`# ${remark}`);
  1034. lines.push('[Peer]', `PublicKey = ${publicKey}`);
  1035. if (psk) lines.push(`PresharedKey = ${psk}`);
  1036. lines.push(`AllowedIPs = ${allowedIPs}`, `Endpoint = ${endpoint}`);
  1037. if (keepAlive && Number(keepAlive) > 0) lines.push(`PersistentKeepalive = ${keepAlive}`);
  1038. return lines.join('\n');
  1039. }
  1040. // Reverse of toBase64Url above -- recovers a vpn:// link's plain .conf
  1041. // payload for display/copy/download/QR, the AmneziaWG counterpart of
  1042. // wireguardConfigFromLink. Simpler than that function: a vpn:// link's
  1043. // payload already *is* the .conf text (see genAmneziaWGLink's own doc
  1044. // comment), so there's nothing to reconstruct from query params -- just
  1045. // decode. Mirrors link-label.tsx's own private fromBase64Url (used there
  1046. // only to pull the remark/port back out for the tag label); duplicated
  1047. // rather than imported since both are tiny, self-contained, and each
  1048. // file already owns the matching encode or decode half of this pair.
  1049. function fromBase64Url(value: string): string {
  1050. const b64 = value.replace(/-/g, '+').replace(/_/g, '/');
  1051. const padded = b64 + '='.repeat((4 - (b64.length % 4)) % 4);
  1052. const binary = atob(padded);
  1053. const bytes = new Uint8Array(binary.length);
  1054. for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
  1055. return new TextDecoder().decode(bytes);
  1056. }
  1057. export function amneziawgConfigFromLink(link: string): string {
  1058. const trimmed = link.trim();
  1059. if (!trimmed.startsWith('vpn://')) return '';
  1060. try {
  1061. return fromBase64Url(trimmed.slice('vpn://'.length));
  1062. } catch {
  1063. return '';
  1064. }
  1065. }
  1066. export type { WireguardInboundPeer };
  1067. function isUnixSocketListen(listen: string): boolean {
  1068. return listen.startsWith('/') || listen.startsWith('@');
  1069. }
  1070. function normalizeShareHost(host: string): string {
  1071. const h = host.trim();
  1072. if (h.length === 0 || h.includes('://') || h.startsWith('//') || /[/?#@]/.test(h)) {
  1073. return '';
  1074. }
  1075. if (h.startsWith('[')) {
  1076. if (!h.endsWith(']')) return '';
  1077. try {
  1078. return new URL(`http://${h}`).hostname;
  1079. } catch {
  1080. return '';
  1081. }
  1082. }
  1083. if (h.includes(':')) {
  1084. try {
  1085. return new URL(`http://[${h}]`).hostname;
  1086. } catch {
  1087. return '';
  1088. }
  1089. }
  1090. return SHARE_HOSTNAME_RE.test(h) ? h : '';
  1091. }
  1092. function isShareableHost(host: string): boolean {
  1093. const h = normalizeShareHost(host)
  1094. .replace(/^\[|\]$/g, '')
  1095. .toLowerCase();
  1096. if (h.length === 0) return false;
  1097. if (h === '0.0.0.0' || h === '::' || h === '::0') return false;
  1098. if (h === 'localhost' || h === '::1' || h.startsWith('127.')) return false;
  1099. return true;
  1100. }
  1101. function shareableListenFrom(listen: string): string {
  1102. const trimmed = listen.trim();
  1103. return trimmed.length > 0 && !isUnixSocketListen(trimmed) && isShareableHost(trimmed)
  1104. ? normalizeShareHost(trimmed)
  1105. : '';
  1106. }
  1107. type ShareAddrStrategy = 'node' | 'listen' | 'custom';
  1108. function normalizeShareAddrStrategy(strategy: string | undefined): ShareAddrStrategy {
  1109. return strategy === 'listen' || strategy === 'custom' ? strategy : 'node';
  1110. }
  1111. // ShareHostFields is the subset of an inbound resolveShareHost needs, so callers
  1112. // holding only a lightweight projection (e.g. the clients page InboundOption)
  1113. // can pick the same host as the full-inbound share/QR path.
  1114. export interface ShareHostFields {
  1115. listen?: string;
  1116. shareAddr?: string;
  1117. shareAddrStrategy?: string;
  1118. }
  1119. // resolveShareHost picks the host that goes into share/QR links, the browser-side
  1120. // analog of the backend resolveInboundAddress. hostOverride is the hosting node's
  1121. // address (empty for this panel's own inbounds); fallbackHostname is the
  1122. // already-resolved panel/public host used as the last resort — kept verbatim when
  1123. // it fails normalization (e.g. an underscore intranet hostname) so the last
  1124. // resort never degrades to an empty host.
  1125. export function resolveShareHost(
  1126. fields: ShareHostFields,
  1127. hostOverride: string,
  1128. fallbackHostname: string,
  1129. ): string {
  1130. const nodeAddr = normalizeShareHost(hostOverride);
  1131. const listenAddr = shareableListenFrom(fields.listen ?? '');
  1132. const customAddr = normalizeShareHost(fields.shareAddr ?? '');
  1133. const fallbackAddr = normalizeShareHost(fallbackHostname) || fallbackHostname.trim();
  1134. switch (normalizeShareAddrStrategy(fields.shareAddrStrategy)) {
  1135. case 'listen':
  1136. return listenAddr || nodeAddr || fallbackAddr;
  1137. case 'custom':
  1138. return customAddr || nodeAddr || listenAddr || fallbackAddr;
  1139. default:
  1140. return nodeAddr || listenAddr || fallbackAddr;
  1141. }
  1142. }
  1143. // Orchestrators.
  1144. // resolveAddr picks the host that goes into share/QR links. The default
  1145. // `node` strategy keeps the previous node-address-first behavior for
  1146. // node-managed inbounds; other strategies let a row prefer its listen address
  1147. // or a custom endpoint.
  1148. export function resolveAddr(
  1149. inbound: Inbound,
  1150. hostOverride: string,
  1151. fallbackHostname: string,
  1152. ): string {
  1153. return resolveShareHost(inbound, hostOverride, fallbackHostname);
  1154. }
  1155. // A loopback browser host means the panel was reached through a tunnel (e.g.
  1156. // SSH-forwarded 127.0.0.1/localhost), so it can never be a shareable link host.
  1157. function isLoopbackHost(host: string): boolean {
  1158. const h = host
  1159. .trim()
  1160. .replace(/^\[|\]$/g, '')
  1161. .toLowerCase();
  1162. return h === 'localhost' || h === '::1' || h.startsWith('127.');
  1163. }
  1164. // preferPublicHost is the browser-side analog of the backend's
  1165. // configuredPublicHost: when the panel is reached on a loopback host, prefer a
  1166. // configured public host (Sub/Web Domain) for share/QR links instead of leaking
  1167. // localhost. An explicit per-inbound listen or node override still wins, since
  1168. // resolveAddr only reaches the fallbackHostname after those.
  1169. export function preferPublicHost(browserHost: string, publicHost: string): string {
  1170. return publicHost && isLoopbackHost(browserHost) ? publicHost : browserHost;
  1171. }
  1172. // Returns the client array for protocols that have one. SS returns its
  1173. // clients only in 2022-blake3 multi-user mode (matches the legacy
  1174. // `this.clients` getter, which used isSSMultiUser to gate). Returns null
  1175. // for SS single-user, http, mixed, tunnel, wireguard, hysteria2-without-
  1176. // clients, and any protocol without a clients array.
  1177. type ClientShape = {
  1178. id?: string;
  1179. security?: VmessSecurity;
  1180. flow?: VlessClient['flow'];
  1181. password?: string;
  1182. auth?: string;
  1183. secret?: string;
  1184. email?: string;
  1185. subId?: string;
  1186. };
  1187. // Mirror of the Go subKey: the stable per-client identity spx derivation
  1188. // keys on — subscription id first, unique email as the fallback.
  1189. function clientSubKey(client: ClientShape): string {
  1190. return client.subId || client.email || '';
  1191. }
  1192. export function getInboundClients(inbound: Inbound): ClientShape[] | null {
  1193. switch (inbound.protocol) {
  1194. case 'vmess':
  1195. return (inbound.settings.clients ?? []) as ClientShape[];
  1196. case 'vless':
  1197. return (inbound.settings.clients ?? []) as ClientShape[];
  1198. case 'trojan':
  1199. return (inbound.settings.clients ?? []) as ClientShape[];
  1200. case 'hysteria':
  1201. return (inbound.settings.clients ?? []) as ClientShape[];
  1202. case 'mtproto':
  1203. return (inbound.settings.clients ?? []) as ClientShape[];
  1204. case 'shadowsocks': {
  1205. const isMultiUser = inbound.settings.method !== '2022-blake3-chacha20-poly1305';
  1206. return isMultiUser ? ((inbound.settings.clients ?? []) as ClientShape[]) : null;
  1207. }
  1208. default:
  1209. return null;
  1210. }
  1211. }
  1212. export interface GenLinkInput {
  1213. inbound: Inbound;
  1214. address: string;
  1215. port?: number;
  1216. forceTls?: ForceTls;
  1217. remark?: string;
  1218. client: ClientShape;
  1219. externalProxy?: ExternalProxyEntry | null;
  1220. }
  1221. // Per-protocol dispatcher matching the legacy `genLink` switch. Returns
  1222. // '' for protocols that don't have client-based share links (wireguard
  1223. // goes through genWireguardLinks/Configs separately, http/mixed/tunnel
  1224. // don't have share URLs).
  1225. export function genLink(input: GenLinkInput): string {
  1226. const {
  1227. inbound,
  1228. address,
  1229. port = inbound.port,
  1230. forceTls = 'same',
  1231. remark = '',
  1232. client,
  1233. externalProxy = null,
  1234. } = input;
  1235. switch (inbound.protocol) {
  1236. case 'vmess':
  1237. return genVmessLink({
  1238. inbound,
  1239. address,
  1240. port,
  1241. forceTls,
  1242. remark,
  1243. clientId: client.id ?? '',
  1244. security: client.security,
  1245. externalProxy,
  1246. });
  1247. case 'vless':
  1248. return genVlessLink({
  1249. inbound,
  1250. address,
  1251. port,
  1252. forceTls,
  1253. remark,
  1254. clientId: client.id ?? '',
  1255. clientKey: clientSubKey(client),
  1256. flow: client.flow,
  1257. externalProxy,
  1258. });
  1259. case 'shadowsocks': {
  1260. const isMultiUser = inbound.settings.method !== '2022-blake3-chacha20-poly1305';
  1261. return genShadowsocksLink({
  1262. inbound,
  1263. address,
  1264. port,
  1265. forceTls,
  1266. remark,
  1267. clientPassword: isMultiUser ? (client.password ?? '') : '',
  1268. externalProxy,
  1269. });
  1270. }
  1271. case 'trojan':
  1272. return genTrojanLink({
  1273. inbound,
  1274. address,
  1275. port,
  1276. forceTls,
  1277. remark,
  1278. clientPassword: client.password ?? '',
  1279. clientKey: clientSubKey(client),
  1280. externalProxy,
  1281. });
  1282. case 'hysteria':
  1283. return genHysteriaLink({
  1284. inbound,
  1285. address,
  1286. port,
  1287. remark,
  1288. clientAuth: client.auth ?? '',
  1289. externalProxy,
  1290. });
  1291. case 'mtproto':
  1292. return genMtprotoLink({ inbound, address, port, clientSecret: client.secret ?? '' });
  1293. default:
  1294. return '';
  1295. }
  1296. }
  1297. export interface GenAllLinksEntry {
  1298. remark: string;
  1299. link: string;
  1300. }
  1301. export interface GenAllLinksInput {
  1302. inbound: Inbound;
  1303. remark?: string;
  1304. client: ClientShape;
  1305. hostOverride?: string;
  1306. fallbackHostname: string;
  1307. }
  1308. // Fans out a single client's link per externalProxy entry, or just one link
  1309. // when there are no external proxies. The panel copy/QR remark is the inbound
  1310. // remark plus the externalProxy remark, dash-joined (the configurable
  1311. // subscription remark model was removed; subscription output uses the template).
  1312. export function genAllLinks(input: GenAllLinksInput): GenAllLinksEntry[] {
  1313. const { inbound, remark = '', client, hostOverride = '', fallbackHostname } = input;
  1314. const addr = resolveAddr(inbound, hostOverride, fallbackHostname);
  1315. const port = inbound.port;
  1316. const composeRemark = (proxyRemark: string): string =>
  1317. [remark, proxyRemark].filter((x) => x.length > 0).join('-');
  1318. const externals = inbound.streamSettings?.externalProxy;
  1319. if (!externals || externals.length === 0) {
  1320. const r = composeRemark('');
  1321. return [
  1322. {
  1323. remark: r,
  1324. link: genLink({ inbound, address: addr, port, forceTls: 'same', remark: r, client }),
  1325. },
  1326. ];
  1327. }
  1328. return externals.map((ep) => {
  1329. const r = composeRemark(ep.remark);
  1330. return {
  1331. remark: r,
  1332. link: genLink({
  1333. inbound,
  1334. address: ep.dest,
  1335. port: ep.port,
  1336. forceTls: ep.forceTls,
  1337. remark: r,
  1338. client,
  1339. externalProxy: ep,
  1340. }),
  1341. };
  1342. });
  1343. }
  1344. export interface GenInboundLinksInput {
  1345. inbound: Inbound;
  1346. remark?: string;
  1347. hostOverride?: string;
  1348. fallbackHostname: string;
  1349. }
  1350. // Top-level entrypoint that produces the full \r\n-joined block a user
  1351. // pastes into a client. Iterates per-client for protocols with clients,
  1352. // falls back to a single SS link for single-user 2022-blake3-chacha20,
  1353. // and emits per-peer .conf blocks for wireguard and amneziawg. Returns '' for the
  1354. // other clientless protocols (http, mixed, tunnel).
  1355. export function genInboundLinks(input: GenInboundLinksInput): string {
  1356. const { inbound, remark = '', hostOverride = '', fallbackHostname } = input;
  1357. const addr = resolveAddr(inbound, hostOverride, fallbackHostname);
  1358. const clients = getInboundClients(inbound);
  1359. if (clients) {
  1360. const links: string[] = [];
  1361. for (const client of clients) {
  1362. const entries = genAllLinks({ inbound, remark, client, hostOverride, fallbackHostname });
  1363. for (const e of entries) links.push(e.link);
  1364. }
  1365. return links.join('\r\n');
  1366. }
  1367. if (inbound.protocol === 'shadowsocks') {
  1368. return genShadowsocksLink({
  1369. inbound,
  1370. address: addr,
  1371. port: inbound.port,
  1372. forceTls: 'same',
  1373. remark,
  1374. });
  1375. }
  1376. if (inbound.protocol === 'wireguard') {
  1377. return genWireguardConfigs({ inbound, remark, hostOverride, fallbackHostname });
  1378. }
  1379. if (inbound.protocol === 'amneziawg') {
  1380. return genAmneziaWGConfigs({ inbound, remark, hostOverride, fallbackHostname });
  1381. }
  1382. return '';
  1383. }
  1384. // Per-peer wireguard fanout. Each peer gets its own link (or .conf
  1385. // block) with an index-suffixed remark, joined by \r\n. Matches the
  1386. // legacy genWireguardLinks / genWireguardConfigs exactly.
  1387. export interface GenWireguardFanoutInput {
  1388. inbound: Inbound;
  1389. remark?: string;
  1390. hostOverride?: string;
  1391. fallbackHostname: string;
  1392. }
  1393. // WireGuard is multi-client: each client is one accepted peer. The canonical
  1394. // store is settings.clients; legacy single-config inbounds (pre-migration) are
  1395. // still rendered from settings.peers. Both carry the privateKey/allowedIPs/
  1396. // preSharedKey/keepAlive the link and .conf need, so they project to the same
  1397. // peer shape and reuse genWireguardLink/genWireguardConfig unchanged.
  1398. function wgRenderPeers(settings: WireguardInboundSettings): WireguardInboundPeer[] {
  1399. const clients = settings.clients ?? [];
  1400. if (clients.length > 0) {
  1401. return clients.map((c) => ({ ...c, publicKey: c.publicKey ?? '' }));
  1402. }
  1403. return settings.peers;
  1404. }
  1405. export function genWireguardLinks(input: GenWireguardFanoutInput): string {
  1406. const { inbound, remark = '', hostOverride = '', fallbackHostname } = input;
  1407. if (inbound.protocol !== 'wireguard') return '';
  1408. const addr = resolveAddr(inbound, hostOverride, fallbackHostname);
  1409. const sep = '-';
  1410. const baseSettings = inbound.settings as WireguardInboundSettings;
  1411. const peers = wgRenderPeers(baseSettings);
  1412. const settings: WireguardInboundSettings = { ...baseSettings, peers };
  1413. return peers
  1414. .map((p, i) =>
  1415. genWireguardLink({
  1416. settings,
  1417. address: addr,
  1418. port: inbound.port,
  1419. remark: `${remark}${sep}${i + 1}${wgPeerCommentSuffix(p)}`,
  1420. peerIndex: i,
  1421. }),
  1422. )
  1423. .join('\r\n');
  1424. }
  1425. export function genWireguardConfigs(input: GenWireguardFanoutInput): string {
  1426. const { inbound, remark = '', hostOverride = '', fallbackHostname } = input;
  1427. if (inbound.protocol !== 'wireguard') return '';
  1428. const addr = resolveAddr(inbound, hostOverride, fallbackHostname);
  1429. const sep = '-';
  1430. const baseSettings = inbound.settings as WireguardInboundSettings;
  1431. const peers = wgRenderPeers(baseSettings);
  1432. const settings: WireguardInboundSettings = { ...baseSettings, peers };
  1433. return peers
  1434. .map((p, i) =>
  1435. genWireguardConfig({
  1436. settings,
  1437. address: addr,
  1438. port: inbound.port,
  1439. remark: `${remark}${sep}${i + 1}${wgPeerCommentSuffix(p)}`,
  1440. peerIndex: i,
  1441. }),
  1442. )
  1443. .join('\r\n');
  1444. }
  1445. // Peer comments (#5168) are panel-side annotations; when present they ride
  1446. // along in the share remark so the device is identifiable in client apps.
  1447. function wgPeerCommentSuffix(peer: unknown): string {
  1448. const comment = (peer as { comment?: unknown })?.comment;
  1449. return typeof comment === 'string' && comment.trim() !== '' ? ` (${comment.trim()})` : '';
  1450. }
  1451. export function isPostQuantumLink(link: string): boolean {
  1452. if (/[?&]pqv=/.test(link)) return true;
  1453. if (link.includes('mlkem768') || link.includes('mldsa65')) return true;
  1454. if (link.includes('ML-KEM-768')) return true;
  1455. return false;
  1456. }