Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
1974 lines (1679 loc) · 78.2 KB
/
Copy pathmain.py
File metadata and controls
1974 lines (1679 loc) · 78.2 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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import threading
import time
import csv
import json
import xml.etree.ElementTree as ET
import uuid
import webbrowser
import argparse
import secrets
import string
import os
import base64
from io import StringIO, BytesIO
from datetime import datetime, timedelta
from flask import Flask, render_template, request, jsonify, session, redirect, url_for
from flask_compress import Compress
from functools import wraps
from src.crawler import WebCrawler
from src.settings_manager import SettingsManager
from src.auth_db import init_db, create_user, authenticate_user, get_user_by_id, log_guest_crawl, get_guest_crawls_last_24h, verify_user, set_user_tier, create_verification_token, verify_token, get_user_by_email, get_or_create_zoho_user
from src.email_service import send_verification_email, send_welcome_email
from src.zoho_oauth import ZohoOAuthConfig, ZohoOAuthError
# Load environment variables from .env file
from dotenv import load_dotenv
load_dotenv()
# Parse command line arguments
parser = argparse.ArgumentParser(description='LibreCrawl - SEO Spider Tool')
parser.add_argument('--local', '-l', action='store_true',
help='Run in local mode (all users get admin tier, no rate limits)')
parser.add_argument('--disable-register', '-dr', action='store_true',
help='Disable new user registrations')
parser.add_argument('--disable-guest', '-dg', action='store_true',
help='Disable guest login')
parser.add_argument('--demo', '-dm', action='store_true',
help='Demo mode: 1.5GB memory limit per user, crawls auto-stop at limit')
parser.add_argument('--dangerously-skip-auth', '-dsa', action='store_true',
help='DANGEROUS: Allow anyone to log in as any username with no password. '
'The username is only used to separate per-user sessions. '
'Do NOT use on a public network or in production.')
args = parser.parse_args()
LOCAL_MODE = args.local or os.getenv('LOCAL_MODE', '').lower() in ('true', '1', 'yes')
DISABLE_REGISTER = args.disable_register or os.getenv('REGISTRATION_DISABLED', '').lower() in ('true', '1', 'yes')
DISABLE_GUEST = args.disable_guest or os.getenv('DISABLE_GUEST', '').lower() in ('true', '1', 'yes')
DEMO_MODE = args.demo or os.getenv('DEMO_MODE', '').lower() in ('true', '1', 'yes')
SKIP_AUTH = args.dangerously_skip_auth or os.getenv('DANGEROUSLY_SKIP_AUTH', '').lower() in ('true', '1', 'yes')
ZOHO = ZohoOAuthConfig(registration_disabled=DISABLE_REGISTER)
app = Flask(__name__, template_folder='web/templates', static_folder='web/static')
app.secret_key = os.environ.get('SECRET_KEY') or secrets.token_hex(32)
if not os.environ.get('SECRET_KEY'):
print('⚠️ WARNING: SECRET_KEY not set — using an ephemeral random key. '
'Sessions will not persist across restarts. Set SECRET_KEY in production.', flush=True)
# Enable compression for all responses
Compress(app)
# Ensure data directory exists before initializing the database
os.makedirs("data", exist_ok=True)
# Initialize database on startup
init_db()
def generate_random_password(length=16):
"""Generate a random password with letters, digits, and symbols"""
alphabet = string.ascii_letters + string.digits + string.punctuation
return ''.join(secrets.choice(alphabet) for _ in range(length))
def auto_login_local_mode():
"""Auto-login for local mode - creates or logs into 'local' admin account"""
import sqlite3
try:
conn = sqlite3.connect(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data', 'users.db'))
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
# Check if 'local' user exists
cursor.execute('SELECT id, username, tier FROM users WHERE username = ?', ('local',))
user = cursor.fetchone()
if user:
# User exists, just log them in
session['user_id'] = user['id']
session['username'] = user['username']
session['tier'] = 'admin'
session.permanent = True
print(f"Auto-logged in as existing 'local' user (ID: {user['id']})")
else:
# Create new local user with random password
random_password = generate_random_password()
from src.auth_db import hash_password
password_hash = hash_password(random_password)
cursor.execute('''
INSERT INTO users (username, email, password_hash, verified, tier)
VALUES (?, ?, ?, 1, 'admin')
''', ('local', 'local@localhost', password_hash))
conn.commit()
user_id = cursor.lastrowid
# Log in the new user
session['user_id'] = user_id
session['username'] = 'local'
session['tier'] = 'admin'
session.permanent = True
print(f"Created and auto-logged in as new 'local' admin user (ID: {user_id})")
print(f"Generated password: {random_password}")
conn.close()
return True
except Exception as e:
print(f"Error in auto_login_local_mode: {e}")
return False
def skip_auth_login(username):
"""Skip-auth login: create user record if missing, log them in.
Each username gets its own user_id, which drives per-user crawler
instance and settings isolation. No password is checked. Always
grants admin tier (matches local-mode behavior).
Returns (success, message).
"""
import sqlite3
try:
conn = sqlite3.connect(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data', 'users.db'))
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
cursor.execute('SELECT id, username FROM users WHERE username = ?', (username,))
user = cursor.fetchone()
if user:
user_id = user['id']
else:
from src.auth_db import hash_password
random_password = generate_random_password()
password_hash = hash_password(random_password)
cursor.execute('''
INSERT INTO users (username, email, password_hash, verified, tier)
VALUES (?, ?, ?, 1, 'admin')
''', (username, f'{username}@skipauth.local', password_hash))
conn.commit()
user_id = cursor.lastrowid
conn.close()
session['user_id'] = user_id
session['username'] = username
session['tier'] = 'admin'
session.permanent = True
return True, 'Logged in (authentication skipped)'
except sqlite3.IntegrityError as e:
# Most likely the generated email collides with an existing account
# whose email happens to match. Fall back to a clearer message.
return False, f'Username conflict: try a different username ({e})'
except Exception as e:
print(f"Error in skip_auth_login: {e}")
return False, f'Login error: {str(e)}'
if LOCAL_MODE:
print("=" * 60)
print("LOCAL MODE ENABLED")
print("All users will have admin tier access")
print("No rate limits or tier restrictions")
print("Auto-login enabled with 'local' admin account")
print("=" * 60)
if DISABLE_REGISTER:
print("=" * 60)
print("REGISTRATION DISABLED")
print("New user registrations are not allowed")
print("=" * 60)
if DISABLE_GUEST:
print("=" * 60)
print("GUEST MODE DISABLED")
print("Guest login is not allowed")
print("=" * 60)
if DEMO_MODE:
print("=" * 60)
print("DEMO MODE ENABLED")
print("Memory limit: 1.5GB per user")
print("Crawls will auto-stop when limit is reached")
print("=" * 60)
if SKIP_AUTH:
print("=" * 60)
print("⚠️ DANGEROUSLY SKIP AUTH ENABLED")
print("Anyone can log in as any username with no password!")
print("Username is used only to separate per-user sessions.")
print("DO NOT use on a public network or production server!")
print("=" * 60)
if ZOHO.enabled:
print("=" * 60)
print("ZOHO OAUTH LOGIN ENABLED")
print(f"Accounts server: {ZOHO.accounts_url}")
if ZOHO.allowed_domains:
print(f"Allowed email domains: {', '.join(ZOHO.allowed_domains)}")
print(f"New Zoho users: {'created with tier ' + repr(ZOHO.default_tier) if ZOHO.allow_signup else 'not allowed'}")
print("=" * 60)
def get_client_ip():
"""Get the real client IP address, checking Cloudflare headers first"""
# Check Cloudflare header first
if 'CF-Connecting-IP' in request.headers:
return request.headers['CF-Connecting-IP']
# Check other common proxy headers
if 'X-Forwarded-For' in request.headers:
# X-Forwarded-For can contain multiple IPs, take the first one
return request.headers['X-Forwarded-For'].split(',')[0].strip()
if 'X-Real-IP' in request.headers:
return request.headers['X-Real-IP']
# Fall back to direct connection IP
return request.remote_addr
def login_required(f):
"""Decorator to require login for routes"""
@wraps(f)
def decorated_function(*args, **kwargs):
# In local mode, auto-login if not already logged in
if LOCAL_MODE and 'user_id' not in session:
auto_login_local_mode()
elif 'user_id' not in session:
# Not in local mode and not logged in
if request.path.startswith('/api/'):
return jsonify({'success': False, 'error': 'Authentication required'}), 401
return redirect(url_for('login_page'))
return f(*args, **kwargs)
return decorated_function
# Multi-tenant crawler instances
crawler_instances = {} # session_id -> {'crawler': WebCrawler, 'settings': SettingsManager, 'last_accessed': datetime}
instances_lock = threading.Lock()
def get_or_create_crawler():
"""Get or create a crawler instance for the current session"""
# Get or create session ID
if 'session_id' not in session:
session['session_id'] = str(uuid.uuid4())
session_id = session['session_id']
user_id = session.get('user_id') # Get user_id from session
tier = session.get('tier', 'guest') # Get tier from session
with instances_lock:
# Check if crawler exists for this session
if session_id not in crawler_instances:
print(f"Creating new crawler instance for session: {session_id}, user: {user_id}, tier: {tier}")
crawler_instances[session_id] = {
'crawler': WebCrawler(),
'settings': SettingsManager(session_id=session_id, user_id=user_id, tier=tier), # Per-user settings
'last_accessed': datetime.now()
}
else:
# Update last accessed time
crawler_instances[session_id]['last_accessed'] = datetime.now()
return crawler_instances[session_id]['crawler']
def get_session_settings():
"""Get the settings manager for the current session"""
# Get or create session ID
if 'session_id' not in session:
session['session_id'] = str(uuid.uuid4())
session_id = session['session_id']
user_id = session.get('user_id') # Get user_id from session
tier = session.get('tier', 'guest') # Get tier from session
with instances_lock:
# Create instance if it doesn't exist
if session_id not in crawler_instances:
print(f"Creating new settings instance for session: {session_id}, user: {user_id}, tier: {tier}")
crawler_instances[session_id] = {
'crawler': WebCrawler(),
'settings': SettingsManager(session_id=session_id, user_id=user_id, tier=tier),
'last_accessed': datetime.now()
}
else:
# Update last accessed time
crawler_instances[session_id]['last_accessed'] = datetime.now()
return crawler_instances[session_id]['settings']
def cleanup_old_instances():
"""Remove crawler instances that haven't been accessed in 1 hour"""
timeout = timedelta(hours=1)
now = datetime.now()
with instances_lock:
sessions_to_remove = []
for session_id, instance_data in crawler_instances.items():
if now - instance_data['last_accessed'] > timeout:
sessions_to_remove.append(session_id)
for session_id in sessions_to_remove:
print(f"Cleaning up crawler instance for session: {session_id}")
# Stop any running crawls
try:
crawler_instances[session_id]['crawler'].stop_crawl()
except:
pass
del crawler_instances[session_id]
if sessions_to_remove:
print(f"Cleaned up {len(sessions_to_remove)} inactive crawler instances")
def start_cleanup_thread():
"""Start background thread to cleanup old instances"""
def cleanup_loop():
while True:
time.sleep(300) # Check every 5 minutes
try:
cleanup_old_instances()
except Exception as e:
print(f"Error in cleanup thread: {e}")
cleanup_thread = threading.Thread(target=cleanup_loop, daemon=True)
cleanup_thread.start()
print("Started crawler instance cleanup thread")
def generate_csv_export(urls, fields):
"""Generate CSV export content"""
output = StringIO()
writer = csv.DictWriter(output, fieldnames=fields)
writer.writeheader()
for url_data in urls:
row = {}
for field in fields:
value = url_data.get(field, '')
# Handle complex data types for CSV
if field == 'analytics' and isinstance(value, dict):
analytics_list = []
if value.get('gtag') or value.get('ga4_id'): analytics_list.append('GA4')
if value.get('google_analytics'): analytics_list.append('GA')
if value.get('gtm_id'): analytics_list.append('GTM')
if value.get('facebook_pixel'): analytics_list.append('FB')
if value.get('hotjar'): analytics_list.append('HJ')
if value.get('mixpanel'): analytics_list.append('MP')
row[field] = ', '.join(analytics_list)
elif field == 'og_tags' and isinstance(value, dict):
row[field] = f"{len(value)} tags" if value else ''
elif field == 'twitter_tags' and isinstance(value, dict):
row[field] = f"{len(value)} tags" if value else ''
elif field == 'json_ld' and isinstance(value, list):
row[field] = f"{len(value)} scripts" if value else ''
elif field == 'images' and isinstance(value, list):
row[field] = f"{len(value)} images" if value else ''
elif field == 'internal_links' and isinstance(value, (int, float)):
row[field] = f"{int(value)} internal links" if value else '0 internal links'
elif field == 'external_links' and isinstance(value, (int, float)):
row[field] = f"{int(value)} external links" if value else '0 external links'
elif field == 'h2' and isinstance(value, list):
row[field] = ', '.join(value[:3]) + ('...' if len(value) > 3 else '')
elif field == 'h3' and isinstance(value, list):
row[field] = ', '.join(value[:3]) + ('...' if len(value) > 3 else '')
elif isinstance(value, (dict, list)):
row[field] = str(value)
else:
row[field] = value
writer.writerow(row)
return output.getvalue()
def generate_json_export(urls, fields):
"""Generate JSON export content"""
filtered_urls = []
for url_data in urls:
filtered_data = {}
for field in fields:
value = url_data.get(field, '')
# Keep complex data structures intact in JSON
filtered_data[field] = value
filtered_urls.append(filtered_data)
return json.dumps({
'export_date': time.strftime('%Y-%m-%d %H:%M:%S'),
'total_urls': len(filtered_urls),
'fields': fields,
'data': filtered_urls
}, indent=2, default=str)
def generate_xml_export(urls, fields):
"""Generate XML export content"""
root = ET.Element('librecrawl_export')
root.set('export_date', time.strftime('%Y-%m-%d %H:%M:%S'))
root.set('total_urls', str(len(urls)))
urls_element = ET.SubElement(root, 'urls')
for url_data in urls:
url_element = ET.SubElement(urls_element, 'url')
for field in fields:
field_element = ET.SubElement(url_element, field)
field_element.text = str(url_data.get(field, ''))
return ET.tostring(root, encoding='unicode')
def generate_links_csv_export(links):
"""Generate CSV export for links data"""
output = StringIO()
fieldnames = ['source_url', 'target_url', 'anchor_text', 'is_internal', 'target_domain', 'target_status', 'placement']
writer = csv.DictWriter(output, fieldnames=fieldnames)
writer.writeheader()
for link in links:
row = {
'source_url': link.get('source_url', ''),
'target_url': link.get('target_url', ''),
'anchor_text': link.get('anchor_text', ''),
'is_internal': 'Yes' if link.get('is_internal') else 'No',
'target_domain': link.get('target_domain', ''),
'target_status': link['target_status'] if link.get('target_status') is not None else 'Not crawled',
'placement': link.get('placement', 'body')
}
writer.writerow(row)
return output.getvalue()
def generate_links_json_export(links):
"""Generate JSON export for links data"""
return json.dumps(links, indent=2)
def issue_matches_exclusion(issue, exclusion_patterns):
"""Check whether a single issue's URL matches any exclusion pattern"""
from fnmatch import fnmatch
from urllib.parse import urlparse
path = urlparse(issue.get('url', '')).path
for pattern in exclusion_patterns:
if not pattern.strip() or pattern.strip().startswith('#'):
continue
if '*' in pattern:
if fnmatch(path, pattern):
return True
elif path == pattern or path.startswith(pattern.rstrip('*')):
return True
return False
def filter_issues_by_exclusion_patterns(issues, exclusion_patterns):
"""Filter issues based on exclusion patterns (applies current settings to loaded crawls)"""
if not exclusion_patterns:
return issues
return [issue for issue in issues if not issue_matches_exclusion(issue, exclusion_patterns)]
def get_exclusion_patterns(settings_manager):
"""Current issue-exclusion patterns as a list of non-empty lines"""
current_settings = settings_manager.get_settings()
exclusion_patterns_text = current_settings.get('issueExclusionPatterns', '')
return [p.strip() for p in exclusion_patterns_text.split('\n') if p.strip()]
def generate_issues_csv_export(issues):
"""Generate CSV export for issues data"""
output = StringIO()
fieldnames = ['url', 'type', 'category', 'issue', 'details']
writer = csv.DictWriter(output, fieldnames=fieldnames)
writer.writeheader()
for issue in issues:
row = {
'url': issue.get('url', ''),
'type': issue.get('type', ''),
'category': issue.get('category', ''),
'issue': issue.get('issue', ''),
'details': issue.get('details', '')
}
writer.writerow(row)
return output.getvalue()
def generate_issues_json_export(issues):
"""Generate JSON export for issues data"""
# Group issues by URL for better organization
issues_by_url = {}
for issue in issues:
url = issue.get('url', '')
if url not in issues_by_url:
issues_by_url[url] = []
issues_by_url[url].append({
'type': issue.get('type', ''),
'category': issue.get('category', ''),
'issue': issue.get('issue', ''),
'details': issue.get('details', '')
})
return json.dumps({
'export_date': time.strftime('%Y-%m-%d %H:%M:%S'),
'total_issues': len(issues),
'total_urls_with_issues': len(issues_by_url),
'issues_by_url': issues_by_url,
'all_issues': issues
}, indent=2)
@app.route('/login')
def login_page():
# In local mode, auto-login and redirect to index
if LOCAL_MODE:
auto_login_local_mode()
return redirect(url_for('index'))
# Redirect to app if already logged in
if 'user_id' in session:
return redirect(url_for('index'))
return render_template('login.html', registration_disabled=DISABLE_REGISTER, guest_disabled=DISABLE_GUEST, skip_auth=SKIP_AUTH,
zoho_enabled=ZOHO.enabled, login_error=session.pop('login_error', None))
def _zoho_redirect_uri():
return ZOHO.redirect_uri or url_for('zoho_callback', _external=True)
@app.route('/auth/zoho/login')
def zoho_login():
if not ZOHO.enabled:
return redirect(url_for('login_page'))
state = secrets.token_urlsafe(32)
session['zoho_oauth_state'] = state
return redirect(ZOHO.authorize_url(_zoho_redirect_uri(), state))
@app.route('/auth/zoho/callback')
def zoho_callback():
if not ZOHO.enabled:
return redirect(url_for('login_page'))
def fail(message):
session['login_error'] = message
return redirect(url_for('login_page'))
expected_state = session.pop('zoho_oauth_state', None)
if request.args.get('error'):
return fail('Zoho login was cancelled or denied.')
if not expected_state or not secrets.compare_digest(expected_state, request.args.get('state', '')):
return fail('Zoho login expired or was invalid. Please try again.')
code = request.args.get('code')
if not code:
return fail('Zoho did not return an authorization code.')
try:
accounts_server = ZOHO.accounts_server_for(request.args.get('accounts-server'))
identity = ZOHO.fetch_identity(code, _zoho_redirect_uri(), accounts_server)
except ZohoOAuthError as e:
print(f"Zoho OAuth error: {e}")
return fail(str(e))
if not ZOHO.domain_allowed(identity['email']):
return fail('Your Zoho account\'s email domain is not allowed to log in here.')
success, message, user_data = get_or_create_zoho_user(
identity['zoho_id'], identity['email'], identity['name'],
default_tier=ZOHO.default_tier, allow_create=ZOHO.allow_signup)
if not success:
return fail(message)
session.clear()
session['user_id'] = user_data['id']
session['username'] = user_data['username']
session['tier'] = user_data['tier']
session.permanent = True
return redirect(url_for('index'))
@app.route('/register')
def register_page():
# Redirect to app if already logged in
if 'user_id' in session:
return redirect(url_for('index'))
return render_template('register.html', registration_disabled=DISABLE_REGISTER)
@app.route('/verify')
def verify_email():
"""Email verification endpoint"""
token = request.args.get('token')
if not token:
return render_template('verification_result.html',
success=False,
message='Invalid verification link',
app_source='main')
# Verify the token
success, message, app_source, user_email = verify_token(token)
# Send welcome email if successful
if success and user_email:
try:
user = get_user_by_email(user_email)
if user:
send_welcome_email(user_email, user['username'], app_source or 'main')
except Exception as e:
print(f"Error sending welcome email: {e}")
# Determine redirect URL based on app_source
redirect_url = None
if success:
if app_source == 'workshop':
redirect_url = os.getenv('WORKSHOP_APP_URL', 'https://workshop.librecrawl.com')
else:
redirect_url = url_for('login_page')
return render_template('verification_result.html',
success=success,
message=message,
app_source=app_source or 'main',
redirect_url=redirect_url)
@app.route('/api/register', methods=['POST'])
def register():
# Check if registration is disabled
if DISABLE_REGISTER:
return jsonify({'success': False, 'message': 'Registration is currently disabled'})
data = request.get_json()
username = data.get('username')
email = data.get('email')
password = data.get('password')
success, message, user_id = create_user(username, email, password)
# In local mode, auto-verify and set to admin tier
if success and LOCAL_MODE:
try:
from src.auth_db import verify_user, set_user_tier
# Get the user that was just created
import sqlite3
conn = sqlite3.connect(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data', 'users.db'))
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
cursor.execute('SELECT id FROM users WHERE username = ?', (username,))
user = cursor.fetchone()
conn.close()
if user:
verify_user(user['id'])
set_user_tier(user['id'], 'admin')
message = 'Account created and verified! You have admin access in local mode.'
except Exception as e:
print(f"Error during local mode auto-verification: {e}")
# Don't fail the registration, just log the error
# The account is still created successfully
elif success:
# Not in local mode - send verification email
is_resend = (message == 'resend')
try:
# Create verification token
token = create_verification_token(user_id, app_source='main')
if token:
# Send verification email
email_success, email_message = send_verification_email(
email, username, token, app_source='main', is_resend=is_resend
)
if email_success:
if is_resend:
message = 'A verification email was already sent to this address. We\'ve updated your account details and sent a new verification link.'
else:
message = 'Registration successful! Please check your email to verify your account.'
else:
message = 'Account created, but we could not send the verification email. Please contact support.'
print(f"Email error: {email_message}")
else:
message = 'Account created, but verification token generation failed. Please contact support.'
except Exception as e:
print(f"Error sending verification email: {e}")
message = 'Account created, but we could not send the verification email. Please contact support.'
return jsonify({'success': success, 'message': message})
@app.route('/api/login', methods=['POST'])
def login():
data = request.get_json()
username = (data.get('username') or '').strip()
password = data.get('password') or ''
# Dangerously skip auth: accept any username with no password.
# Username is only used to separate per-user sessions.
if SKIP_AUTH:
if not username:
return jsonify({'success': False, 'message': 'Username required'})
if len(username) > 50:
return jsonify({'success': False, 'message': 'Username must be 50 characters or less'})
success, message = skip_auth_login(username)
return jsonify({'success': success, 'message': message})
success, message, user_data = authenticate_user(username, password)
if success:
session['user_id'] = user_data['id']
session['username'] = user_data['username']
# In local mode, always give admin tier
session['tier'] = 'admin' if LOCAL_MODE else user_data['tier']
session.permanent = True # Remember login
return jsonify({'success': success, 'message': message})
@app.route('/api/guest-login', methods=['POST'])
def guest_login():
"""Login as a guest user (no account required, limited to 3 crawls/24h)"""
if DISABLE_GUEST:
return jsonify({'success': False, 'message': 'Guest login is disabled'})
# Create a guest session with no user_id but with tier='guest'
# In local mode, guests also get admin tier
session['user_id'] = None
session['username'] = 'Guest'
session['tier'] = 'admin' if LOCAL_MODE else 'guest'
session.permanent = False # Don't persist guest sessions
return jsonify({'success': True, 'message': 'Logged in as guest'})
@app.route('/api/logout', methods=['POST'])
@login_required
def logout():
session.clear()
return jsonify({'success': True, 'message': 'Logged out successfully'})
@app.route('/api/user/info')
@login_required
def user_info():
"""Get current user info including tier"""
from src.auth_db import get_crawls_last_24h
user_id = session.get('user_id')
tier = session.get('tier', 'guest')
username = session.get('username')
# Get crawl count
crawls_today = 0
if tier == 'guest':
# For guests, count from IP address
client_ip = get_client_ip()
crawls_today = get_guest_crawls_last_24h(client_ip)
else:
# For registered users, count from database
crawls_today = get_crawls_last_24h(user_id)
return jsonify({
'success': True,
'user': {
'id': user_id,
'username': username,
'tier': tier,
'crawls_today': crawls_today,
'crawls_remaining': max(0, 3 - crawls_today) if tier == 'guest' else -1
}
})
@app.route('/')
def index():
# In local mode, auto-login if not already logged in
if LOCAL_MODE and 'user_id' not in session:
auto_login_local_mode()
elif 'user_id' not in session:
# Not in local mode and not logged in, redirect to login
return redirect(url_for('login_page'))
return render_template('index.html')
@app.route('/dashboard')
@login_required
def dashboard():
"""Crawl history dashboard"""
return render_template('dashboard.html')
@app.route('/debug/memory')
@login_required
def debug_memory_page():
"""Debug page with nice UI for memory monitoring"""
return render_template('debug_memory.html')
@app.route('/api/start_crawl', methods=['POST'])
@login_required
def start_crawl():
from src.auth_db import get_crawls_last_24h, log_crawl_start
data = request.get_json()
url = data.get('url')
if not url:
return jsonify({'success': False, 'error': 'URL is required'})
user_id = session.get('user_id')
tier = session.get('tier', 'guest')
# Check guest limits (IP-based) - skip in local mode
if tier == 'guest' and not LOCAL_MODE:
client_ip = get_client_ip()
crawls_from_ip = get_guest_crawls_last_24h(client_ip)
if crawls_from_ip >= 3:
return jsonify({
'success': False,
'error': 'Guest limit reached: 3 crawls per 24 hours from your IP address. Please register for unlimited crawls.'
})
# Log this guest crawl
log_guest_crawl(client_ip)
# Get or create crawler for this session (this also ensures the session
# has a session_id — reading it earlier would return None on a session
# whose first API call is start_crawl, silently disabling persistence)
crawler = get_or_create_crawler()
settings_manager = get_session_settings()
session_id = session.get('session_id')
# Apply current settings to crawler before starting
try:
crawler_config = settings_manager.get_crawler_config()
crawler.update_config(crawler_config)
except Exception as e:
print(f"Warning: Could not apply settings: {e}")
# Enforce demo mode limits
if DEMO_MODE:
crawler.config['demo_mode'] = True
crawler.config['demo_memory_limit_bytes'] = int(1.5 * 1024 * 1024 * 1024) # 1.5GB
# Pass user_id and session_id for database persistence
success, message = crawler.start_crawl(url, user_id=user_id, session_id=session_id)
# Store crawl_id in session
if success and crawler.crawl_id:
session['current_crawl_id'] = crawler.crawl_id
# Also log to old crawl_history for compatibility
log_crawl_start(user_id, url)
return jsonify({'success': success, 'message': message, 'crawl_id': crawler.crawl_id})
@app.route('/api/stop_crawl', methods=['POST'])
@login_required
def stop_crawl():
crawler = get_or_create_crawler()
success, message = crawler.stop_crawl()
return jsonify({'success': success, 'message': message})
@app.route('/api/crawl_status')
@login_required
def crawl_status():
crawler = get_or_create_crawler()
settings_manager = get_session_settings()
# Lightweight probe: status + stats only, no data (export pre-checks etc.)
if request.args.get('stats_only'):
status_data = crawler.get_status_light()
if crawler.base_url:
status_data['stats']['baseUrl'] = crawler.base_url
return jsonify(status_data)
since_seq = request.args.get('since_seq', type=int)
if since_seq is None:
# Full snapshot (initial page load, save-crawl fetch)
status_data = crawler.get_status()
if crawler.base_url:
status_data['stats']['baseUrl'] = crawler.base_url
exclusion_patterns = get_exclusion_patterns(settings_manager)
status_data['issues'] = filter_issues_by_exclusion_patterns(
status_data.get('issues', []), exclusion_patterns)
return jsonify(status_data)
# Event mode: everything that changed after since_seq. If the client's
# epoch is stale (new crawl / loaded crawl / resume), reset=True and the
# events replay from zero so the client rebuilds its state.
#
# Events are read before the stats snapshot on purpose: a crawl running
# between the two calls should make the counters look newer than the rows,
# never older, so the UI never shows fewer crawled URLs than it lists.
epoch = request.args.get('epoch', '')
reset, events, latest_seq, current_epoch = crawler.event_log.events_since(since_seq, epoch)
status_data = crawler.get_status_light()
if crawler.base_url:
status_data['stats']['baseUrl'] = crawler.base_url
exclusion_patterns = get_exclusion_patterns(settings_manager)
if exclusion_patterns:
events = [ev for ev in events
if ev['kind'] != 'issue' or not issue_matches_exclusion(ev['data'], exclusion_patterns)]
status_data.update({
'reset': reset,
'epoch': current_epoch,
'latest_seq': latest_seq,
'events': events
})
return jsonify(status_data)
@app.route('/api/visualization_data')
@login_required
def visualization_data():
"""Get graph data for site structure visualization"""
try:
crawler = get_or_create_crawler()
status_data = crawler.get_status()
# Get URLs from the status data
crawled_pages = status_data.get('urls', [])
all_links = status_data.get('links', [])
# Build nodes and edges for the graph
nodes = []
edges = []
url_to_id = {}
# Create nodes from crawled pages (limit to prevent lag)
max_nodes = 500 # Optimization: limit nodes for performance
pages_to_visualize = crawled_pages[:max_nodes]
for idx, page in enumerate(pages_to_visualize):
url = page.get('url', '')
status_code = page.get('status_code', 0)
# Assign color based on status code
if 200 <= status_code < 300:
color = '#10b981' # Green for 2xx
elif 300 <= status_code < 400:
color = '#3b82f6' # Blue for 3xx
elif 400 <= status_code < 500:
color = '#f59e0b' # Orange for 4xx
elif 500 <= status_code < 600:
color = '#ef4444' # Red for 5xx
else:
color = '#6b7280' # Gray for other
# Create node
node = {
'data': {
'id': f'node-{idx}',
'label': url.split('/')[-1] or url.split('//')[-1], # Use last path segment or domain
'url': url,
'status_code': status_code,
'title': page.get('title', ''),
'color': color,
'size': 30 if idx == 0 else 20, # Make root node larger
'depth': page.get('depth', 0)
}
}
nodes.append(node)
url_to_id[url] = f'node-{idx}'
# Create edges from links data
# Links are stored as: {'source_url': url, 'target_url': url, 'is_internal': bool, ...}
edges_set = set() # Use set to avoid duplicate edges
for link in all_links:
if link.get('is_internal'): # Only use internal links
source_url = link.get('source_url', '')
target_url = link.get('target_url', '')
source_id = url_to_id.get(source_url)
target_id = url_to_id.get(target_url)
if source_id and target_id and source_id != target_id:
edge_key = f'{source_id}-{target_id}'
if edge_key not in edges_set:
edges_set.add(edge_key)
edge = {
'data': {
'id': f'edge-{edge_key}',
'source': source_id,
'target': target_id
}
}
edges.append(edge)
return jsonify({
'success': True,
'nodes': nodes,
'edges': edges,
'total_pages': len(crawled_pages),
'visualized_pages': len(nodes),
'truncated': len(crawled_pages) > max_nodes
})
except Exception as e:
print(f"Error generating visualization data: {e}")
import traceback
traceback.print_exc()
return jsonify({
'success': False,
'error': str(e),
'nodes': [],
'edges': []
})
@app.route('/api/debug/memory')
@login_required
def debug_memory():
"""Debug endpoint showing memory stats for all active crawler instances"""
with instances_lock:
memory_stats = {
'total_instances': len(crawler_instances),
'instances': []