ntb-67-client 0.1.0__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.
@@ -0,0 +1,25 @@
1
+ NTB-67 SOURCE-AVAILABLE COMMERCIAL LICENSE
2
+ Copyright (c) 2026 Timur Zolotov (netbiom)
3
+
4
+ 1. PERMITTED USE
5
+ The Licensor hereby grants permission to individuals, educational institutions,
6
+ and non-profit organizations to use, copy, modify, and distribute the source
7
+ code of ntb-67 free of charge solely for personal, educational, or hobby use.
8
+
9
+ 2. COMMERCIAL RESTRICTIONS
10
+ Any use of this software for commercial purposes, including but not limited to:
11
+ - Running the software within the IT infrastructure of corporate entities, startups, or legal domains;
12
+ - Using the software to provide paid services to third parties;
13
+ is strictly PROHIBITED without a valid Paid Subscription (Commercial License).
14
+
15
+ 3. PRICING AND INQUIRIES
16
+ The cost of the Commercial License is determined by the Licensor. Current subscription
17
+ rates, volume discounts, and accepted payment methods (including stablecoins like USDT/USDC)
18
+ are provided upon request.
19
+
20
+ To inquire about purchasing a Commercial License or to request a crypto invoice, please contact:
21
+ - Telegram: https://t.me/netbiom
22
+
23
+ 4. TERMINATION
24
+ Any commercial use of this software without an active paid subscription constitutes
25
+ copyright infringement and automatically terminates all rights granted under this license.
@@ -0,0 +1,46 @@
1
+ Metadata-Version: 2.4
2
+ Name: ntb-67-client
3
+ Version: 0.1.0
4
+ Summary: Asyncio Tunneling Proxy Client — alternative for ngrok/localtunnel
5
+ Author-email: "Timur Zolotov (netbiom)" <helloworldbooo@gmail.com>
6
+ License: NTB-67 Source-Available Commercial License
7
+ Project-URL: Homepage, https://github.com/TZbooo/ntb-67
8
+ Project-URL: Telegram Support, https://t.me/netbiom
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Operating System :: OS Independent
11
+ Requires-Python: >=3.10
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Dynamic: license-file
15
+
16
+ # ntb-67
17
+
18
+ [English](#english) | [Русский](#русский)
19
+
20
+ ---
21
+
22
+ ## English
23
+
24
+ ### 🚧 Under Construction (Work in Progress)
25
+
26
+ This project is currently in the **active development stage**. It is essentially a clean canvas where core mechanics, architecture, and features are being built from scratch.
27
+
28
+ * **No docs yet:** We haven't written detailed instructions, setup guides, or user manuals because everything is shifting and changing daily.
29
+ * **No UX guarantees:** The project is absolutely not ready for end-users or a smooth user experience. Expect bugs, broken endpoints, and incomplete features.
30
+ * **For developers:** If you stumbled upon this repository, feel free to look around the source code, but do so at your own risk.
31
+
32
+ As soon as the foundation becomes stable, a proper, comprehensive `README.md` with installation and usage instructions will be provided. Thanks for understanding!
33
+
34
+ ---
35
+
36
+ ## Русский
37
+
38
+ ### 🚧 В процессе разработки (Work in Progress)
39
+
40
+ Этот проект сейчас находится в стадии **активной чистой разработки**. На данном этапе закладывается архитектура, базовая логика и ключевой функционал.
41
+
42
+ * **Инструкций пока нет:** Мы намеренно не пишем подробные руководства по установке и настройке, так как кодовая база и структура проекта меняются каждый день.
43
+ * **Никаких гарантий стабильности:** Проект абсолютно не готов для конечного пользователя (UX). Всё может ломаться, падать или быть недописанным — это нормальное состояние для текущего этапа.
44
+ * **Для любопытных:** Если вы заглянули в этот репозиторий, вы можете изучить исходный код, но учитывайте, что «из коробки» сейчас ничего стабильно не работает.
45
+
46
+ Как только проект обретет стабильную форму и базовый каркас будет готов, мы обязательно добавим полноценный `README.md` с инструкциями по запуску. Спасибо за понимание!
@@ -0,0 +1,31 @@
1
+ # ntb-67
2
+
3
+ [English](#english) | [Русский](#русский)
4
+
5
+ ---
6
+
7
+ ## English
8
+
9
+ ### 🚧 Under Construction (Work in Progress)
10
+
11
+ This project is currently in the **active development stage**. It is essentially a clean canvas where core mechanics, architecture, and features are being built from scratch.
12
+
13
+ * **No docs yet:** We haven't written detailed instructions, setup guides, or user manuals because everything is shifting and changing daily.
14
+ * **No UX guarantees:** The project is absolutely not ready for end-users or a smooth user experience. Expect bugs, broken endpoints, and incomplete features.
15
+ * **For developers:** If you stumbled upon this repository, feel free to look around the source code, but do so at your own risk.
16
+
17
+ As soon as the foundation becomes stable, a proper, comprehensive `README.md` with installation and usage instructions will be provided. Thanks for understanding!
18
+
19
+ ---
20
+
21
+ ## Русский
22
+
23
+ ### 🚧 В процессе разработки (Work in Progress)
24
+
25
+ Этот проект сейчас находится в стадии **активной чистой разработки**. На данном этапе закладывается архитектура, базовая логика и ключевой функционал.
26
+
27
+ * **Инструкций пока нет:** Мы намеренно не пишем подробные руководства по установке и настройке, так как кодовая база и структура проекта меняются каждый день.
28
+ * **Никаких гарантий стабильности:** Проект абсолютно не готов для конечного пользователя (UX). Всё может ломаться, падать или быть недописанным — это нормальное состояние для текущего этапа.
29
+ * **Для любопытных:** Если вы заглянули в этот репозиторий, вы можете изучить исходный код, но учитывайте, что «из коробки» сейчас ничего стабильно не работает.
30
+
31
+ Как только проект обретет стабильную форму и базовый каркас будет готов, мы обязательно добавим полноценный `README.md` с инструкциями по запуску. Спасибо за понимание!
@@ -0,0 +1,8 @@
1
+ # -*- coding: utf-8 -*-
2
+ # ntb-67 — Asyncio Tunneling Proxy Server
3
+ # Copyright (c) 2026 Timur Zolotov (netbiom). All rights reserved.
4
+ #
5
+ # This source code is licensed under the NTB-67 Source-Available Commercial License.
6
+ # Commercial use requires a valid paid subscription.
7
+ # See the LICENSE file in the root directory for full terms and conditions.
8
+ # For commercial inquiries, contact Telegram: https://t.me/netbiom
@@ -0,0 +1,8 @@
1
+ # -*- coding: utf-8 -*-
2
+ # ntb-67 — Asyncio Tunneling Proxy Server
3
+ # Copyright (c) 2026 Timur Zolotov (netbiom). All rights reserved.
4
+ #
5
+ # This source code is licensed under the NTB-67 Source-Available Commercial License.
6
+ # Commercial use requires a valid paid subscription.
7
+ # See the LICENSE file in the root directory for full terms and conditions.
8
+ # For commercial inquiries, contact Telegram: https://t.me/netbiom
@@ -0,0 +1,179 @@
1
+ # -*- coding: utf-8 -*-
2
+ # ntb-67 — Asyncio Tunneling Proxy Server
3
+ # Copyright (c) 2026 Timur Zolotov (netbiom). All rights reserved.
4
+ #
5
+ # This source code is licensed under the NTB-67 Source-Available Commercial License.
6
+ # Commercial use requires a valid paid subscription.
7
+ # See the LICENSE file in the root directory for full terms and conditions.
8
+ # For commercial inquiries, contact Telegram: https://t.me/netbiom
9
+
10
+ """Клиентское приложение для динамического подключения к серверу маршрутизации.
11
+
12
+ Данный модуль отвечает за авторизацию поддомена на сервере, обработку сигналов
13
+ выделения дата-каналов и проброс входящих пакетов на локальный порт разработчика.
14
+ """
15
+
16
+ import argparse
17
+ import asyncio
18
+ import sys
19
+
20
+ from common.utils import close_writer, pipe
21
+
22
+
23
+ class NTBClient:
24
+ """Клиент туннелирования с поддержкой динамических поддоменов."""
25
+
26
+ def __init__(self, server_host: str, server_port: int, local_port: int) -> None:
27
+ """Инициализирует NTBClient."""
28
+
29
+ self.server_host = server_host
30
+ self.server_port = server_port
31
+ self.local_port = local_port
32
+ self.subdomain = None
33
+
34
+ async def open_connection(self) -> tuple[asyncio.StreamReader, asyncio.StreamWriter]:
35
+ """Хелпер для быстрого открытия TCP-соединения до сервера."""
36
+
37
+ return await asyncio.open_connection(self.server_host, self.server_port)
38
+
39
+ async def start(self) -> None:
40
+ """Запускает бесконечный цикл удержания управляющего соединения."""
41
+
42
+ while True:
43
+ try:
44
+ await self._start_tunnel()
45
+ except Exception as e:
46
+ print(f"❌ Ошибка соединения с сервером: {e}")
47
+ print("⏳ Переподключение через 5 секунд...")
48
+ await asyncio.sleep(5)
49
+
50
+ async def _start_tunnel(self) -> None:
51
+ """Устанавливает управляющий канал и слушает команды от сервера."""
52
+
53
+ reader, writer = await self.open_connection()
54
+
55
+ if self.subdomain:
56
+ # Отправляем запрос на инициализацию с указанием поддомена
57
+ writer.write(f"INIT:{self.subdomain}\n".encode('utf-8'))
58
+ await writer.drain()
59
+ else:
60
+ # Отправляем запрос на инициализацию без указания поддомена
61
+ writer.write(b"INIT\n")
62
+ await writer.drain()
63
+
64
+ # Ждем ответ от сервера с назначенным UUID/хэшем
65
+ response_bytes = await reader.readline()
66
+ if not response_bytes:
67
+ await close_writer(writer)
68
+ return
69
+
70
+ response = response_bytes.decode('utf-8').strip()
71
+ if response.startswith("ASSIGNED:"):
72
+ self.subdomain = response.split(":", 1)[1].strip()
73
+
74
+ print("\n" + "="*50)
75
+ print(f"🎉 Туннель успешно запущен!")
76
+ print(f"🔗 Публичный адрес: https://{self.subdomain}.24tunl.ru")
77
+ print(f"🏠 Локальный порт: http://127.0.0.1:{self.local_port}")
78
+ print("="*50 + "\n")
79
+ else:
80
+ print("❌ Сервер отказал в инициализации туннеля.")
81
+ await close_writer(writer)
82
+ return
83
+
84
+ # Запускаем фоновую задачу для пинга
85
+ heartbeat_task = asyncio.create_task(self.start_heartbeat(writer))
86
+
87
+ try:
88
+ while True:
89
+ line_bytes = await reader.readline()
90
+ if not line_bytes:
91
+ break
92
+
93
+ cmd = line_bytes.decode('utf-8').strip()
94
+ if cmd == "REQUEST_CONN":
95
+ # Ссылаемся на правильное имя метода: spawn_data_connection
96
+ asyncio.create_task(self.spawn_data_connection())
97
+ finally:
98
+ heartbeat_task.cancel()
99
+ await close_writer(writer)
100
+
101
+ async def spawn_data_connection(self) -> None:
102
+ """Создает новый выделенный дата-канал для конкретного HTTP-запроса."""
103
+
104
+ try:
105
+ # Открываем сокет к серверу туннелирования
106
+ server_reader, server_writer = await self.open_connection()
107
+
108
+ # Маркируем сокет, чтобы сервер понял, какому поддомену он принадлежит
109
+ server_writer.write(f"DATA:{self.subdomain}\n".encode('utf-8'))
110
+ await server_writer.drain()
111
+
112
+ # Открываем сокет к нашему локальному сайту/серверу (например, к порту 3000 или 80)
113
+ local_reader, local_writer = await asyncio.open_connection('127.0.0.1', self.local_port)
114
+
115
+ except Exception as e:
116
+ print(f"❌ Не удалось связать дата-каналы: {e}")
117
+ return
118
+
119
+ # Начинаем качать байты в обе стороны
120
+ await asyncio.gather(
121
+ pipe(server_reader, local_writer),
122
+ pipe(local_reader, server_writer)
123
+ )
124
+
125
+ async def start_heartbeat(self, writer: asyncio.StreamWriter) -> None:
126
+ """Каждые 10 секунд шлет PING, защищая сокет от молчаливого дропа файрволами."""
127
+
128
+ try:
129
+ while True:
130
+ await asyncio.sleep(10)
131
+ writer.write(b'PING\n')
132
+ await writer.drain()
133
+ except Exception:
134
+ pass
135
+
136
+
137
+ def main() -> None:
138
+ """Точка входа для консольного запуска утилиты."""
139
+
140
+ parser = argparse.ArgumentParser(
141
+ description="ntb-67 — Скоростной асинхронный туннель для локальных портов."
142
+ )
143
+ # Позиционный аргумент: порт локального веб-сервера
144
+ parser.add_argument(
145
+ "local_port",
146
+ type=int,
147
+ help="Локальный порт, который необходимо пробросить наружу (например, 8000)"
148
+ )
149
+ # Опциональный аргумент для смены хоста сервера туннелей
150
+ parser.add_argument(
151
+ "--host",
152
+ type=str,
153
+ default="24tunl.ru",
154
+ help="Хост удаленного сервера NTB (дефолт: 24tunl.ru)"
155
+ )
156
+ # Опциональный аргумент для порта сервера туннелей
157
+ parser.add_argument(
158
+ "--port",
159
+ type=int,
160
+ default=9000,
161
+ help="Управляющий порт удаленного сервера NTB (дефолт: 9000)"
162
+ )
163
+
164
+ args = parser.parse_args()
165
+
166
+ try:
167
+ client = NTBClient(
168
+ server_host=args.host,
169
+ server_port=args.port,
170
+ local_port=args.local_port
171
+ )
172
+ asyncio.run(client.start())
173
+ except KeyboardInterrupt:
174
+ print("\n👋 Туннель закрыт пользователем. До встречи!")
175
+ sys.exit(0)
176
+
177
+
178
+ if __name__ == "__main__":
179
+ main()
@@ -0,0 +1,8 @@
1
+ # -*- coding: utf-8 -*-
2
+ # ntb-67 — Asyncio Tunneling Proxy Server
3
+ # Copyright (c) 2026 Timur Zolotov (netbiom). All rights reserved.
4
+ #
5
+ # This source code is licensed under the NTB-67 Source-Available Commercial License.
6
+ # Commercial use requires a valid paid subscription.
7
+ # See the LICENSE file in the root directory for full terms and conditions.
8
+ # For commercial inquiries, contact Telegram: https://t.me/netbiom
@@ -0,0 +1,8 @@
1
+ # -*- coding: utf-8 -*-
2
+ # ntb-67 — Asyncio Tunneling Proxy Server
3
+ # Copyright (c) 2026 Timur Zolotov (netbiom). All rights reserved.
4
+ #
5
+ # This source code is licensed under the NTB-67 Source-Available Commercial License.
6
+ # Commercial use requires a valid paid subscription.
7
+ # See the LICENSE file in the root directory for full terms and conditions.
8
+ # For commercial inquiries, contact Telegram: https://t.me/netbiom
@@ -0,0 +1,36 @@
1
+ # -*- coding: utf-8 -*-
2
+ # ntb-67 — Asyncio Tunneling Proxy Server
3
+ # Copyright (c) 2026 Timur Zolotov (netbiom). All rights reserved.
4
+ #
5
+ # This source code is licensed under the NTB-67 Source-Available Commercial License.
6
+ # Commercial use requires a valid paid subscription.
7
+ # See the LICENSE file in the root directory for full terms and conditions.
8
+ # For commercial inquiries, contact Telegram: https://t.me/netbiom
9
+
10
+ import asyncio
11
+
12
+
13
+ async def close_writer(writer: asyncio.StreamWriter) -> None:
14
+ """Безопасно закрывает StreamWriter, игнорируя возможные ошибки."""
15
+
16
+ writer.close()
17
+ try:
18
+ await writer.wait_closed()
19
+ except Exception:
20
+ pass
21
+
22
+
23
+ async def pipe(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
24
+ """Односторонняя перекачка байт reader → writer до EOF или ошибки."""
25
+
26
+ try:
27
+ while True:
28
+ data = await reader.read(4096)
29
+ if not data:
30
+ break
31
+ writer.write(data)
32
+ await writer.drain()
33
+ except Exception:
34
+ pass
35
+ finally:
36
+ await close_writer(writer)
@@ -0,0 +1,46 @@
1
+ Metadata-Version: 2.4
2
+ Name: ntb-67-client
3
+ Version: 0.1.0
4
+ Summary: Asyncio Tunneling Proxy Client — alternative for ngrok/localtunnel
5
+ Author-email: "Timur Zolotov (netbiom)" <helloworldbooo@gmail.com>
6
+ License: NTB-67 Source-Available Commercial License
7
+ Project-URL: Homepage, https://github.com/TZbooo/ntb-67
8
+ Project-URL: Telegram Support, https://t.me/netbiom
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Operating System :: OS Independent
11
+ Requires-Python: >=3.10
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Dynamic: license-file
15
+
16
+ # ntb-67
17
+
18
+ [English](#english) | [Русский](#русский)
19
+
20
+ ---
21
+
22
+ ## English
23
+
24
+ ### 🚧 Under Construction (Work in Progress)
25
+
26
+ This project is currently in the **active development stage**. It is essentially a clean canvas where core mechanics, architecture, and features are being built from scratch.
27
+
28
+ * **No docs yet:** We haven't written detailed instructions, setup guides, or user manuals because everything is shifting and changing daily.
29
+ * **No UX guarantees:** The project is absolutely not ready for end-users or a smooth user experience. Expect bugs, broken endpoints, and incomplete features.
30
+ * **For developers:** If you stumbled upon this repository, feel free to look around the source code, but do so at your own risk.
31
+
32
+ As soon as the foundation becomes stable, a proper, comprehensive `README.md` with installation and usage instructions will be provided. Thanks for understanding!
33
+
34
+ ---
35
+
36
+ ## Русский
37
+
38
+ ### 🚧 В процессе разработки (Work in Progress)
39
+
40
+ Этот проект сейчас находится в стадии **активной чистой разработки**. На данном этапе закладывается архитектура, базовая логика и ключевой функционал.
41
+
42
+ * **Инструкций пока нет:** Мы намеренно не пишем подробные руководства по установке и настройке, так как кодовая база и структура проекта меняются каждый день.
43
+ * **Никаких гарантий стабильности:** Проект абсолютно не готов для конечного пользователя (UX). Всё может ломаться, падать или быть недописанным — это нормальное состояние для текущего этапа.
44
+ * **Для любопытных:** Если вы заглянули в этот репозиторий, вы можете изучить исходный код, но учитывайте, что «из коробки» сейчас ничего стабильно не работает.
45
+
46
+ Как только проект обретет стабильную форму и базовый каркас будет готов, мы обязательно добавим полноценный `README.md` с инструкциями по запуску. Спасибо за понимание!
@@ -0,0 +1,14 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ client/__init__.py
5
+ client/cli.py
6
+ client/tunnel_client.py
7
+ common/__init__.py
8
+ common/protocol.py
9
+ common/utils.py
10
+ ntb_67_client.egg-info/PKG-INFO
11
+ ntb_67_client.egg-info/SOURCES.txt
12
+ ntb_67_client.egg-info/dependency_links.txt
13
+ ntb_67_client.egg-info/entry_points.txt
14
+ ntb_67_client.egg-info/top_level.txt
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ ntb-client = client.tunnel_client:main
@@ -0,0 +1,2 @@
1
+ client
2
+ common
@@ -0,0 +1,29 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "ntb-67-client"
7
+ version = "0.1.0"
8
+ description = "Asyncio Tunneling Proxy Client — alternative for ngrok/localtunnel"
9
+ readme = "README.md"
10
+ authors = [
11
+ { name = "Timur Zolotov (netbiom)", email = "helloworldbooo@gmail.com" }
12
+ ]
13
+ license = { text = "NTB-67 Source-Available Commercial License" }
14
+ classifiers = [
15
+ "Programming Language :: Python :: 3",
16
+ "Operating System :: OS Independent",
17
+ ]
18
+ requires-python = ">=3.10"
19
+ dependencies = [] # Если появятся внешние библиотеки вроде httpx, пишите их сюда
20
+
21
+ [project.urls]
22
+ Homepage = "https://github.com/TZbooo/ntb-67"
23
+ "Telegram Support" = "https://t.me/netbiom"
24
+
25
+ [project.scripts]
26
+ ntb-client = "client.tunnel_client:main"
27
+
28
+ [tool.setuptools]
29
+ packages = ["client", "common"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+