-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
3886 lines (3463 loc) · 142 KB
/
Copy pathapp.py
File metadata and controls
3886 lines (3463 loc) · 142 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 os
import json
import re
import secrets
from pathlib import Path
from datetime import datetime, timedelta, timezone
from typing import Optional
from urllib.parse import unquote, urlencode, urlsplit
from fastapi import FastAPI, Form, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import HTMLResponse, RedirectResponse, JSONResponse, Response
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from fastapi.exception_handlers import http_exception_handler
from starlette.exceptions import HTTPException as StarletteHTTPException
from starlette.middleware.sessions import SessionMiddleware
from sqlalchemy import func
from sqlalchemy.exc import IntegrityError, SQLAlchemyError
from sqlalchemy.orm import Session
import requests
from database import SessionLocal
from models import (
DeveloperProfile,
Event,
MaintainerAnalysis,
OpportunityFeedItem,
Target,
User,
)
from auth import (
hash_password,
verify_password,
generate_csrf_token,
verify_csrf_token,
)
from analytics import (
analytics_summary,
track_analysis,
update_pipeline_status,
generate_pitch,
save_pitch,
daily_analysis_count,
lifetime_analysis_count,
)
import paddle_billing
import email_utils
import pricing
from analysis_service import build_analysis_result, contract_potential, to_public_api_payload
from radar import OPPORTUNITY_SCORE_COMPONENTS, RECOMMENDATION_RULES
from discovery_service import DiscoveryError, category_options, discover_opportunities
from maintainer_schemas import MaintainerReport
from maintainer_service import ANALYSIS_VERSION as MAINTAINER_ANALYSIS_VERSION
from maintainer_service import MaintainerServiceError, build_maintainer_report, parse_repository_url
from developer_profile_service import (
OWNER_REFRESH_HOURS,
PROFILE_CACHE_HOURS,
DeveloperProfileError,
analyze_developer_profile,
normalize_github_username,
)
from opportunity_service import (
DISMISS_COOLDOWN_DAYS,
FREE_RECOMMENDATION_LIMIT,
PRO_RECOMMENDATION_LIMIT,
PUBLIC_RECOMMENDATION_LIMIT,
OpportunityFeedError,
can_save_more,
curated_opportunity_sections,
feed_freshness,
interaction_ids,
load_feed_items,
normalize_repository_full_name,
ranked_recommendations,
public_opportunity_payload,
recently_viewed_items,
refresh_opportunity_feed,
saved_items,
upsert_interaction,
)
from share_card_service import render_developer_profile_card, render_opportunity_card
import config
try:
import google.generativeai as genai
except Exception:
genai = None
# SECRET_KEY is required, not defaulted. A hardcoded fallback would mean
# every session cookie (and CSRF token) is forgeable if the env var is ever
# missing on deploy. Fail loudly at startup instead of failing silently in
# production.
SECRET_KEY = os.environ.get("SECRET_KEY")
if not SECRET_KEY:
raise RuntimeError(
"SECRET_KEY environment variable is not set. Set it before starting "
"the app (e.g. `SECRET_KEY=$(openssl rand -hex 32)`). Refusing to "
"start with an insecure default."
)
app = FastAPI(title="BashOps Radar")
app.add_middleware(
CORSMiddleware,
allow_origin_regex=r"^chrome-extension://[a-p]{32}$",
allow_credentials=False,
allow_methods=["GET"],
allow_headers=["Accept"],
)
def session_cookie_https_only(site_url: str) -> bool:
"""Keep production cookies HTTPS-only while allowing explicit HTTP local URLs."""
try:
return urlsplit(site_url).scheme.casefold() == "https"
except (TypeError, ValueError):
return False
app.add_middleware(
SessionMiddleware,
secret_key=SECRET_KEY,
https_only=session_cookie_https_only(config.SITE_URL),
same_site="lax",
)
app.mount("/static", StaticFiles(directory="static"), name="static")
templates = Jinja2Templates(directory="templates")
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
BETA_FILE = Path("beta_signups.csv")
FREE_ANALYSIS_LIMIT = 2
ANONYMOUS_ANALYSIS_LIMIT = 1
MAINTAINER_PENDING_PARTIAL_SESSION_KEY = "maintainer_pending_partial"
POST_AUTH_NEXT_SESSION_KEY = "post_auth_next"
GITHUB_OAUTH_NEXT_SESSION_KEY = "github_oauth_next"
EMAIL_VERIFICATION_MAX_AGE_SECONDS = 24 * 60 * 60
PASSWORD_RESET_MAX_AGE_SECONDS = 60 * 60
ANONYMOUS_DEVELOPER_PROFILE_LIMIT = 3
ANONYMOUS_DEVELOPER_PROFILE_WINDOW_SECONDS = 60 * 60
if GEMINI_API_KEY and genai:
genai.configure(api_key=GEMINI_API_KEY)
def clean_ai_summary_text(text: str) -> str:
"""Keep model output readable in the HTML card without touching GitHub data."""
if not text:
return "AI summary temporarily unavailable."
cleaned = text.strip()
cleaned = re.sub(r"^\s*#{1,6}\s*", "", cleaned, flags=re.MULTILINE)
cleaned = re.sub(r"^\s*[-*]\s+", "", cleaned, flags=re.MULTILINE)
cleaned = re.sub(r"\*\*(.*?)\*\*", r"\1", cleaned)
cleaned = re.sub(r"__(.*?)__", r"\1", cleaned)
cleaned = re.sub(r"`([^`]+)`", r"\1", cleaned)
cleaned = cleaned.replace("**", "").replace("__", "")
cleaned = re.sub(r"\n{3,}", "\n\n", cleaned)
unsafe_outcome = re.compile(
r"\b(?:will|would|guaranteed?|definitely|certainly|ensures?)\b"
r"[^.!?]{0,100}\b(?:merge|accept|hire|job|contract|pay|paid|notice|attention|respond|reply)\w*",
flags=re.IGNORECASE,
)
safe_sentences = [
sentence
for sentence in re.split(r"(?<=[.!?])\s+", cleaned.strip())
if sentence and not unsafe_outcome.search(sentence)
]
return " ".join(safe_sentences).strip() or "AI interpretation temporarily unavailable."
def generate_ai_summary(
repo_full_name,
repo,
best_issue,
repo_score,
angle,
languages=None,
repository_intelligence=None,
confidence=None,
recommendation_label=None,
):
if not GEMINI_API_KEY or not genai:
return {
"text": "AI interpretation is temporarily unavailable. Deterministic repository analysis remains available.",
"status": "unavailable",
}
issue_text = "No best issue found."
if best_issue:
issue_text = (
f"#{best_issue['number']} - {best_issue['title']} "
f"({best_issue['type']}, score {best_issue['score']}/100)"
)
intelligence = {item.get("key"): item for item in (repository_intelligence or [])}
commercial = intelligence.get("commercial") or {}
friendliness = intelligence.get("friendliness") or {}
language_names = ", ".join(list((languages or {}).keys())[:4]) or "Unavailable"
purpose = repo.get("description") or "Repository purpose unavailable"
activity = repo.get("pushed_at") or "Unavailable"
prompt = f"""
You are BashOps Radar, an AI opportunity analyst for developers.
Interpret the deterministic public evidence below as a proof-of-work opportunity.
Do not repeat the numeric score or recommendation. Do not invent missing facts.
Repository: {repo_full_name}
Repository purpose: {purpose}
Languages: {language_names}
Stars: {repo.get("stargazers_count")}
Forks: {repo.get("forks_count")}
Open Issues: {repo.get("open_issues_count")}
Last push: {activity}
Opportunity Score: {repo_score}/100
Confidence: {confidence or "Unavailable"}
Deterministic recommendation: {recommendation_label or "Unavailable"}
Best Issue: {issue_text}
Proof-of-Work Angle: {angle}
Contributor friendliness: {friendliness.get("value") or "Unavailable"} - {friendliness.get("detail") or "No sampled signal"}
Commercial context: {commercial.get("value") or "Unavailable"} - {commercial.get("detail") or "No public metadata signal"}
Write one or two concise plain-text paragraphs that add project-specific interpretation:
- connect the repository purpose and language to the named issue category and title;
- state what the developer should verify before beginning;
- describe a focused contribution approach;
- mention paid-work potential only as a conditional possibility after maintainer trust is established.
If the repository purpose or best issue is unavailable, use one short paragraph and state the limitation.
Never promise attention, merge, employment, a contract, or maintainer response.
Keep it practical, direct, and under 120 words.
Do not use Markdown, headings, bold markers, bullets, numbered lists, or code formatting.
"""
try:
model = genai.GenerativeModel("gemini-2.5-flash-lite")
response = model.generate_content(prompt)
cleaned_summary = clean_ai_summary_text(response.text if response.text else "")
return {
"text": cleaned_summary,
"status": "unavailable" if cleaned_summary == "AI interpretation temporarily unavailable." else "available",
}
except Exception as e:
error = str(e).lower()
if "429" in error or "quota" in error or "rate limit" in error:
return {
"text": "Gemini free-tier quota reached. Core repository analysis completed successfully.",
"status": "unavailable",
}
return {
"text": "AI summary temporarily unavailable. Core repository analysis completed successfully.",
"status": "unavailable",
}
def get_current_user(request: Request):
user_id = request.session.get("user_id")
if not user_id:
return None
db: Session = SessionLocal()
try:
return db.query(User).filter(User.id == user_id).first()
finally:
db.close()
def is_admin(user) -> bool:
return bool(user and user.email and user.email.strip().lower() in config.ADMIN_EMAILS)
def has_owner_pro_override(user) -> bool:
if not user or not user.email:
return False
email = user.email.strip().lower()
return email == "bashops1@gmail.com" or email in config.ADMIN_EMAILS
def has_pro_access(user) -> bool:
return bool(
user
and (
user.plan in {pricing.RADAR_PRO_PLAN, pricing.LEGACY_RADAR_PRO_PLAN}
or has_owner_pro_override(user)
)
)
def require_admin_or_redirect(request: Request, current_user):
if not current_user:
return RedirectResponse(url="/login", status_code=303)
if not is_admin(current_user):
return HTMLResponse(
"Admin access required. Confirm this account email is listed in ADMIN_EMAILS.",
status_code=403,
)
return None
def user_context(request: Request, current_user=None) -> dict:
"""Standard current_user / is_admin pair every template needs for the
navbar to render the right links."""
if current_user is None:
current_user = get_current_user(request)
pro_access = has_pro_access(current_user)
return {
"current_user": current_user,
"is_admin": is_admin(current_user),
"has_pro_access": pro_access,
"effective_plan": pricing.RADAR_PRO_PLAN if pro_access else pricing.FREE_PLAN,
"maintainer_enabled": config.MAINTAINER_ENABLED,
}
def csrf_context(request: Request) -> dict:
"""Every template that renders a POST form should merge this in so the
form can include the hidden csrf_token field."""
token = generate_csrf_token()
request.session["csrf_token"] = token
return {"csrf_token": token}
def check_csrf(request: Request, csrf_token: str) -> bool:
session_token = request.session.get("csrf_token", "")
# The token must both verify its own signature/expiry AND match the one
# issued for this session, so a stolen token from a different session
# can't be replayed.
return verify_csrf_token(csrf_token) and csrf_token == session_token
def now_utc() -> datetime:
return datetime.now(timezone.utc)
def token_age_seconds(sent_at) -> float:
if not sent_at:
return float("inf")
if sent_at.tzinfo is None:
sent_at = sent_at.replace(tzinfo=timezone.utc)
return (now_utc() - sent_at).total_seconds()
def validate_password_strength(password: str) -> Optional[str]:
if len(password or "") < 8:
return "Password must be at least 8 characters long."
if not any(char.isupper() for char in password):
return "Password must include at least one uppercase letter."
if not any(char.islower() for char in password):
return "Password must include at least one lowercase letter."
if not any(char.isdigit() for char in password):
return "Password must include at least one number."
return None
def safe_next_path(value: str, default: str = "/dashboard") -> str:
"""Return a local BashOps path or the existing dashboard fallback."""
candidate = (value or "").strip()
if not candidate or "\\" in candidate or any(ord(char) < 32 for char in candidate):
return default
# Query parsing decodes once. Decode a few more times so double-encoded
# protocol-relative and backslash redirects cannot survive validation.
for _ in range(3):
decoded = unquote(candidate)
if decoded == candidate:
break
candidate = decoded
if "%" in candidate or "\\" in candidate or any(ord(char) < 32 for char in candidate):
return default
parsed = urlsplit(candidate)
if parsed.scheme or parsed.netloc or not candidate.startswith("/") or candidate.startswith("//"):
return default
return candidate
def user_by_email(db: Session, email: str):
normalized_email = (email or "").strip().lower()
return db.query(User).filter(func.lower(User.email) == normalized_email).first()
def auth_url(path: str, next_path: str, **params) -> str:
values = {**params, "next": safe_next_path(next_path)}
return f"{path}?{urlencode(values)}"
def new_token() -> str:
return secrets.token_urlsafe(48)
def verification_link(token: str) -> str:
return f"{config.SITE_URL}/verify-email?token={token}"
def reset_link(token: str) -> str:
return f"{config.SITE_URL}/reset-password?token={token}"
def render_login(
request: Request,
error: Optional[str] = None,
joined: bool = False,
registered: bool = False,
verified: bool = False,
reset: bool = False,
next_path: str = "/dashboard",
):
next_path = safe_next_path(next_path)
return templates.TemplateResponse(
request=request,
name="login.html",
context={
"joined": joined,
"registered": registered,
"verified": verified,
"reset": reset,
"error": error,
"next_path": next_path,
"is_maintainer_destination": next_path.startswith("/maintainer"),
"register_url": auth_url("/register", next_path),
"github_login_url": auth_url("/auth/github/login", next_path),
"github_oauth_configured": config.github_oauth_configured,
**user_context(request),
**csrf_context(request),
},
)
def render_register(
request: Request,
error: Optional[str] = None,
next_path: str = "/dashboard",
account_exists: bool = False,
):
next_path = safe_next_path(next_path)
return templates.TemplateResponse(
request=request,
name="register.html",
context={
"error": error,
"account_exists": account_exists,
"next_path": next_path,
"is_maintainer_destination": next_path.startswith("/maintainer"),
"login_url": auth_url("/login", next_path),
"github_login_url": auth_url("/auth/github/login", next_path),
"github_oauth_configured": config.github_oauth_configured,
**user_context(request),
**csrf_context(request),
},
)
def sanitize_referrer(referrer: str) -> str:
"""Retain attribution without persisting tokens from URL queries/fragments."""
if not referrer:
return ""
try:
parsed = urlsplit(referrer)
if parsed.scheme.casefold() not in {"http", "https"} or not parsed.netloc:
return ""
if parsed.username or parsed.password:
return ""
return parsed._replace(query="", fragment="").geturl()[:500]
except (TypeError, ValueError):
return ""
def track_event(request: Request, event_name: str, user=None, metadata=None) -> None:
try:
db: Session = SessionLocal()
try:
event = Event(
user_id=user.id if user else None,
event_name=event_name,
page=str(request.url.path)[:500],
referrer=sanitize_referrer(request.headers.get("referer") or ""),
user_agent=(request.headers.get("user-agent") or "")[:500],
metadata_json=json.dumps(metadata or {}, default=str),
)
db.add(event)
db.commit()
finally:
db.close()
except Exception as exc:
print(f"[event tracking failed] {event_name}: {exc!r}")
def user_has_vscode_interest(user) -> bool:
if not user:
return False
db: Session = SessionLocal()
try:
return (
db.query(Event.id)
.filter(
Event.user_id == user.id,
Event.event_name == "vscode_interest_submitted",
)
.first()
is not None
)
finally:
db.close()
def anonymous_website_analysis_used(request: Request, ip: str) -> bool:
"""
Website-only anonymous trial guard. The session flag is the primary signal;
the existing anonymous Target/IP count remains a soft fallback for the
current network without adding fingerprinting or new storage.
"""
if request.session.get("anonymous_analysis_used"):
return True
return daily_analysis_count(ip=ip) >= ANONYMOUS_ANALYSIS_LIMIT
def free_account_analysis_count(user) -> int:
"""Free account quota is derived from successful Target rows."""
if not user:
return 0
return lifetime_analysis_count(user.id)
def require_maintainer_enabled() -> None:
if not config.MAINTAINER_ENABLED:
raise HTTPException(status_code=404, detail="Not found")
def has_maintainer_access(user) -> bool:
return bool(
user
and (
has_owner_pro_override(user)
or bool(getattr(user, "maintainer_pilot_access", False))
)
)
def maintainer_trial_used(request: Request, user, ip: str) -> bool:
if has_maintainer_access(user):
return False
if not user and request.session.get("maintainer_trial_used"):
return True
db: Session = SessionLocal()
try:
query = db.query(MaintainerAnalysis).filter(
MaintainerAnalysis.status == "completed",
MaintainerAnalysis.is_partial.is_(False),
)
if user:
query = query.filter(MaintainerAnalysis.user_id == user.id)
else:
query = query.filter(
MaintainerAnalysis.user_id.is_(None),
MaintainerAnalysis.ip_address == ip,
)
return query.count() >= 1
finally:
db.close()
def maintainer_pending_partial_repository(request: Request, user) -> Optional[str]:
"""Return the Free user's session-bound partial repository, if any."""
if not user or has_maintainer_access(user):
return None
pending = request.session.get(MAINTAINER_PENDING_PARTIAL_SESSION_KEY)
if not isinstance(pending, dict) or pending.get("user_id") != user.id:
return None
repository = pending.get("repository")
return repository if isinstance(repository, str) and repository else None
def maintainer_plan_context(user) -> str:
if has_owner_pro_override(user):
return "owner_admin"
if user and getattr(user, "maintainer_pilot_access", False):
return "pilot"
return "registered_trial" if user else "anonymous_trial"
def maintainer_template_context(request: Request, current_user=None) -> dict:
if current_user is None:
current_user = get_current_user(request)
maintainer_access = has_maintainer_access(current_user)
return {
**user_context(request, current_user),
"maintainer_access": maintainer_access,
"maintainer_effective_plan": (
pricing.MAINTAINER_PRO_PLAN if maintainer_access else pricing.FREE_PLAN
),
**pricing.template_context(),
"maintainer_billing_available": bool(
config.PADDLE_CLIENT_TOKEN
and (
pricing.PADDLE_MAINTAINER_MONTHLY_PRICE_ID
or pricing.PADDLE_MAINTAINER_ANNUAL_PRICE_ID
)
),
"maintainer_subscription_status": (
getattr(current_user, "maintainer_subscription_status", None) if current_user else None
),
"site_url": config.SITE_URL,
}
def _aware_utc(value):
if value is None:
return None
return value.replace(tzinfo=timezone.utc) if value.tzinfo is None else value.astimezone(timezone.utc)
def developer_profile_by_username(db: Session, username: str):
normalized = (username or "").strip().lower()
return (
db.query(DeveloperProfile)
.filter(
(func.lower(DeveloperProfile.github_username) == normalized)
| (func.lower(DeveloperProfile.public_slug) == normalized)
)
.first()
)
def developer_profile_is_fresh(profile) -> bool:
expires_at = _aware_utc(getattr(profile, "expires_at", None))
return bool(expires_at and expires_at > now_utc())
def developer_profile_is_owner(profile, user) -> bool:
return bool(profile and user and profile.user_id == user.id and profile.is_claimed)
def developer_profile_can_be_claimed(profile, user) -> bool:
providers = {item.strip() for item in (getattr(user, "auth_provider", "") or "").split(",")}
return bool(
profile
and user
and "github" in providers
and user.github_id
and str(user.github_id) == str(profile.github_user_id)
and (profile.user_id is None or profile.user_id == user.id)
)
def consume_anonymous_developer_generation(request: Request) -> bool:
now_timestamp = now_utc().timestamp()
history = request.session.get("developer_profile_generation_times", [])
if not isinstance(history, list):
history = []
recent = [
float(value)
for value in history
if isinstance(value, (int, float)) and now_timestamp - float(value) < ANONYMOUS_DEVELOPER_PROFILE_WINDOW_SECONDS
]
if len(recent) >= ANONYMOUS_DEVELOPER_PROFILE_LIMIT:
request.session["developer_profile_generation_times"] = recent
return False
recent.append(now_timestamp)
request.session["developer_profile_generation_times"] = recent
return True
def apply_developer_profile_analysis(profile, analysis: dict) -> None:
analyzed_at = now_utc()
profile.github_username = analysis["github_username"]
profile.github_user_id = analysis["github_user_id"]
profile.display_name = analysis["display_name"]
profile.avatar_url = analysis["avatar_url"]
profile.bio = analysis["bio"]
profile.public_location = analysis["public_location"]
profile.profile_url = analysis["profile_url"]
profile.profile_data = analysis["profile_data"]
profile.strength_data = analysis["strength_data"]
profile.contribution_data = analysis["contribution_data"]
profile.analyzed_at = analyzed_at
profile.expires_at = analyzed_at + timedelta(hours=PROFILE_CACHE_HOURS)
profile.public_slug = analysis["github_username"]
def render_developer_landing(request: Request, error: str = "", username: str = "", status_code: int = 200):
current_user = get_current_user(request)
return templates.TemplateResponse(
request=request,
name="developer_landing.html",
context={
"error": error,
"username": username,
"site_url": config.SITE_URL,
**user_context(request, current_user),
**csrf_context(request),
},
status_code=status_code,
)
@app.exception_handler(StarletteHTTPException)
async def not_found_handler(request: Request, exc: StarletteHTTPException):
if exc.status_code == 404:
return templates.TemplateResponse(
request=request,
name="404.html",
context={**user_context(request)},
status_code=404,
)
# Any other raised HTTPException (403, 401, etc.) keeps FastAPI's
# default plain response — only 404 gets the branded page, so real
# status codes used by API-style clients aren't silently reshaped.
return await http_exception_handler(request, exc)
@app.exception_handler(Exception)
async def server_error_handler(request: Request, exc: Exception):
# Last-resort safety net: if a route raises anything unhandled, log it
# server-side and show the branded 500 page instead of a raw traceback
# or FastAPI's default plain-text error leaking internals to the user.
print(f"[unhandled error] {request.method} {request.url.path}: {exc!r}")
return templates.TemplateResponse(
request=request,
name="500.html",
context={**user_context(request)},
status_code=500,
)
@app.get("/robots.txt")
def robots_txt():
lines = [
"User-agent: *",
"Allow: /",
"Disallow: /dashboard",
"Disallow: /pipeline",
"Disallow: /admin/",
"Disallow: /billing/",
"Disallow: /maintainer/dashboard",
"Disallow: /maintainer/report/",
"Disallow: /export-pipeline",
f"Sitemap: {config.SITE_URL}/sitemap.xml",
]
return Response(content="\n".join(lines) + "\n", media_type="text/plain")
@app.get("/sitemap.xml")
def sitemap_xml():
# Only the public, indexable marketing pages — the app pages behind
# login are excluded via robots.txt above and noindex tags on the
# pages themselves.
urls = [
"/",
"/pricing",
"/methodology",
"/tools/github-opportunity-score",
"/tools/best-first-issue-finder",
"/developer",
"/today",
"/jobs",
"/login",
"/register",
"/terms",
"/privacy",
"/refund",
"/contact",
]
if config.MAINTAINER_ENABLED:
urls.extend(
[
"/maintainer",
"/maintainer/pricing",
"/tools/github-maintainer-workload-report",
]
)
db: Session = SessionLocal()
try:
public_slugs = (
db.query(DeveloperProfile.public_slug)
.filter(
DeveloperProfile.is_claimed.is_(True),
DeveloperProfile.is_public.is_(True),
)
.order_by(DeveloperProfile.public_slug)
.all()
)
urls.extend(f"/developer/{slug}" for (slug,) in public_slugs)
except SQLAlchemyError:
pass
finally:
db.close()
body = ['<?xml version="1.0" encoding="UTF-8"?>', '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">']
for path in urls:
body.append(f"<url><loc>{config.SITE_URL}{path}</loc></url>")
body.append("</urlset>")
return Response(content="\n".join(body), media_type="application/xml")
@app.get("/", response_class=HTMLResponse)
def home(request: Request, source: str = "", vscode_interest: str = "", repo_url: str = ""):
current_user = get_current_user(request)
if source == "maintainer":
track_event(request, "maintainer_to_radar_clicked", user=current_user)
elif source == "extension-analyze":
track_event(request, "extension_analyze_click", user=current_user)
track_event(request, "landing_view", user=current_user)
return templates.TemplateResponse(
request=request,
name="index.html",
context={
"result": None,
"error": None,
"limit_reached": False,
"site_url": config.SITE_URL,
"repo_url": repo_url if source == "extension-analyze" else "",
**pricing.template_context(),
"vscode_interest_status": vscode_interest if vscode_interest in {"joined", "already", "error"} else "",
"has_vscode_interest": user_has_vscode_interest(current_user),
**user_context(request, current_user),
**csrf_context(request),
},
)
@app.get("/export-pipeline")
def export_pipeline(request: Request):
current_user = get_current_user(request)
if not current_user:
return RedirectResponse(url="/login", status_code=303)
if not has_pro_access(current_user):
track_event(request, "export_blocked", user=current_user, metadata={"reason": "radar_pro_required"})
return RedirectResponse(url="/pricing", status_code=303)
import csv
import io
summary = analytics_summary(user_id=current_user.id)
buffer = io.StringIO()
writer = csv.writer(buffer)
writer.writerow(["repo", "score", "status", "best_issue", "difficulty", "merge_probability", "estimated_time", "created_at"])
for row in summary["rows"]:
writer.writerow([
row["repo"], row["score"], row["status"], row["best_issue"],
row["difficulty"], row["merge_probability"], row["estimated_time"], row["pretty_time"],
])
from fastapi.responses import Response
return Response(
content=buffer.getvalue(),
media_type="text/csv",
headers={"Content-Disposition": "attachment; filename=bashops_pipeline.csv"},
)
@app.get("/pricing", response_class=HTMLResponse)
def pricing_page(request: Request, source: str = ""):
current_user = get_current_user(request)
track_event(request, "pricing_view", user=current_user)
if source == "opportunity":
track_event(request, "opportunity_upgrade_clicked", user=current_user)
return templates.TemplateResponse(
request=request,
name="pricing.html",
context={
"result": None,
"error": None,
"limit_reached": False,
**pricing.template_context(),
"billing_error": None,
"site_url": config.SITE_URL,
**user_context(request, current_user),
},
)
@app.get("/methodology", response_class=HTMLResponse)
def methodology_page(request: Request):
"""Public technical documentation for Radar's deterministic score."""
current_user = get_current_user(request)
return templates.TemplateResponse(
request=request,
name="methodology.html",
context={
"score_components": OPPORTUNITY_SCORE_COMPONENTS,
"recommendation_rules": RECOMMENDATION_RULES,
"evidence_config": {
"open_pull_sample": config.EVIDENCE_OPEN_PR_SAMPLE,
"closed_pull_sample": config.EVIDENCE_CLOSED_PR_SAMPLE,
"release_sample": config.EVIDENCE_RELEASE_SAMPLE,
"minimum_closed_pull_sample": config.EVIDENCE_MIN_CLOSED_PR_SAMPLE,
"cache_ttl_hours": config.EVIDENCE_CACHE_TTL_HOURS,
"partial_cache_ttl_hours": min(config.EVIDENCE_CACHE_TTL_HOURS, 1),
"stale_hours": config.EVIDENCE_CACHE_STALE_HOURS,
},
"site_url": config.SITE_URL,
**user_context(request, current_user),
},
)
def render_maintainer_landing(
request: Request,
current_user=None,
error: Optional[str] = None,
trial_blocked: bool = False,
trial_block_reason: Optional[str] = None,
status_code: int = 200,
):
return templates.TemplateResponse(
request=request,
name="maintainer/landing.html",
context={
"error": error,
"trial_blocked": trial_blocked,
"trial_block_reason": trial_block_reason,
**maintainer_template_context(request, current_user),
**csrf_context(request),
},
status_code=status_code,
)
@app.get("/maintainer", response_class=HTMLResponse)
def maintainer_landing(request: Request, source: str = ""):
require_maintainer_enabled()
current_user = get_current_user(request)
if source == "radar":
track_event(request, "radar_to_maintainer_clicked", user=current_user)
track_event(request, "maintainer_page_viewed", user=current_user)
return render_maintainer_landing(request, current_user)
@app.post("/maintainer/analyze", response_class=HTMLResponse)
def maintainer_analyze(
request: Request,
repo_url: str = Form(...),
csrf_token: str = Form(""),
):
require_maintainer_enabled()
current_user = get_current_user(request)
ip = request.client.host if request.client else "unknown"
if not check_csrf(request, csrf_token):
return render_maintainer_landing(
request,
current_user,
error="Your session expired. Please try again.",
status_code=400,
)
if current_user and not current_user.email_verified:
request.session[POST_AUTH_NEXT_SESSION_KEY] = "/maintainer"
return templates.TemplateResponse(
request=request,
name="verify_notice.html",
context={
"email": current_user.email,
"message": "Please verify your email before creating a Maintainer report.",
"next_path": "/maintainer",
"login_url": auth_url("/login", "/maintainer"),
**user_context(request, current_user),
**csrf_context(request),
},
status_code=403,
)
if maintainer_trial_used(request, current_user, ip):
track_event(
request,
"maintainer_trial_blocked",
user=current_user,
metadata={"access": maintainer_plan_context(current_user)},
)
return render_maintainer_landing(
request,
current_user,
trial_blocked=True,
status_code=429,
)
pending_repository = maintainer_pending_partial_repository(request, current_user)
if pending_repository:
try:
owner, repository, _ = parse_repository_url(repo_url)
except MaintainerServiceError as exc:
return render_maintainer_landing(
request,
current_user,
error=exc.public_message,
status_code=400,
)
if f"{owner}/{repository}".casefold() != pending_repository:
track_event(
request,
"maintainer_trial_blocked",