itcpr 2.0.7__tar.gz → 2.0.9__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.
- itcpr-2.0.9/LICENSE +0 -0
- {itcpr-2.0.7/itcpr.egg-info → itcpr-2.0.9}/PKG-INFO +31 -5
- {itcpr-2.0.7 → itcpr-2.0.9}/README.md +30 -4
- {itcpr-2.0.7 → itcpr-2.0.9}/itcpr/__init__.py +1 -1
- itcpr-2.0.9/itcpr/api.py +115 -0
- itcpr-2.0.9/itcpr/auth.py +289 -0
- {itcpr-2.0.7 → itcpr-2.0.9}/itcpr/cli.py +13 -6
- {itcpr-2.0.7 → itcpr-2.0.9}/itcpr/config.py +6 -1
- {itcpr-2.0.7 → itcpr-2.0.9}/itcpr/gitops.py +65 -19
- {itcpr-2.0.7 → itcpr-2.0.9}/itcpr/sync.py +12 -6
- {itcpr-2.0.7 → itcpr-2.0.9}/itcpr/utils.py +2 -2
- {itcpr-2.0.7 → itcpr-2.0.9/itcpr.egg-info}/PKG-INFO +31 -5
- {itcpr-2.0.7 → itcpr-2.0.9}/pyproject.toml +1 -1
- {itcpr-2.0.7 → itcpr-2.0.9}/setup.py +1 -1
- itcpr-2.0.7/LICENSE +0 -22
- itcpr-2.0.7/itcpr/api.py +0 -73
- itcpr-2.0.7/itcpr/auth.py +0 -167
- {itcpr-2.0.7 → itcpr-2.0.9}/MANIFEST.in +0 -0
- {itcpr-2.0.7 → itcpr-2.0.9}/itcpr/storage.py +0 -0
- {itcpr-2.0.7 → itcpr-2.0.9}/itcpr.egg-info/SOURCES.txt +0 -0
- {itcpr-2.0.7 → itcpr-2.0.9}/itcpr.egg-info/dependency_links.txt +0 -0
- {itcpr-2.0.7 → itcpr-2.0.9}/itcpr.egg-info/entry_points.txt +0 -0
- {itcpr-2.0.7 → itcpr-2.0.9}/itcpr.egg-info/requires.txt +0 -0
- {itcpr-2.0.7 → itcpr-2.0.9}/itcpr.egg-info/top_level.txt +0 -0
- {itcpr-2.0.7 → itcpr-2.0.9}/setup.cfg +0 -0
itcpr-2.0.9/LICENSE
ADDED
|
File without changes
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: itcpr
|
|
3
|
-
Version: 2.0.
|
|
3
|
+
Version: 2.0.9
|
|
4
4
|
Summary: CLI tool for syncing GitHub repositories from ITCPR Cloud
|
|
5
5
|
Home-page: https://itcpr.org
|
|
6
6
|
Author: ITCPR
|
|
@@ -38,7 +38,7 @@ A production-ready CLI tool for syncing GitHub repositories from ITCPR Cloud to
|
|
|
38
38
|
|
|
39
39
|
## Features
|
|
40
40
|
|
|
41
|
-
- 🔐 Device-based authentication with
|
|
41
|
+
- 🔐 Device-based authentication with ITCPR Cloud
|
|
42
42
|
- 📦 Automatic repository synchronization
|
|
43
43
|
- 🔄 Manual or continuous sync modes
|
|
44
44
|
- 💾 Local SQLite database for metadata tracking
|
|
@@ -107,7 +107,7 @@ rm -rf ~/.itcpr
|
|
|
107
107
|
|
|
108
108
|
- Python 3.10+
|
|
109
109
|
- Git (system installation)
|
|
110
|
-
- Access to cloud.itcpr.org
|
|
110
|
+
- Access to api.itcpr.org (API) and cloud.itcpr.org (frontend)
|
|
111
111
|
|
|
112
112
|
## Quick Start
|
|
113
113
|
|
|
@@ -187,7 +187,7 @@ itcpr logout
|
|
|
187
187
|
|
|
188
188
|
### `itcpr login`
|
|
189
189
|
|
|
190
|
-
Starts device authentication flow. Opens browser to `cloud.itcpr.org/device` and polls for approval.
|
|
190
|
+
Starts device authentication flow. Opens browser to `cloud.itcpr.org/device` and polls the API at `api.itcpr.org` for approval.
|
|
191
191
|
|
|
192
192
|
### `itcpr logout`
|
|
193
193
|
|
|
@@ -304,11 +304,37 @@ pip install itcpr[yaml]
|
|
|
304
304
|
pip install PyYAML
|
|
305
305
|
```
|
|
306
306
|
|
|
307
|
+
## Development / Mock Mode
|
|
308
|
+
|
|
309
|
+
When the API at `api.itcpr.org` is unavailable, the CLI automatically falls back to mock API responses for testing and development.
|
|
310
|
+
|
|
311
|
+
**Automatic Mock Mode:**
|
|
312
|
+
- If the backend returns 404 or is unreachable, mock responses are used automatically
|
|
313
|
+
- You'll see a warning: "⚠️ Backend unavailable, using mock mode for testing"
|
|
314
|
+
|
|
315
|
+
**Manual Mock Mode:**
|
|
316
|
+
You can also enable mock mode explicitly:
|
|
317
|
+
|
|
318
|
+
```bash
|
|
319
|
+
# Using environment variable
|
|
320
|
+
export ITCPR_MOCK_MODE=true
|
|
321
|
+
itcpr login
|
|
322
|
+
|
|
323
|
+
# Or set in config file (~/.itcpr/config.toml)
|
|
324
|
+
# mock_mode = true
|
|
325
|
+
```
|
|
326
|
+
|
|
327
|
+
**Mock Features:**
|
|
328
|
+
- Auto-approves device login after 2 seconds
|
|
329
|
+
- Provides sample user and repository data
|
|
330
|
+
- Generates mock GitHub tokens
|
|
331
|
+
- All commands work in mock mode for testing
|
|
332
|
+
|
|
307
333
|
## Troubleshooting
|
|
308
334
|
|
|
309
335
|
### "Not logged in" error
|
|
310
336
|
|
|
311
|
-
Run `itcpr login` to authenticate your device.
|
|
337
|
+
Run `itcpr login` to authenticate your device. If the backend is unavailable, mock mode will activate automatically.
|
|
312
338
|
|
|
313
339
|
### "Repository not assigned" error
|
|
314
340
|
|
|
@@ -4,7 +4,7 @@ A production-ready CLI tool for syncing GitHub repositories from ITCPR Cloud to
|
|
|
4
4
|
|
|
5
5
|
## Features
|
|
6
6
|
|
|
7
|
-
- 🔐 Device-based authentication with
|
|
7
|
+
- 🔐 Device-based authentication with ITCPR Cloud
|
|
8
8
|
- 📦 Automatic repository synchronization
|
|
9
9
|
- 🔄 Manual or continuous sync modes
|
|
10
10
|
- 💾 Local SQLite database for metadata tracking
|
|
@@ -73,7 +73,7 @@ rm -rf ~/.itcpr
|
|
|
73
73
|
|
|
74
74
|
- Python 3.10+
|
|
75
75
|
- Git (system installation)
|
|
76
|
-
- Access to cloud.itcpr.org
|
|
76
|
+
- Access to api.itcpr.org (API) and cloud.itcpr.org (frontend)
|
|
77
77
|
|
|
78
78
|
## Quick Start
|
|
79
79
|
|
|
@@ -153,7 +153,7 @@ itcpr logout
|
|
|
153
153
|
|
|
154
154
|
### `itcpr login`
|
|
155
155
|
|
|
156
|
-
Starts device authentication flow. Opens browser to `cloud.itcpr.org/device` and polls for approval.
|
|
156
|
+
Starts device authentication flow. Opens browser to `cloud.itcpr.org/device` and polls the API at `api.itcpr.org` for approval.
|
|
157
157
|
|
|
158
158
|
### `itcpr logout`
|
|
159
159
|
|
|
@@ -270,11 +270,37 @@ pip install itcpr[yaml]
|
|
|
270
270
|
pip install PyYAML
|
|
271
271
|
```
|
|
272
272
|
|
|
273
|
+
## Development / Mock Mode
|
|
274
|
+
|
|
275
|
+
When the API at `api.itcpr.org` is unavailable, the CLI automatically falls back to mock API responses for testing and development.
|
|
276
|
+
|
|
277
|
+
**Automatic Mock Mode:**
|
|
278
|
+
- If the backend returns 404 or is unreachable, mock responses are used automatically
|
|
279
|
+
- You'll see a warning: "⚠️ Backend unavailable, using mock mode for testing"
|
|
280
|
+
|
|
281
|
+
**Manual Mock Mode:**
|
|
282
|
+
You can also enable mock mode explicitly:
|
|
283
|
+
|
|
284
|
+
```bash
|
|
285
|
+
# Using environment variable
|
|
286
|
+
export ITCPR_MOCK_MODE=true
|
|
287
|
+
itcpr login
|
|
288
|
+
|
|
289
|
+
# Or set in config file (~/.itcpr/config.toml)
|
|
290
|
+
# mock_mode = true
|
|
291
|
+
```
|
|
292
|
+
|
|
293
|
+
**Mock Features:**
|
|
294
|
+
- Auto-approves device login after 2 seconds
|
|
295
|
+
- Provides sample user and repository data
|
|
296
|
+
- Generates mock GitHub tokens
|
|
297
|
+
- All commands work in mock mode for testing
|
|
298
|
+
|
|
273
299
|
## Troubleshooting
|
|
274
300
|
|
|
275
301
|
### "Not logged in" error
|
|
276
302
|
|
|
277
|
-
Run `itcpr login` to authenticate your device.
|
|
303
|
+
Run `itcpr login` to authenticate your device. If the backend is unavailable, mock mode will activate automatically.
|
|
278
304
|
|
|
279
305
|
### "Repository not assigned" error
|
|
280
306
|
|
itcpr-2.0.9/itcpr/api.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
"""API client for api.itcpr.org."""
|
|
2
|
+
|
|
3
|
+
import requests
|
|
4
|
+
from typing import List, Dict, Any, Optional
|
|
5
|
+
from .auth import Auth
|
|
6
|
+
from .config import config
|
|
7
|
+
from .utils import get_logger, print_error
|
|
8
|
+
|
|
9
|
+
logger = get_logger(__name__)
|
|
10
|
+
|
|
11
|
+
# Import mock API for fallback
|
|
12
|
+
try:
|
|
13
|
+
from .mock_api import _mock_api
|
|
14
|
+
MOCK_AVAILABLE = True
|
|
15
|
+
except ImportError:
|
|
16
|
+
MOCK_AVAILABLE = False
|
|
17
|
+
_mock_api = None
|
|
18
|
+
|
|
19
|
+
class APIClient:
|
|
20
|
+
"""Client for ITCPR Cloud API."""
|
|
21
|
+
|
|
22
|
+
def __init__(self, auth: Auth):
|
|
23
|
+
self.auth = auth
|
|
24
|
+
self.api_base = auth.api_base
|
|
25
|
+
|
|
26
|
+
def _get_headers(self) -> Dict[str, str]:
|
|
27
|
+
"""Get request headers with authentication."""
|
|
28
|
+
headers = {"Content-Type": "application/json"}
|
|
29
|
+
token = self.auth.get_token()
|
|
30
|
+
if token:
|
|
31
|
+
headers["Authorization"] = f"Bearer {token}"
|
|
32
|
+
return headers
|
|
33
|
+
|
|
34
|
+
def _request(self, method: str, endpoint: str, **kwargs) -> requests.Response:
|
|
35
|
+
"""Make authenticated API request."""
|
|
36
|
+
url = f"{self.api_base}{endpoint}"
|
|
37
|
+
headers = self._get_headers()
|
|
38
|
+
headers.update(kwargs.pop("headers", {}))
|
|
39
|
+
|
|
40
|
+
use_mock = config.mock_mode or (MOCK_AVAILABLE and _mock_api is not None)
|
|
41
|
+
|
|
42
|
+
try:
|
|
43
|
+
response = requests.request(method, url, headers=headers, timeout=5 if use_mock else 30, **kwargs)
|
|
44
|
+
# If we get 404 and mock is available, we'll handle it in the calling methods
|
|
45
|
+
return response
|
|
46
|
+
except requests.RequestException as e:
|
|
47
|
+
if use_mock:
|
|
48
|
+
logger.debug(f"API request failed, will use mock: {e}")
|
|
49
|
+
else:
|
|
50
|
+
logger.error(f"API request failed: {e}")
|
|
51
|
+
raise
|
|
52
|
+
|
|
53
|
+
def get_me(self) -> Dict[str, Any]:
|
|
54
|
+
"""Get current user/device information."""
|
|
55
|
+
use_mock = config.mock_mode or (MOCK_AVAILABLE and _mock_api is not None)
|
|
56
|
+
|
|
57
|
+
try:
|
|
58
|
+
response = self._request("GET", "/api/agent/me")
|
|
59
|
+
response.raise_for_status()
|
|
60
|
+
return response.json()
|
|
61
|
+
except (requests.HTTPError, requests.RequestException) as e:
|
|
62
|
+
if use_mock and (isinstance(e, requests.HTTPError) and e.response.status_code == 404):
|
|
63
|
+
logger.info("Backend unavailable, using mock API")
|
|
64
|
+
return _mock_api.get_me()
|
|
65
|
+
raise
|
|
66
|
+
|
|
67
|
+
def get_repos(self) -> List[Dict[str, Any]]:
|
|
68
|
+
"""Get list of assigned repositories."""
|
|
69
|
+
use_mock = config.mock_mode or (MOCK_AVAILABLE and _mock_api is not None)
|
|
70
|
+
|
|
71
|
+
try:
|
|
72
|
+
response = self._request("GET", "/api/agent/repos")
|
|
73
|
+
response.raise_for_status()
|
|
74
|
+
data = response.json()
|
|
75
|
+
return data.get("repos", [])
|
|
76
|
+
except (requests.HTTPError, requests.RequestException) as e:
|
|
77
|
+
if use_mock and (isinstance(e, requests.HTTPError) and e.response.status_code == 404):
|
|
78
|
+
logger.info("Backend unavailable, using mock API")
|
|
79
|
+
return _mock_api.get_repos()
|
|
80
|
+
raise
|
|
81
|
+
|
|
82
|
+
def get_github_token(self, repo_name: Optional[str] = None) -> str:
|
|
83
|
+
"""Get short-lived GitHub installation token."""
|
|
84
|
+
use_mock = config.mock_mode or (MOCK_AVAILABLE and _mock_api is not None)
|
|
85
|
+
|
|
86
|
+
payload = {}
|
|
87
|
+
if repo_name:
|
|
88
|
+
payload["repo"] = repo_name
|
|
89
|
+
|
|
90
|
+
try:
|
|
91
|
+
response = self._request("POST", "/api/agent/token", json=payload)
|
|
92
|
+
response.raise_for_status()
|
|
93
|
+
data = response.json()
|
|
94
|
+
token = data.get("token")
|
|
95
|
+
if not token:
|
|
96
|
+
raise ValueError("Token not found in response")
|
|
97
|
+
return token
|
|
98
|
+
except (requests.HTTPError, requests.RequestException) as e:
|
|
99
|
+
if use_mock and (isinstance(e, requests.HTTPError) and e.response.status_code == 404):
|
|
100
|
+
logger.info("Backend unavailable, using mock API")
|
|
101
|
+
return _mock_api.get_github_token(repo_name)
|
|
102
|
+
raise
|
|
103
|
+
|
|
104
|
+
def validate_token(self) -> bool:
|
|
105
|
+
"""Validate current device token."""
|
|
106
|
+
try:
|
|
107
|
+
self.get_me()
|
|
108
|
+
return True
|
|
109
|
+
except requests.HTTPError as e:
|
|
110
|
+
if e.response.status_code == 401:
|
|
111
|
+
return False
|
|
112
|
+
raise
|
|
113
|
+
except Exception:
|
|
114
|
+
return False
|
|
115
|
+
|
|
@@ -0,0 +1,289 @@
|
|
|
1
|
+
"""Authentication management for ITCPR Agent."""
|
|
2
|
+
|
|
3
|
+
import keyring
|
|
4
|
+
import time
|
|
5
|
+
import webbrowser
|
|
6
|
+
import requests
|
|
7
|
+
import socket
|
|
8
|
+
import platform
|
|
9
|
+
from typing import Optional, Dict, Any
|
|
10
|
+
from .config import config
|
|
11
|
+
from .utils import get_logger, print_error, print_success, print_info
|
|
12
|
+
|
|
13
|
+
logger = get_logger(__name__)
|
|
14
|
+
|
|
15
|
+
# Import mock API for fallback
|
|
16
|
+
try:
|
|
17
|
+
from .mock_api import _mock_api
|
|
18
|
+
MOCK_AVAILABLE = True
|
|
19
|
+
except ImportError:
|
|
20
|
+
MOCK_AVAILABLE = False
|
|
21
|
+
_mock_api = None
|
|
22
|
+
|
|
23
|
+
# Keyring service name
|
|
24
|
+
KEYRING_SERVICE = "itcpr"
|
|
25
|
+
KEYRING_USERNAME = "device-token"
|
|
26
|
+
|
|
27
|
+
class Auth:
|
|
28
|
+
"""Manages device authentication."""
|
|
29
|
+
|
|
30
|
+
def __init__(self):
|
|
31
|
+
self.api_base = config.api_base
|
|
32
|
+
self.device_id: Optional[str] = None
|
|
33
|
+
self.device_token: Optional[str] = None
|
|
34
|
+
self._load_token()
|
|
35
|
+
|
|
36
|
+
def _load_token(self):
|
|
37
|
+
"""Load device token from keyring."""
|
|
38
|
+
try:
|
|
39
|
+
token = keyring.get_password(KEYRING_SERVICE, KEYRING_USERNAME)
|
|
40
|
+
if token:
|
|
41
|
+
# Token format: device_id:token
|
|
42
|
+
parts = token.split(":", 1)
|
|
43
|
+
if len(parts) == 2:
|
|
44
|
+
self.device_id, self.device_token = parts
|
|
45
|
+
logger.debug(f"Loaded device token for device: {self.device_id}")
|
|
46
|
+
except Exception as e:
|
|
47
|
+
logger.debug(f"Could not load token from keyring: {e}")
|
|
48
|
+
self.device_token = None
|
|
49
|
+
self.device_id = None
|
|
50
|
+
|
|
51
|
+
def is_authenticated(self) -> bool:
|
|
52
|
+
"""Check if user is authenticated (has valid token)."""
|
|
53
|
+
if not self.device_token:
|
|
54
|
+
return False
|
|
55
|
+
|
|
56
|
+
# Optionally verify token is still valid on server
|
|
57
|
+
# This is a lightweight check - we'll do full validation when needed
|
|
58
|
+
return True
|
|
59
|
+
|
|
60
|
+
def verify_token(self) -> bool:
|
|
61
|
+
"""Verify that the stored token is still valid on the server."""
|
|
62
|
+
if not self.device_token:
|
|
63
|
+
return False
|
|
64
|
+
|
|
65
|
+
try:
|
|
66
|
+
from .api import APIClient
|
|
67
|
+
api = APIClient(self)
|
|
68
|
+
return api.validate_token()
|
|
69
|
+
except Exception as e:
|
|
70
|
+
logger.debug(f"Token validation failed: {e}")
|
|
71
|
+
return False
|
|
72
|
+
|
|
73
|
+
def _get_device_name(self) -> str:
|
|
74
|
+
"""Get device name (hostname)"""
|
|
75
|
+
try:
|
|
76
|
+
hostname = socket.gethostname()
|
|
77
|
+
# Try to get a more descriptive name on macOS
|
|
78
|
+
if platform.system() == 'Darwin': # macOS
|
|
79
|
+
try:
|
|
80
|
+
import subprocess
|
|
81
|
+
name = subprocess.check_output(['scutil', '--get', 'ComputerName'], text=True).strip()
|
|
82
|
+
if name:
|
|
83
|
+
return name
|
|
84
|
+
except:
|
|
85
|
+
pass
|
|
86
|
+
return hostname or 'Unknown Device'
|
|
87
|
+
except:
|
|
88
|
+
return 'Unknown Device'
|
|
89
|
+
|
|
90
|
+
def login(self) -> bool:
|
|
91
|
+
"""Start device login flow."""
|
|
92
|
+
print_info("Starting device login flow...")
|
|
93
|
+
|
|
94
|
+
# Try real API first, fall back to mock on 404
|
|
95
|
+
use_mock = False
|
|
96
|
+
try:
|
|
97
|
+
# Step 1: Request device code
|
|
98
|
+
response = requests.post(
|
|
99
|
+
f"{self.api_base}/api/device/start",
|
|
100
|
+
json={},
|
|
101
|
+
timeout=10
|
|
102
|
+
)
|
|
103
|
+
response.raise_for_status()
|
|
104
|
+
data = response.json()
|
|
105
|
+
except requests.HTTPError as e:
|
|
106
|
+
# If 404 and mock is available, use mock
|
|
107
|
+
if e.response.status_code == 404 and MOCK_AVAILABLE and _mock_api is not None:
|
|
108
|
+
logger.info("Backend unavailable (404), using mock API")
|
|
109
|
+
print_info("⚠️ Backend unavailable, using mock mode for testing")
|
|
110
|
+
use_mock = True
|
|
111
|
+
data = _mock_api.device_start()
|
|
112
|
+
else:
|
|
113
|
+
raise
|
|
114
|
+
except requests.RequestException as e:
|
|
115
|
+
# Network error - try mock if available
|
|
116
|
+
if MOCK_AVAILABLE and _mock_api is not None and not config.mock_mode:
|
|
117
|
+
# Only use mock on network errors if explicitly enabled
|
|
118
|
+
raise
|
|
119
|
+
elif MOCK_AVAILABLE and _mock_api is not None:
|
|
120
|
+
logger.info("Network error, using mock API")
|
|
121
|
+
print_info("⚠️ Network error, using mock mode for testing")
|
|
122
|
+
use_mock = True
|
|
123
|
+
data = _mock_api.device_start()
|
|
124
|
+
else:
|
|
125
|
+
raise
|
|
126
|
+
|
|
127
|
+
device_code = data.get("device_code")
|
|
128
|
+
user_code = data.get("user_code")
|
|
129
|
+
verification_uri = data.get("verification_uri")
|
|
130
|
+
# Replace api.itcpr.org with cloud.itcpr.org for frontend URL
|
|
131
|
+
if verification_uri and "api.itcpr.org" in verification_uri:
|
|
132
|
+
verification_uri = verification_uri.replace("api.itcpr.org", "cloud.itcpr.org")
|
|
133
|
+
expires_in = data.get("expires_in", 600)
|
|
134
|
+
interval = data.get("interval", 5)
|
|
135
|
+
|
|
136
|
+
# Format user code for display (e.g., ABCD-1234) to match web page
|
|
137
|
+
# Remove any existing hyphens first, then format
|
|
138
|
+
clean_code = user_code.replace('-', '')
|
|
139
|
+
if len(clean_code) == 8:
|
|
140
|
+
# Format as ABCD-1234 (4 chars, hyphen, 4 chars)
|
|
141
|
+
formatted_code = f"{clean_code[:4]}-{clean_code[4:]}"
|
|
142
|
+
else:
|
|
143
|
+
# If not 8 chars, just use as-is
|
|
144
|
+
formatted_code = user_code
|
|
145
|
+
|
|
146
|
+
print_info(f"\nDevice code: {formatted_code}")
|
|
147
|
+
print_info(f"Please visit: {verification_uri}")
|
|
148
|
+
print_info("\nWaiting for approval...")
|
|
149
|
+
|
|
150
|
+
# Open browser
|
|
151
|
+
try:
|
|
152
|
+
webbrowser.open(verification_uri)
|
|
153
|
+
except Exception as e:
|
|
154
|
+
logger.debug(f"Could not open browser: {e}")
|
|
155
|
+
print_info("Please open the URL manually in your browser.")
|
|
156
|
+
|
|
157
|
+
# Step 2: Poll for approval
|
|
158
|
+
start_time = time.time()
|
|
159
|
+
while time.time() - start_time < expires_in:
|
|
160
|
+
time.sleep(interval)
|
|
161
|
+
|
|
162
|
+
try:
|
|
163
|
+
if use_mock:
|
|
164
|
+
# Use mock API
|
|
165
|
+
token_data = _mock_api.device_poll(device_code)
|
|
166
|
+
if token_data is None:
|
|
167
|
+
print_info(".", end="", flush=True)
|
|
168
|
+
continue
|
|
169
|
+
else:
|
|
170
|
+
# Try real API
|
|
171
|
+
try:
|
|
172
|
+
# Get device name for header
|
|
173
|
+
device_name = self._get_device_name()
|
|
174
|
+
poll_response = requests.get(
|
|
175
|
+
f"{self.api_base}/api/device/poll",
|
|
176
|
+
params={"device_code": device_code},
|
|
177
|
+
headers={"X-Device-Name": device_name},
|
|
178
|
+
timeout=10
|
|
179
|
+
)
|
|
180
|
+
|
|
181
|
+
if poll_response.status_code == 200:
|
|
182
|
+
token_data = poll_response.json()
|
|
183
|
+
elif poll_response.status_code == 202:
|
|
184
|
+
# Still waiting
|
|
185
|
+
print_info(".", end="", flush=True)
|
|
186
|
+
continue
|
|
187
|
+
elif poll_response.status_code == 400:
|
|
188
|
+
error_data = poll_response.json()
|
|
189
|
+
error = error_data.get("error", "Unknown error")
|
|
190
|
+
print_error(f"Authentication failed: {error}")
|
|
191
|
+
return False
|
|
192
|
+
elif poll_response.status_code == 404 and MOCK_AVAILABLE and _mock_api is not None:
|
|
193
|
+
# Backend unavailable, switch to mock
|
|
194
|
+
logger.info("Backend unavailable (404), switching to mock API")
|
|
195
|
+
use_mock = True
|
|
196
|
+
token_data = _mock_api.device_poll(device_code)
|
|
197
|
+
if token_data is None:
|
|
198
|
+
print_info(".", end="", flush=True)
|
|
199
|
+
continue
|
|
200
|
+
else:
|
|
201
|
+
continue
|
|
202
|
+
except requests.HTTPError as e:
|
|
203
|
+
if e.response.status_code == 404 and MOCK_AVAILABLE and _mock_api is not None:
|
|
204
|
+
# Switch to mock
|
|
205
|
+
use_mock = True
|
|
206
|
+
token_data = _mock_api.device_poll(device_code)
|
|
207
|
+
if token_data is None:
|
|
208
|
+
print_info(".", end="", flush=True)
|
|
209
|
+
continue
|
|
210
|
+
else:
|
|
211
|
+
raise
|
|
212
|
+
|
|
213
|
+
device_id = token_data.get("device_id")
|
|
214
|
+
device_token = token_data.get("device_token")
|
|
215
|
+
|
|
216
|
+
if device_id and device_token:
|
|
217
|
+
# Store token
|
|
218
|
+
self.device_id = device_id
|
|
219
|
+
self.device_token = device_token
|
|
220
|
+
self._save_token()
|
|
221
|
+
if use_mock:
|
|
222
|
+
print_success("Device authenticated successfully! (Mock mode)")
|
|
223
|
+
else:
|
|
224
|
+
print_success("Device authenticated successfully!")
|
|
225
|
+
return True
|
|
226
|
+
|
|
227
|
+
except requests.RequestException as e:
|
|
228
|
+
logger.debug(f"Poll request failed: {e}")
|
|
229
|
+
if use_mock:
|
|
230
|
+
# Try mock
|
|
231
|
+
token_data = _mock_api.device_poll(device_code)
|
|
232
|
+
if token_data:
|
|
233
|
+
device_id = token_data.get("device_id")
|
|
234
|
+
device_token = token_data.get("device_token")
|
|
235
|
+
if device_id and device_token:
|
|
236
|
+
self.device_id = device_id
|
|
237
|
+
self.device_token = device_token
|
|
238
|
+
self._save_token()
|
|
239
|
+
print_success("Device authenticated successfully! (Mock mode)")
|
|
240
|
+
return True
|
|
241
|
+
print_info(".", end="", flush=True)
|
|
242
|
+
continue
|
|
243
|
+
|
|
244
|
+
print_error("Authentication timed out. Please try again.")
|
|
245
|
+
return False
|
|
246
|
+
|
|
247
|
+
def _save_token(self):
|
|
248
|
+
"""Save device token to keyring."""
|
|
249
|
+
if self.device_id and self.device_token:
|
|
250
|
+
try:
|
|
251
|
+
token_string = f"{self.device_id}:{self.device_token}"
|
|
252
|
+
keyring.set_password(KEYRING_SERVICE, KEYRING_USERNAME, token_string)
|
|
253
|
+
logger.debug("Token saved to keyring")
|
|
254
|
+
except Exception as e:
|
|
255
|
+
logger.error(f"Failed to save token to keyring: {e}")
|
|
256
|
+
raise
|
|
257
|
+
|
|
258
|
+
def logout(self):
|
|
259
|
+
"""Logout and clear stored token."""
|
|
260
|
+
if self.device_token:
|
|
261
|
+
try:
|
|
262
|
+
# Revoke token on server
|
|
263
|
+
requests.post(
|
|
264
|
+
f"{self.api_base}/api/device/revoke",
|
|
265
|
+
json={"device_id": self.device_id},
|
|
266
|
+
headers={"Authorization": f"Bearer {self.device_token}"},
|
|
267
|
+
timeout=10
|
|
268
|
+
)
|
|
269
|
+
except Exception as e:
|
|
270
|
+
logger.debug(f"Could not revoke token on server: {e}")
|
|
271
|
+
|
|
272
|
+
# Clear local token
|
|
273
|
+
try:
|
|
274
|
+
keyring.delete_password(KEYRING_SERVICE, KEYRING_USERNAME)
|
|
275
|
+
except Exception as e:
|
|
276
|
+
logger.debug(f"Could not delete token from keyring: {e}")
|
|
277
|
+
|
|
278
|
+
self.device_token = None
|
|
279
|
+
self.device_id = None
|
|
280
|
+
print_success("Logged out successfully")
|
|
281
|
+
|
|
282
|
+
def get_token(self) -> Optional[str]:
|
|
283
|
+
"""Get current device token."""
|
|
284
|
+
return self.device_token
|
|
285
|
+
|
|
286
|
+
def get_device_id(self) -> Optional[str]:
|
|
287
|
+
"""Get current device ID."""
|
|
288
|
+
return self.device_id
|
|
289
|
+
|
|
@@ -17,12 +17,20 @@ def cli(ctx, verbose):
|
|
|
17
17
|
|
|
18
18
|
@cli.command()
|
|
19
19
|
def login():
|
|
20
|
-
"""Authenticate this device with
|
|
20
|
+
"""Authenticate this device with ITCPR Cloud."""
|
|
21
21
|
from .auth import Auth
|
|
22
22
|
auth = Auth()
|
|
23
23
|
if auth.is_authenticated():
|
|
24
|
-
|
|
25
|
-
|
|
24
|
+
# Verify token is still valid
|
|
25
|
+
if auth.verify_token():
|
|
26
|
+
if not click.confirm("You are already logged in. Do you want to login again?"):
|
|
27
|
+
return
|
|
28
|
+
else:
|
|
29
|
+
# Token exists but is invalid (device was revoked)
|
|
30
|
+
click.echo("Your device token is no longer valid (device may have been removed).")
|
|
31
|
+
click.echo("Logging in again...")
|
|
32
|
+
# Clear invalid token
|
|
33
|
+
auth.logout()
|
|
26
34
|
|
|
27
35
|
success = auth.login()
|
|
28
36
|
if not success:
|
|
@@ -190,9 +198,8 @@ def clone(ctx, repo, path):
|
|
|
190
198
|
if path:
|
|
191
199
|
local_path = Path(path)
|
|
192
200
|
else:
|
|
193
|
-
# Default: clone to
|
|
194
|
-
|
|
195
|
-
local_path = default_dir / repo_name
|
|
201
|
+
# Default: clone to current working directory
|
|
202
|
+
local_path = Path.cwd() / repo_name
|
|
196
203
|
|
|
197
204
|
# Check if already cloned
|
|
198
205
|
existing = storage.get_repo(repo_name)
|
|
@@ -19,7 +19,7 @@ CONFIG_FILE = CONFIG_DIR / "config.toml"
|
|
|
19
19
|
DB_FILE = CONFIG_DIR / "repos.db"
|
|
20
20
|
|
|
21
21
|
# Default API endpoint
|
|
22
|
-
DEFAULT_API_BASE = "https://
|
|
22
|
+
DEFAULT_API_BASE = "https://api.itcpr.org"
|
|
23
23
|
|
|
24
24
|
class Config:
|
|
25
25
|
"""Manages application configuration."""
|
|
@@ -29,8 +29,13 @@ class Config:
|
|
|
29
29
|
self.config_file = CONFIG_FILE
|
|
30
30
|
self.db_file = DB_FILE
|
|
31
31
|
self.api_base = os.getenv("ITCPR_API_BASE", DEFAULT_API_BASE)
|
|
32
|
+
# Enable mock mode if explicitly set or if backend is unavailable
|
|
33
|
+
self.mock_mode = os.getenv("ITCPR_MOCK_MODE", "").lower() in ("true", "1", "yes")
|
|
32
34
|
self._config_data: Dict[str, Any] = {}
|
|
33
35
|
self._load_config()
|
|
36
|
+
# Check config file for mock mode
|
|
37
|
+
if not self.mock_mode:
|
|
38
|
+
self.mock_mode = self.get("mock_mode", False)
|
|
34
39
|
|
|
35
40
|
def _load_config(self):
|
|
36
41
|
"""Load configuration from file."""
|
|
@@ -17,15 +17,18 @@ class GitOps:
|
|
|
17
17
|
if not self.git:
|
|
18
18
|
raise RuntimeError("git command not found. Please install git.")
|
|
19
19
|
|
|
20
|
-
def _run_git(self, *args, check: bool = True, capture_output: bool = True) -> subprocess.CompletedProcess:
|
|
20
|
+
def _run_git(self, *args, check: bool = True, capture_output: bool = True, cwd: Optional[Path] = None) -> subprocess.CompletedProcess:
|
|
21
21
|
"""Run git command."""
|
|
22
22
|
cmd = [self.git] + list(args)
|
|
23
|
-
|
|
23
|
+
working_dir = cwd if cwd else self.repo_path
|
|
24
|
+
# Convert Path to string for cwd
|
|
25
|
+
cwd_str = str(working_dir) if working_dir else None
|
|
26
|
+
logger.debug(f"Running: {' '.join(cmd)} in {cwd_str}")
|
|
24
27
|
|
|
25
28
|
try:
|
|
26
29
|
result = subprocess.run(
|
|
27
30
|
cmd,
|
|
28
|
-
cwd=
|
|
31
|
+
cwd=cwd_str,
|
|
29
32
|
check=check,
|
|
30
33
|
capture_output=capture_output,
|
|
31
34
|
text=True,
|
|
@@ -52,17 +55,35 @@ class GitOps:
|
|
|
52
55
|
if token:
|
|
53
56
|
# Insert token into URL
|
|
54
57
|
if remote_url.startswith("https://"):
|
|
55
|
-
#
|
|
58
|
+
# GitHub App installation tokens need x-access-token: prefix
|
|
59
|
+
# https://github.com/owner/repo.git -> https://x-access-token:TOKEN@github.com/owner/repo.git
|
|
56
60
|
url_parts = remote_url.split("://", 1)
|
|
57
|
-
remote_url = f"{url_parts[0]}://{token}@{url_parts[1]}"
|
|
61
|
+
remote_url = f"{url_parts[0]}://x-access-token:{token}@{url_parts[1]}"
|
|
58
62
|
elif remote_url.startswith("git@"):
|
|
59
63
|
# For SSH, we'd need to use GIT_SSH_COMMAND, but we'll use HTTPS with token
|
|
60
|
-
|
|
64
|
+
# Convert SSH URL to HTTPS with token
|
|
65
|
+
# git@github.com:owner/repo.git -> https://x-access-token:TOKEN@github.com/owner/repo.git
|
|
66
|
+
ssh_parts = remote_url.replace("git@", "").replace(":", "/", 1)
|
|
67
|
+
remote_url = f"https://x-access-token:{token}@{ssh_parts}"
|
|
61
68
|
|
|
62
69
|
try:
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
70
|
+
# Ensure parent directory exists
|
|
71
|
+
parent_dir = self.repo_path.parent
|
|
72
|
+
parent_dir.mkdir(parents=True, exist_ok=True)
|
|
73
|
+
|
|
74
|
+
# Git clone needs to be run from the parent directory
|
|
75
|
+
# Clone to the repo name in the parent directory
|
|
76
|
+
repo_name = self.repo_path.name
|
|
77
|
+
|
|
78
|
+
# Run git clone from parent directory
|
|
79
|
+
self._run_git("clone", remote_url, repo_name, check=True, cwd=parent_dir)
|
|
80
|
+
|
|
81
|
+
# Verify the clone was successful
|
|
82
|
+
cloned_path = parent_dir / repo_name
|
|
83
|
+
if not cloned_path.exists():
|
|
84
|
+
raise RuntimeError(f"Clone completed but repository not found at {cloned_path}")
|
|
85
|
+
|
|
86
|
+
logger.info(f"Cloned repository to {cloned_path}")
|
|
66
87
|
return True
|
|
67
88
|
except Exception as e:
|
|
68
89
|
logger.error(f"Clone failed: {e}")
|
|
@@ -90,19 +111,44 @@ class GitOps:
|
|
|
90
111
|
status_result = self._run_git("status", "--porcelain", check=True)
|
|
91
112
|
has_changes = bool(status_result.stdout.strip())
|
|
92
113
|
|
|
93
|
-
#
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
behind = True
|
|
97
|
-
except:
|
|
98
|
-
behind = False
|
|
114
|
+
# Get current branch
|
|
115
|
+
current_branch_result = self._run_git("rev-parse", "--abbrev-ref", "HEAD", check=True)
|
|
116
|
+
current_branch = current_branch_result.stdout.strip()
|
|
99
117
|
|
|
100
|
-
#
|
|
118
|
+
# Get remote tracking branch (e.g., origin/main)
|
|
119
|
+
remote_branch = None
|
|
101
120
|
try:
|
|
102
|
-
self._run_git("rev-
|
|
103
|
-
|
|
121
|
+
remote_result = self._run_git("rev-parse", "--abbrev-ref", f"{current_branch}@{{upstream}}", check=True)
|
|
122
|
+
remote_branch = remote_result.stdout.strip()
|
|
104
123
|
except:
|
|
105
|
-
|
|
124
|
+
# No upstream branch set, try origin/{current_branch}
|
|
125
|
+
remote_branch = f"origin/{current_branch}"
|
|
126
|
+
|
|
127
|
+
# Check if there are remote commits to pull (behind)
|
|
128
|
+
behind = False
|
|
129
|
+
if remote_branch:
|
|
130
|
+
try:
|
|
131
|
+
# Check if remote branch exists
|
|
132
|
+
self._run_git("rev-parse", "--verify", remote_branch, check=True)
|
|
133
|
+
# Count commits in remote that aren't in local
|
|
134
|
+
behind_result = self._run_git("rev-list", "--count", f"HEAD..{remote_branch}", check=True)
|
|
135
|
+
behind_count = int(behind_result.stdout.strip())
|
|
136
|
+
behind = behind_count > 0
|
|
137
|
+
except:
|
|
138
|
+
behind = False
|
|
139
|
+
|
|
140
|
+
# Check if there are local commits to push (ahead)
|
|
141
|
+
ahead = False
|
|
142
|
+
if remote_branch:
|
|
143
|
+
try:
|
|
144
|
+
# Check if remote branch exists
|
|
145
|
+
self._run_git("rev-parse", "--verify", remote_branch, check=True)
|
|
146
|
+
# Count commits in local that aren't in remote
|
|
147
|
+
ahead_result = self._run_git("rev-list", "--count", f"{remote_branch}..HEAD", check=True)
|
|
148
|
+
ahead_count = int(ahead_result.stdout.strip())
|
|
149
|
+
ahead = ahead_count > 0
|
|
150
|
+
except:
|
|
151
|
+
ahead = False
|
|
106
152
|
|
|
107
153
|
return {
|
|
108
154
|
"clean": not has_changes,
|
|
@@ -112,14 +112,16 @@ class SyncManager:
|
|
|
112
112
|
"error": "Uncommitted changes detected and auto_commit is disabled in itcpr.yml"
|
|
113
113
|
}
|
|
114
114
|
|
|
115
|
-
# Fetch latest
|
|
116
|
-
print_info(f" Fetching latest changes...")
|
|
115
|
+
# Fetch latest (silently, to update remote refs)
|
|
117
116
|
git.fetch()
|
|
118
117
|
|
|
119
|
-
# Check
|
|
118
|
+
# Check status after fetch
|
|
120
119
|
status = git.get_status()
|
|
121
|
-
|
|
122
|
-
|
|
120
|
+
is_behind = status.get("behind", False)
|
|
121
|
+
is_ahead = status.get("ahead", False)
|
|
122
|
+
|
|
123
|
+
# Pull if behind
|
|
124
|
+
if is_behind:
|
|
123
125
|
try:
|
|
124
126
|
print_info(f" Pulling changes...")
|
|
125
127
|
git.pull_rebase()
|
|
@@ -133,7 +135,7 @@ class SyncManager:
|
|
|
133
135
|
raise
|
|
134
136
|
|
|
135
137
|
# Push if ahead (check auto_push rule)
|
|
136
|
-
if
|
|
138
|
+
if is_ahead:
|
|
137
139
|
if rules.get('auto_push', True):
|
|
138
140
|
print_info(f" Pushing local commits...")
|
|
139
141
|
try:
|
|
@@ -148,6 +150,10 @@ class SyncManager:
|
|
|
148
150
|
logger.info(f"Push skipped for {repo_name} (auto_push disabled in itcpr.yml)")
|
|
149
151
|
print_info(f" Local commits not pushed (auto_push disabled)")
|
|
150
152
|
|
|
153
|
+
# If no changes, just log silently (no output to user)
|
|
154
|
+
if not is_behind and not is_ahead:
|
|
155
|
+
logger.debug(f"Repository {repo_name} is up to date")
|
|
156
|
+
|
|
151
157
|
# Update sync time
|
|
152
158
|
self.storage.update_sync_time(repo_name)
|
|
153
159
|
self.storage.add_sync_history(repo_name, "success", "Sync completed")
|
|
@@ -25,9 +25,9 @@ def print_success(message: str):
|
|
|
25
25
|
"""Print success message."""
|
|
26
26
|
print(f"✓ {message}")
|
|
27
27
|
|
|
28
|
-
def print_info(message: str):
|
|
28
|
+
def print_info(message: str, end: str = "\n", flush: bool = False):
|
|
29
29
|
"""Print info message."""
|
|
30
|
-
print(message)
|
|
30
|
+
print(message, end=end, flush=flush)
|
|
31
31
|
|
|
32
32
|
def format_duration(seconds: float) -> str:
|
|
33
33
|
"""Format duration in human-readable format."""
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: itcpr
|
|
3
|
-
Version: 2.0.
|
|
3
|
+
Version: 2.0.9
|
|
4
4
|
Summary: CLI tool for syncing GitHub repositories from ITCPR Cloud
|
|
5
5
|
Home-page: https://itcpr.org
|
|
6
6
|
Author: ITCPR
|
|
@@ -38,7 +38,7 @@ A production-ready CLI tool for syncing GitHub repositories from ITCPR Cloud to
|
|
|
38
38
|
|
|
39
39
|
## Features
|
|
40
40
|
|
|
41
|
-
- 🔐 Device-based authentication with
|
|
41
|
+
- 🔐 Device-based authentication with ITCPR Cloud
|
|
42
42
|
- 📦 Automatic repository synchronization
|
|
43
43
|
- 🔄 Manual or continuous sync modes
|
|
44
44
|
- 💾 Local SQLite database for metadata tracking
|
|
@@ -107,7 +107,7 @@ rm -rf ~/.itcpr
|
|
|
107
107
|
|
|
108
108
|
- Python 3.10+
|
|
109
109
|
- Git (system installation)
|
|
110
|
-
- Access to cloud.itcpr.org
|
|
110
|
+
- Access to api.itcpr.org (API) and cloud.itcpr.org (frontend)
|
|
111
111
|
|
|
112
112
|
## Quick Start
|
|
113
113
|
|
|
@@ -187,7 +187,7 @@ itcpr logout
|
|
|
187
187
|
|
|
188
188
|
### `itcpr login`
|
|
189
189
|
|
|
190
|
-
Starts device authentication flow. Opens browser to `cloud.itcpr.org/device` and polls for approval.
|
|
190
|
+
Starts device authentication flow. Opens browser to `cloud.itcpr.org/device` and polls the API at `api.itcpr.org` for approval.
|
|
191
191
|
|
|
192
192
|
### `itcpr logout`
|
|
193
193
|
|
|
@@ -304,11 +304,37 @@ pip install itcpr[yaml]
|
|
|
304
304
|
pip install PyYAML
|
|
305
305
|
```
|
|
306
306
|
|
|
307
|
+
## Development / Mock Mode
|
|
308
|
+
|
|
309
|
+
When the API at `api.itcpr.org` is unavailable, the CLI automatically falls back to mock API responses for testing and development.
|
|
310
|
+
|
|
311
|
+
**Automatic Mock Mode:**
|
|
312
|
+
- If the backend returns 404 or is unreachable, mock responses are used automatically
|
|
313
|
+
- You'll see a warning: "⚠️ Backend unavailable, using mock mode for testing"
|
|
314
|
+
|
|
315
|
+
**Manual Mock Mode:**
|
|
316
|
+
You can also enable mock mode explicitly:
|
|
317
|
+
|
|
318
|
+
```bash
|
|
319
|
+
# Using environment variable
|
|
320
|
+
export ITCPR_MOCK_MODE=true
|
|
321
|
+
itcpr login
|
|
322
|
+
|
|
323
|
+
# Or set in config file (~/.itcpr/config.toml)
|
|
324
|
+
# mock_mode = true
|
|
325
|
+
```
|
|
326
|
+
|
|
327
|
+
**Mock Features:**
|
|
328
|
+
- Auto-approves device login after 2 seconds
|
|
329
|
+
- Provides sample user and repository data
|
|
330
|
+
- Generates mock GitHub tokens
|
|
331
|
+
- All commands work in mock mode for testing
|
|
332
|
+
|
|
307
333
|
## Troubleshooting
|
|
308
334
|
|
|
309
335
|
### "Not logged in" error
|
|
310
336
|
|
|
311
|
-
Run `itcpr login` to authenticate your device.
|
|
337
|
+
Run `itcpr login` to authenticate your device. If the backend is unavailable, mock mode will activate automatically.
|
|
312
338
|
|
|
313
339
|
### "Repository not assigned" error
|
|
314
340
|
|
|
@@ -9,7 +9,7 @@ long_description = readme_file.read_text() if readme_file.exists() else ""
|
|
|
9
9
|
|
|
10
10
|
setup(
|
|
11
11
|
name="itcpr",
|
|
12
|
-
version="2.0.
|
|
12
|
+
version="2.0.9",
|
|
13
13
|
description="CLI tool for syncing GitHub repositories from ITCPR Cloud",
|
|
14
14
|
long_description=long_description,
|
|
15
15
|
long_description_content_type="text/markdown",
|
itcpr-2.0.7/LICENSE
DELETED
|
@@ -1,22 +0,0 @@
|
|
|
1
|
-
MIT License
|
|
2
|
-
|
|
3
|
-
Copyright (c) 2025 ITCPR
|
|
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.
|
|
22
|
-
|
itcpr-2.0.7/itcpr/api.py
DELETED
|
@@ -1,73 +0,0 @@
|
|
|
1
|
-
"""API client for cloud.itcpr.org."""
|
|
2
|
-
|
|
3
|
-
import requests
|
|
4
|
-
from typing import List, Dict, Any, Optional
|
|
5
|
-
from .auth import Auth
|
|
6
|
-
from .utils import get_logger, print_error
|
|
7
|
-
|
|
8
|
-
logger = get_logger(__name__)
|
|
9
|
-
|
|
10
|
-
class APIClient:
|
|
11
|
-
"""Client for ITCPR Cloud API."""
|
|
12
|
-
|
|
13
|
-
def __init__(self, auth: Auth):
|
|
14
|
-
self.auth = auth
|
|
15
|
-
self.api_base = auth.api_base
|
|
16
|
-
|
|
17
|
-
def _get_headers(self) -> Dict[str, str]:
|
|
18
|
-
"""Get request headers with authentication."""
|
|
19
|
-
headers = {"Content-Type": "application/json"}
|
|
20
|
-
token = self.auth.get_token()
|
|
21
|
-
if token:
|
|
22
|
-
headers["Authorization"] = f"Bearer {token}"
|
|
23
|
-
return headers
|
|
24
|
-
|
|
25
|
-
def _request(self, method: str, endpoint: str, **kwargs) -> requests.Response:
|
|
26
|
-
"""Make authenticated API request."""
|
|
27
|
-
url = f"{self.api_base}{endpoint}"
|
|
28
|
-
headers = self._get_headers()
|
|
29
|
-
headers.update(kwargs.pop("headers", {}))
|
|
30
|
-
|
|
31
|
-
try:
|
|
32
|
-
response = requests.request(method, url, headers=headers, timeout=30, **kwargs)
|
|
33
|
-
return response
|
|
34
|
-
except requests.RequestException as e:
|
|
35
|
-
logger.error(f"API request failed: {e}")
|
|
36
|
-
raise
|
|
37
|
-
|
|
38
|
-
def get_me(self) -> Dict[str, Any]:
|
|
39
|
-
"""Get current user/device information."""
|
|
40
|
-
response = self._request("GET", "/api/agent/me")
|
|
41
|
-
response.raise_for_status()
|
|
42
|
-
return response.json()
|
|
43
|
-
|
|
44
|
-
def get_repos(self) -> List[Dict[str, Any]]:
|
|
45
|
-
"""Get list of assigned repositories."""
|
|
46
|
-
response = self._request("GET", "/api/agent/repos")
|
|
47
|
-
response.raise_for_status()
|
|
48
|
-
data = response.json()
|
|
49
|
-
return data.get("repos", [])
|
|
50
|
-
|
|
51
|
-
def get_github_token(self, repo_name: Optional[str] = None) -> str:
|
|
52
|
-
"""Get short-lived GitHub installation token."""
|
|
53
|
-
payload = {}
|
|
54
|
-
if repo_name:
|
|
55
|
-
payload["repo"] = repo_name
|
|
56
|
-
|
|
57
|
-
response = self._request("POST", "/api/agent/token", json=payload)
|
|
58
|
-
response.raise_for_status()
|
|
59
|
-
data = response.json()
|
|
60
|
-
return data.get("token")
|
|
61
|
-
|
|
62
|
-
def validate_token(self) -> bool:
|
|
63
|
-
"""Validate current device token."""
|
|
64
|
-
try:
|
|
65
|
-
self.get_me()
|
|
66
|
-
return True
|
|
67
|
-
except requests.HTTPError as e:
|
|
68
|
-
if e.response.status_code == 401:
|
|
69
|
-
return False
|
|
70
|
-
raise
|
|
71
|
-
except Exception:
|
|
72
|
-
return False
|
|
73
|
-
|
itcpr-2.0.7/itcpr/auth.py
DELETED
|
@@ -1,167 +0,0 @@
|
|
|
1
|
-
"""Authentication management for ITCPR Agent."""
|
|
2
|
-
|
|
3
|
-
import keyring
|
|
4
|
-
import time
|
|
5
|
-
import webbrowser
|
|
6
|
-
import requests
|
|
7
|
-
from typing import Optional, Dict, Any
|
|
8
|
-
from .config import config
|
|
9
|
-
from .utils import get_logger, print_error, print_success, print_info
|
|
10
|
-
|
|
11
|
-
logger = get_logger(__name__)
|
|
12
|
-
|
|
13
|
-
# Keyring service name
|
|
14
|
-
KEYRING_SERVICE = "itcpr"
|
|
15
|
-
KEYRING_USERNAME = "device-token"
|
|
16
|
-
|
|
17
|
-
class Auth:
|
|
18
|
-
"""Manages device authentication."""
|
|
19
|
-
|
|
20
|
-
def __init__(self):
|
|
21
|
-
self.api_base = config.api_base
|
|
22
|
-
self.device_id: Optional[str] = None
|
|
23
|
-
self.device_token: Optional[str] = None
|
|
24
|
-
self._load_token()
|
|
25
|
-
|
|
26
|
-
def _load_token(self):
|
|
27
|
-
"""Load device token from keyring."""
|
|
28
|
-
try:
|
|
29
|
-
token = keyring.get_password(KEYRING_SERVICE, KEYRING_USERNAME)
|
|
30
|
-
if token:
|
|
31
|
-
# Token format: device_id:token
|
|
32
|
-
parts = token.split(":", 1)
|
|
33
|
-
if len(parts) == 2:
|
|
34
|
-
self.device_id, self.device_token = parts
|
|
35
|
-
logger.debug(f"Loaded device token for device: {self.device_id}")
|
|
36
|
-
except Exception as e:
|
|
37
|
-
logger.debug(f"Could not load token from keyring: {e}")
|
|
38
|
-
self.device_token = None
|
|
39
|
-
self.device_id = None
|
|
40
|
-
|
|
41
|
-
def is_authenticated(self) -> bool:
|
|
42
|
-
"""Check if user is authenticated."""
|
|
43
|
-
return self.device_token is not None
|
|
44
|
-
|
|
45
|
-
def login(self) -> bool:
|
|
46
|
-
"""Start device login flow."""
|
|
47
|
-
print_info("Starting device login flow...")
|
|
48
|
-
|
|
49
|
-
try:
|
|
50
|
-
# Step 1: Request device code
|
|
51
|
-
response = requests.post(
|
|
52
|
-
f"{self.api_base}/api/device/start",
|
|
53
|
-
json={},
|
|
54
|
-
timeout=10
|
|
55
|
-
)
|
|
56
|
-
response.raise_for_status()
|
|
57
|
-
data = response.json()
|
|
58
|
-
|
|
59
|
-
device_code = data.get("device_code")
|
|
60
|
-
user_code = data.get("user_code")
|
|
61
|
-
verification_uri = data.get("verification_uri", f"{self.api_base}/device")
|
|
62
|
-
expires_in = data.get("expires_in", 600)
|
|
63
|
-
interval = data.get("interval", 5)
|
|
64
|
-
|
|
65
|
-
print_info(f"\nDevice code: {user_code}")
|
|
66
|
-
print_info(f"Please visit: {verification_uri}")
|
|
67
|
-
print_info("\nWaiting for approval...")
|
|
68
|
-
|
|
69
|
-
# Open browser
|
|
70
|
-
try:
|
|
71
|
-
webbrowser.open(verification_uri)
|
|
72
|
-
except Exception as e:
|
|
73
|
-
logger.debug(f"Could not open browser: {e}")
|
|
74
|
-
print_info("Please open the URL manually in your browser.")
|
|
75
|
-
|
|
76
|
-
# Step 2: Poll for approval
|
|
77
|
-
start_time = time.time()
|
|
78
|
-
while time.time() - start_time < expires_in:
|
|
79
|
-
time.sleep(interval)
|
|
80
|
-
|
|
81
|
-
try:
|
|
82
|
-
poll_response = requests.get(
|
|
83
|
-
f"{self.api_base}/api/device/poll",
|
|
84
|
-
params={"device_code": device_code},
|
|
85
|
-
timeout=10
|
|
86
|
-
)
|
|
87
|
-
|
|
88
|
-
if poll_response.status_code == 200:
|
|
89
|
-
token_data = poll_response.json()
|
|
90
|
-
device_id = token_data.get("device_id")
|
|
91
|
-
device_token = token_data.get("device_token")
|
|
92
|
-
|
|
93
|
-
if device_id and device_token:
|
|
94
|
-
# Store token
|
|
95
|
-
self.device_id = device_id
|
|
96
|
-
self.device_token = device_token
|
|
97
|
-
self._save_token()
|
|
98
|
-
print_success("Device authenticated successfully!")
|
|
99
|
-
return True
|
|
100
|
-
|
|
101
|
-
elif poll_response.status_code == 202:
|
|
102
|
-
# Still waiting
|
|
103
|
-
print_info(".", end="", flush=True)
|
|
104
|
-
continue
|
|
105
|
-
|
|
106
|
-
elif poll_response.status_code == 400:
|
|
107
|
-
error_data = poll_response.json()
|
|
108
|
-
error = error_data.get("error", "Unknown error")
|
|
109
|
-
print_error(f"Authentication failed: {error}")
|
|
110
|
-
return False
|
|
111
|
-
|
|
112
|
-
except requests.RequestException as e:
|
|
113
|
-
logger.debug(f"Poll request failed: {e}")
|
|
114
|
-
print_info(".", end="", flush=True)
|
|
115
|
-
continue
|
|
116
|
-
|
|
117
|
-
print_error("Authentication timed out. Please try again.")
|
|
118
|
-
return False
|
|
119
|
-
|
|
120
|
-
except requests.RequestException as e:
|
|
121
|
-
print_error(f"Failed to start login: {e}")
|
|
122
|
-
logger.exception("Login error")
|
|
123
|
-
return False
|
|
124
|
-
|
|
125
|
-
def _save_token(self):
|
|
126
|
-
"""Save device token to keyring."""
|
|
127
|
-
if self.device_id and self.device_token:
|
|
128
|
-
try:
|
|
129
|
-
token_string = f"{self.device_id}:{self.device_token}"
|
|
130
|
-
keyring.set_password(KEYRING_SERVICE, KEYRING_USERNAME, token_string)
|
|
131
|
-
logger.debug("Token saved to keyring")
|
|
132
|
-
except Exception as e:
|
|
133
|
-
logger.error(f"Failed to save token to keyring: {e}")
|
|
134
|
-
raise
|
|
135
|
-
|
|
136
|
-
def logout(self):
|
|
137
|
-
"""Logout and clear stored token."""
|
|
138
|
-
if self.device_token:
|
|
139
|
-
try:
|
|
140
|
-
# Revoke token on server
|
|
141
|
-
requests.post(
|
|
142
|
-
f"{self.api_base}/api/device/revoke",
|
|
143
|
-
json={"device_id": self.device_id},
|
|
144
|
-
headers={"Authorization": f"Bearer {self.device_token}"},
|
|
145
|
-
timeout=10
|
|
146
|
-
)
|
|
147
|
-
except Exception as e:
|
|
148
|
-
logger.debug(f"Could not revoke token on server: {e}")
|
|
149
|
-
|
|
150
|
-
# Clear local token
|
|
151
|
-
try:
|
|
152
|
-
keyring.delete_password(KEYRING_SERVICE, KEYRING_USERNAME)
|
|
153
|
-
except Exception as e:
|
|
154
|
-
logger.debug(f"Could not delete token from keyring: {e}")
|
|
155
|
-
|
|
156
|
-
self.device_token = None
|
|
157
|
-
self.device_id = None
|
|
158
|
-
print_success("Logged out successfully")
|
|
159
|
-
|
|
160
|
-
def get_token(self) -> Optional[str]:
|
|
161
|
-
"""Get current device token."""
|
|
162
|
-
return self.device_token
|
|
163
|
-
|
|
164
|
-
def get_device_id(self) -> Optional[str]:
|
|
165
|
-
"""Get current device ID."""
|
|
166
|
-
return self.device_id
|
|
167
|
-
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|