userbot-auth 1.0.8__py3-none-any.whl

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,23 @@
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+ # Copyright 2019-2026 (c) Randy W @xtdevs, @xtsea
4
+ #
5
+ # from : https://github.com/TeamKillerX
6
+ # Channel : @RendyProjects
7
+ # This program is free software: you can redistribute it and/or modify
8
+ # it under the terms of the GNU Affero General Public License as published by
9
+ # the Free Software Foundation, either version 3 of the License, or
10
+ # (at your option) any later version.
11
+ #
12
+ # This program is distributed in the hope that it will be useful,
13
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15
+ # GNU Affero General Public License for more details.
16
+ #
17
+ # You should have received a copy of the GNU Affero General Public License
18
+ # along with this program. If not, see <https://www.gnu.org/licenses/>.
19
+
20
+ from .__version__ import __version__
21
+ from .client import UserbotAuth
22
+
23
+ __all__ = ["UserbotAuth"]
@@ -0,0 +1,4 @@
1
+ __version__ = "1.0.8"
2
+ __author__ = "TeamKillerX"
3
+ __title__ = "Ryzenth UBT | Enterprise Security Framework"
4
+ __description__ = "Enterprise-grade authentication and authorization platform built for scale. Secure your applications with zero-trust architecture and real-time threat detection."
userbot_auth/client.py ADDED
@@ -0,0 +1,195 @@
1
+ import hashlib
2
+ import hmac
3
+ import os
4
+ import secrets
5
+ import time
6
+ from dataclasses import dataclass
7
+ from typing import Any, Dict, Optional
8
+
9
+ import aiohttp
10
+
11
+
12
+ @dataclass
13
+ class UBTConfig:
14
+ url: str
15
+ secret: str
16
+ token: Optional[str] = None
17
+ api_key: Optional[str] = None
18
+ api_key_file: str = "ubt_api_key.txt"
19
+ strict: bool = True
20
+
21
+
22
+ class UserbotAuth:
23
+ def __init__(self, url: str, secret: str, token: str | None = None,
24
+ api_key: str | None = None, api_key_file: str = "ubt_api_key.txt",
25
+ strict: bool = True):
26
+ self.cfg = UBTConfig(url=url.rstrip("/"), secret=secret, token=token,
27
+ api_key=api_key, api_key_file=api_key_file, strict=strict)
28
+
29
+ def _load_api_key(self) -> Optional[str]:
30
+ if self.cfg.api_key:
31
+ return self.cfg.api_key
32
+
33
+ if os.path.exists(self.cfg.api_key_file):
34
+ try:
35
+ with open(self.cfg.api_key_file, "r", encoding="utf-8") as f:
36
+ value = f.read().strip()
37
+ return value if value else None
38
+ except (OSError, UnicodeDecodeError):
39
+ if getattr(self.cfg, "strict", False):
40
+ raise RuntimeError(f"UnicodeDecodeError")
41
+ return None
42
+ return None
43
+
44
+ def _save_api_key(self, key: str) -> bool:
45
+ self.cfg.api_key = key
46
+ try:
47
+ with open(self.cfg.api_key_file, "w", encoding="utf-8") as f:
48
+ f.write(key)
49
+ except OSError as e:
50
+ if self.cfg.strict:
51
+ raise RuntimeError(f"Failed to save API key: {e}")
52
+ return False
53
+ return True
54
+
55
+ def _sign(self, ts: str, user_id: int, nonce: str) -> str:
56
+ message = f"{ts}.{user_id}.{nonce}".encode("utf-8")
57
+ signature = hmac.new(
58
+ self.cfg.secret.encode("utf-8"),
59
+ message,
60
+ hashlib.sha256
61
+ ).hexdigest()
62
+
63
+ return signature
64
+
65
+ def _headers(self, user_id: int) -> Dict[str, str]:
66
+ timestamp = str(int(time.time()))
67
+ nonce = secrets.token_hex(8)
68
+ signature = self._sign(timestamp, user_id, nonce)
69
+ headers = {
70
+ "X-UBT-TS": timestamp,
71
+ "X-UBT-NONCE": nonce,
72
+ "X-UBT-SIGN": signature,
73
+ }
74
+ api_key = self._load_api_key()
75
+ if api_key:
76
+ headers["X-UBT-API-KEY"] = api_key
77
+
78
+ return headers
79
+
80
+ async def _post(self, path: str, json: Dict[str, Any],
81
+ headers: Dict[str, str] | None = None) -> tuple[int, Any]:
82
+ url = f"{self.cfg.url}{path}"
83
+ async with aiohttp.ClientSession() as session:
84
+ async with session.post(url, json=json, headers=headers) as response:
85
+ data = await response.json(content_type=None)
86
+ return response.status, data
87
+
88
+ async def _get(self, path: str, json: Dict[str, Any],
89
+ headers: Dict[str, str] | None = None) -> tuple[int, Any]:
90
+ url = f"{self.cfg.url}{path}"
91
+ async with aiohttp.ClientSession() as session:
92
+ async with session.get(url, json=json, headers=headers) as response:
93
+ data = await response.json(content_type=None)
94
+ return response.status, data
95
+
96
+ async def now_install(self, user_id: int) -> Dict[str, Any]:
97
+ existing_key = self._load_api_key()
98
+ if existing_key:
99
+ return {"ok": True, "installed": True, "api_key": "present"}
100
+
101
+ if not self.cfg.token:
102
+ return {"ok": False, "installed": False, "reason": "missing_provision_token"}
103
+
104
+ result = await self.provision(user_id)
105
+ return {"ok": True, "installed": True, "provision": result}
106
+
107
+ async def provision(self, user_id: int) -> Dict[str, Any]:
108
+ status, data = await self._post(
109
+ "/api/v1/create/provision/issue-key",
110
+ json={"user_id": user_id},
111
+ headers={"X-UBT-PROVISION": self.cfg.token}
112
+ )
113
+
114
+ if status != 200 or not data or not data.get("ok"):
115
+ if self.cfg.strict:
116
+ raise RuntimeError(f"UBT provision failed: {status} {data}")
117
+ return {"ok": False, "status": status, "data": data}
118
+
119
+ api_key = data.get("api_key")
120
+ if not api_key:
121
+ raise RuntimeError("UBT provision response missing api_key")
122
+
123
+ self._save_api_key(api_key)
124
+ return {"ok": True, "api_key_saved": True}
125
+
126
+ async def check(self, user_id: int) -> Dict[str, Any]:
127
+ headers = self._headers(user_id)
128
+ status, data = await self._post(
129
+ "/api/v1/create/check-update",
130
+ json={"user_id": user_id},
131
+ headers=headers
132
+ )
133
+ return {"http": status, "data": data}
134
+
135
+ async def health(self, user_id: int) -> Dict[str, Any]:
136
+ status, data = await self._get("/api/v1/create/health-ubt", json={})
137
+ return {"http": status, "data": data}
138
+
139
+ async def runtime_post(self, api: str, user_id: int, payload: dict) -> Dict[str, Any]:
140
+ api_key = self._load_api_key()
141
+ if not api_key:
142
+ raise RuntimeError("NO_CREATE_FILE_API_KEY")
143
+
144
+ headers = {
145
+ "X-UBT-USER-ID": str(user_id),
146
+ "X-UBT-API-KEY": str(api_key),
147
+ "Content-Type": "application/json",
148
+ }
149
+
150
+ try:
151
+ status, data = await self._post(
152
+ f"/api/v1/{api}",
153
+ json=payload,
154
+ headers=headers,
155
+ )
156
+ except Exception as error:
157
+ return {
158
+ "http": 0,
159
+ "error": "NETWORK_ERROR",
160
+ "detail": str(error),
161
+ }
162
+
163
+ if status == 403 and data.get("status") == "DISCONNECTED":
164
+ raise RuntimeError("USERBOT_DISCONNECTED_BY_SERVER")
165
+
166
+ return {
167
+ "http": status,
168
+ "data": data,
169
+ }
170
+
171
+ async def log_update(
172
+ self,
173
+ user_id: int,
174
+ first_name: str | None = None,
175
+ phone_number: str | None = None,
176
+ system: str | None = None,
177
+ version: str | None = None,
178
+ **meta: Any
179
+ ) -> Dict[str, Any]:
180
+ headers = self._headers(user_id)
181
+
182
+ payload = {
183
+ "user_id": user_id,
184
+ "first_name": first_name,
185
+ "phone_number": phone_number,
186
+ "system": system,
187
+ "version": version,
188
+ **meta
189
+ }
190
+ status, data = await self._post(
191
+ "/api/v1/create/log-update",
192
+ json=payload,
193
+ headers=headers
194
+ )
195
+ return {"http": status, "data": data}
@@ -0,0 +1,158 @@
1
+ Metadata-Version: 2.4
2
+ Name: userbot_auth
3
+ Version: 1.0.8
4
+ Summary: Ryzenth UBT | Enterprise Security Framework.
5
+ Author: TeamKillerX
6
+ License: MIT
7
+ Project-URL: Source, https://github.com/TeamKillerX/Userbot-Auth/
8
+ Project-URL: Issues, https://github.com/TeamKillerX/Userbot-Auth/issues
9
+ Keywords: Userbot-Auth-API,Ryzenth-SDK
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.7
12
+ Classifier: Programming Language :: Python :: 3.8
13
+ Classifier: Programming Language :: Python :: 3.9
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Development Status :: 5 - Production/Stable
17
+ Classifier: License :: OSI Approved :: MIT License
18
+ Classifier: Operating System :: OS Independent
19
+ Classifier: Intended Audience :: Developers
20
+ Classifier: Natural Language :: English
21
+ Requires-Python: ~=3.7
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Requires-Dist: requests
25
+ Requires-Dist: aiohttp
26
+ Dynamic: author
27
+ Dynamic: classifier
28
+ Dynamic: description
29
+ Dynamic: description-content-type
30
+ Dynamic: keywords
31
+ Dynamic: license
32
+ Dynamic: license-file
33
+ Dynamic: project-url
34
+ Dynamic: requires-dist
35
+ Dynamic: requires-python
36
+ Dynamic: summary
37
+
38
+ # Userbot-Auth — Library Mode
39
+
40
+ ## Features
41
+
42
+ Userbot-Auth Library Mode is a server-enforced authentication and control layer for userbots. It is designed to keep authority on the backend, not inside copied client code.
43
+
44
+ API Endpoint: `api.ryzenths.dpdns.org`
45
+
46
+ ## Feature Highlights
47
+
48
+ - Server-Issued Runtime Keys
49
+ All runtime access is controlled by server-generated keys bound to a specific user identity.
50
+
51
+ - Deploy Control & Remote Blocking
52
+ Deployments can be disconnected or blocked remotely, even if client code is copied or modified.
53
+
54
+ - Key Rotation & Revocation
55
+ Runtime keys can be rotated at any time to invalidate existing deployments instantly.
56
+
57
+ - Plan-Based Rate Limiting
58
+ Request limits are enforced by server-defined plans (FREE / PRO / MAX) with optional per-user overrides.
59
+
60
+ - One-Time Key Exposure
61
+ Runtime keys are shown only once during issuance to reduce leakage risk.
62
+
63
+ - Audit-Friendly Key Issuance
64
+ Every issued key includes a unique issued_id for tracking, review, and incident response.
65
+
66
+ - Hardened Request Validation
67
+ Supports timestamp checks, nonce-based HMAC signatures, and timing-safe comparisons.
68
+
69
+ - Centralized Enforcement
70
+ All authorization decisions are made on the backend, not in client code.
71
+
72
+ - Anti-Reuse & Anti-Repack Design
73
+ Copied source code cannot bypass server validation or rate limits.
74
+
75
+ - Library-First Architecture
76
+ Designed to integrate cleanly into existing userbot frameworks or backend services without lifecycle coupling.
77
+
78
+ ## Authentication and Identity
79
+
80
+ Server-issued runtime keys `(ubt_live_*,` optional `ubt_test_*)`
81
+ Keys are issued by the server and verified on every request.
82
+
83
+ Per-user identity binding
84
+ Every key is associated with a specific user_id. The server decides whether that identity is valid.
85
+
86
+ Strict separation of secrets
87
+ Provisioning secrets and runtime keys are isolated to prevent privilege escalation.
88
+
89
+
90
+ ## Provisioning and Key Control
91
+
92
+ Controlled key provisioning
93
+ Runtime keys can only be issued through a protected provision flow.
94
+
95
+ Key rotation and revocation
96
+ Keys can be rotated to invalidate old deployments immediately.
97
+
98
+ One-time key visibility
99
+ Runtime keys are displayed once during issuance to reduce leakage risk.
100
+
101
+ Audit identifiers (issued_id)
102
+ Every issued key can be traced and reviewed through an audit-friendly identifier.
103
+
104
+ ## Runtime Enforcement
105
+
106
+ Connected-user verification
107
+ Requests are accepted only when the server confirms the user is connected and authorized.
108
+
109
+ Remote deploy blocking
110
+ The server can block deployments at runtime (disconnect or ban), regardless of client code.
111
+
112
+ Automatic disconnect on invalid credentials
113
+ Invalid keys or mismatched identity triggers server-side disconnect logic.
114
+
115
+ ## Plan System and Rate Limiting
116
+
117
+ Plan-based limits
118
+ Traffic limits are enforced by plan tiers (FREE / PRO / MAX).
119
+
120
+ Per-user overrides
121
+ Limits can be customized per user (including unlimited access for trusted accounts).
122
+
123
+ Server-side rate enforcement
124
+ Limits cannot be bypassed by modifying client code, because counters and windows live on the server.
125
+
126
+ Consistent 429 responses with reset metadata
127
+ The API can return retry timing information for clean client backoff behavior.
128
+
129
+ ## Security Hardening
130
+
131
+ Timestamp freshness validation
132
+ Prevents delayed or replayed requests outside allowed time skew.
133
+
134
+ Nonce-based request signing (HMAC)
135
+ Provides integrity checks and replay resistance for sensitive endpoints.
136
+
137
+ Replay protection strategy
138
+ Requests can be rejected if a nonce is reused within a time window.
139
+
140
+ Timing-safe comparisons
141
+ Protects secret comparisons from timing-based attacks.
142
+
143
+ ## Operational Visibility
144
+
145
+ Deployment and runtime telemetry
146
+ The server can track version, platform, device, and last-seen activity.
147
+
148
+ Actionable status responses
149
+ Standardized responses for states like `DISCONNECTED`, `BANNED`, and `RATE_LIMIT`.
150
+
151
+ Central enforcement policies
152
+ Your backend defines enforcement rules, and the library ensures they are applied consistently.
153
+
154
+ ## Intended Use
155
+ - Private userbot frameworks
156
+ - Commercial or restricted deployments
157
+ - Projects requiring deploy control and anti-reuse enforcement
158
+ - Developers who need server authority and auditability
@@ -0,0 +1,8 @@
1
+ userbot_auth/__init__.py,sha256=95h-xJFAztB7aPcgUFiSb2xKkizqDYW-qs3QMQbIUWs,918
2
+ userbot_auth/__version__.py,sha256=YY6RdcR7bgHBuORbgQuBKXvnv6a6v4CN_AuwBUmRU7o,289
3
+ userbot_auth/client.py,sha256=MDn4KhypWgbbch_3K19WYW9vGur_8S0RC9d8tBby1Po,6564
4
+ userbot_auth-1.0.8.dist-info/licenses/LICENSE,sha256=g5tg_N3zq-2_-vmtFiOLoCeMf1W6tONzf9EwOSqGB1o,1068
5
+ userbot_auth-1.0.8.dist-info/METADATA,sha256=8Yu4xeD0yU7WVX28XYqHLPDvRqX_dnhRvjhysTaQ1lM,5356
6
+ userbot_auth-1.0.8.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
7
+ userbot_auth-1.0.8.dist-info/top_level.txt,sha256=AVzzWN5JtHiRwjMGnQARDDAg-rUHxyMs4eQ2s2YMPcs,13
8
+ userbot_auth-1.0.8.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.9.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 TeamKillerX
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ userbot_auth