-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathcli.js
More file actions
executable file
·534 lines (457 loc) · 19.4 KB
/
Copy pathcli.js
File metadata and controls
executable file
·534 lines (457 loc) · 19.4 KB
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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
#!/usr/bin/env node
const { spawn, spawnSync } = require('child_process');
const fs = require('fs');
const path = require('path');
const os = require('os');
const readline = require('readline');
const ROOT = __dirname;
const IS_WIN = process.platform === 'win32';
// ============================================================
// VENV LOCATION - Use writable, accessible path
// ============================================================
function getVenvDir() {
if (IS_WIN) {
const appData = process.env.LOCALAPPDATA || path.join(process.env.USERPROFILE || process.env.HOME || '', 'AppData', 'Local');
return path.join(appData, 'auto-freecf', 'venv');
} else {
const home = process.env.HOME || process.env.USERPROFILE || '/tmp';
return path.join(home, '.local', 'share', 'auto-freecf', 'venv');
}
}
const VENV_DIR = getVenvDir();
const INSTALLED_MARKER = path.join(VENV_DIR, '.installed');
// Python/pip executables inside venv
const PYTHON_EXE = path.join(VENV_DIR, IS_WIN ? 'Scripts' : 'bin', IS_WIN ? 'python.exe' : 'python');
const PIP_EXE = path.join(VENV_DIR, IS_WIN ? 'Scripts' : 'bin', IS_WIN ? 'pip.exe' : 'pip');
// ============================================================
// COLORS
// ============================================================
const colors = {
reset: '\x1b[0m',
bold: '\x1b[1m',
dim: '\x1b[2m',
cyan: '\x1b[36m',
green: '\x1b[32m',
yellow: '\x1b[33m',
red: '\x1b[31m',
magenta: '\x1b[35m',
};
// ============================================================
// AUTO-DETECT XVFB DISPLAY (for headless VPS running Xvfb)
// ============================================================
function detectXvfb() {
if (IS_WIN) return;
if (process.env.DISPLAY) return; // already set
const result = spawnSync('pgrep', ['-a', 'Xvfb'], { encoding: 'utf8' });
if (result.status === 0 && result.stdout.trim()) {
const match = result.stdout.match(/:(\d+)/);
if (match) {
process.env.DISPLAY = `:${match[1]}`;
// Silently set — will appear in child processes
}
}
}
detectXvfb(); // Run immediately on startup
function log(msg) { console.log(msg); }
function logOk(msg) { console.log(`${colors.green}✓${colors.reset} ${msg}`); }
function logInfo(msg) { console.log(`${colors.cyan}ℹ${colors.reset} ${msg}`); }
function logStep(msg) { console.log(`${colors.yellow}➤${colors.reset} ${msg}`); }
function logErr(msg) { console.log(`${colors.red}✗${colors.reset} ${msg}`); }
// ============================================================
// FIND PYTHON - Resolve to FULL PATH (critical for Windows)
// ============================================================
function findPython() {
const candidates = IS_WIN ? ['python', 'py'] : ['python3', 'python'];
for (const cmd of candidates) {
try {
// Step 1: Resolve to full path using 'where' (Win) or 'which' (Linux)
const whereCmd = IS_WIN ? 'where' : 'which';
const whereResult = spawnSync(whereCmd, [cmd], { encoding: 'utf8' });
if (whereResult.status !== 0 || !whereResult.stdout.trim()) continue;
// Get first match (full path)
const fullPath = whereResult.stdout.trim().split(/\r?\n/)[0].trim();
if (!fullPath) continue;
// Step 2: Verify it's Python 3.x
// IMPORTANT: No shell:true here - pass full path directly
const versionResult = spawnSync(fullPath, ['--version'], { encoding: 'utf8' });
if (versionResult.status === 0) {
const version = (versionResult.stdout || versionResult.stderr || '').trim();
if (version.match(/Python 3\./)) {
logInfo(`Found ${version} at ${fullPath}`);
return fullPath;
}
}
} catch {}
}
return null;
}
// ============================================================
// RUN COMMANDS - WITHOUT shell:true (fixes space-in-path bug)
// ============================================================
/**
* Run command synchronously with output capture.
* CRITICAL: No shell:true - this fixes WinError 5 on paths with spaces.
* When shell:true is used on Windows, cmd.exe splits paths on spaces.
*/
function runCapture(exe, args, options = {}) {
const opts = { encoding: 'utf8', ...options };
try {
const result = spawnSync(exe, args, opts);
return {
success: result.status === 0,
stdout: result.stdout || '',
stderr: result.stderr || '',
status: result.status,
error: result.error ? result.error.message : null
};
} catch (err) {
return {
success: false,
stdout: '',
stderr: err.message,
status: -1,
error: err.message
};
}
}
/**
* Run command asynchronously with visible output.
* No shell:true - fixes space-in-path issues.
*/
function runAsync(exe, args, options = {}) {
return new Promise((resolve) => {
const opts = { stdio: 'inherit', ...options };
let proc;
try {
proc = spawn(exe, args, opts);
} catch (err) {
logErr(`Failed to start: ${err.message}`);
resolve(false);
return;
}
proc.on('error', (err) => {
logErr(`Process error: ${err.message}`);
resolve(false);
});
proc.on('close', (code) => resolve(code === 0));
});
}
function formatTime(ms) {
const sec = Math.floor(ms / 1000);
const min = Math.floor(sec / 60);
const s = sec % 60;
if (min > 0) return `${min}m ${s}s`;
return `${s}s`;
}
function ensureDir(dirPath) {
if (!fs.existsSync(dirPath)) {
fs.mkdirSync(dirPath, { recursive: true });
}
}
// Remove directory recursively (for cleanup on failure)
function removeDir(dirPath) {
try {
if (fs.existsSync(dirPath)) {
fs.rmSync(dirPath, { recursive: true, force: true });
}
} catch {}
}
// ============================================================
// SETUP
// ============================================================
async function setup() {
const pythonExe = findPython();
if (!pythonExe) {
logErr('Python 3 not found! Please install Python 3.10+');
logInfo('Download from: https://www.python.org/downloads/');
logInfo('IMPORTANT: Check "Add Python to PATH" during installation');
process.exit(1);
}
if (!fs.existsSync(INSTALLED_MARKER)) {
log('\n📦 Installing dependencies (first time only)...');
log(`${colors.dim}This may take a few minutes...${colors.reset}\n`);
// Ensure venv parent directory exists
logStep(`Creating virtual environment...`);
logInfo(`Location: ${VENV_DIR}`);
ensureDir(path.dirname(VENV_DIR));
// Clean up any partial venv from previous failed attempt
removeDir(VENV_DIR);
// Create venv - NO shell:true (fixes space-in-path bug)
const venvResult = runCapture(pythonExe, ['-m', 'venv', VENV_DIR], {
timeout: 120000
});
if (!venvResult.success) {
logErr('Failed to create virtual environment');
if (venvResult.stderr) log(`${colors.dim}${venvResult.stderr}${colors.reset}`);
if (venvResult.error) log(`${colors.dim}${venvResult.error}${colors.reset}`);
// Try alternative: --without-pip
logInfo('Trying alternative method (--without-pip)...');
const altResult = runCapture(pythonExe, ['-m', 'venv', '--without-pip', VENV_DIR], {
timeout: 120000
});
if (!altResult.success) {
logErr('Alternative method also failed');
if (altResult.stderr) log(`${colors.dim}${altResult.stderr}${colors.reset}`);
logInfo('\n⚠ Troubleshooting:');
logInfo('1. Try manually: ' + pythonExe + ' -m venv "' + VENV_DIR + '"');
logInfo('2. Check antivirus is not blocking venv creation');
logInfo('3. Try running PowerShell as Administrator');
process.exit(1);
}
// If --without-pip worked, bootstrap pip
logInfo('Bootstrapping pip...');
const getpipResult = runCapture(pythonExe, ['-m', 'ensurepip', '--default-pip'], {
timeout: 60000
});
if (!getpipResult.success) {
logErr('Failed to bootstrap pip');
process.exit(1);
}
}
// Verify python.exe exists in venv
if (!fs.existsSync(PYTHON_EXE)) {
logErr('Virtual environment python not found at: ' + PYTHON_EXE);
process.exit(1);
}
logOk('Virtual environment created');
// Install Python packages - NO shell:true
logStep('Installing Python packages...');
const pipStart = Date.now();
const reqPath = path.join(ROOT, 'requirements.txt');
const pipResult = runCapture(PYTHON_EXE, ['-m', 'pip', 'install', '-q', '-r', reqPath], {
timeout: 300000
});
if (!pipResult.success) {
logErr('Failed to install Python packages');
if (pipResult.stderr) log(`${colors.dim}${pipResult.stderr}${colors.reset}`);
process.exit(1);
}
logOk(`Python packages installed (${formatTime(Date.now() - pipStart)})`);
// Install patchright browsers - NO shell:true
logStep('Installing browser (patchright/chromium)...');
const pwStart = Date.now();
const pwResult = runCapture(PYTHON_EXE, ['-m', 'patchright', 'install', 'chromium'], {
timeout: 600000
});
if (!pwResult.success) {
// Fallback: try playwright command (in case patchright aliases it)
logInfo('Trying alternative browser install...');
const pwResult2 = runCapture(PYTHON_EXE, ['-m', 'playwright', 'install', 'chromium'], {
timeout: 600000
});
if (!pwResult2.success) {
logErr('Failed to install browser');
if (pwResult.stderr) log(`${colors.dim}${pwResult.stderr}${colors.reset}`);
if (pwResult2.stderr) log(`${colors.dim}${pwResult2.stderr}${colors.reset}`);
process.exit(1);
}
}
logOk(`Browser installed (${formatTime(Date.now() - pwStart)})`);
fs.writeFileSync(INSTALLED_MARKER, new Date().toISOString());
logOk('Setup complete!');
}
}
function getPythonCmd() {
return PYTHON_EXE;
}
// ============================================================
// PROCESS ACCOUNTS
// ============================================================
async function processSingle(emailPass, proxyFile, loginMethod = 'email') {
const pyCmd = getPythonCmd();
const browserBot = path.join(ROOT, 'browser_bot.py');
const cmdArgs = [browserBot, '--single', emailPass];
if (proxyFile) {
cmdArgs.push('--proxy', proxyFile);
}
if (loginMethod === 'google') {
cmdArgs.push('--login-method', 'google');
}
// NO shell:true - fixes space-in-path
const success = await runAsync(pyCmd, cmdArgs);
process.exit(success ? 0 : 1);
}
async function processBulk(filePath, proxyFile, loginMethod = 'email') {
const pyCmd = getPythonCmd();
const browserBot = path.join(ROOT, 'browser_bot.py');
const cmdArgs = [browserBot, '--accounts', filePath];
if (proxyFile) {
cmdArgs.push('--proxy', proxyFile);
}
if (loginMethod === 'google') {
cmdArgs.push('--login-method', 'google');
}
// NO shell:true - fixes space-in-path
const success = await runAsync(pyCmd, cmdArgs);
process.exit(success ? 0 : 1);
}
// ============================================================
// SIGNUP FROM SCRATCH
// ============================================================
async function processSignup(numAccounts, proxyFile, mailApi) {
const pyCmd = getPythonCmd();
const signupMain = path.join(ROOT, 'signup_from_scratch', 'main.py');
const cmdArgs = [signupMain, '--accounts', String(numAccounts || 1)];
if (proxyFile) {
cmdArgs.push('--proxy', proxyFile);
}
if (mailApi) {
cmdArgs.push('--mail-api', mailApi);
}
logStep(`Starting signup flow (${numAccounts || 1} account(s))...`);
const success = await runAsync(pyCmd, cmdArgs);
process.exit(success ? 0 : 1);
}
// Signup setup — install signup_from_scratch dependencies
async function setupSignup() {
const signupReqPath = path.join(ROOT, 'signup_from_scratch', 'requirements.txt');
if (!fs.existsSync(signupReqPath)) return;
const markerPath = path.join(VENV_DIR, '.signup_installed');
if (fs.existsSync(markerPath)) return;
logStep('Installing signup dependencies...');
const pipResult = runCapture(PYTHON_EXE, ['-m', 'pip', 'install', '-q', '-r', signupReqPath], {
timeout: 300000
});
if (pipResult.success) {
fs.writeFileSync(markerPath, new Date().toISOString());
logOk('Signup dependencies installed');
} else {
logErr('Failed to install signup dependencies');
if (pipResult.stderr) log(`${colors.dim}${pipResult.stderr}${colors.reset}`);
}
}
async function main() {
log(`${colors.cyan}${colors.bold}`);
log('╔══════════════════════════════════════════════════════════╗');
log('║ ║');
log('║ 🚀 Auto-FreeCF ║');
log('║ Cloudflare AI Account — Login & Signup ║');
log('║ ║');
log('╚══════════════════════════════════════════════════════════╝');
log(`${colors.reset}${colors.magenta} By mmoaa${colors.reset}`);
log(`${colors.yellow}${colors.bold} ⚠️ BETA TESTING - Use at your own risk${colors.reset}\n`);
await setup();
await setupSignup();
// Parse arguments
const args = process.argv.slice(2);
const proxyArg = args.find(a => a.startsWith('--proxy='));
const proxyFile = proxyArg ? proxyArg.split('=')[1] : null;
const loginMethod = args.includes('--google') ? 'google' : 'email';
// --signup flag for direct CLI signup
if (args.includes('--signup')) {
const numIdx = args.indexOf('--accounts');
const numAccounts = numIdx !== -1 ? parseInt(args[numIdx + 1]) || 1 : 1;
const mailIdx = args.indexOf('--mail-api');
const mailApi = mailIdx !== -1 ? args[mailIdx + 1] : null;
await processSignup(numAccounts, proxyFile, mailApi);
return;
}
const fileArg = args.find(a => !a.startsWith('--') && (a.endsWith('.txt') || a.endsWith('.json')));
const singleArg = args.find(a => !a.startsWith('--') && a.includes('@') && a.includes(':'));
if (fileArg) {
logInfo(`Bulk mode: ${fileArg}`);
logInfo(`Login method: ${loginMethod}`);
if (proxyFile) logInfo(`Proxy: ${proxyFile}`);
await processBulk(fileArg, proxyFile, loginMethod);
return;
}
if (singleArg) {
logInfo(`Single mode: ${singleArg.split(':')[0]}`);
logInfo(`Login method: ${loginMethod}`);
if (proxyFile) logInfo(`Proxy: ${proxyFile}`);
await processSingle(singleArg, proxyFile, loginMethod);
return;
}
// Interactive mode
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
const question = (prompt) => new Promise(resolve => rl.question(prompt, resolve));
log(`\n${colors.bold}Choose mode:${colors.reset}`);
log(` ${colors.green}[1]${colors.reset} Login — Single ${colors.dim}(email:password)${colors.reset}`);
log(` ${colors.green}[2]${colors.reset} Login — Google OAuth ${colors.dim}(google email)${colors.reset}`);
log(` ${colors.green}[3]${colors.reset} Login — Bulk ${colors.dim}(from file)${colors.reset}`);
log(` ${colors.green}[4]${colors.reset} Signup — Create new account ${colors.dim}(from scratch)${colors.reset}`);
log(` ${colors.green}[5]${colors.reset} Exit\n`);
const choice = await question(`${colors.bold}Select${colors.reset} ${colors.dim}(1-5)${colors.reset}: `);
if (choice === '1') {
const emailPass = await question(`${colors.cyan}Enter email:password${colors.reset}: `);
if (!emailPass || !emailPass.includes(':')) {
logErr('Invalid format. Use: email:password');
rl.close();
process.exit(1);
}
const proxy = await question(`${colors.dim}Proxy file (optional, Enter to skip)${colors.reset}: `);
await processSingle(emailPass.trim(), proxy.trim() || null, 'email');
} else if (choice === '2') {
const emailPass = await question(`${colors.cyan}Enter Google email:password${colors.reset}: `);
if (!emailPass || !emailPass.includes(':')) {
logErr('Invalid format. Use: google_email:password');
rl.close();
process.exit(1);
}
const proxy = await question(`${colors.dim}Proxy file (optional, Enter to skip)${colors.reset}: `);
await processSingle(emailPass.trim(), proxy.trim() || null, 'google');
} else if (choice === '3') {
const file = await question(`${colors.cyan}Enter file path${colors.reset} ${colors.dim}(default: accounts.txt)${colors.reset}: `);
const filePath = file.trim() || 'accounts.txt';
if (!fs.existsSync(filePath)) {
logErr(`File not found: ${filePath}`);
rl.close();
process.exit(1);
}
const proxy = await question(`${colors.dim}Proxy file (optional, Enter to skip)${colors.reset}: `);
await processBulk(filePath, proxy.trim() || null, 'email');
} else if (choice === '4') {
// ---- Email Provider Selection ----
const defaultMailApi = 'https://convergence-lobby-portal-planes.trycloudflare.com/new_address';
log(`\n${colors.bold}Select mail provider:${colors.reset}`);
log(` ${colors.green}[1]${colors.reset} Public relay ${colors.dim}(default, zero setup)${colors.reset}`);
log(` ${colors.green}[2]${colors.reset} Custom mail API ${colors.dim}(your own URL)${colors.reset}`);
log(` ${colors.green}[3]${colors.reset} Deploy your own ${colors.dim}(guide)${colors.reset}\n`);
const mailChoice = await question(`${colors.bold}Provider${colors.reset} ${colors.dim}(1-3)${colors.reset}: `);
let mailApi = null;
if (mailChoice === '2') {
mailApi = await question(`${colors.cyan}Mail API URL${colors.reset} ${colors.dim}(e.g. https://your-relay.example.com/new_address)${colors.reset}: `);
if (!mailApi.trim()) {
logErr('URL required for custom provider');
rl.close();
process.exit(1);
}
mailApi = mailApi.trim();
} else if (mailChoice === '3') {
log(`\n${colors.bold}📘 Deploy your own mail relay:${colors.reset}`);
log(` 1. Create Supabase project at ${colors.cyan}https://supabase.com${colors.reset}`);
log(` 2. Deploy the Edge Function from ${colors.cyan}mail-adapter/${colors.reset}`);
log(` 3. Set your custom domain in ${colors.cyan}mail-adapter/config.json${colors.reset}`);
log(` 4. Run: ${colors.yellow}python3 adapter.py${colors.reset}`);
log(` 5. Expose via Cloudflare Tunnel or public VPS`);
log(` 6. Use the resulting URL as your mail_api\n`);
log(`${colors.dim} Then re-run ${colors.yellow}moycf${colors.dim} and pick option [2]${colors.reset}\n`);
rl.close();
process.exit(0);
}
// Option 1 or default = public relay
if (mailChoice !== '2' && mailChoice !== '3') {
mailApi = defaultMailApi;
}
const numStr = await question(`${colors.cyan}Number of accounts${colors.reset} ${colors.dim}(default: 1)${colors.reset}: `);
const numAccounts = parseInt(numStr.trim()) || 1;
const proxy = await question(`${colors.dim}Proxy file (optional, Enter to skip)${colors.reset}: `);
await processSignup(numAccounts, proxy.trim() || null, mailApi);
} else if (choice === '5') {
log('\nGoodbye! 👋\n');
rl.close();
process.exit(0);
} else {
logErr('Invalid option');
rl.close();
process.exit(1);
}
rl.close();
}
main().catch(err => {
logErr(err.message);
process.exit(1);
});