wireguardConfig.ts 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import { formatInboundLabel } from '@/lib/inbounds/label';
  2. import { preferPublicHost, resolveShareHost } from '@/lib/xray/inbound-link';
  3. import type { ClientRecord, InboundOption } from '@/hooks/useClients';
  4. export function isWireguardClient(client: ClientRecord | null | undefined): boolean {
  5. if (!client) return false;
  6. return !!(
  7. client.privateKey ||
  8. client.publicKey ||
  9. client.allowedIPs ||
  10. client.preSharedKey ||
  11. client.keepAlive
  12. );
  13. }
  14. export function findWireguardInbounds(
  15. client: ClientRecord | null | undefined,
  16. inboundsById: Record<number, InboundOption>,
  17. ): InboundOption[] {
  18. return (client?.inboundIds || [])
  19. .map((id) => inboundsById?.[id])
  20. .filter((ib): ib is InboundOption => ib?.protocol === 'wireguard');
  21. }
  22. export function buildWireguardClientConfig(
  23. client: ClientRecord,
  24. inbound: InboundOption | undefined,
  25. host = window.location.hostname,
  26. publicHost = '',
  27. addressOverride = '',
  28. ): string {
  29. const endpointHost = resolveShareHost(
  30. inbound ?? {},
  31. inbound?.nodeAddress ?? '',
  32. preferPublicHost(host, publicHost),
  33. );
  34. const address = addressOverride || client.allowedIPs || '10.0.0.2/32';
  35. const endpoint = `${endpointHost}:${inbound?.port || ''}`;
  36. const inboundName = inbound ? formatInboundLabel(inbound.tag, inbound.remark) : '';
  37. const remark = [inboundName, client.email, client.comment].filter(Boolean).join(' - ');
  38. const lines = [
  39. '[Interface]',
  40. `PrivateKey = ${client.privateKey || client.password || ''}`,
  41. `Address = ${address}`,
  42. `DNS = ${inbound?.wgDns || '1.1.1.1, 1.0.0.1'}`,
  43. ];
  44. if (inbound?.wgMtu && inbound.wgMtu > 0) lines.push(`MTU = ${inbound.wgMtu}`);
  45. lines.push('');
  46. if (remark) lines.push(`# ${remark}`);
  47. lines.push('[Peer]', `PublicKey = ${inbound?.wgPublicKey || ''}`);
  48. if (client.preSharedKey) lines.push(`PresharedKey = ${client.preSharedKey}`);
  49. lines.push('AllowedIPs = 0.0.0.0/0, ::/0', `Endpoint = ${endpoint}`);
  50. if (client.keepAlive && client.keepAlive > 0)
  51. lines.push(`PersistentKeepalive = ${client.keepAlive}`);
  52. return lines.join('\n');
  53. }