File size: 11,104 Bytes
494c89b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
#!/usr/bin/env python3
"""
Token Pool Manager

Manages a pool of Kiro tokens with:
- Round-robin rotation
- Automatic refresh
- Ban detection
- Usage tracking
"""

import asyncio
import json
import time
from dataclasses import dataclass, field
from datetime import datetime, timedelta
from pathlib import Path
from typing import Dict, List, Optional, Any

import aiofiles

import sys
sys.path.insert(0, str(Path(__file__).parent.parent))

from core.paths import get_paths
from services.token_service import TokenService

# ============================================================================
# Data Classes
# ============================================================================

@dataclass
class PoolToken:
    """Token in the pool."""
    filename: str
    account_name: str
    email: str
    access_token: str
    refresh_token: str
    expires_at: datetime
    region: str = "us-east-1"
    auth_method: str = "social"
    
    # Status
    is_banned: bool = False
    ban_reason: str = ""
    
    # Usage tracking
    request_count: int = 0
    error_count: int = 0
    last_used: float = 0
    last_error: str = ""
    
    # Quota (if known)
    quota_used: int = 0
    quota_limit: int = 500
    
    @property
    def is_expired(self) -> bool:
        if not self.expires_at:
            return True
        return datetime.now(self.expires_at.tzinfo) > self.expires_at
    
    @property
    def is_available(self) -> bool:
        return not self.is_banned and not self.is_expired
    
    @property
    def quota_percent(self) -> float:
        if self.quota_limit <= 0:
            return 0
        return (self.quota_used / self.quota_limit) * 100
    
    def to_dict(self) -> Dict[str, Any]:
        return {
            "account": self.account_name or self.email,
            "region": self.region,
            "is_banned": self.is_banned,
            "ban_reason": self.ban_reason,
            "is_expired": self.is_expired,
            "is_available": self.is_available,
            "request_count": self.request_count,
            "error_count": self.error_count,
            "quota_used": self.quota_used,
            "quota_limit": self.quota_limit,
            "quota_percent": round(self.quota_percent, 1)
        }

# ============================================================================
# Token Pool
# ============================================================================

class TokenPool:
    """Manages pool of Kiro tokens."""
    
    def __init__(self):
        self.paths = get_paths()
        self.token_service = TokenService()
        self.tokens: List[PoolToken] = []
        self._lock = asyncio.Lock()
        self._current_index = 0
    
    # =========================================================================
    # Properties
    # =========================================================================
    
    @property
    def total_count(self) -> int:
        return len(self.tokens)
    
    @property
    def available_count(self) -> int:
        return sum(1 for t in self.tokens if t.is_available)
    
    @property
    def banned_count(self) -> int:
        return sum(1 for t in self.tokens if t.is_banned)
    
    @property
    def expired_count(self) -> int:
        return sum(1 for t in self.tokens if t.is_expired and not t.is_banned)
    
    # =========================================================================
    # Load/Save
    # =========================================================================
    
    async def load_tokens(self) -> int:
        """Load all tokens from storage."""
        self.tokens = []
        
        # Load from token service
        token_infos = self.token_service.list_tokens()
        
        for info in token_infos:
            try:
                data = info.raw_data
                if not data.get('accessToken'):
                    continue
                
                # Parse expiry
                expires_at = None
                if data.get('expiresAt'):
                    try:
                        expires_at = datetime.fromisoformat(
                            data['expiresAt'].replace('Z', '+00:00')
                        )
                    except:
                        pass
                
                token = PoolToken(
                    filename=info.path.name,
                    account_name=data.get('accountName', ''),
                    email=data.get('email', ''),
                    access_token=data.get('accessToken', ''),
                    refresh_token=data.get('refreshToken', ''),
                    expires_at=expires_at,
                    region=data.get('region', 'us-east-1'),
                    auth_method=data.get('authMethod', 'social')
                )
                
                self.tokens.append(token)
                
            except Exception as e:
                print(f"[!] Error loading token {info.path.name}: {e}")
        
        # Sort by availability (available first)
        self.tokens.sort(key=lambda t: (t.is_banned, t.is_expired))
        
        print(f"\n[Pool] Loaded {len(self.tokens)} tokens:")
        for t in self.tokens:
            status = "BANNED" if t.is_banned else ("EXPIRED" if t.is_expired else "OK")
            print(f"  [{status}] {t.account_name or t.email}")
        
        return len(self.tokens)
    
    # =========================================================================
    # Token Selection
    # =========================================================================
    
    async def get_token(self) -> Optional[PoolToken]:
        """Get next available token (round-robin)."""
        async with self._lock:
            available = [t for t in self.tokens if t.is_available]
            
            if not available:
                # Try to refresh expired tokens
                for t in self.tokens:
                    if t.is_expired and not t.is_banned:
                        if await self._refresh_token(t):
                            available.append(t)
                            break
            
            if not available:
                return None
            
            # Round-robin
            self._current_index = self._current_index % len(available)
            token = available[self._current_index]
            self._current_index += 1
            
            # Update usage
            token.last_used = time.time()
            token.request_count += 1
            
            return token
    
    async def get_token_data(self) -> Optional[Dict[str, Any]]:
        """Get token data for API request."""
        token = await self.get_token()
        if not token:
            return None
        
        return {
            "filename": token.filename,
            "accountName": token.account_name,
            "email": token.email,
            "accessToken": token.access_token,
            "refreshToken": token.refresh_token,
            "region": token.region,
            "authMethod": token.auth_method
        }
    
    # =========================================================================
    # Token Status Updates
    # =========================================================================
    
    async def mark_success(self, filename: str):
        """Mark token as successfully used."""
        for token in self.tokens:
            if token.filename == filename:
                token.error_count = 0
                token.last_error = ""
                break
    
    async def mark_error(self, filename: str, error: str):
        """Mark token as having an error."""
        for token in self.tokens:
            if token.filename == filename:
                token.error_count += 1
                token.last_error = error
                
                # Check for ban indicators
                error_lower = error.lower()
                if any(x in error_lower for x in [
                    'banned', 'suspended', 'disabled', 
                    'unauthorized', 'forbidden', 'blocked'
                ]):
                    token.is_banned = True
                    token.ban_reason = error
                    print(f"[!] Token {token.account_name} marked as BANNED: {error}")
                
                # Too many errors = temporary ban
                elif token.error_count >= 5:
                    token.is_banned = True
                    token.ban_reason = f"Too many errors: {error}"
                    print(f"[!] Token {token.account_name} disabled due to errors")
                
                break
    
    async def mark_quota_exceeded(self, filename: str):
        """Mark token as quota exceeded."""
        for token in self.tokens:
            if token.filename == filename:
                token.quota_used = token.quota_limit
                print(f"[!] Token {token.account_name} quota exceeded")
                break
    
    # =========================================================================
    # Token Refresh
    # =========================================================================
    
    async def _refresh_token(self, token: PoolToken) -> bool:
        """Refresh a single token."""
        try:
            # Find token info
            token_info = self.token_service.get_token(token.filename)
            if not token_info:
                return False
            
            # Refresh
            new_data = self.token_service.refresh_token(token_info)
            
            # Update pool token
            token.access_token = new_data.get('accessToken', token.access_token)
            if new_data.get('refreshToken'):
                token.refresh_token = new_data['refreshToken']
            
            if new_data.get('expiresAt'):
                try:
                    token.expires_at = datetime.fromisoformat(
                        new_data['expiresAt'].replace('Z', '+00:00')
                    )
                except:
                    pass
            
            print(f"[+] Refreshed token: {token.account_name}")
            return True
            
        except Exception as e:
            print(f"[!] Failed to refresh {token.account_name}: {e}")
            return False
    
    async def refresh_all(self) -> int:
        """Refresh all tokens that need it."""
        refreshed = 0
        
        for token in self.tokens:
            if token.is_expired and not token.is_banned:
                if await self._refresh_token(token):
                    refreshed += 1
        
        return refreshed
    
    # =========================================================================
    # Status
    # =========================================================================
    
    def get_status(self) -> Dict[str, Any]:
        """Get pool status."""
        return {
            "total": self.total_count,
            "available": self.available_count,
            "banned": self.banned_count,
            "expired": self.expired_count,
            "tokens": [t.to_dict() for t in self.tokens]
        }