itcpr 2.0.6__tar.gz → 2.0.8__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.8/LICENSE +0 -0
- {itcpr-2.0.6/itcpr.egg-info → itcpr-2.0.8}/PKG-INFO +86 -5
- {itcpr-2.0.6 → itcpr-2.0.8}/README.md +83 -4
- {itcpr-2.0.6 → itcpr-2.0.8}/itcpr/__init__.py +1 -1
- itcpr-2.0.8/itcpr/api.py +115 -0
- itcpr-2.0.8/itcpr/auth.py +296 -0
- {itcpr-2.0.6 → itcpr-2.0.8}/itcpr/cli.py +13 -6
- {itcpr-2.0.6 → itcpr-2.0.8}/itcpr/config.py +6 -1
- {itcpr-2.0.6 → itcpr-2.0.8}/itcpr/gitops.py +65 -19
- {itcpr-2.0.6 → itcpr-2.0.8}/itcpr/sync.py +108 -29
- {itcpr-2.0.6 → itcpr-2.0.8}/itcpr/utils.py +2 -2
- {itcpr-2.0.6 → itcpr-2.0.8/itcpr.egg-info}/PKG-INFO +86 -5
- {itcpr-2.0.6 → itcpr-2.0.8}/itcpr.egg-info/requires.txt +3 -0
- {itcpr-2.0.6 → itcpr-2.0.8}/pyproject.toml +2 -1
- {itcpr-2.0.6 → itcpr-2.0.8}/setup.py +3 -2
- itcpr-2.0.6/LICENSE +0 -22
- itcpr-2.0.6/itcpr/api.py +0 -73
- itcpr-2.0.6/itcpr/auth.py +0 -167
- {itcpr-2.0.6 → itcpr-2.0.8}/MANIFEST.in +0 -0
- {itcpr-2.0.6 → itcpr-2.0.8}/itcpr/storage.py +0 -0
- {itcpr-2.0.6 → itcpr-2.0.8}/itcpr.egg-info/SOURCES.txt +0 -0
- {itcpr-2.0.6 → itcpr-2.0.8}/itcpr.egg-info/dependency_links.txt +0 -0
- {itcpr-2.0.6 → itcpr-2.0.8}/itcpr.egg-info/entry_points.txt +0 -0
- {itcpr-2.0.6 → itcpr-2.0.8}/itcpr.egg-info/top_level.txt +0 -0
- {itcpr-2.0.6 → itcpr-2.0.8}/setup.cfg +0 -0
itcpr-2.0.8/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.8
|
|
4
4
|
Summary: CLI tool for syncing GitHub repositories from ITCPR Cloud
|
|
5
5
|
Home-page: https://itcpr.org
|
|
6
6
|
Author: ITCPR
|
|
@@ -25,6 +25,8 @@ Provides-Extra: dev
|
|
|
25
25
|
Requires-Dist: pytest; extra == "dev"
|
|
26
26
|
Requires-Dist: black; extra == "dev"
|
|
27
27
|
Requires-Dist: flake8; extra == "dev"
|
|
28
|
+
Provides-Extra: yaml
|
|
29
|
+
Requires-Dist: PyYAML>=6.0; extra == "yaml"
|
|
28
30
|
Dynamic: author
|
|
29
31
|
Dynamic: home-page
|
|
30
32
|
Dynamic: license-file
|
|
@@ -36,7 +38,7 @@ A production-ready CLI tool for syncing GitHub repositories from ITCPR Cloud to
|
|
|
36
38
|
|
|
37
39
|
## Features
|
|
38
40
|
|
|
39
|
-
- 🔐 Device-based authentication with
|
|
41
|
+
- 🔐 Device-based authentication with ITCPR Cloud
|
|
40
42
|
- 📦 Automatic repository synchronization
|
|
41
43
|
- 🔄 Manual or continuous sync modes
|
|
42
44
|
- 💾 Local SQLite database for metadata tracking
|
|
@@ -105,7 +107,7 @@ rm -rf ~/.itcpr
|
|
|
105
107
|
|
|
106
108
|
- Python 3.10+
|
|
107
109
|
- Git (system installation)
|
|
108
|
-
- Access to cloud.itcpr.org
|
|
110
|
+
- Access to api.itcpr.org (API) and cloud.itcpr.org (frontend)
|
|
109
111
|
|
|
110
112
|
## Quick Start
|
|
111
113
|
|
|
@@ -185,7 +187,7 @@ itcpr logout
|
|
|
185
187
|
|
|
186
188
|
### `itcpr login`
|
|
187
189
|
|
|
188
|
-
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.
|
|
189
191
|
|
|
190
192
|
### `itcpr logout`
|
|
191
193
|
|
|
@@ -218,6 +220,23 @@ Options:
|
|
|
218
220
|
- `--watch, -w`: Run continuous sync loop
|
|
219
221
|
- `--interval, -i`: Sync interval in seconds (watch mode only, default: 60)
|
|
220
222
|
|
|
223
|
+
**Sync Rules (itcpr.yml):**
|
|
224
|
+
|
|
225
|
+
You can configure per-repository sync behavior by creating an `itcpr.yml` file in the repository root:
|
|
226
|
+
|
|
227
|
+
```yaml
|
|
228
|
+
sync:
|
|
229
|
+
enabled: true # Enable/disable sync for this repo (default: true)
|
|
230
|
+
auto_commit: true # Auto-commit local changes (default: true)
|
|
231
|
+
auto_push: true # Auto-push local commits (default: true)
|
|
232
|
+
branch: main # Optional: specific branch to sync
|
|
233
|
+
ignore: # Optional: patterns to ignore
|
|
234
|
+
- "*.log"
|
|
235
|
+
- "temp/"
|
|
236
|
+
```
|
|
237
|
+
|
|
238
|
+
**Note:** To use `itcpr.yml`, install PyYAML: `pip install itcpr[yaml]` or `pip install PyYAML`
|
|
239
|
+
|
|
221
240
|
## How It Works
|
|
222
241
|
|
|
223
242
|
### Authentication
|
|
@@ -245,15 +264,77 @@ Options:
|
|
|
245
264
|
|
|
246
265
|
## Configuration
|
|
247
266
|
|
|
267
|
+
### Global Configuration
|
|
268
|
+
|
|
248
269
|
Configuration is stored in `~/.itcpr/config.toml`.
|
|
249
270
|
|
|
250
271
|
Repository metadata is stored in `~/.itcpr/repos.db` (SQLite).
|
|
251
272
|
|
|
273
|
+
### Per-Repository Configuration (itcpr.yml)
|
|
274
|
+
|
|
275
|
+
Each repository can have its own `itcpr.yml` file in the repository root to control sync behavior:
|
|
276
|
+
|
|
277
|
+
```yaml
|
|
278
|
+
sync:
|
|
279
|
+
enabled: true # Enable/disable sync for this repo
|
|
280
|
+
auto_commit: true # Automatically commit local changes
|
|
281
|
+
auto_push: true # Automatically push local commits
|
|
282
|
+
branch: main # Optional: sync specific branch
|
|
283
|
+
ignore: [] # Optional: file patterns to ignore
|
|
284
|
+
```
|
|
285
|
+
|
|
286
|
+
**Example: Disable auto-push for a repository**
|
|
287
|
+
|
|
288
|
+
```yaml
|
|
289
|
+
sync:
|
|
290
|
+
auto_push: false
|
|
291
|
+
```
|
|
292
|
+
|
|
293
|
+
**Example: Disable sync entirely for a repository**
|
|
294
|
+
|
|
295
|
+
```yaml
|
|
296
|
+
sync:
|
|
297
|
+
enabled: false
|
|
298
|
+
```
|
|
299
|
+
|
|
300
|
+
**Installation:** To use `itcpr.yml` files, install the optional YAML dependency:
|
|
301
|
+
```bash
|
|
302
|
+
pip install itcpr[yaml]
|
|
303
|
+
# OR
|
|
304
|
+
pip install PyYAML
|
|
305
|
+
```
|
|
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
|
+
|
|
252
333
|
## Troubleshooting
|
|
253
334
|
|
|
254
335
|
### "Not logged in" error
|
|
255
336
|
|
|
256
|
-
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.
|
|
257
338
|
|
|
258
339
|
### "Repository not assigned" error
|
|
259
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
|
|
|
@@ -186,6 +186,23 @@ Options:
|
|
|
186
186
|
- `--watch, -w`: Run continuous sync loop
|
|
187
187
|
- `--interval, -i`: Sync interval in seconds (watch mode only, default: 60)
|
|
188
188
|
|
|
189
|
+
**Sync Rules (itcpr.yml):**
|
|
190
|
+
|
|
191
|
+
You can configure per-repository sync behavior by creating an `itcpr.yml` file in the repository root:
|
|
192
|
+
|
|
193
|
+
```yaml
|
|
194
|
+
sync:
|
|
195
|
+
enabled: true # Enable/disable sync for this repo (default: true)
|
|
196
|
+
auto_commit: true # Auto-commit local changes (default: true)
|
|
197
|
+
auto_push: true # Auto-push local commits (default: true)
|
|
198
|
+
branch: main # Optional: specific branch to sync
|
|
199
|
+
ignore: # Optional: patterns to ignore
|
|
200
|
+
- "*.log"
|
|
201
|
+
- "temp/"
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
**Note:** To use `itcpr.yml`, install PyYAML: `pip install itcpr[yaml]` or `pip install PyYAML`
|
|
205
|
+
|
|
189
206
|
## How It Works
|
|
190
207
|
|
|
191
208
|
### Authentication
|
|
@@ -213,15 +230,77 @@ Options:
|
|
|
213
230
|
|
|
214
231
|
## Configuration
|
|
215
232
|
|
|
233
|
+
### Global Configuration
|
|
234
|
+
|
|
216
235
|
Configuration is stored in `~/.itcpr/config.toml`.
|
|
217
236
|
|
|
218
237
|
Repository metadata is stored in `~/.itcpr/repos.db` (SQLite).
|
|
219
238
|
|
|
239
|
+
### Per-Repository Configuration (itcpr.yml)
|
|
240
|
+
|
|
241
|
+
Each repository can have its own `itcpr.yml` file in the repository root to control sync behavior:
|
|
242
|
+
|
|
243
|
+
```yaml
|
|
244
|
+
sync:
|
|
245
|
+
enabled: true # Enable/disable sync for this repo
|
|
246
|
+
auto_commit: true # Automatically commit local changes
|
|
247
|
+
auto_push: true # Automatically push local commits
|
|
248
|
+
branch: main # Optional: sync specific branch
|
|
249
|
+
ignore: [] # Optional: file patterns to ignore
|
|
250
|
+
```
|
|
251
|
+
|
|
252
|
+
**Example: Disable auto-push for a repository**
|
|
253
|
+
|
|
254
|
+
```yaml
|
|
255
|
+
sync:
|
|
256
|
+
auto_push: false
|
|
257
|
+
```
|
|
258
|
+
|
|
259
|
+
**Example: Disable sync entirely for a repository**
|
|
260
|
+
|
|
261
|
+
```yaml
|
|
262
|
+
sync:
|
|
263
|
+
enabled: false
|
|
264
|
+
```
|
|
265
|
+
|
|
266
|
+
**Installation:** To use `itcpr.yml` files, install the optional YAML dependency:
|
|
267
|
+
```bash
|
|
268
|
+
pip install itcpr[yaml]
|
|
269
|
+
# OR
|
|
270
|
+
pip install PyYAML
|
|
271
|
+
```
|
|
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
|
+
|
|
220
299
|
## Troubleshooting
|
|
221
300
|
|
|
222
301
|
### "Not logged in" error
|
|
223
302
|
|
|
224
|
-
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.
|
|
225
304
|
|
|
226
305
|
### "Repository not assigned" error
|
|
227
306
|
|
itcpr-2.0.8/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,296 @@
|
|
|
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
|
+
# Frontend device page is at localhost (not cloud.itcpr.org or api.itcpr.org)
|
|
130
|
+
verification_uri = data.get("verification_uri", "http://localhost:5173/device")
|
|
131
|
+
# Always replace cloud.itcpr.org or api.itcpr.org with localhost for device page
|
|
132
|
+
if verification_uri:
|
|
133
|
+
if "cloud.itcpr.org" in verification_uri:
|
|
134
|
+
verification_uri = verification_uri.replace("cloud.itcpr.org", "localhost:5173")
|
|
135
|
+
if "api.itcpr.org" in verification_uri:
|
|
136
|
+
verification_uri = verification_uri.replace("api.itcpr.org", "localhost:5173")
|
|
137
|
+
# Ensure http (not https) for localhost
|
|
138
|
+
if verification_uri.startswith("https://"):
|
|
139
|
+
verification_uri = verification_uri.replace("https://", "http://")
|
|
140
|
+
expires_in = data.get("expires_in", 600)
|
|
141
|
+
interval = data.get("interval", 5)
|
|
142
|
+
|
|
143
|
+
# Format user code for display (e.g., ABCD-1234) to match web page
|
|
144
|
+
# Remove any existing hyphens first, then format
|
|
145
|
+
clean_code = user_code.replace('-', '')
|
|
146
|
+
if len(clean_code) == 8:
|
|
147
|
+
# Format as ABCD-1234 (4 chars, hyphen, 4 chars)
|
|
148
|
+
formatted_code = f"{clean_code[:4]}-{clean_code[4:]}"
|
|
149
|
+
else:
|
|
150
|
+
# If not 8 chars, just use as-is
|
|
151
|
+
formatted_code = user_code
|
|
152
|
+
|
|
153
|
+
print_info(f"\nDevice code: {formatted_code}")
|
|
154
|
+
print_info(f"Please visit: {verification_uri}")
|
|
155
|
+
print_info("\nWaiting for approval...")
|
|
156
|
+
|
|
157
|
+
# Open browser
|
|
158
|
+
try:
|
|
159
|
+
webbrowser.open(verification_uri)
|
|
160
|
+
except Exception as e:
|
|
161
|
+
logger.debug(f"Could not open browser: {e}")
|
|
162
|
+
print_info("Please open the URL manually in your browser.")
|
|
163
|
+
|
|
164
|
+
# Step 2: Poll for approval
|
|
165
|
+
start_time = time.time()
|
|
166
|
+
while time.time() - start_time < expires_in:
|
|
167
|
+
time.sleep(interval)
|
|
168
|
+
|
|
169
|
+
try:
|
|
170
|
+
if use_mock:
|
|
171
|
+
# Use mock API
|
|
172
|
+
token_data = _mock_api.device_poll(device_code)
|
|
173
|
+
if token_data is None:
|
|
174
|
+
print_info(".", end="", flush=True)
|
|
175
|
+
continue
|
|
176
|
+
else:
|
|
177
|
+
# Try real API
|
|
178
|
+
try:
|
|
179
|
+
# Get device name for header
|
|
180
|
+
device_name = self._get_device_name()
|
|
181
|
+
poll_response = requests.get(
|
|
182
|
+
f"{self.api_base}/api/device/poll",
|
|
183
|
+
params={"device_code": device_code},
|
|
184
|
+
headers={"X-Device-Name": device_name},
|
|
185
|
+
timeout=10
|
|
186
|
+
)
|
|
187
|
+
|
|
188
|
+
if poll_response.status_code == 200:
|
|
189
|
+
token_data = poll_response.json()
|
|
190
|
+
elif poll_response.status_code == 202:
|
|
191
|
+
# Still waiting
|
|
192
|
+
print_info(".", end="", flush=True)
|
|
193
|
+
continue
|
|
194
|
+
elif poll_response.status_code == 400:
|
|
195
|
+
error_data = poll_response.json()
|
|
196
|
+
error = error_data.get("error", "Unknown error")
|
|
197
|
+
print_error(f"Authentication failed: {error}")
|
|
198
|
+
return False
|
|
199
|
+
elif poll_response.status_code == 404 and MOCK_AVAILABLE and _mock_api is not None:
|
|
200
|
+
# Backend unavailable, switch to mock
|
|
201
|
+
logger.info("Backend unavailable (404), switching to mock API")
|
|
202
|
+
use_mock = True
|
|
203
|
+
token_data = _mock_api.device_poll(device_code)
|
|
204
|
+
if token_data is None:
|
|
205
|
+
print_info(".", end="", flush=True)
|
|
206
|
+
continue
|
|
207
|
+
else:
|
|
208
|
+
continue
|
|
209
|
+
except requests.HTTPError as e:
|
|
210
|
+
if e.response.status_code == 404 and MOCK_AVAILABLE and _mock_api is not None:
|
|
211
|
+
# Switch to mock
|
|
212
|
+
use_mock = True
|
|
213
|
+
token_data = _mock_api.device_poll(device_code)
|
|
214
|
+
if token_data is None:
|
|
215
|
+
print_info(".", end="", flush=True)
|
|
216
|
+
continue
|
|
217
|
+
else:
|
|
218
|
+
raise
|
|
219
|
+
|
|
220
|
+
device_id = token_data.get("device_id")
|
|
221
|
+
device_token = token_data.get("device_token")
|
|
222
|
+
|
|
223
|
+
if device_id and device_token:
|
|
224
|
+
# Store token
|
|
225
|
+
self.device_id = device_id
|
|
226
|
+
self.device_token = device_token
|
|
227
|
+
self._save_token()
|
|
228
|
+
if use_mock:
|
|
229
|
+
print_success("Device authenticated successfully! (Mock mode)")
|
|
230
|
+
else:
|
|
231
|
+
print_success("Device authenticated successfully!")
|
|
232
|
+
return True
|
|
233
|
+
|
|
234
|
+
except requests.RequestException as e:
|
|
235
|
+
logger.debug(f"Poll request failed: {e}")
|
|
236
|
+
if use_mock:
|
|
237
|
+
# Try mock
|
|
238
|
+
token_data = _mock_api.device_poll(device_code)
|
|
239
|
+
if token_data:
|
|
240
|
+
device_id = token_data.get("device_id")
|
|
241
|
+
device_token = token_data.get("device_token")
|
|
242
|
+
if device_id and device_token:
|
|
243
|
+
self.device_id = device_id
|
|
244
|
+
self.device_token = device_token
|
|
245
|
+
self._save_token()
|
|
246
|
+
print_success("Device authenticated successfully! (Mock mode)")
|
|
247
|
+
return True
|
|
248
|
+
print_info(".", end="", flush=True)
|
|
249
|
+
continue
|
|
250
|
+
|
|
251
|
+
print_error("Authentication timed out. Please try again.")
|
|
252
|
+
return False
|
|
253
|
+
|
|
254
|
+
def _save_token(self):
|
|
255
|
+
"""Save device token to keyring."""
|
|
256
|
+
if self.device_id and self.device_token:
|
|
257
|
+
try:
|
|
258
|
+
token_string = f"{self.device_id}:{self.device_token}"
|
|
259
|
+
keyring.set_password(KEYRING_SERVICE, KEYRING_USERNAME, token_string)
|
|
260
|
+
logger.debug("Token saved to keyring")
|
|
261
|
+
except Exception as e:
|
|
262
|
+
logger.error(f"Failed to save token to keyring: {e}")
|
|
263
|
+
raise
|
|
264
|
+
|
|
265
|
+
def logout(self):
|
|
266
|
+
"""Logout and clear stored token."""
|
|
267
|
+
if self.device_token:
|
|
268
|
+
try:
|
|
269
|
+
# Revoke token on server
|
|
270
|
+
requests.post(
|
|
271
|
+
f"{self.api_base}/api/device/revoke",
|
|
272
|
+
json={"device_id": self.device_id},
|
|
273
|
+
headers={"Authorization": f"Bearer {self.device_token}"},
|
|
274
|
+
timeout=10
|
|
275
|
+
)
|
|
276
|
+
except Exception as e:
|
|
277
|
+
logger.debug(f"Could not revoke token on server: {e}")
|
|
278
|
+
|
|
279
|
+
# Clear local token
|
|
280
|
+
try:
|
|
281
|
+
keyring.delete_password(KEYRING_SERVICE, KEYRING_USERNAME)
|
|
282
|
+
except Exception as e:
|
|
283
|
+
logger.debug(f"Could not delete token from keyring: {e}")
|
|
284
|
+
|
|
285
|
+
self.device_token = None
|
|
286
|
+
self.device_id = None
|
|
287
|
+
print_success("Logged out successfully")
|
|
288
|
+
|
|
289
|
+
def get_token(self) -> Optional[str]:
|
|
290
|
+
"""Get current device token."""
|
|
291
|
+
return self.device_token
|
|
292
|
+
|
|
293
|
+
def get_device_id(self) -> Optional[str]:
|
|
294
|
+
"""Get current device ID."""
|
|
295
|
+
return self.device_id
|
|
296
|
+
|