File size: 6,597 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
"""
Автоматическая регистрация без интерактивного подтверждения
С выводом прогресса для VS Code extension
"""
import sys
import os
import time
import json
import argparse
import random
from pathlib import Path

# Fix encoding for Windows (cp1251 doesn't support emoji)
if sys.platform == 'win32':
    # Try to set UTF-8 mode
    if hasattr(sys.stdout, 'reconfigure'):
        try:
            sys.stdout.reconfigure(encoding='utf-8', errors='replace')
            sys.stderr.reconfigure(encoding='utf-8', errors='replace')
        except Exception:
            pass
    # Set environment variable for child processes
    os.environ['PYTHONIOENCODING'] = 'utf-8'

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

from .register import AWSRegistration, generate_emails
from core.config import get_config, save_config

def get_setting(path, default=None):
    return get_config().get(path, default)

def set_setting(path, value):
    config = get_config()
    config.set(path, value)
    save_config()


FIRST_NAMES = [
    'James', 'John', 'Robert', 'Michael', 'David', 'William', 'Richard', 'Joseph',
    'Thomas', 'Christopher', 'Charles', 'Daniel', 'Matthew', 'Anthony', 'Mark',
    'Steven', 'Paul', 'Andrew', 'Joshua', 'Kevin', 'Brian', 'George', 'Edward',
    'Mary', 'Patricia', 'Jennifer', 'Linda', 'Elizabeth', 'Susan', 'Jessica',
    'Sarah', 'Karen', 'Lisa', 'Nancy', 'Betty', 'Margaret', 'Sandra', 'Ashley',
    'Emily', 'Amanda', 'Melissa', 'Stephanie', 'Rebecca', 'Laura', 'Helen',
    'Alex', 'Sam', 'Jordan', 'Taylor', 'Morgan', 'Casey', 'Riley', 'Quinn',
    'Max', 'Ben', 'Jake', 'Ryan', 'Nick', 'Tom', 'Jack', 'Luke', 'Adam', 'Eric'
]

LAST_NAMES = [
    'Smith', 'Johnson', 'Williams', 'Brown', 'Jones', 'Garcia', 'Miller', 'Davis',
    'Rodriguez', 'Martinez', 'Wilson', 'Anderson', 'Taylor', 'Thomas', 'Moore',
    'Jackson', 'Martin', 'Lee', 'Thompson', 'White', 'Harris', 'Clark', 'Lewis',
    'Walker', 'Young', 'Allen', 'King', 'Wright', 'Scott', 'Green', 'Baker',
    'Adams', 'Nelson', 'Hill', 'Campbell', 'Mitchell', 'Roberts', 'Carter',
    'Phillips', 'Evans', 'Turner', 'Parker', 'Collins', 'Edwards', 'Stewart',
    'Morris', 'Murphy', 'Cook', 'Rogers', 'Morgan', 'Peterson', 'Cooper', 'Reed'
]


def generate_human_email(domain: str) -> str:
    first = random.choice(FIRST_NAMES)
    last = random.choice(LAST_NAMES)
    number = random.randint(100, 9999)
    username = f"{first}{last}{number}"
    return f"{username}@{domain}"


def progress(step: int, total: int, name: str, detail: str = ""):
    """Выводит прогресс в JSON формате для extension"""
    data = {
        "step": step,
        "totalSteps": total,
        "stepName": name,
        "detail": detail
    }
    print(f"PROGRESS:{json.dumps(data)}", flush=True)


def main():
    parser = argparse.ArgumentParser(description='Auto-register AWS Builder ID')
    parser.add_argument('--headless', action='store_true', help='Run browser in headless mode')
    parser.add_argument('--no-headless', action='store_true', help='Show browser window')
    parser.add_argument('--verbose', '-v', action='store_true', help='Verbose output')
    parser.add_argument('--email', type=str, help='Custom email to use (overrides strategy)')
    parser.add_argument('--count', '-c', type=int, default=1, help='Number of accounts to register')
    parser.add_argument('--device-flow', action='store_true', help='Use Device Flow OAuth instead of PKCE')
    args = parser.parse_args()

    # Determine headless mode
    if args.headless:
        headless = True
    elif args.no_headless:
        headless = False
    else:
        headless = get_setting('browser.headless', False)
    
    # Determine device flow mode (from args or env)
    device_flow = args.device_flow or os.environ.get('DEVICE_FLOW', '0') == '1'

    if args.verbose:
        set_setting('debug.verbose', True)

    # Get strategy from environment
    strategy = os.environ.get('EMAIL_STRATEGY', 'single')
    
    progress(1, 8, "Initializing", f"Strategy: {strategy}")

    if args.verbose:
        print(f"[DEBUG] Headless: {headless}")
        print(f"[DEBUG] Device Flow: {device_flow}")
        print(f"[DEBUG] Strategy: {strategy}")
        print(f"[DEBUG] IMAP User: {os.environ.get('IMAP_USER', 'not set')}")

    reg = AWSRegistration(headless=headless, device_flow=device_flow)

    try:
        progress(2, 8, "Starting OAuth", "Getting auth URL...")
        
        if args.email and args.count > 1:
            raise ValueError("Cannot use --email with --count > 1")
        
        results = []
        for i in range(args.count):
            if args.count > 1:
                print(f"\n=== Registering {i + 1}/{args.count} ===")
            
            # Use register_auto which handles email strategies
            if args.email:
                # Manual email override
                result = reg.register_single(args.email)
            else:
                # Use configured strategy
                result = reg.register_auto()
            results.append(result)
            
            if not result.get('success'):
                progress(8, 8, "Failed", result.get('error', 'Unknown error'))
                print(f"\n[X] FAILED: {result.get('error', 'Unknown')}")
                if args.count > 1:
                    continue
                return result
        
        if args.count == 1:
            result = results[0]
            if result.get('success'):
                progress(8, 8, "Complete", f"Account: {result['email']}")
                print("\n[OK] SUCCESS")
                print(f"Email: {result['email']}")
                print(f"Password: {result['password']}")
                print(f"Token: {result.get('token_file', 'N/A')}")
                if result.get('strategy'):
                    print(f"Strategy: {result['strategy']}")
            return result
        
        success_count = len([r for r in results if r.get('success')])
        progress(8, 8, "Complete", f"Success: {success_count}/{args.count}")
        print(f"\n[OK] Completed: {success_count}/{args.count} succeeded")
        return {'success': success_count == args.count, 'results': results}

    except Exception as e:
        progress(8, 8, "Error", str(e))
        print(f"\n[X] ERROR: {e}")
        if args.verbose:
            import traceback
            traceback.print_exc()
        return {'success': False, 'error': str(e)}

    finally:
        reg.close()


if __name__ == '__main__':
    main()