-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.py
More file actions
3938 lines (3476 loc) · 151 KB
/
Copy pathapi.py
File metadata and controls
3938 lines (3476 loc) · 151 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
# SPDX-License-Identifier: MIT
# Copyright (c) 2026 Toske-Programer (Web Security Scanner contributors)
"""
Security Scanner API
FastAPI backend — run with: uvicorn api:app --host 0.0.0.0 --port 8000
"""
import os
# ============================================================
# FIX: PostgreSQL sets OPENSSL_CONF which breaks requests SSL
# Must be cleared BEFORE any import of requests/ssl/httpx
#
# CURL_CA_BUNDLE is added because PostgreSQL 17 on Windows points it
# at a non-existent path that pip / requests / urllib3 will try to
# use before falling back to certifi. See:
# https://github.com/psf/requests/blob/main/src/requests/sessions.py
# (DEFAULT_CA_BUNDLE_PATH resolution order).
# ============================================================
os.environ.pop("OPENSSL_CONF", None)
os.environ.pop("SSL_CERT_FILE", None)
os.environ.pop("REQUESTS_CA_BUNDLE", None)
os.environ.pop("CURL_CA_BUNDLE", None)
try:
import certifi
os.environ["REQUESTS_CA_BUNDLE"] = certifi.where()
os.environ["SSL_CERT_FILE"] = certifi.where()
except ImportError:
pass
import uuid
import time
import threading
from collections import defaultdict
from datetime import datetime
from typing import Dict, Any, List, Optional
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.gzip import GZipMiddleware
from fastapi.responses import JSONResponse, FileResponse
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel, HttpUrl, field_validator
import re
import requests
import scanner
import malware_scanner
from malware_scanner import config as malware_config
import db
import verification
import subscription
import secrets as _secrets
from security_utils import is_safe_target
# Public defaults — can be overridden via env vars if we ever need to tune
# rate limits per environment without code changes.
_RATE_LIMIT = int(os.environ.get("RATE_LIMIT_MAX", "2"))
_RATE_WINDOW = int(os.environ.get("RATE_LIMIT_WINDOW_SECONDS", "7200"))
app = FastAPI(
title="Web Security Scanner API",
description="Passive security analysis for websites — no exploitation, read-only.",
version="1.0.0",
)
app.add_middleware(GZipMiddleware, minimum_size=500)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["GET", "POST"],
allow_headers=["*"],
)
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.requests import Request
class SecurityHeadersMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next):
response = await call_next(request)
response.headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains"
# CSP: use WILDCARD host patterns for the Google advertising stack
# rather than listing individual subdomains. AdSense uses many
# subdomains (pagead2, tpc, ep1, ep2, googleads, securepubads,
# stats, pubads, etc.) and maintaining an explicit list is a
# losing game — every few months Google adds a new one and we
# get CSP violations in user devtools.
#
# The wildcards cover:
# *.googlesyndication.com — pagead2, tpc, securepubads, etc.
# *.g.doubleclick.net — googleads, stats, pubads, securepubads
# *.adtrafficquality.google — ep1, ep2 (ad quality sandbox)
#
# Non-ad Google endpoints (fonts, analytics, tag services) stay
# explicit so we can see exactly which capabilities we allow.
#
# script-src MUST include *.adtrafficquality.google because
# AdSense loads sodar2.js from ep2.adtrafficquality.google for
# quality verification; without it, the ad request returns 403.
response.headers["Content-Security-Policy"] = (
"default-src 'self'; "
"script-src 'self' 'unsafe-inline' "
"https://fonts.googleapis.com https://www.gstatic.com "
"https://*.googlesyndication.com https://*.g.doubleclick.net "
"https://*.adtrafficquality.google "
"https://www.googletagservices.com https://www.googletagmanager.com "
"https://adservice.google.com https://fundingchoicesmessages.google.com; "
"style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; "
"font-src https://fonts.gstatic.com; "
"img-src 'self' data: https:; "
"connect-src 'self' https://unlimitededition-web-security-scanner.hf.space "
"https://api.ipify.org https://api64.ipify.org https://icanhazip.com "
"https://*.googlesyndication.com https://*.g.doubleclick.net "
"https://*.adtrafficquality.google "
# Funding Choices (Google consent framework) fetches
# /el/... endpoints from fundingchoicesmessages — needs
# both script-src (script load) AND connect-src (fetch).
"https://fundingchoicesmessages.google.com "
"https://www.google.com https://www.googletagservices.com "
"https://www.googletagmanager.com https://csi.gstatic.com; "
"frame-src https://*.googlesyndication.com https://*.g.doubleclick.net "
"https://*.adtrafficquality.google https://www.google.com; "
"frame-ancestors 'self' https://huggingface.co https://*.hf.space"
)
response.headers["X-Frame-Options"] = "ALLOW-FROM https://huggingface.co"
response.headers["X-Content-Type-Options"] = "nosniff"
response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
response.headers["Permissions-Policy"] = "camera=(), microphone=(), geolocation=()"
response.headers["Cross-Origin-Opener-Policy"] = "same-origin"
if "server" in response.headers:
del response.headers["server"]
if "x-powered-by" in response.headers:
del response.headers["x-powered-by"]
return response
app.add_middleware(SecurityHeadersMiddleware)
# ── SSRF audit logging for Pydantic validation errors ────────────────
# Pydantic validators run before the handler, so SSRF blocks from
# is_safe_target() surface as 422 ValidationError. We intercept these
# to log scan_blocked_ssrf events with the caller's IP.
from fastapi.exceptions import RequestValidationError
from starlette.responses import JSONResponse
@app.exception_handler(RequestValidationError)
async def _validation_error_handler(request: Request, exc: RequestValidationError):
# Check if any error message contains our SSRF marker
ssrf_markers = ("Target not allowed", "nije dozvoljena")
is_ssrf = any(
any(m in str(e.get("msg", "")) for m in ssrf_markers)
for e in exc.errors()
)
if is_ssrf:
client_ip = _client_ip(request)
user_agent = request.headers.get("user-agent", "")[:500] or None
url_value = None
try:
body = await request.json()
url_value = body.get("url", "")[:200]
except Exception:
pass
db.log_audit_event(
event="scan_blocked_ssrf",
ip=client_ip, ua=user_agent,
details={"url": url_value, "errors": [str(e) for e in exc.errors()[:3]]},
)
return JSONResponse(
status_code=422,
content={"detail": exc.errors()},
)
# In-memory scan cache — fast path for the hot /scan/{id} polling loop.
# The authoritative copy of each scan lives in the Supabase `scans` table
# when db.is_configured(). Cache misses fall back to db.get_scan_from_db().
scans: Dict[str, Dict[str, Any]] = {}
# In-memory rate-limit backstop. db.check_rate_limit() is the primary
# enforcement point when the DB is reachable; _rate_store only kicks in
# if the DB is not configured or a write fails.
_rate_store: Dict[str, list] = defaultdict(list)
# Queue system: max 1 concurrent scan
_scan_queue: list = []
_active_scans: set = set() # Track multiple concurrent scans
_MAX_CONCURRENT = 8
# Pending activations — maps activation_token → license_key.
# Populated by webhook handler, consumed by frontend polling.
# TTL: entries older than 30 min are evicted on read.
_pending_activations: Dict[str, Dict[str, Any]] = {}
_ACTIVATION_TTL_S = 1800
def _on_license_key_ready(activation_token: str, license_key: str) -> None:
_pending_activations[activation_token] = {
"license_key": license_key,
"ts": time.time(),
}
subscription.set_activation_callback(_on_license_key_ready)
def _check_rate_limit_in_memory(ip: str) -> bool:
"""
Legacy sliding-window limiter — kept as a fallback when the DB is
unreachable. Not used as the primary path when db.is_configured().
"""
now = time.time()
_rate_store[ip] = [t for t in _rate_store[ip] if now - t < _RATE_WINDOW]
if len(_rate_store[ip]) >= _RATE_LIMIT:
return False
_rate_store[ip].append(now)
return True
def _check_rate_limit(ip: str) -> bool:
"""
Primary rate-limit gate. Consults the DB first (db.check_rate_limit);
if the DB path returns "fail-open" (None) or raises, falls back to
the in-memory limiter so a DB outage can't both lose persistence AND
disable the rate limit entirely.
"""
if db.is_configured():
allowed, _count = db.check_rate_limit(
ip=ip, max_count=_RATE_LIMIT, window_seconds=_RATE_WINDOW
)
if not allowed:
return False
# Still run the in-memory limiter as a belt-and-suspenders check.
return _check_rate_limit_in_memory(ip)
return _check_rate_limit_in_memory(ip)
def _make_progress_cb(scan_id: str, _unused: float = 0.0):
"""
Returns a progress callback closure that updates the in-memory cache
on every tick but only writes to the DB when progress crosses a 10%
threshold. This keeps DB write volume bounded to ~10 writes per scan
instead of ~100+.
Ad-blocker throttle: reads scans[scan_id]["ad_blocked"] on every tick
so if the user disables their blocker mid-scan, it speeds up immediately.
"""
last_db_pct = [0] # mutable closure holder
def cb(step: str, pct: int):
# Live throttle check — reads current state, not initial
if scans.get(scan_id, {}).get("ad_blocked"):
import time
time.sleep(8.0)
scans[scan_id]["step"] = step
scans[scan_id]["progress"] = pct
# Debounced DB write: only on 10% thresholds
if db.is_configured() and pct - last_db_pct[0] >= 10:
last_db_pct[0] = pct
db.update_scan_progress(scan_id, pct, step)
return cb
def _run_scan_inline(
scan_id: str,
url: str,
client_ip: str,
user_agent: Optional[str],
max_pages: int = 1,
preselected_pages: Optional[List[str]] = None,
mode: str = "safe",
scan_request_id: Optional[str] = None,
ad_blocked: bool = False,
strictness: str = scanner.DEFAULT_STRICTNESS,
):
"""
Executes a single scan. Shared between the "start immediately" path
in /scan and the "pull from queue" path in _process_queue, so both
share identical DB + audit-log semantics.
max_pages controls the Pro multi-page pass in scanner.scan():
- 1 (default): free tier behaviour, homepage only
- up to 10: Pro tier, scanner.py will loop page-level checks on
each additional page discovered by the crawler
preselected_pages, if provided, is a list of URLs the user already
picked via the discovery flow. scanner.scan() will skip its internal
crawler and scan exactly this list.
mode (gate-before-scan model from migrations 014/015):
- 'safe' (default): only the SAFE / SAFE+REDACTED checks run.
scanner.py refuses to send any probe to private surface
(no /.env, /wp-admin/, port scan, vuln scan, GraphQL
introspection, etc.). The 3 SAFE+REDACTED checks
(disclosure, js, jwt) emit sumary-only findings.
- 'full': every check runs at full fidelity. Only allowed
when the scan was authorized through the wizard flow
(POST /scan/request → consent → verify → execute) and the
caller's IP hash is recorded in verified_domains for the
target domain. The /scan/request/{id}/execute endpoint
is the only path that should pass mode='full'.
scan_request_id, if provided, links this scan back to the
scan_requests row that authorized it. Used to mark the wizard
state machine as 'completed' once the scanner finishes.
"""
# Ad-blocker throttle: if the user is blocking ads, we slow down
# the scan by injecting delays between progress updates. Total scan
# time stretches from ~90s to ~300s (5 minutes). This is server-side
# so the user cannot bypass it by editing frontend code.
# Store ad_blocked in scan dict so it can be updated mid-scan
# when the user disables their ad blocker during polling
scans[scan_id]["ad_blocked"] = ad_blocked
# Transition to running (both in-memory and DB)
scans[scan_id]["status"] = "running"
scans[scan_id]["step"] = "Pokretanje skeniranja..."
db.mark_scan_running(scan_id)
db.log_audit_event(
event="scan_start",
ip=client_ip,
ua=user_agent,
scan_id=scan_id,
domain=scans[scan_id].get("domain"),
session_id=scans[scan_id].get("session_id"),
fingerprint_hash=scans[scan_id].get("fingerprint_hash"),
details={"mode": mode, "scan_request_id": scan_request_id, "strictness": strictness},
)
progress_cb = _make_progress_cb(scan_id)
try:
result = scanner.scan(
url,
progress_callback=progress_cb,
max_pages=max_pages,
preselected_pages=preselected_pages,
mode=mode,
strictness=strictness,
)
scans[scan_id]["status"] = "completed"
scans[scan_id]["progress"] = 100
scans[scan_id]["result"] = result
db.mark_scan_completed(scan_id, result)
# If this scan was authorized through the wizard flow, flip the
# scan_requests row from 'executing' to 'completed'. Best-effort:
# a DB outage here doesn't fail the scan, but it does mean the
# wizard row will sit in 'executing' until the next reconciliation
# (no functional impact — the user already has results).
if scan_request_id:
db.mark_scan_request_completed(scan_request_id)
# Detect deadline truncation from scanner.py's errors list
errors = (result or {}).get("errors") or []
truncated = any("vremenski limit" in (e or "").lower() or "prekoracio" in (e or "").lower() for e in errors)
_sid = scans[scan_id].get("session_id")
_fph = scans[scan_id].get("fingerprint_hash")
if truncated:
db.log_audit_event(
event="scan_truncated_deadline",
ip=client_ip, ua=user_agent,
scan_id=scan_id, domain=scans[scan_id].get("domain"),
session_id=_sid, fingerprint_hash=_fph,
details={"errors": errors[:5]},
)
db.log_audit_event(
event="scan_complete",
ip=client_ip, ua=user_agent,
scan_id=scan_id, domain=scans[scan_id].get("domain"),
session_id=_sid, fingerprint_hash=_fph,
details={"score": (result or {}).get("score"), "truncated": truncated},
)
except Exception as e:
msg = str(e)[:200]
scans[scan_id]["status"] = "error"
scans[scan_id]["error"] = msg
db.mark_scan_error(scan_id, msg)
db.log_audit_event(
event="scan_error",
ip=client_ip, ua=user_agent,
scan_id=scan_id, domain=scans[scan_id].get("domain"),
session_id=scans[scan_id].get("session_id"),
fingerprint_hash=scans[scan_id].get("fingerprint_hash"),
details={"error": msg},
)
finally:
_active_scans.discard(scan_id)
_process_queue()
def _process_queue():
"""Process queued scans up to _MAX_CONCURRENT slots."""
# Clean up finished scans from active set
finished = {sid for sid in _active_scans
if sid in scans and scans[sid]["status"] in ("completed", "error")}
_active_scans.difference_update(finished)
# Fill available slots
while len(_active_scans) < _MAX_CONCURRENT and _scan_queue:
scan_id = _scan_queue.pop(0)
scan = scans.get(scan_id)
if not scan:
continue
_active_scans.add(scan_id)
thread = threading.Thread(
target=_run_scan_inline,
args=(
scan_id,
scan["url"],
scan.get("client_ip", "unknown"),
scan.get("user_agent"),
int(scan.get("max_pages") or 1),
scan.get("preselected_pages"),
scan.get("mode", "safe"),
scan.get("scan_request_id"),
bool(scan.get("ad_blocked")),
scan.get("strictness") or scanner.DEFAULT_STRICTNESS,
),
daemon=True,
)
thread.start()
class ScanRequest(BaseModel):
url: str
# Consent is optional for backward compat with the current frontend.
# When the frontend is updated to send the checkbox state + version,
# we can tighten this to `consent_accepted: bool` (no default) and
# reject non-consenting scans at the pydantic layer.
consent_accepted: bool = False
consent_version: Optional[str] = None
session_id: Optional[str] = None
fingerprint_hash: Optional[str] = None
ad_blocked: bool = False
# Pro two-phase flow: frontend calls POST /api/discover first to get
# a list of pages, user ticks up to 10, frontend sends them back in
# this field. When present and caller is Pro, the scanner skips its
# internal crawler and scans exactly these URLs.
selected_pages: Optional[List[str]] = None
# Gate-before-scan model (migrations 014/015). When the frontend
# hits POST /scan directly (the legacy / "Brzi javni sken" path),
# mode is forced to 'safe' regardless of what the body says — full
# mode requires going through POST /scan/request → wizard → execute,
# which is the only place a server-side full mode flag gets set.
# Including the field in this model allows the legacy endpoint to
# accept and ignore it without raising a validation error.
mode: Optional[str] = None
# V4 strictness profile. Whitelisted against STRICTNESS_PROFILES in
# scanner.py. Unknown or missing values fall back to scanner's
# DEFAULT_STRICTNESS ("standard"), which replicates V3 scoring exactly.
strictness: Optional[str] = None
@field_validator("strictness")
@classmethod
def validate_strictness(cls, v: Optional[str]) -> Optional[str]:
if v is None:
return None
v = v.strip().lower()
if v not in scanner.STRICTNESS_PROFILES:
raise ValueError(
"Neispravna strogost. Dozvoljeno: "
+ ", ".join(scanner.STRICTNESS_PROFILES.keys())
)
return v
@field_validator("url")
@classmethod
def validate_url(cls, v: str) -> str:
v = v.strip()
if not v:
raise ValueError("URL ne sme biti prazan.")
# Add https:// if missing
if not v.startswith(("http://", "https://")):
v = "https://" + v
# Basic domain check
domain_pattern = r'^https?://[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}'
if not re.match(domain_pattern, v):
raise ValueError("Neispravan URL format.")
# SSRF protection: resolve DNS, block private/reserved ranges,
# loopback, link-local (AWS metadata), IPv6 ULA, etc.
# This runs again inside safe_get() for every redirect hop.
safe, reason = is_safe_target(v)
if not safe:
raise ValueError(
"Ciljna adresa nije dozvoljena (interna, privatna ili "
f"nerazrešiva). / Target not allowed: {reason}"
)
return v
@app.api_route("/", methods=["GET", "HEAD"])
@app.api_route("/index.html", methods=["GET", "HEAD"])
def root():
index_path = os.path.join(os.path.dirname(__file__), "index.html")
if os.path.exists(index_path):
return FileResponse(index_path, media_type="text/html")
return {"status": "ok", "service": "Web Security Scanner"}
@app.api_route("/privacy.html", methods=["GET", "HEAD"])
def privacy():
path = os.path.join(os.path.dirname(__file__), "privacy.html")
if os.path.exists(path):
return FileResponse(path, media_type="text/html")
@app.api_route("/terms.html", methods=["GET", "HEAD"])
def terms():
path = os.path.join(os.path.dirname(__file__), "terms.html")
if os.path.exists(path):
return FileResponse(path, media_type="text/html")
@app.api_route("/abuse-report.html", methods=["GET", "HEAD"])
def abuse_report_page():
"""Dedicated abuse-report page (form + FAQ + process explanation)."""
path = os.path.join(os.path.dirname(__file__), "abuse-report.html")
if os.path.exists(path):
return FileResponse(path, media_type="text/html")
@app.api_route("/refund-policy.html", methods=["GET", "HEAD"])
def refund_policy_page():
"""Dedicated refund policy page (Pro plan refund terms)."""
path = os.path.join(os.path.dirname(__file__), "refund-policy.html")
if os.path.exists(path):
return FileResponse(path, media_type="text/html")
@app.api_route("/user-rights.html", methods=["GET", "HEAD"])
def user_rights_page():
"""Dedicated user rights page (GDPR rights specific to this service)."""
path = os.path.join(os.path.dirname(__file__), "user-rights.html")
if os.path.exists(path):
return FileResponse(path, media_type="text/html")
@app.api_route("/pricing.html", methods=["GET", "HEAD"])
def pricing_page():
"""Dedicated pricing page (Pro plan feature comparison, buy buttons, FAQ)."""
path = os.path.join(os.path.dirname(__file__), "pricing.html")
if os.path.exists(path):
return FileResponse(path, media_type="text/html")
@app.api_route("/account.html", methods=["GET", "HEAD"])
def account_page():
"""Pro account page — subscription info + scan history. Client-side
access control: the page loads for anyone, but its JS fetches
/api/subscription/me and redirects free-tier visitors back to /pricing."""
path = os.path.join(os.path.dirname(__file__), "account.html")
if os.path.exists(path):
return FileResponse(path, media_type="text/html")
@app.api_route("/404.html", methods=["GET", "HEAD"])
def not_found_page():
"""Explicit route for the branded 404 page (also served by the exception
handler below for any unknown route requested with an HTML Accept header)."""
path = os.path.join(os.path.dirname(__file__), "404.html")
if os.path.exists(path):
return FileResponse(path, media_type="text/html", status_code=404)
@app.exception_handler(404)
async def custom_404_handler(request: Request, exc):
"""
Return the branded 404.html for browser requests, JSON for API clients.
The Accept header is the signal: if the caller wants HTML (browser
navigation, search engine crawler), we serve the styled error page.
API clients (curl, monitoring, the frontend's fetch() calls) get the
default JSON shape with a 'detail' field — same as before this
handler existed, so we don't break any existing code path.
"""
accept = (request.headers.get("accept") or "").lower()
if "text/html" in accept:
path = os.path.join(os.path.dirname(__file__), "404.html")
if os.path.exists(path):
return FileResponse(path, media_type="text/html", status_code=404)
return JSONResponse(
status_code=404,
content={"detail": getattr(exc, "detail", "Not found")},
)
@app.api_route("/blog-common.css", methods=["GET", "HEAD"])
def blog_common_css():
path = os.path.join(os.path.dirname(__file__), "blog-common.css")
if os.path.exists(path):
return FileResponse(path, media_type="text/css")
raise HTTPException(status_code=404, detail="File not found")
@app.api_route("/blog-common.js", methods=["GET", "HEAD"])
def blog_common_js():
path = os.path.join(os.path.dirname(__file__), "blog-common.js")
if os.path.exists(path):
return FileResponse(path, media_type="application/javascript")
raise HTTPException(status_code=404, detail="File not found")
@app.api_route("/cookie-consent.js", methods=["GET", "HEAD"])
def cookie_consent_js():
"""GDPR cookie consent script shared across all pages."""
path = os.path.join(os.path.dirname(__file__), "cookie-consent.js")
if os.path.exists(path):
return FileResponse(path, media_type="application/javascript")
raise HTTPException(status_code=404, detail="File not found")
@app.api_route("/status.html", methods=["GET", "HEAD"])
def status_page():
"""System status page — real-time health of frontend, backend, database."""
path = os.path.join(os.path.dirname(__file__), "status.html")
if os.path.exists(path):
return FileResponse(path, media_type="text/html")
raise HTTPException(status_code=404, detail="File not found")
@app.api_route("/data-protection-badge.png", methods=["GET", "HEAD"])
def data_protection_badge():
"""Data protection trust badge image."""
path = os.path.join(os.path.dirname(__file__), "data-protection-badge.png")
if os.path.exists(path):
return FileResponse(path, media_type="image/png")
raise HTTPException(status_code=404, detail="File not found")
@app.api_route("/blog-{page}.html", methods=["GET", "HEAD"])
def blog_page(page: str):
path = os.path.join(os.path.dirname(__file__), f"blog-{page}.html")
if os.path.exists(path):
return FileResponse(path, media_type="text/html")
raise HTTPException(status_code=404, detail="Page not found")
# NOTE: these static-file routes use api_route(methods=["GET","HEAD"])
# instead of @app.get(...) because Google's AdSense crawler (and
# other web crawlers like Googlebot, Search Console verifier, Bing,
# etc.) do a HEAD request BEFORE a GET to check file existence and
# size. FastAPI's @app.get decorator only binds GET, so HEAD returned
# 405 Method Not Allowed — the crawler interprets that as "file does
# not exist" and refuses to validate ads.txt / robots.txt / the
# verification files. That was blocking multiple integrations silently.
@app.api_route("/google739403949172c6ee.html", methods=["GET", "HEAD"])
def google_verify():
path = os.path.join(os.path.dirname(__file__), "google739403949172c6ee.html")
if os.path.exists(path):
return FileResponse(path, media_type="text/html")
@app.api_route("/google6b954a0930cdbbcc.html", methods=["GET", "HEAD"])
def google_verify2():
path = os.path.join(os.path.dirname(__file__), "google6b954a0930cdbbcc.html")
if os.path.exists(path):
return FileResponse(path, media_type="text/html")
@app.api_route("/ads.txt", methods=["GET", "HEAD"])
def ads_txt():
path = os.path.join(os.path.dirname(__file__), "ads.txt")
if os.path.exists(path):
return FileResponse(path, media_type="text/plain")
@app.api_route("/robots.txt", methods=["GET", "HEAD"])
def robots():
path = os.path.join(os.path.dirname(__file__), "robots.txt")
if os.path.exists(path):
return FileResponse(path, media_type="text/plain")
@app.api_route("/sitemap.xml", methods=["GET", "HEAD"])
def sitemap():
path = os.path.join(os.path.dirname(__file__), "sitemap.xml")
if os.path.exists(path):
return FileResponse(path, media_type="application/xml")
@app.api_route("/.well-known/security.txt", methods=["GET", "HEAD"])
def security_txt():
path = os.path.join(os.path.dirname(__file__), ".well-known", "security.txt")
if os.path.exists(path):
return FileResponse(path, media_type="text/plain")
# ═══════════════════════════════════════════════════════════════════════
# Abuse reports — Function 3
# ═══════════════════════════════════════════════════════════════════════
# When a site owner sees their domain in our scan logs (e.g. via a bot
# crawling the results page, or via Cloudflare alert firing on our scan
# UA), they need a way to say "stop". This endpoint is that channel.
#
# The submitted report lands in `abuse_reports` with status='open'.
# The operator triages reports through the Supabase dashboard and
# manually transitions them to 'reviewed' → 'confirmed' or 'dismissed'.
# Confirmed reports block any future scans of the reported domain via
# `is_domain_blocked()` checked in /scan.
#
# When the reporter cites specific scan_ids, we flag the corresponding
# audit_log rows to exempt them from 90-day pruning. They then persist
# as legal evidence for as long as the operator needs them.
#
# There's no rate limit specifically for abuse reports separate from
# the global /scan rate limit, because legitimate reporters won't
# submit hundreds of reports. Malicious floods would show up in the
# audit log under abuse_report_submitted and can be handled manually.
# Maximum length for free-text fields (chars). DB column is TEXT but
# we guard at the API layer too to prevent trivial storage blowup.
MAX_REPORT_DESCRIPTION = 4000
MAX_REPORT_EMAIL = 320 # RFC 5321 max practical length
MAX_RELATED_SCAN_IDS = 20
class AbuseReport(BaseModel):
reported_domain: str
description: str
reporter_email: Optional[str] = None
related_scan_ids: Optional[list] = None
@field_validator("reported_domain")
@classmethod
def validate_domain(cls, v: str) -> str:
normalized = verification.normalize_domain(v)
if not normalized:
raise ValueError("Neispravan format domena.")
return normalized
@field_validator("description")
@classmethod
def validate_description(cls, v: str) -> str:
v = (v or "").strip()
if len(v) < 10:
raise ValueError("Opis prijave mora imati bar 10 karaktera.")
if len(v) > MAX_REPORT_DESCRIPTION:
raise ValueError(f"Opis ne sme biti duzi od {MAX_REPORT_DESCRIPTION} karaktera.")
return v
@field_validator("reporter_email")
@classmethod
def validate_email(cls, v: Optional[str]) -> Optional[str]:
if v is None or v.strip() == "":
return None
v = v.strip()
if len(v) > MAX_REPORT_EMAIL:
raise ValueError(f"Email predug (max {MAX_REPORT_EMAIL}).")
# Minimal sanity check — not a full RFC validator, just "looks
# like an email". If the operator needs to contact back, they'll
# notice if it's broken.
if not re.match(r"^[^@\s]+@[^@\s]+\.[^@\s]+$", v):
raise ValueError("Email nije u ispravnom formatu.")
return v
@field_validator("related_scan_ids")
@classmethod
def validate_scan_ids(cls, v: Optional[list]) -> Optional[list]:
if not v:
return None
if len(v) > MAX_RELATED_SCAN_IDS:
raise ValueError(f"Najvise {MAX_RELATED_SCAN_IDS} scan ID-jeva po prijavi.")
# scan_ids are 8-char hex from uuid4[:8]
cleaned = []
for sid in v:
if not isinstance(sid, str):
raise ValueError("scan_ids mora biti lista stringova.")
sid = sid.strip()
if not re.match(r"^[a-f0-9]{8}$", sid):
raise ValueError(f"Neispravan scan_id format: {sid[:12]}")
cleaned.append(sid)
return cleaned
@app.post("/abuse-report")
def abuse_report_endpoint(req: AbuseReport, request: Request):
"""
Accept an abuse report from a site owner. Creates an abuse_reports
row with status='open', flags any cited scan_ids' audit_log rows
for legal retention, and emits an audit event.
"""
reporter_ip = _client_ip(request)
user_agent = request.headers.get("user-agent", "")[:500] or None
# Global rate limit applies — same check as /scan to prevent a
# single IP from flooding the abuse queue
if not _check_rate_limit(reporter_ip):
db.log_audit_event(
event="scan_blocked_rate_limit",
ip=reporter_ip, ua=user_agent,
details={
"endpoint": "/abuse-report",
"reported_domain": req.reported_domain,
},
)
raise HTTPException(
status_code=429,
detail="Previse zahteva. Pokusajte ponovo za nekoliko minuta.",
)
row = db.create_abuse_report(
reported_domain=req.reported_domain,
description=req.description,
reporter_ip=reporter_ip,
reporter_email=req.reporter_email,
related_scan_ids=req.related_scan_ids,
)
# Flag any cited scans' audit_log rows for legal-hold retention
flagged_count = 0
if req.related_scan_ids:
flagged_count = db.flag_audit_rows_for_scans(req.related_scan_ids)
db.log_audit_event(
event="abuse_report_submitted",
ip=reporter_ip, ua=user_agent, domain=req.reported_domain,
details={
"report_id": (row or {}).get("id"),
"has_email": bool(req.reporter_email),
"related_scan_count": len(req.related_scan_ids or []),
"audit_rows_flagged": flagged_count,
},
)
return {
"ok": True,
"report_id": (row or {}).get("id"),
"reported_domain": req.reported_domain,
"status": "open",
"message": (
"Prijava je primljena i bice pregledana u roku od 72 sata. "
"Ako ste ostavili email, kontaktiracemo vas sa ishodom."
),
}
# ═══════════════════════════════════════════════════════════════════════
# Function 6 — ownership verification
# ═══════════════════════════════════════════════════════════════════════
# Before a user can see the full scan findings (URLs of exposed files,
# admin paths, payload hints, etc.), they must prove they control the
# domain. Three methods are supported: meta tag on homepage, file at
# /.well-known/scanner-verify.txt, or a DNS TXT record. Any one is
# sufficient. Successful verification binds the domain to the requester's
# IP hash for 30 days in the `verified_domains` table. Unverified scans
# still run and still store full results in the DB — only the GET
# endpoint redacts sensitive fields before returning them.
# Cap on verification attempts per token before we kill it, to prevent
# an attacker from brute-forcing the meta tag / file path of a domain
# they don't control by iterating through many scan tokens.
MAX_VERIFY_ATTEMPTS = 5
# Check-id prefixes whose findings expose specific attack surface
# (file locations, admin URLs, exploitable vulnerabilities, API
# endpoints, server fingerprints). These are hidden from unverified
# callers — the mere existence of a "file_env" finding tells an
# attacker there's a .env at /.env even if we scrub the description.
#
# Hardening-level findings (missing HSTS, weak SPF, SEO issues,
# accessibility gaps, etc.) stay visible because they describe
# *what's missing* rather than *where to attack*, and seeing them is
# the whole value of running the scan.
SENSITIVE_CHECK_PREFIXES = (
"file_", # exposed sensitive files — exact path is the exploit
"admin_", # discovered admin panels — exact URL is the login target
"vuln_", # actively detected vulnerabilities
"api_", # exposed API endpoints (GraphQL introspection, swagger, etc.)
"disc_", # information disclosure (server version, debug info, etc.)
)
REDACTION_PLACEHOLDER = (
"[Verifikujte vlasnistvo domena da vidite detalje. / "
"Verify domain ownership to see details.]"
)
def _is_sensitive_finding(finding: Dict[str, Any]) -> bool:
"""
True if this finding's check_id starts with any of the sensitive
prefixes. Unknown / missing IDs default to "not sensitive" — we
don't want a typo in the check catalog to accidentally mask a
hardening finding.
"""
fid = str(finding.get("id") or "").lower()
return any(fid.startswith(p) for p in SENSITIVE_CHECK_PREFIXES)
def _redact_finding(finding: Any) -> Any:
"""
For sensitive findings, return a stub that preserves the useful
public facts (severity, category, passed) but replaces all
human-readable fields with a placeholder. Non-sensitive findings
pass through unchanged so the user still sees their full
hardening report.
"""
if not isinstance(finding, dict):
return finding
if not _is_sensitive_finding(finding):
return finding
return {
"id": "redacted",
"category": finding.get("category", "Locked"),
"severity": finding.get("severity", "UNKNOWN"),
"passed": finding.get("passed", False),
"title": REDACTION_PLACEHOLDER,
"title_en": REDACTION_PLACEHOLDER,
"description": REDACTION_PLACEHOLDER,
"description_en": REDACTION_PLACEHOLDER,
"recommendation": REDACTION_PLACEHOLDER,
"recommendation_en": REDACTION_PLACEHOLDER,
"_was_redacted": True,
}
def _redact_result(result: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]:
"""
Returns a shallow copy of the scan result with sensitive findings
replaced by stubs. score, grade, counts, and errors are preserved
— those are the public summary a visitor is allowed to see.
Adds `_redacted_count` so the frontend can render a "N findings
hidden, verify to unlock" hint without re-scanning the list.
"""
if not isinstance(result, dict):
return result
redacted = dict(result)
findings = result.get("results")
redacted_count = 0
if isinstance(findings, list):
new_findings = []
for f in findings:
new_f = _redact_finding(f)
if isinstance(new_f, dict) and new_f.get("_was_redacted"):
redacted_count += 1
new_findings.append(new_f)
redacted["results"] = new_findings
redacted["_redacted"] = True
redacted["_redacted_count"] = redacted_count
redacted["_redaction_notice"] = (
"Specificni pronalazi vezani za izlozene fajlove, admin stranice, "
"ranjivosti, API endpoint-e i otkrivanje sistemskih informacija su "
"sakriveni dok ne verifikujete vlasnistvo domena. Koristite "
"POST /verify/request da pokrenete verifikaciju. "
"/ Specific findings related to exposed files, admin pages, "
"vulnerabilities, API endpoints and information disclosure are "
"hidden until you verify ownership of the domain. Use "
"POST /verify/request to start."
)
return redacted
class VerifyRequest(BaseModel):
domain: str
method: str # "meta" | "file" | "dns"
@field_validator("method")
@classmethod
def validate_method(cls, v: str) -> str:
if v not in ("meta", "file", "dns"):
raise ValueError("Metoda mora biti meta, file ili dns.")
return v
class VerifyCheckRequest(BaseModel):
token: str
@field_validator("token")
@classmethod
def validate_token(cls, v: str) -> str:
v = (v or "").strip()
# Tokens are 32 hex chars (secrets.token_hex(16)). Reject anything
# that doesn't look like one to fail fast on malformed input.
if not re.match(r"^[a-f0-9]{32}$", v):
raise ValueError("Neispravan format tokena.")
return v
def _client_ip(request: Request) -> str:
"""Extract real client IP honoring proxy headers (Vercel/HF/Cloudflare)."""
return (
request.headers.get("x-forwarded-for", "").split(",")[0].strip()
or request.headers.get("x-real-ip", "")
or request.headers.get("cf-connecting-ip", "")
or (request.client.host if request.client else "unknown")
)
def _client_fingerprint(request: Request) -> Optional[str]:
"""Extract browser fingerprint from X-Fingerprint-Hash header."""
fp = request.headers.get("x-fingerprint-hash", "")[:128]
return fp if fp else None