nord-config-generator 1.0.0__tar.gz → 1.0.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: nord-config-generator
3
- Version: 1.0.0
3
+ Version: 1.0.1
4
4
  Summary: A command-line tool for generating optimized NordVPN WireGuard configurations.
5
5
  Author-email: Ahmed Touhami <mustafachyi272@gmail.com>
6
6
  Project-URL: Homepage, https://github.com/mustafachyi/NordVPN-WireGuard-Config-Generator
@@ -10,11 +10,11 @@ Classifier: License :: OSI Approved :: GNU General Public License v3 (GPLv3)
10
10
  Classifier: Operating System :: OS Independent
11
11
  Classifier: Topic :: System :: Networking
12
12
  Classifier: Environment :: Console
13
- Requires-Python: >=3.8
13
+ Requires-Python: >=3.9
14
14
  Description-Content-Type: text/markdown
15
- Requires-Dist: aiohttp>=3.8.0
16
- Requires-Dist: aiofiles>=0.8.0
17
- Requires-Dist: rich>=12.0.0
15
+ Requires-Dist: aiohttp<4.0,>=3.12.14
16
+ Requires-Dist: aiofiles<25.0,>=24.1.0
17
+ Requires-Dist: rich<15.0,>=14.0.0
18
18
 
19
19
  # NordVPN WireGuard Configuration Generator
20
20
 
@@ -39,11 +39,11 @@ This consolidated effort ensures a higher standard of quality and a more reliabl
39
39
  * **Performance:** Asynchronous architecture processes the entire NordVPN server list in seconds.
40
40
  * **Optimization:** Intelligently sorts servers by current load and geographic proximity to the user, generating configurations for the most performant connections.
41
41
  * **Structured Output:** Automatically creates a clean directory structure containing standard configurations, a `best_configs` folder for optimal servers per location, and a `servers.json` file with detailed metadata for analysis.
42
- * **Interactive and Non-Interactive:** A guided TUI for interactive use. The core logic is structured to be scriptable.
42
+ * **Interactive and Non-Interactive:** A guided rich-CLI for interactive use. The core logic is structured to be scriptable.
43
43
 
44
44
  ## Installation
45
45
 
46
- Prerequisites: Python 3.8+
46
+ Prerequisites: Python 3.9+
47
47
 
48
48
  Install the package using `pip`:
49
49
 
@@ -53,14 +53,24 @@ pip install nord-config-generator
53
53
 
54
54
  ## Usage
55
55
 
56
- Execute the installed application:
56
+ ### Generate Configurations (Default Action)
57
+
58
+ Execute the application without any arguments. This is the primary function.
57
59
 
58
60
  ```bash
59
- nord-generator
61
+ nordgen
60
62
  ```
61
63
 
62
64
  The application will prompt for the required access token and configuration preferences.
63
65
 
66
+ ### Retrieve Private Key
67
+
68
+ To retrieve and display your NordLynx private key without generating configurations, use the `get-key` command:
69
+
70
+ ```bash
71
+ nordgen get-key
72
+ ```
73
+
64
74
  ## Web Version
65
75
 
66
76
  A graphical alternative is available for direct use in a web browser.
@@ -21,11 +21,11 @@ This consolidated effort ensures a higher standard of quality and a more reliabl
21
21
  * **Performance:** Asynchronous architecture processes the entire NordVPN server list in seconds.
22
22
  * **Optimization:** Intelligently sorts servers by current load and geographic proximity to the user, generating configurations for the most performant connections.
23
23
  * **Structured Output:** Automatically creates a clean directory structure containing standard configurations, a `best_configs` folder for optimal servers per location, and a `servers.json` file with detailed metadata for analysis.
24
- * **Interactive and Non-Interactive:** A guided TUI for interactive use. The core logic is structured to be scriptable.
24
+ * **Interactive and Non-Interactive:** A guided rich-CLI for interactive use. The core logic is structured to be scriptable.
25
25
 
26
26
  ## Installation
27
27
 
28
- Prerequisites: Python 3.8+
28
+ Prerequisites: Python 3.9+
29
29
 
30
30
  Install the package using `pip`:
31
31
 
@@ -35,14 +35,24 @@ pip install nord-config-generator
35
35
 
36
36
  ## Usage
37
37
 
38
- Execute the installed application:
38
+ ### Generate Configurations (Default Action)
39
+
40
+ Execute the application without any arguments. This is the primary function.
39
41
 
40
42
  ```bash
41
- nord-generator
43
+ nordgen
42
44
  ```
43
45
 
44
46
  The application will prompt for the required access token and configuration preferences.
45
47
 
48
+ ### Retrieve Private Key
49
+
50
+ To retrieve and display your NordLynx private key without generating configurations, use the `get-key` command:
51
+
52
+ ```bash
53
+ nordgen get-key
54
+ ```
55
+
46
56
  ## Web Version
47
57
 
48
58
  A graphical alternative is available for direct use in a web browser.
@@ -4,14 +4,14 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "nord-config-generator"
7
- version = "1.0.0"
7
+ version = "1.0.1"
8
8
  authors = [
9
9
  { name="Ahmed Touhami", email="mustafachyi272@gmail.com" },
10
10
  ]
11
11
  description = "A command-line tool for generating optimized NordVPN WireGuard configurations."
12
12
  readme = "README.md"
13
13
  license = { file="LICENSE" }
14
- requires-python = ">=3.8"
14
+ requires-python = ">=3.9"
15
15
  classifiers = [
16
16
  "Programming Language :: Python :: 3",
17
17
  "License :: OSI Approved :: GNU General Public License v3 (GPLv3)",
@@ -20,9 +20,9 @@ classifiers = [
20
20
  "Environment :: Console",
21
21
  ]
22
22
  dependencies = [
23
- "aiohttp>=3.8.0",
24
- "aiofiles>=0.8.0",
25
- "rich>=12.0.0",
23
+ "aiohttp>=3.12.14, <4.0",
24
+ "aiofiles>=24.1.0, <25.0",
25
+ "rich>=14.0.0, <15.0",
26
26
  ]
27
27
 
28
28
  [project.urls]
@@ -30,4 +30,4 @@ dependencies = [
30
30
  "Bug Tracker" = "https://github.com/mustafachyi/NordVPN-WireGuard-Config-Generator/issues"
31
31
 
32
32
  [project.scripts]
33
- nord-generator = "nord_config_generator.main:cli_entry_point"
33
+ nordgen = "nord_config_generator.main:cli_entry_point"
@@ -0,0 +1,317 @@
1
+ import sys
2
+ import os
3
+ import asyncio
4
+ import json
5
+ import base64
6
+ import re
7
+ import time
8
+ from typing import List, Tuple, Optional, Dict, Any
9
+ from dataclasses import dataclass
10
+ from pathlib import Path
11
+ from math import radians, sin, cos, asin, sqrt
12
+ from functools import partial
13
+ from concurrent.futures import ThreadPoolExecutor
14
+ from datetime import datetime
15
+
16
+ import aiohttp
17
+ import aiofiles
18
+
19
+ from .ui import ConsoleManager
20
+
21
+ @dataclass
22
+ class Server:
23
+ name: str
24
+ hostname: str
25
+ station: str
26
+ load: int
27
+ country: str
28
+ city: str
29
+ latitude: float
30
+ longitude: float
31
+ public_key: str
32
+ distance: float = 0.0
33
+
34
+ @dataclass
35
+ class UserPreferences:
36
+ dns: str = "103.86.96.100"
37
+ use_ip_for_endpoint: bool = False
38
+ persistent_keepalive: int = 25
39
+
40
+ @dataclass
41
+ class GenerationStats:
42
+ total_configs: int = 0
43
+ best_configs: int = 0
44
+
45
+ class NordVpnApiClient:
46
+ NORD_API_BASE_URL = "https://api.nordvpn.com/v1"
47
+ LOCATION_API_URL = "https://ipinfo.io/json"
48
+
49
+ def __init__(self, console_manager: ConsoleManager):
50
+ self._console = console_manager
51
+ self._session: Optional[aiohttp.ClientSession] = None
52
+
53
+ async def __aenter__(self):
54
+ self._session = aiohttp.ClientSession()
55
+ return self
56
+
57
+ async def __aexit__(self, exc_type, exc_val, exc_tb):
58
+ if self._session:
59
+ await self._session.close()
60
+
61
+ async def get_private_key(self, token: str) -> Optional[str]:
62
+ auth_header = base64.b64encode(f'token:{token}'.encode()).decode()
63
+ url = f"{self.NORD_API_BASE_URL}/users/services/credentials"
64
+ headers = {'Authorization': f'Basic {auth_header}'}
65
+ data = await self._get(url, headers=headers)
66
+ if isinstance(data, dict):
67
+ return data.get('nordlynx_private_key')
68
+ return None
69
+
70
+ async def get_all_servers(self) -> List[Dict[str, Any]]:
71
+ url = f"{self.NORD_API_BASE_URL}/servers"
72
+ params = {'limit': 9000, 'filters[servers_technologies][identifier]': 'wireguard_udp'}
73
+ data = await self._get(url, params=params)
74
+ return data if isinstance(data, list) else []
75
+
76
+ async def get_user_geolocation(self) -> Optional[Tuple[float, float]]:
77
+ data = await self._get(self.LOCATION_API_URL)
78
+ if not isinstance(data, dict):
79
+ return None
80
+ try:
81
+ lat, lon = data.get('loc', '').split(',')
82
+ return float(lat), float(lon)
83
+ except (ValueError, IndexError):
84
+ self._console.print_message("error", "Could not parse location data.")
85
+ return None
86
+
87
+ async def _get(self, url: str, **kwargs) -> Optional[Any]:
88
+ if not self._session:
89
+ return None
90
+ try:
91
+ async with self._session.get(url, **kwargs) as response:
92
+ response.raise_for_status()
93
+ return await response.json()
94
+ except (aiohttp.ClientError, json.JSONDecodeError) as e:
95
+ self._console.print_message("error", f"API request failed for {url}: {e}")
96
+ return None
97
+
98
+ class ConfigurationOrchestrator:
99
+ CONCURRENT_LIMIT = 200
100
+
101
+ def __init__(self, private_key: str, preferences: UserPreferences, console_manager: ConsoleManager, api_client: NordVpnApiClient):
102
+ self._private_key = private_key
103
+ self._preferences = preferences
104
+ self._console = console_manager
105
+ self._api_client = api_client
106
+ self._output_dir = Path(f'nordvpn_configs_{datetime.now().strftime("%Y%m%d_%H%M%S")}')
107
+ self._semaphore = asyncio.Semaphore(self.CONCURRENT_LIMIT)
108
+ self.stats = GenerationStats()
109
+
110
+ async def generate(self) -> Optional[Path]:
111
+ user_location, all_servers_data = await self._fetch_remote_data()
112
+ if not user_location or not all_servers_data:
113
+ return None
114
+
115
+ processed_servers = await self._process_server_data(all_servers_data, user_location)
116
+ sorted_servers = sorted(processed_servers, key=lambda s: (s.load, s.distance))
117
+ best_servers_by_location = self._get_best_servers(sorted_servers)
118
+
119
+ self._output_dir.mkdir(exist_ok=True)
120
+ servers_info = self._build_servers_info(sorted_servers)
121
+
122
+ await self._save_all_configurations(sorted_servers, best_servers_by_location, servers_info)
123
+ return self._output_dir
124
+
125
+ async def _fetch_remote_data(self) -> Tuple[Optional[Tuple[float, float]], List[Dict[str, Any]]]:
126
+ with self._console.create_progress_bar() as progress:
127
+ task = progress.add_task("Fetching remote data...", total=2)
128
+ user_location, all_servers_data = await asyncio.gather(
129
+ self._api_client.get_user_geolocation(),
130
+ self._api_client.get_all_servers()
131
+ )
132
+ progress.update(task, advance=2)
133
+ return user_location, all_servers_data
134
+
135
+ async def _process_server_data(self, all_servers_data: List[Dict[str, Any]], user_location: Tuple[float, float]) -> List[Server]:
136
+ loop = asyncio.get_running_loop()
137
+ parse_func = partial(self._parse_server_data, user_location=user_location)
138
+ with ThreadPoolExecutor(max_workers=min(32, (os.cpu_count() or 1) + 4)) as executor:
139
+ tasks = [loop.run_in_executor(executor, parse_func, s) for s in all_servers_data]
140
+ processed_servers = await asyncio.gather(*tasks)
141
+ return [server for server in processed_servers if server]
142
+
143
+ def _get_best_servers(self, sorted_servers: List[Server]) -> Dict[Tuple[str, str], Server]:
144
+ best = {}
145
+ for server in sorted_servers:
146
+ key = (server.country, server.city)
147
+ if key not in best or server.load < best[key].load:
148
+ best[key] = server
149
+ return best
150
+
151
+ def _build_servers_info(self, sorted_servers: List[Server]) -> Dict:
152
+ info = {}
153
+ for server in sorted_servers:
154
+ country_info = info.setdefault(server.country, {})
155
+ city_info = country_info.setdefault(server.city, {"distance": int(server.distance), "servers": []})
156
+ city_info["servers"].append((server.name, server.load))
157
+ return info
158
+
159
+ async def _save_all_configurations(self, sorted_servers: List[Server], best_servers: Dict, servers_info: Dict):
160
+ with self._console.create_progress_bar(transient=False) as progress:
161
+ self.stats.total_configs = len(sorted_servers)
162
+ self.stats.best_configs = len(best_servers)
163
+
164
+ task_all = progress.add_task("Generating standard configs...", total=self.stats.total_configs)
165
+ task_best = progress.add_task("Generating optimized configs...", total=self.stats.best_configs)
166
+
167
+ save_tasks = [self._create_save_task(s, 'configs', progress, task_all) for s in sorted_servers]
168
+ save_tasks.extend([self._create_save_task(s, 'best_configs', progress, task_best) for s in best_servers.values()])
169
+
170
+ await asyncio.gather(*save_tasks)
171
+ async with aiofiles.open(self._output_dir / 'servers.json', 'w') as f:
172
+ await f.write(json.dumps(servers_info, indent=2, separators=(',', ':'), ensure_ascii=False))
173
+
174
+ def _create_save_task(self, server: Server, subfolder: str, progress, task_id):
175
+ config_str = self._generate_wireguard_config_string(server, self._preferences, self._private_key)
176
+ path = self._output_dir / subfolder / self._sanitize_path_part(server.country) / self._sanitize_path_part(server.city)
177
+ filename = f"{self._sanitize_path_part(server.name)}.conf"
178
+ return self._save_config_file(config_str, path, filename, progress, task_id)
179
+
180
+ async def _save_config_file(self, config_string: str, path: Path, filename: str, progress, task_id):
181
+ path.mkdir(parents=True, exist_ok=True)
182
+ async with self._semaphore:
183
+ async with aiofiles.open(path / filename, 'w') as f:
184
+ await f.write(config_string)
185
+ progress.update(task_id, advance=1)
186
+
187
+ @staticmethod
188
+ def _generate_wireguard_config_string(server: Server, preferences: UserPreferences, private_key: str) -> str:
189
+ endpoint = server.station if preferences.use_ip_for_endpoint else server.hostname
190
+ return f"[Interface]\nPrivateKey = {private_key}\nAddress = 10.5.0.2/16\nDNS = {preferences.dns}\n\n[Peer]\nPublicKey = {server.public_key}\nAllowedIPs = 0.0.0.0/0, ::/0\nEndpoint = {endpoint}:51820\nPersistentKeepalive = {preferences.persistent_keepalive}"
191
+
192
+ @staticmethod
193
+ def _parse_server_data(server_data: Dict[str, Any], user_location: Tuple[float, float]) -> Optional[Server]:
194
+ try:
195
+ location = server_data['locations'][0]
196
+ public_key = next(
197
+ m['value'] for t in server_data['technologies']
198
+ if t['identifier'] == 'wireguard_udp'
199
+ for m in t['metadata'] if m['name'] == 'public_key'
200
+ )
201
+ distance = ConfigurationOrchestrator._calculate_distance(
202
+ user_location[0], user_location[1], location['latitude'], location['longitude']
203
+ )
204
+ return Server(
205
+ name=server_data['name'], hostname=server_data['hostname'],
206
+ station=server_data['station'], load=int(server_data.get('load', 0)),
207
+ country=location['country']['name'], city=location['country'].get('city', {}).get('name', 'Unknown'),
208
+ latitude=location['latitude'], longitude=location['longitude'],
209
+ public_key=public_key, distance=distance
210
+ )
211
+ except (KeyError, IndexError, StopIteration):
212
+ return None
213
+
214
+ @staticmethod
215
+ def _calculate_distance(lat1: float, lon1: float, lat2: float, lon2: float) -> float:
216
+ lon1_rad, lat1_rad, lon2_rad, lat2_rad = map(radians, [lon1, lat1, lon2, lat2])
217
+ dlon = lon2_rad - lon1_rad
218
+ dlat = lat2_rad - lat1_rad
219
+ a = sin(dlat / 2)**2 + cos(lat1_rad) * cos(lat2_rad) * sin(dlon / 2)**2
220
+ c = 2 * asin(sqrt(a))
221
+ return c * 6371
222
+
223
+ @staticmethod
224
+ def _sanitize_path_part(part: str) -> str:
225
+ return re.sub(r'[<>:"/\\|?*\0]', '', part.lower().replace(' ', '_')).replace('#', '')
226
+
227
+ class Application:
228
+ def __init__(self):
229
+ self._console = ConsoleManager()
230
+
231
+ async def run(self, args: List[str]):
232
+ async with NordVpnApiClient(self._console) as api_client:
233
+ try:
234
+ if not args:
235
+ await self._run_generate_command(api_client)
236
+ elif args[0] == "get-key" and len(args) == 1:
237
+ await self._run_get_key_command(api_client)
238
+ else:
239
+ command = " ".join(args)
240
+ self._console.print_message("error", f"Unknown command or invalid arguments: '{command}'.")
241
+ self._console.print_message("info", "Usage: nordgen | nordgen get-key")
242
+ except Exception as e:
243
+ self._console.print_message("error", f"An unrecoverable error occurred: {e}")
244
+
245
+ async def _run_get_key_command(self, api_client: NordVpnApiClient):
246
+ self._console.clear()
247
+ self._console.print_title()
248
+ private_key = await self._get_validated_private_key(api_client)
249
+ if private_key:
250
+ self._console.display_key(private_key)
251
+
252
+ async def _run_generate_command(self, api_client: NordVpnApiClient):
253
+ self._console.clear()
254
+ self._console.print_title()
255
+ private_key = await self._get_validated_private_key(api_client)
256
+ if not private_key:
257
+ return
258
+
259
+ preferences = self._collect_user_preferences()
260
+
261
+ self._console.clear()
262
+
263
+ start_time = time.time()
264
+ orchestrator = ConfigurationOrchestrator(private_key, preferences, self._console, api_client)
265
+ output_dir = await orchestrator.generate()
266
+ elapsed_time = time.time() - start_time
267
+
268
+ if output_dir:
269
+ self._console.display_summary(output_dir, orchestrator.stats, elapsed_time)
270
+ else:
271
+ self._console.print_message("error", "Process failed. Check logs for details.")
272
+
273
+ def _collect_user_preferences(self) -> UserPreferences:
274
+ defaults = UserPreferences()
275
+ user_input = self._console.get_preferences(defaults)
276
+
277
+ dns_input = user_input.get("dns")
278
+ dns = dns_input if dns_input and re.match(r'^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$', dns_input) else defaults.dns
279
+
280
+ use_ip = user_input.get("endpoint_type", "").lower() == 'y'
281
+
282
+ keepalive = defaults.persistent_keepalive
283
+ keepalive_input = user_input.get("keepalive")
284
+ if keepalive_input and keepalive_input.isdigit():
285
+ keepalive_val = int(keepalive_input)
286
+ if 15 <= keepalive_val <= 120:
287
+ keepalive = keepalive_val
288
+
289
+ return UserPreferences(dns=dns, use_ip_for_endpoint=use_ip, persistent_keepalive=keepalive)
290
+
291
+ async def _get_validated_private_key(self, api_client: NordVpnApiClient) -> Optional[str]:
292
+ token = self._console.get_user_input("Please enter your NordVPN access token: ", is_secret=True)
293
+ if not re.match(r'^[a-fA-F0-9]{64}$', token):
294
+ self._console.print_message("error", "Invalid token format.")
295
+ return None
296
+
297
+ with self._console.create_progress_bar() as progress:
298
+ task = progress.add_task("Validating token...", total=1)
299
+ private_key = await api_client.get_private_key(token)
300
+ progress.update(task, advance=1)
301
+
302
+ if private_key:
303
+ self._console.print_message("success", "Token validated successfully.")
304
+ return private_key
305
+ else:
306
+ self._console.print_message("error", "Token is invalid or could not be verified.")
307
+ return None
308
+
309
+ def cli_entry_point():
310
+ try:
311
+ app = Application()
312
+ asyncio.run(app.run(sys.argv[1:]))
313
+ except KeyboardInterrupt:
314
+ print("\nProcess interrupted by user.")
315
+
316
+ if __name__ == "__main__":
317
+ cli_entry_point()
@@ -4,8 +4,12 @@ from rich.progress import Progress, SpinnerColumn, BarColumn, TextColumn, TimeEl
4
4
  from rich.theme import Theme
5
5
  from rich.table import Table
6
6
  from pathlib import Path
7
+ from typing import TYPE_CHECKING
7
8
  import os
8
9
 
10
+ if TYPE_CHECKING:
11
+ from .main import UserPreferences, GenerationStats
12
+
9
13
  class ConsoleManager:
10
14
  def __init__(self):
11
15
  custom_theme = Theme({
@@ -27,7 +31,7 @@ class ConsoleManager:
27
31
  def get_user_input(self, prompt: str, is_secret: bool = False) -> str:
28
32
  return self.console.input(f"[info]{prompt}[/info]", password=is_secret).strip()
29
33
 
30
- def get_preferences(self, defaults) -> dict:
34
+ def get_preferences(self, defaults: "UserPreferences") -> dict:
31
35
  self.console.print("\n[info]Configuration Options (press Enter to use defaults)[/info]")
32
36
  dns = self.get_user_input(f"Enter DNS server IP (default: {defaults.dns}): ")
33
37
  endpoint_type = self.get_user_input("Use IP instead of hostname for endpoints? (y/N): ")
@@ -48,13 +52,17 @@ class ConsoleManager:
48
52
  transient=transient
49
53
  )
50
54
 
51
- def print_summary(self, output_dir: Path, total_configs: int, best_configs: int, elapsed_time: float):
55
+ def display_key(self, key: str):
56
+ key_panel = Panel(key, title="NordLynx Private Key", border_style="success", expand=False)
57
+ self.console.print(key_panel)
58
+
59
+ def display_summary(self, output_dir: Path, stats: "GenerationStats", elapsed_time: float):
52
60
  summary_table = Table.grid(padding=(0, 2))
53
61
  summary_table.add_column(style="info")
54
62
  summary_table.add_column()
55
63
  summary_table.add_row("Output Directory:", f"[path]{output_dir}[/path]")
56
- summary_table.add_row("Standard Configs:", f"{total_configs}")
57
- summary_table.add_row("Optimized Configs:", f"{best_configs}")
64
+ summary_table.add_row("Standard Configs:", f"{stats.total_configs}")
65
+ summary_table.add_row("Optimized Configs:", f"{stats.best_configs}")
58
66
  summary_table.add_row("Time Taken:", f"{elapsed_time:.2f} seconds")
59
67
 
60
68
  self.console.print(Panel(
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: nord-config-generator
3
- Version: 1.0.0
3
+ Version: 1.0.1
4
4
  Summary: A command-line tool for generating optimized NordVPN WireGuard configurations.
5
5
  Author-email: Ahmed Touhami <mustafachyi272@gmail.com>
6
6
  Project-URL: Homepage, https://github.com/mustafachyi/NordVPN-WireGuard-Config-Generator
@@ -10,11 +10,11 @@ Classifier: License :: OSI Approved :: GNU General Public License v3 (GPLv3)
10
10
  Classifier: Operating System :: OS Independent
11
11
  Classifier: Topic :: System :: Networking
12
12
  Classifier: Environment :: Console
13
- Requires-Python: >=3.8
13
+ Requires-Python: >=3.9
14
14
  Description-Content-Type: text/markdown
15
- Requires-Dist: aiohttp>=3.8.0
16
- Requires-Dist: aiofiles>=0.8.0
17
- Requires-Dist: rich>=12.0.0
15
+ Requires-Dist: aiohttp<4.0,>=3.12.14
16
+ Requires-Dist: aiofiles<25.0,>=24.1.0
17
+ Requires-Dist: rich<15.0,>=14.0.0
18
18
 
19
19
  # NordVPN WireGuard Configuration Generator
20
20
 
@@ -39,11 +39,11 @@ This consolidated effort ensures a higher standard of quality and a more reliabl
39
39
  * **Performance:** Asynchronous architecture processes the entire NordVPN server list in seconds.
40
40
  * **Optimization:** Intelligently sorts servers by current load and geographic proximity to the user, generating configurations for the most performant connections.
41
41
  * **Structured Output:** Automatically creates a clean directory structure containing standard configurations, a `best_configs` folder for optimal servers per location, and a `servers.json` file with detailed metadata for analysis.
42
- * **Interactive and Non-Interactive:** A guided TUI for interactive use. The core logic is structured to be scriptable.
42
+ * **Interactive and Non-Interactive:** A guided rich-CLI for interactive use. The core logic is structured to be scriptable.
43
43
 
44
44
  ## Installation
45
45
 
46
- Prerequisites: Python 3.8+
46
+ Prerequisites: Python 3.9+
47
47
 
48
48
  Install the package using `pip`:
49
49
 
@@ -53,14 +53,24 @@ pip install nord-config-generator
53
53
 
54
54
  ## Usage
55
55
 
56
- Execute the installed application:
56
+ ### Generate Configurations (Default Action)
57
+
58
+ Execute the application without any arguments. This is the primary function.
57
59
 
58
60
  ```bash
59
- nord-generator
61
+ nordgen
60
62
  ```
61
63
 
62
64
  The application will prompt for the required access token and configuration preferences.
63
65
 
66
+ ### Retrieve Private Key
67
+
68
+ To retrieve and display your NordLynx private key without generating configurations, use the `get-key` command:
69
+
70
+ ```bash
71
+ nordgen get-key
72
+ ```
73
+
64
74
  ## Web Version
65
75
 
66
76
  A graphical alternative is available for direct use in a web browser.
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ nordgen = nord_config_generator.main:cli_entry_point
@@ -0,0 +1,3 @@
1
+ aiohttp<4.0,>=3.12.14
2
+ aiofiles<25.0,>=24.1.0
3
+ rich<15.0,>=14.0.0
@@ -1,282 +0,0 @@
1
- import sys
2
- import os
3
- import asyncio
4
- import json
5
- import base64
6
- import re
7
- import time
8
- from typing import List, Tuple, Optional, Dict, Any
9
- from dataclasses import dataclass
10
- from pathlib import Path
11
- from math import radians, sin, cos, asin, sqrt
12
- from functools import partial
13
- from concurrent.futures import ThreadPoolExecutor
14
- from datetime import datetime
15
-
16
- import aiohttp
17
- import aiofiles
18
-
19
- from .ui import ConsoleManager
20
-
21
- NORD_API_BASE_URL = "https://api.nordvpn.com/v1"
22
- LOCATION_API_URL = "https://ipinfo.io/json"
23
- CONCURRENT_LIMIT = 200
24
-
25
- @dataclass
26
- class Server:
27
- name: str
28
- hostname: str
29
- station: str
30
- load: int
31
- country: str
32
- city: str
33
- latitude: float
34
- longitude: float
35
- public_key: str
36
- distance: float = 0.0
37
-
38
- @dataclass
39
- class UserPreferences:
40
- dns: str = "103.86.96.100"
41
- use_ip_for_endpoint: bool = False
42
- persistent_keepalive: int = 25
43
-
44
- def update_from_input(self, user_input: dict):
45
- dns_input = user_input.get("dns")
46
- if dns_input and re.match(r'^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$', dns_input):
47
- self.dns = dns_input
48
-
49
- self.use_ip_for_endpoint = user_input.get("endpoint_type", "").lower() == 'y'
50
-
51
- keepalive_input = user_input.get("keepalive")
52
- if keepalive_input and keepalive_input.isdigit() and 15 <= int(keepalive_input) <= 120:
53
- self.persistent_keepalive = int(keepalive_input)
54
-
55
- class NordVpnApiClient:
56
- def __init__(self, console_manager: ConsoleManager):
57
- self._session = aiohttp.ClientSession()
58
- self._console = console_manager
59
-
60
- async def _get(self, url: str, **kwargs) -> Optional[Any]:
61
- try:
62
- async with self._session.get(url, **kwargs) as response:
63
- response.raise_for_status()
64
- return await response.json()
65
- except (aiohttp.ClientError, json.JSONDecodeError) as e:
66
- self._console.print_message("error", f"API request failed for {url}: {e}")
67
- return None
68
-
69
- async def get_private_key(self, token: str) -> Optional[str]:
70
- auth_header = base64.b64encode(f'token:{token}'.encode()).decode()
71
- url = f"{NORD_API_BASE_URL}/users/services/credentials"
72
- data = await self._get(url, headers={'Authorization': f'Basic {auth_header}'})
73
- if isinstance(data, dict):
74
- return data.get('nordlynx_private_key')
75
- return None
76
-
77
- async def get_all_servers(self) -> List[Dict[str, Any]]:
78
- url = f"{NORD_API_BASE_URL}/servers"
79
- params = {'limit': 9000, 'filters[servers_technologies][identifier]': 'wireguard_udp'}
80
- data = await self._get(url, params=params)
81
- if isinstance(data, list):
82
- return data
83
- return []
84
-
85
- async def get_user_geolocation(self) -> Optional[Tuple[float, float]]:
86
- data = await self._get(LOCATION_API_URL)
87
- if not isinstance(data, dict):
88
- return None
89
- try:
90
- lat, lon = data.get('loc', '').split(',')
91
- return float(lat), float(lon)
92
- except (ValueError, IndexError):
93
- self._console.print_message("error", "Could not parse location data.")
94
- return None
95
-
96
- async def close(self):
97
- if self._session and not self._session.closed:
98
- await self._session.close()
99
-
100
- class ConfigurationOrchestrator:
101
- def __init__(self, private_key: str, preferences: UserPreferences, console_manager: ConsoleManager, api_client: NordVpnApiClient):
102
- self._api_client = api_client
103
- self._private_key = private_key
104
- self._preferences = preferences
105
- self._console = console_manager
106
- self._output_dir = Path(f'nordvpn_configs_{datetime.now().strftime("%Y%m%d_%H%M%S")}')
107
- self._semaphore = asyncio.Semaphore(CONCURRENT_LIMIT)
108
- self._thread_pool = ThreadPoolExecutor(max_workers=min(32, (os.cpu_count() or 1) + 4))
109
- self.generation_succeeded = False
110
- self.stats = {"total": 0, "best": 0}
111
-
112
- @staticmethod
113
- def _calculate_distance(lat1: float, lon1: float, lat2: float, lon2: float) -> float:
114
- lon1_rad, lat1_rad, lon2_rad, lat2_rad = map(radians, [lon1, lat1, lon2, lat2])
115
- a = sin((lat2_rad - lat1_rad) / 2)**2 + cos(lat1_rad) * cos(lat2_rad) * sin((lon2_rad - lon1_rad) / 2)**2
116
- return 2 * asin(sqrt(a)) * 6371
117
-
118
- def _parse_server_data(self, server_data: Dict[str, Any], user_location: Tuple[float, float]) -> Optional[Server]:
119
- try:
120
- location = server_data['locations'][0]
121
- public_key = next(
122
- tech_meta['value']
123
- for tech in server_data['technologies'] if tech['identifier'] == 'wireguard_udp'
124
- for tech_meta in tech['metadata'] if tech_meta['name'] == 'public_key'
125
- )
126
- return Server(
127
- name=server_data['name'], hostname=server_data['hostname'], station=server_data['station'],
128
- load=int(server_data.get('load', 0)), country=location['country']['name'],
129
- city=location['country'].get('city', {}).get('name', 'Unknown'), latitude=location['latitude'],
130
- longitude=location['longitude'], public_key=public_key,
131
- distance=self._calculate_distance(user_location[0], user_location[1], location['latitude'], location['longitude'])
132
- )
133
- except (KeyError, IndexError, StopIteration):
134
- return None
135
-
136
- def _generate_wireguard_config_string(self, server: Server) -> str:
137
- endpoint = server.station if self._preferences.use_ip_for_endpoint else server.hostname
138
- return f"[Interface]\nPrivateKey = {self._private_key}\nAddress = 10.5.0.2/16\nDNS = {self._preferences.dns}\n\n[Peer]\nPublicKey = {server.public_key}\nAllowedIPs = 0.0.0.0/0, ::/0\nEndpoint = {endpoint}:51820\nPersistentKeepalive = {self._preferences.persistent_keepalive}"
139
-
140
- @staticmethod
141
- def _sanitize_path_part(part: str) -> str:
142
- return re.sub(r'[<>:"/\\|?*\0]', '', part.lower().replace(' ', '_')).replace('#', '')
143
-
144
- async def _save_config_file(self, config_string: str, path: Path, filename: str, progress, task):
145
- path.mkdir(parents=True, exist_ok=True)
146
- async with self._semaphore:
147
- async with aiofiles.open(path / filename, 'w') as f:
148
- await f.write(config_string)
149
- progress.update(task, advance=1)
150
-
151
- async def generate(self) -> Optional[Path]:
152
- progress = self._console.create_progress_bar()
153
- with progress:
154
- task_data = progress.add_task("Fetching remote data...", total=2)
155
-
156
- progress.update(task_data, description="Fetching user location...")
157
- user_location, all_servers_data = await asyncio.gather(
158
- self._api_client.get_user_geolocation(),
159
- self._api_client.get_all_servers()
160
- )
161
-
162
- if not user_location or not all_servers_data:
163
- return None
164
-
165
- progress.update(task_data, advance=2, description="Processing servers...")
166
-
167
- loop = asyncio.get_running_loop()
168
- parse_func = partial(self._parse_server_data, user_location=user_location)
169
- parse_tasks = [loop.run_in_executor(self._thread_pool, parse_func, s) for s in all_servers_data]
170
-
171
- processed_servers = [server for server in await asyncio.gather(*parse_tasks) if server]
172
- self._thread_pool.shutdown(wait=False, cancel_futures=True)
173
-
174
- sorted_servers = sorted(processed_servers, key=lambda s: (s.load, s.distance))
175
-
176
- self._output_dir.mkdir(exist_ok=True)
177
- servers_info, best_servers_by_location = {}, {}
178
-
179
- config_progress = self._console.create_progress_bar(transient=False)
180
- with config_progress:
181
- total_configs = len(sorted_servers)
182
- best_configs = 0
183
-
184
- save_tasks = []
185
- task_save_all = config_progress.add_task("Generating configs...", total=total_configs)
186
- for server in sorted_servers:
187
- country_sanitized = self._sanitize_path_part(server.country)
188
- city_sanitized = self._sanitize_path_part(server.city)
189
- config_str = self._generate_wireguard_config_string(server)
190
- path = self._output_dir / 'configs' / country_sanitized / city_sanitized
191
- filename = f"{self._sanitize_path_part(server.name)}.conf"
192
- save_tasks.append(self._save_config_file(config_str, path, filename, config_progress, task_save_all))
193
-
194
- location_key = (server.country, server.city)
195
- if location_key not in best_servers_by_location or server.load < best_servers_by_location[location_key].load:
196
- best_servers_by_location[location_key] = server
197
-
198
- country_info = servers_info.setdefault(server.country, {})
199
- city_info = country_info.setdefault(server.city, {"distance": int(server.distance), "servers": []})
200
- city_info["servers"].append((server.name, server.load))
201
-
202
- self.stats["total"] = total_configs
203
- await asyncio.gather(*save_tasks)
204
-
205
- best_save_tasks = []
206
- best_configs = len(best_servers_by_location)
207
- task_save_best = config_progress.add_task("Generating optimized configs...", total=best_configs)
208
- for server in best_servers_by_location.values():
209
- country_sanitized = self._sanitize_path_part(server.country)
210
- city_sanitized = self._sanitize_path_part(server.city)
211
- config_str = self._generate_wireguard_config_string(server)
212
- path = self._output_dir / 'best_configs' / country_sanitized / city_sanitized
213
- filename = f"{self._sanitize_path_part(server.name)}.conf"
214
- best_save_tasks.append(self._save_config_file(config_str, path, filename, config_progress, task_save_best))
215
-
216
- self.stats["best"] = best_configs
217
- await asyncio.gather(*best_save_tasks)
218
-
219
- async with aiofiles.open(self._output_dir / 'servers.json', 'w') as f:
220
- await f.write(json.dumps(servers_info, indent=2, separators=(',', ':'), ensure_ascii=False))
221
-
222
- self.generation_succeeded = True
223
- return self._output_dir
224
-
225
- def is_valid_token_format(token: str) -> bool:
226
- return bool(re.match(r'^[a-fA-F0-9]{64}$', token))
227
-
228
- async def main_async():
229
- console = ConsoleManager()
230
- api_client = NordVpnApiClient(console)
231
-
232
- try:
233
- console.clear()
234
- console.print_title()
235
-
236
- token = console.get_user_input("Please enter your NordVPN access token: ", is_secret=True)
237
- if not is_valid_token_format(token):
238
- console.print_message("error", "Invalid token format.")
239
- return
240
-
241
- private_key = None
242
- with console.create_progress_bar() as progress:
243
- task = progress.add_task("Validating token...", total=1)
244
- private_key = await api_client.get_private_key(token)
245
- progress.update(task, advance=1)
246
-
247
- if not private_key:
248
- console.print_message("error", "Token is invalid or could not be verified. Please check the token and try again.")
249
- return
250
-
251
- console.print_message("success", "Token validated successfully.")
252
-
253
- preferences = UserPreferences()
254
- user_input = console.get_preferences(preferences)
255
- preferences.update_from_input(user_input)
256
-
257
- console.clear()
258
-
259
- start_time = time.time()
260
- orchestrator = ConfigurationOrchestrator(private_key, preferences, console, api_client)
261
-
262
- output_directory = await orchestrator.generate()
263
- elapsed_time = time.time() - start_time
264
-
265
- if orchestrator.generation_succeeded and output_directory:
266
- console.print_summary(output_directory, orchestrator.stats["total"], orchestrator.stats["best"], elapsed_time)
267
- else:
268
- console.print_message("error", "Process failed. Check the logs for details.")
269
-
270
- except Exception as e:
271
- console.print_message("error", f"An unrecoverable error occurred: {e}")
272
- finally:
273
- await api_client.close()
274
-
275
- def cli_entry_point():
276
- try:
277
- asyncio.run(main_async())
278
- except KeyboardInterrupt:
279
- print("\nProcess interrupted by user.")
280
-
281
- if __name__ == "__main__":
282
- cli_entry_point()
@@ -1,2 +0,0 @@
1
- [console_scripts]
2
- nord-generator = nord_config_generator.main:cli_entry_point
@@ -1,3 +0,0 @@
1
- aiohttp>=3.8.0
2
- aiofiles>=0.8.0
3
- rich>=12.0.0