Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion backend/models/__init__.py
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
from typing import Optional, Union, List
from typing import Optional, Union, List, Literal
from pydantic import BaseModel, Field


Expand All@@ -10,6 +10,7 @@ class StartSessionBody(BaseModel):
mode: str = "socratic"
use_shared_context: bool = True
course_id: Optional[str] = None # Direct course_id lookup instead of resolving from topic
model_pref: Optional[Literal["fast", "smart"]] = None # "fast" (default, gemini-2.5-flash) or "smart" (gemini-2.5-pro)


class ChatBody(BaseModel):
Expand All@@ -18,6 +19,7 @@ class ChatBody(BaseModel):
message: str
mode: str = "socratic"
use_shared_context: bool = True
model_pref: Optional[Literal["fast", "smart"]] = None # "fast" (default, gemini-2.5-flash) or "smart" (gemini-2.5-pro)


class EndSessionBody(BaseModel):
Expand All@@ -31,6 +33,7 @@ class ActionBody(BaseModel):
action_type: str = "hint"
mode: str = "socratic"
use_shared_context: bool = True
model_pref: Optional[Literal["fast", "smart"]] = None # "fast" (default, gemini-2.5-flash) or "smart" (gemini-2.5-pro)


# ── Quiz ──────────────────────────────────────────────────────────────────────
Expand Down
164 changes: 152 additions & 12 deletions backend/routes/auth.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,6 +9,7 @@
import base64
import hashlib
import hmac as _hmac
import re
import secrets
import time as _time
from urllib.parse import urlencode
Expand DownExpand Up@@ -39,6 +40,14 @@

router = APIRouter()

OAUTH_STATE_COOKIE = "sapling_oauth_state"
_OAUTH_COOKIE_MAX_AGE = 600
_POPUP_ID_RE = re.compile(r"^[A-Za-z0-9_-]{1,128}$")

# Fallback in-memory store for environments without SESSION_SECRET; entries
# are keyed by nonce and expire after _OAUTH_COOKIE_MAX_AGE seconds.
_OAUTH_FALLBACK_STORE: dict[str, tuple[float, dict]] = {}


def _google_client_config() -> dict:
return {
Expand DownExpand Up@@ -73,6 +82,68 @@ def _generate_pkce_pair():
return code_verifier, code_challenge


def _clean_popup_id(s: str | None) -> str | None:
if not s:
return None
return s if _POPUP_ID_RE.match(s) else None


def _encode_oauth_cookie(payload: dict) -> str:
raw = json.dumps(payload, separators=(",", ":")).encode()
payload_b64 = base64.urlsafe_b64encode(raw).decode().rstrip("=")
if SESSION_SECRET:
sig_bytes = _hmac.new(SESSION_SECRET.encode(), payload_b64.encode(), hashlib.sha256).digest()
sig_b64 = base64.urlsafe_b64encode(sig_bytes).decode().rstrip("=")
return f"{payload_b64}.{sig_b64}"
nonce = payload.get("n", "")
if nonce:
_OAUTH_FALLBACK_STORE[nonce] = (_time.monotonic() + _OAUTH_COOKIE_MAX_AGE, payload)
_prune_fallback_store()
return payload_b64


def _decode_oauth_cookie(cookie_value: str | None) -> dict | None:
if not cookie_value:
return None
if SESSION_SECRET:
if "." not in cookie_value:
return None
try:
payload_b64, sig_b64 = cookie_value.rsplit(".", 1)
except ValueError:
return None
expected = _hmac.new(SESSION_SECRET.encode(), payload_b64.encode(), hashlib.sha256).digest()
expected_b64 = base64.urlsafe_b64encode(expected).decode().rstrip("=")
if not _hmac.compare_digest(expected_b64, sig_b64):
return None
try:
padded = payload_b64 + "=" * (-len(payload_b64) % 4)
payload = json.loads(base64.urlsafe_b64decode(padded.encode()).decode())
except Exception:
return None
return payload if isinstance(payload, dict) else None
try:
padded = cookie_value + "=" * (-len(cookie_value) % 4)
payload = json.loads(base64.urlsafe_b64decode(padded.encode()).decode())
except Exception:
return None
if not isinstance(payload, dict):
return None
nonce = payload.get("n")
_prune_fallback_store()
entry = _OAUTH_FALLBACK_STORE.get(nonce or "")
if not entry:
return None
return entry[1]


def _prune_fallback_store() -> None:
now = _time.monotonic()
expired = [k for k, (exp, _) in _OAUTH_FALLBACK_STORE.items() if exp < now]
for k in expired:
_OAUTH_FALLBACK_STORE.pop(k, None)


@router.get("/me")
def get_me(request: Request):
"""Return approval and onboarding status for a given user_id."""
Expand DownExpand Up@@ -136,36 +207,84 @@ def get_me(request: Request):


@router.get("/google")
def google_login():
def google_login(popup_id: str = Query(None)):
"""Redirect to Google consent screen with identity + calendar scopes."""
if not GOOGLE_AVAILABLE or not GOOGLE_CLIENT_ID:
raise HTTPException(status_code=400, detail="Google OAuth not configured")

code_verifier, code_challenge = _generate_pkce_pair()
nonce = secrets.token_urlsafe(32)
clean_popup = _clean_popup_id(popup_id)

flow = Flow.from_client_config(_google_client_config(), scopes=AUTH_SCOPES)
flow.redirect_uri = GOOGLE_AUTH_REDIRECT_URI
auth_url, _ = flow.authorization_url(
prompt="consent",
access_type="offline",
state=_encode_state({"action": "signin", "cv": code_verifier}),
state=_encode_state({"action": "signin", "n": nonce}),
code_challenge=code_challenge,
code_challenge_method="S256",
)
return RedirectResponse(auth_url)

cookie_value = _encode_oauth_cookie({
"n": nonce,
"cv": code_verifier,
"popup_id": clean_popup,
})
response = RedirectResponse(auth_url)
response.set_cookie(
key=OAUTH_STATE_COOKIE,
value=cookie_value,
max_age=_OAUTH_COOKIE_MAX_AGE,
httponly=True,
secure=True,
samesite="lax",
path="/",
)
return response


@router.get("/google/callback")
def google_callback(code: str = Query(...), state: str = Query(None)):
def google_callback(request: Request, code: str = Query(...), state: str = Query(None)):
"""Exchange auth code for tokens, validate @bu.edu, upsert user."""
cookie_payload = _decode_oauth_cookie(request.cookies.get(OAUTH_STATE_COOKIE))
code_verifier = cookie_payload.get("cv") if cookie_payload else None
popup_id = _clean_popup_id(cookie_payload.get("popup_id")) if cookie_payload else None
cookie_nonce = cookie_payload.get("n") if cookie_payload else None

def _fail_redirect(error_code: str, fallback_path: str = "/auth") -> RedirectResponse:
# In popup mode, route failures through /auth/callback so the popup
# can broadcast the error and self-close instead of stranding the opener.
if popup_id:
params = urlencode({"error": error_code, "popup_id": popup_id})
resp = RedirectResponse(f"{FRONTEND_URL}/auth/callback?{params}")
else:
resp = RedirectResponse(f"{FRONTEND_URL}{fallback_path}?error={error_code}")
resp.set_cookie(
key=OAUTH_STATE_COOKIE,
value="",
max_age=0,
httponly=True,
secure=True,
samesite="lax",
path="/",
)
return resp

if not GOOGLE_AVAILABLE:
return RedirectResponse(f"{FRONTEND_URL}/auth?error=google_not_configured")
return _fail_redirect("google_not_configured")

state_data = _decode_state(state) if state else {}
code_verifier = state_data.get("cv")
state_nonce = state_data.get("n")
if not cookie_payload or not cookie_nonce or not state_nonce or not _hmac.compare_digest(str(state_nonce), str(cookie_nonce)):
return _fail_redirect("invalid_state")

flow = Flow.from_client_config(_google_client_config(), scopes=AUTH_SCOPES)
flow.redirect_uri = GOOGLE_AUTH_REDIRECT_URI
flow.fetch_token(code=code, code_verifier=code_verifier)
try:
flow.fetch_token(code=code, code_verifier=code_verifier)
except Exception:
return _fail_redirect("oauth_exchange_failed")
creds = flow.credentials

# Fetch user info from Google
Expand All@@ -184,9 +303,7 @@ def google_callback(code: str = Query(...), state: str = Query(None)):

# Restrict to @bu.edu accounts
if not email.endswith("@bu.edu"):
return RedirectResponse(
f"{FRONTEND_URL}/auth?error=invalid_domain"
)
return _fail_redirect("invalid_domain")

# Determine user_id: check if this Google ID already exists
existing = table("users").select("id,is_approved", filters={"google_id": f"eq.{google_id}"})
Expand DownExpand Up@@ -233,7 +350,19 @@ def google_callback(code: str = Query(...), state: str = Query(None)):
)

if not is_approved:
return RedirectResponse(f"{FRONTEND_URL}/pending")
if popup_id:
return _fail_redirect("not_approved")
resp = RedirectResponse(f"{FRONTEND_URL}/pending")
resp.set_cookie(
key=OAUTH_STATE_COOKIE,
value="",
max_age=0,
httponly=True,
secure=True,
samesite="lax",
path="/",
)
return resp

# Build a short-lived HMAC token so the frontend can verify this redirect
# without a second round-trip to the backend.
Expand All@@ -250,5 +379,16 @@ def google_callback(code: str = Query(...), state: str = Query(None)):
"avatar": avatar_url,
"is_approved": "true",
**({"auth_token": auth_token} if auth_token else {}),
**({"popup_id": popup_id} if popup_id else {}),
})
return RedirectResponse(f"{FRONTEND_URL}/auth/callback?{params}")
resp = RedirectResponse(f"{FRONTEND_URL}/auth/callback?{params}")
resp.set_cookie(
key=OAUTH_STATE_COOKIE,
value="",
max_age=0,
httponly=True,
secure=True,
samesite="lax",
path="/",
)
return resp
33 changes: 28 additions & 5 deletions backend/routes/learn.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,7 +11,12 @@
from models import StartSessionBody, ChatBody, EndSessionBody, ActionBody, ModeSwitchBody
from services.auth_guard import require_self, get_session_user_id
from services.encryption import encrypt_if_present, encrypt_json, decrypt_if_present, decrypt_json
from services.gemini_service import MODEL_SMART, call_gemini_multiturn, extract_graph_update
from services.gemini_service import (
MODEL_DEFAULT,
MODEL_SMART,
call_gemini_multiturn,
extract_graph_update,
)
from services.graph_service import get_graph, apply_graph_update

router = APIRouter()
Expand All@@ -28,6 +33,18 @@
"teachback": "Teach-back (you explain to me)",
}

# User-facing speed/quality knob for the tutor chat.
# "fast" = flash (default, faster), "smart" = pro (opt-in, slower but stronger reasoning).
# Anything unrecognized falls back to fast so the default is the snappy one.
_MODEL_PREF_TO_MODEL = {
"fast": MODEL_DEFAULT,
"smart": MODEL_SMART,
}


def _resolve_tutor_model(model_pref: str | None) -> str:
return _MODEL_PREF_TO_MODEL.get(model_pref or "", MODEL_DEFAULT)


def _load_prompt(name: str) -> str:
with open(os.path.join(PROMPTS_DIR, name)) as f:
Expand DownExpand Up@@ -293,13 +310,15 @@ def start_session(body: StartSessionBody, request: Request):
)

try:
raw = call_gemini_multiturn(system_prompt, [], user_message, model=MODEL_SMART)
raw = call_gemini_multiturn(
system_prompt, [], user_message, model=_resolve_tutor_model(body.model_pref)
)
except Exception as e:
raise HTTPException(status_code=502, detail=f"Gemini error: {e}")

reply, graph_update = extract_graph_update(raw)
apply_graph_update(body.user_id, graph_update, course_id=course_id)

PENDING_SESSIONS[session_id] = {
"user_id": body.user_id,
"mode": body.mode,
Expand DownExpand Up@@ -339,7 +358,9 @@ def chat(body: ChatBody, request: Request):
)

try:
raw = call_gemini_multiturn(system_prompt, history, body.message, model=MODEL_SMART)
raw = call_gemini_multiturn(
system_prompt, history, body.message, model=_resolve_tutor_model(body.model_pref)
)
except Exception as e:
raise HTTPException(status_code=502, detail=f"Gemini error: {e}")

Expand DownExpand Up@@ -558,7 +579,9 @@ def action(body: ActionBody, request: Request):
action_message = f"[ACTION: {action_prompts.get(body.action_type, '')}]"

try:
raw = call_gemini_multiturn(system_prompt, history, action_message, model=MODEL_SMART)
raw = call_gemini_multiturn(
system_prompt, history, action_message, model=_resolve_tutor_model(body.model_pref)
)
except Exception as e:
raise HTTPException(status_code=502, detail=f"Gemini error: {e}")

Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion backend/models/__init__.py
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
from typing import Optional, Union, List
from typing import Optional, Union, List, Literal
from pydantic import BaseModel, Field


Expand All@@ -10,6 +10,7 @@ class StartSessionBody(BaseModel):
mode: str = "socratic"
use_shared_context: bool = True
course_id: Optional[str] = None # Direct course_id lookup instead of resolving from topic
model_pref: Optional[Literal["fast", "smart"]] = None # "fast" (default, gemini-2.5-flash) or "smart" (gemini-2.5-pro)


class ChatBody(BaseModel):
Expand All@@ -18,6 +19,7 @@ class ChatBody(BaseModel):
message: str
mode: str = "socratic"
use_shared_context: bool = True
model_pref: Optional[Literal["fast", "smart"]] = None # "fast" (default, gemini-2.5-flash) or "smart" (gemini-2.5-pro)


class EndSessionBody(BaseModel):
Expand All@@ -31,6 +33,7 @@ class ActionBody(BaseModel):
action_type: str = "hint"
mode: str = "socratic"
use_shared_context: bool = True
model_pref: Optional[Literal["fast", "smart"]] = None # "fast" (default, gemini-2.5-flash) or "smart" (gemini-2.5-pro)


# ── Quiz ──────────────────────────────────────────────────────────────────────
Expand Down
164 changes: 152 additions & 12 deletions backend/routes/auth.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,6 +9,7 @@
import base64
import hashlib
import hmac as _hmac
import re
import secrets
import time as _time
from urllib.parse import urlencode
Expand DownExpand Up@@ -39,6 +40,14 @@

router = APIRouter()

OAUTH_STATE_COOKIE = "sapling_oauth_state"
_OAUTH_COOKIE_MAX_AGE = 600
_POPUP_ID_RE = re.compile(r"^[A-Za-z0-9_-]{1,128}$")

# Fallback in-memory store for environments without SESSION_SECRET; entries
# are keyed by nonce and expire after _OAUTH_COOKIE_MAX_AGE seconds.
_OAUTH_FALLBACK_STORE: dict[str, tuple[float, dict]] = {}


def _google_client_config() -> dict:
return {
Expand DownExpand Up@@ -73,6 +82,68 @@ def _generate_pkce_pair():
return code_verifier, code_challenge


def _clean_popup_id(s: str | None) -> str | None:
if not s:
return None
return s if _POPUP_ID_RE.match(s) else None


def _encode_oauth_cookie(payload: dict) -> str:
raw = json.dumps(payload, separators=(",", ":")).encode()
payload_b64 = base64.urlsafe_b64encode(raw).decode().rstrip("=")
if SESSION_SECRET:
sig_bytes = _hmac.new(SESSION_SECRET.encode(), payload_b64.encode(), hashlib.sha256).digest()
sig_b64 = base64.urlsafe_b64encode(sig_bytes).decode().rstrip("=")
return f"{payload_b64}.{sig_b64}"
nonce = payload.get("n", "")
if nonce:
_OAUTH_FALLBACK_STORE[nonce] = (_time.monotonic() + _OAUTH_COOKIE_MAX_AGE, payload)
_prune_fallback_store()
return payload_b64


def _decode_oauth_cookie(cookie_value: str | None) -> dict | None:
if not cookie_value:
return None
if SESSION_SECRET:
if "." not in cookie_value:
return None
try:
payload_b64, sig_b64 = cookie_value.rsplit(".", 1)
except ValueError:
return None
expected = _hmac.new(SESSION_SECRET.encode(), payload_b64.encode(), hashlib.sha256).digest()
expected_b64 = base64.urlsafe_b64encode(expected).decode().rstrip("=")
if not _hmac.compare_digest(expected_b64, sig_b64):
return None
try:
padded = payload_b64 + "=" * (-len(payload_b64) % 4)
payload = json.loads(base64.urlsafe_b64decode(padded.encode()).decode())
except Exception:
return None
return payload if isinstance(payload, dict) else None
try:
padded = cookie_value + "=" * (-len(cookie_value) % 4)
payload = json.loads(base64.urlsafe_b64decode(padded.encode()).decode())
except Exception:
return None
if not isinstance(payload, dict):
return None
nonce = payload.get("n")
_prune_fallback_store()
entry = _OAUTH_FALLBACK_STORE.get(nonce or "")
if not entry:
return None
return entry[1]


def _prune_fallback_store() -> None:
now = _time.monotonic()
expired = [k for k, (exp, _) in _OAUTH_FALLBACK_STORE.items() if exp < now]
for k in expired:
_OAUTH_FALLBACK_STORE.pop(k, None)


@router.get("/me")
def get_me(request: Request):
"""Return approval and onboarding status for a given user_id."""
Expand DownExpand Up@@ -136,36 +207,84 @@ def get_me(request: Request):


@router.get("/google")
def google_login():
def google_login(popup_id: str = Query(None)):
"""Redirect to Google consent screen with identity + calendar scopes."""
if not GOOGLE_AVAILABLE or not GOOGLE_CLIENT_ID:
raise HTTPException(status_code=400, detail="Google OAuth not configured")

code_verifier, code_challenge = _generate_pkce_pair()
nonce = secrets.token_urlsafe(32)
clean_popup = _clean_popup_id(popup_id)

flow = Flow.from_client_config(_google_client_config(), scopes=AUTH_SCOPES)
flow.redirect_uri = GOOGLE_AUTH_REDIRECT_URI
auth_url, _ = flow.authorization_url(
prompt="consent",
access_type="offline",
state=_encode_state({"action": "signin", "cv": code_verifier}),
state=_encode_state({"action": "signin", "n": nonce}),
code_challenge=code_challenge,
code_challenge_method="S256",
)
return RedirectResponse(auth_url)

cookie_value = _encode_oauth_cookie({
"n": nonce,
"cv": code_verifier,
"popup_id": clean_popup,
})
response = RedirectResponse(auth_url)
response.set_cookie(
key=OAUTH_STATE_COOKIE,
value=cookie_value,
max_age=_OAUTH_COOKIE_MAX_AGE,
httponly=True,
secure=True,
samesite="lax",
path="/",
)
return response


@router.get("/google/callback")
def google_callback(code: str = Query(...), state: str = Query(None)):
def google_callback(request: Request, code: str = Query(...), state: str = Query(None)):
"""Exchange auth code for tokens, validate @bu.edu, upsert user."""
cookie_payload = _decode_oauth_cookie(request.cookies.get(OAUTH_STATE_COOKIE))
code_verifier = cookie_payload.get("cv") if cookie_payload else None
popup_id = _clean_popup_id(cookie_payload.get("popup_id")) if cookie_payload else None
cookie_nonce = cookie_payload.get("n") if cookie_payload else None

def _fail_redirect(error_code: str, fallback_path: str = "/auth") -> RedirectResponse:
# In popup mode, route failures through /auth/callback so the popup
# can broadcast the error and self-close instead of stranding the opener.
if popup_id:
params = urlencode({"error": error_code, "popup_id": popup_id})
resp = RedirectResponse(f"{FRONTEND_URL}/auth/callback?{params}")
else:
resp = RedirectResponse(f"{FRONTEND_URL}{fallback_path}?error={error_code}")
resp.set_cookie(
key=OAUTH_STATE_COOKIE,
value="",
max_age=0,
httponly=True,
secure=True,
samesite="lax",
path="/",
)
return resp

if not GOOGLE_AVAILABLE:
return RedirectResponse(f"{FRONTEND_URL}/auth?error=google_not_configured")
return _fail_redirect("google_not_configured")

state_data = _decode_state(state) if state else {}
code_verifier = state_data.get("cv")
state_nonce = state_data.get("n")
if not cookie_payload or not cookie_nonce or not state_nonce or not _hmac.compare_digest(str(state_nonce), str(cookie_nonce)):
return _fail_redirect("invalid_state")

flow = Flow.from_client_config(_google_client_config(), scopes=AUTH_SCOPES)
flow.redirect_uri = GOOGLE_AUTH_REDIRECT_URI
flow.fetch_token(code=code, code_verifier=code_verifier)
try:
flow.fetch_token(code=code, code_verifier=code_verifier)
except Exception:
return _fail_redirect("oauth_exchange_failed")
creds = flow.credentials

# Fetch user info from Google
Expand All@@ -184,9 +303,7 @@ def google_callback(code: str = Query(...), state: str = Query(None)):

# Restrict to @bu.edu accounts
if not email.endswith("@bu.edu"):
return RedirectResponse(
f"{FRONTEND_URL}/auth?error=invalid_domain"
)
return _fail_redirect("invalid_domain")

# Determine user_id: check if this Google ID already exists
existing = table("users").select("id,is_approved", filters={"google_id": f"eq.{google_id}"})
Expand DownExpand Up@@ -233,7 +350,19 @@ def google_callback(code: str = Query(...), state: str = Query(None)):
)

if not is_approved:
return RedirectResponse(f"{FRONTEND_URL}/pending")
if popup_id:
return _fail_redirect("not_approved")
resp = RedirectResponse(f"{FRONTEND_URL}/pending")
resp.set_cookie(
key=OAUTH_STATE_COOKIE,
value="",
max_age=0,
httponly=True,
secure=True,
samesite="lax",
path="/",
)
return resp

# Build a short-lived HMAC token so the frontend can verify this redirect
# without a second round-trip to the backend.
Expand All@@ -250,5 +379,16 @@ def google_callback(code: str = Query(...), state: str = Query(None)):
"avatar": avatar_url,
"is_approved": "true",
**({"auth_token": auth_token} if auth_token else {}),
**({"popup_id": popup_id} if popup_id else {}),
})
return RedirectResponse(f"{FRONTEND_URL}/auth/callback?{params}")
resp = RedirectResponse(f"{FRONTEND_URL}/auth/callback?{params}")
resp.set_cookie(
key=OAUTH_STATE_COOKIE,
value="",
max_age=0,
httponly=True,
secure=True,
samesite="lax",
path="/",
)
return resp
33 changes: 28 additions & 5 deletions backend/routes/learn.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,7 +11,12 @@
from models import StartSessionBody, ChatBody, EndSessionBody, ActionBody, ModeSwitchBody
from services.auth_guard import require_self, get_session_user_id
from services.encryption import encrypt_if_present, encrypt_json, decrypt_if_present, decrypt_json
from services.gemini_service import MODEL_SMART, call_gemini_multiturn, extract_graph_update
from services.gemini_service import (
MODEL_DEFAULT,
MODEL_SMART,
call_gemini_multiturn,
extract_graph_update,
)
from services.graph_service import get_graph, apply_graph_update

router = APIRouter()
Expand All@@ -28,6 +33,18 @@
"teachback": "Teach-back (you explain to me)",
}

# User-facing speed/quality knob for the tutor chat.
# "fast" = flash (default, faster), "smart" = pro (opt-in, slower but stronger reasoning).
# Anything unrecognized falls back to fast so the default is the snappy one.
_MODEL_PREF_TO_MODEL = {
"fast": MODEL_DEFAULT,
"smart": MODEL_SMART,
}


def _resolve_tutor_model(model_pref: str | None) -> str:
return _MODEL_PREF_TO_MODEL.get(model_pref or "", MODEL_DEFAULT)


def _load_prompt(name: str) -> str:
with open(os.path.join(PROMPTS_DIR, name)) as f:
Expand DownExpand Up@@ -293,13 +310,15 @@ def start_session(body: StartSessionBody, request: Request):
)

try:
raw = call_gemini_multiturn(system_prompt, [], user_message, model=MODEL_SMART)
raw = call_gemini_multiturn(
system_prompt, [], user_message, model=_resolve_tutor_model(body.model_pref)
)
except Exception as e:
raise HTTPException(status_code=502, detail=f"Gemini error: {e}")

reply, graph_update = extract_graph_update(raw)
apply_graph_update(body.user_id, graph_update, course_id=course_id)

PENDING_SESSIONS[session_id] = {
"user_id": body.user_id,
"mode": body.mode,
Expand DownExpand Up@@ -339,7 +358,9 @@ def chat(body: ChatBody, request: Request):
)

try:
raw = call_gemini_multiturn(system_prompt, history, body.message, model=MODEL_SMART)
raw = call_gemini_multiturn(
system_prompt, history, body.message, model=_resolve_tutor_model(body.model_pref)
)
except Exception as e:
raise HTTPException(status_code=502, detail=f"Gemini error: {e}")

Expand DownExpand Up@@ -558,7 +579,9 @@ def action(body: ActionBody, request: Request):
action_message = f"[ACTION: {action_prompts.get(body.action_type, '')}]"

try:
raw = call_gemini_multiturn(system_prompt, history, action_message, model=MODEL_SMART)
raw = call_gemini_multiturn(
system_prompt, history, action_message, model=_resolve_tutor_model(body.model_pref)
)
except Exception as e:
raise HTTPException(status_code=502, detail=f"Gemini error: {e}")

Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion backend/models/__init__.py
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
from typing import Optional, Union, List
from typing import Optional, Union, List, Literal
from pydantic import BaseModel, Field


Expand All@@ -10,6 +10,7 @@ class StartSessionBody(BaseModel):
mode: str = "socratic"
use_shared_context: bool = True
course_id: Optional[str] = None # Direct course_id lookup instead of resolving from topic
model_pref: Optional[Literal["fast", "smart"]] = None # "fast" (default, gemini-2.5-flash) or "smart" (gemini-2.5-pro)


class ChatBody(BaseModel):
Expand All@@ -18,6 +19,7 @@ class ChatBody(BaseModel):
message: str
mode: str = "socratic"
use_shared_context: bool = True
model_pref: Optional[Literal["fast", "smart"]] = None # "fast" (default, gemini-2.5-flash) or "smart" (gemini-2.5-pro)


class EndSessionBody(BaseModel):
Expand All@@ -31,6 +33,7 @@ class ActionBody(BaseModel):
action_type: str = "hint"
mode: str = "socratic"
use_shared_context: bool = True
model_pref: Optional[Literal["fast", "smart"]] = None # "fast" (default, gemini-2.5-flash) or "smart" (gemini-2.5-pro)


# ── Quiz ──────────────────────────────────────────────────────────────────────
Expand Down
164 changes: 152 additions & 12 deletions backend/routes/auth.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,6 +9,7 @@
import base64
import hashlib
import hmac as _hmac
import re
import secrets
import time as _time
from urllib.parse import urlencode
Expand DownExpand Up@@ -39,6 +40,14 @@

router = APIRouter()

OAUTH_STATE_COOKIE = "sapling_oauth_state"
_OAUTH_COOKIE_MAX_AGE = 600
_POPUP_ID_RE = re.compile(r"^[A-Za-z0-9_-]{1,128}$")

# Fallback in-memory store for environments without SESSION_SECRET; entries
# are keyed by nonce and expire after _OAUTH_COOKIE_MAX_AGE seconds.
_OAUTH_FALLBACK_STORE: dict[str, tuple[float, dict]] = {}


def _google_client_config() -> dict:
return {
Expand DownExpand Up@@ -73,6 +82,68 @@ def _generate_pkce_pair():
return code_verifier, code_challenge


def _clean_popup_id(s: str | None) -> str | None:
if not s:
return None
return s if _POPUP_ID_RE.match(s) else None


def _encode_oauth_cookie(payload: dict) -> str:
raw = json.dumps(payload, separators=(",", ":")).encode()
payload_b64 = base64.urlsafe_b64encode(raw).decode().rstrip("=")
if SESSION_SECRET:
sig_bytes = _hmac.new(SESSION_SECRET.encode(), payload_b64.encode(), hashlib.sha256).digest()
sig_b64 = base64.urlsafe_b64encode(sig_bytes).decode().rstrip("=")
return f"{payload_b64}.{sig_b64}"
nonce = payload.get("n", "")
if nonce:
_OAUTH_FALLBACK_STORE[nonce] = (_time.monotonic() + _OAUTH_COOKIE_MAX_AGE, payload)
_prune_fallback_store()
return payload_b64


def _decode_oauth_cookie(cookie_value: str | None) -> dict | None:
if not cookie_value:
return None
if SESSION_SECRET:
if "." not in cookie_value:
return None
try:
payload_b64, sig_b64 = cookie_value.rsplit(".", 1)
except ValueError:
return None
expected = _hmac.new(SESSION_SECRET.encode(), payload_b64.encode(), hashlib.sha256).digest()
expected_b64 = base64.urlsafe_b64encode(expected).decode().rstrip("=")
if not _hmac.compare_digest(expected_b64, sig_b64):
return None
try:
padded = payload_b64 + "=" * (-len(payload_b64) % 4)
payload = json.loads(base64.urlsafe_b64decode(padded.encode()).decode())
except Exception:
return None
return payload if isinstance(payload, dict) else None
try:
padded = cookie_value + "=" * (-len(cookie_value) % 4)
payload = json.loads(base64.urlsafe_b64decode(padded.encode()).decode())
except Exception:
return None
if not isinstance(payload, dict):
return None
nonce = payload.get("n")
_prune_fallback_store()
entry = _OAUTH_FALLBACK_STORE.get(nonce or "")
if not entry:
return None
return entry[1]


def _prune_fallback_store() -> None:
now = _time.monotonic()
expired = [k for k, (exp, _) in _OAUTH_FALLBACK_STORE.items() if exp < now]
for k in expired:
_OAUTH_FALLBACK_STORE.pop(k, None)


@router.get("/me")
def get_me(request: Request):
"""Return approval and onboarding status for a given user_id."""
Expand DownExpand Up@@ -136,36 +207,84 @@ def get_me(request: Request):


@router.get("/google")
def google_login():
def google_login(popup_id: str = Query(None)):
"""Redirect to Google consent screen with identity + calendar scopes."""
if not GOOGLE_AVAILABLE or not GOOGLE_CLIENT_ID:
raise HTTPException(status_code=400, detail="Google OAuth not configured")

code_verifier, code_challenge = _generate_pkce_pair()
nonce = secrets.token_urlsafe(32)
clean_popup = _clean_popup_id(popup_id)

flow = Flow.from_client_config(_google_client_config(), scopes=AUTH_SCOPES)
flow.redirect_uri = GOOGLE_AUTH_REDIRECT_URI
auth_url, _ = flow.authorization_url(
prompt="consent",
access_type="offline",
state=_encode_state({"action": "signin", "cv": code_verifier}),
state=_encode_state({"action": "signin", "n": nonce}),
code_challenge=code_challenge,
code_challenge_method="S256",
)
return RedirectResponse(auth_url)

cookie_value = _encode_oauth_cookie({
"n": nonce,
"cv": code_verifier,
"popup_id": clean_popup,
})
response = RedirectResponse(auth_url)
response.set_cookie(
key=OAUTH_STATE_COOKIE,
value=cookie_value,
max_age=_OAUTH_COOKIE_MAX_AGE,
httponly=True,
secure=True,
samesite="lax",
path="/",
)
return response


@router.get("/google/callback")
def google_callback(code: str = Query(...), state: str = Query(None)):
def google_callback(request: Request, code: str = Query(...), state: str = Query(None)):
"""Exchange auth code for tokens, validate @bu.edu, upsert user."""
cookie_payload = _decode_oauth_cookie(request.cookies.get(OAUTH_STATE_COOKIE))
code_verifier = cookie_payload.get("cv") if cookie_payload else None
popup_id = _clean_popup_id(cookie_payload.get("popup_id")) if cookie_payload else None
cookie_nonce = cookie_payload.get("n") if cookie_payload else None

def _fail_redirect(error_code: str, fallback_path: str = "/auth") -> RedirectResponse:
# In popup mode, route failures through /auth/callback so the popup
# can broadcast the error and self-close instead of stranding the opener.
if popup_id:
params = urlencode({"error": error_code, "popup_id": popup_id})
resp = RedirectResponse(f"{FRONTEND_URL}/auth/callback?{params}")
else:
resp = RedirectResponse(f"{FRONTEND_URL}{fallback_path}?error={error_code}")
resp.set_cookie(
key=OAUTH_STATE_COOKIE,
value="",
max_age=0,
httponly=True,
secure=True,
samesite="lax",
path="/",
)
return resp

if not GOOGLE_AVAILABLE:
return RedirectResponse(f"{FRONTEND_URL}/auth?error=google_not_configured")
return _fail_redirect("google_not_configured")

state_data = _decode_state(state) if state else {}
code_verifier = state_data.get("cv")
state_nonce = state_data.get("n")
if not cookie_payload or not cookie_nonce or not state_nonce or not _hmac.compare_digest(str(state_nonce), str(cookie_nonce)):
return _fail_redirect("invalid_state")

flow = Flow.from_client_config(_google_client_config(), scopes=AUTH_SCOPES)
flow.redirect_uri = GOOGLE_AUTH_REDIRECT_URI
flow.fetch_token(code=code, code_verifier=code_verifier)
try:
flow.fetch_token(code=code, code_verifier=code_verifier)
except Exception:
return _fail_redirect("oauth_exchange_failed")
creds = flow.credentials

# Fetch user info from Google
Expand All@@ -184,9 +303,7 @@ def google_callback(code: str = Query(...), state: str = Query(None)):

# Restrict to @bu.edu accounts
if not email.endswith("@bu.edu"):
return RedirectResponse(
f"{FRONTEND_URL}/auth?error=invalid_domain"
)
return _fail_redirect("invalid_domain")

# Determine user_id: check if this Google ID already exists
existing = table("users").select("id,is_approved", filters={"google_id": f"eq.{google_id}"})
Expand DownExpand Up@@ -233,7 +350,19 @@ def google_callback(code: str = Query(...), state: str = Query(None)):
)

if not is_approved:
return RedirectResponse(f"{FRONTEND_URL}/pending")
if popup_id:
return _fail_redirect("not_approved")
resp = RedirectResponse(f"{FRONTEND_URL}/pending")
resp.set_cookie(
key=OAUTH_STATE_COOKIE,
value="",
max_age=0,
httponly=True,
secure=True,
samesite="lax",
path="/",
)
return resp

# Build a short-lived HMAC token so the frontend can verify this redirect
# without a second round-trip to the backend.
Expand All@@ -250,5 +379,16 @@ def google_callback(code: str = Query(...), state: str = Query(None)):
"avatar": avatar_url,
"is_approved": "true",
**({"auth_token": auth_token} if auth_token else {}),
**({"popup_id": popup_id} if popup_id else {}),
})
return RedirectResponse(f"{FRONTEND_URL}/auth/callback?{params}")
resp = RedirectResponse(f"{FRONTEND_URL}/auth/callback?{params}")
resp.set_cookie(
key=OAUTH_STATE_COOKIE,
value="",
max_age=0,
httponly=True,
secure=True,
samesite="lax",
path="/",
)
return resp
33 changes: 28 additions & 5 deletions backend/routes/learn.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,7 +11,12 @@
from models import StartSessionBody, ChatBody, EndSessionBody, ActionBody, ModeSwitchBody
from services.auth_guard import require_self, get_session_user_id
from services.encryption import encrypt_if_present, encrypt_json, decrypt_if_present, decrypt_json
from services.gemini_service import MODEL_SMART, call_gemini_multiturn, extract_graph_update
from services.gemini_service import (
MODEL_DEFAULT,
MODEL_SMART,
call_gemini_multiturn,
extract_graph_update,
)
from services.graph_service import get_graph, apply_graph_update

router = APIRouter()
Expand All@@ -28,6 +33,18 @@
"teachback": "Teach-back (you explain to me)",
}

# User-facing speed/quality knob for the tutor chat.
# "fast" = flash (default, faster), "smart" = pro (opt-in, slower but stronger reasoning).
# Anything unrecognized falls back to fast so the default is the snappy one.
_MODEL_PREF_TO_MODEL = {
"fast": MODEL_DEFAULT,
"smart": MODEL_SMART,
}


def _resolve_tutor_model(model_pref: str | None) -> str:
return _MODEL_PREF_TO_MODEL.get(model_pref or "", MODEL_DEFAULT)


def _load_prompt(name: str) -> str:
with open(os.path.join(PROMPTS_DIR, name)) as f:
Expand DownExpand Up@@ -293,13 +310,15 @@ def start_session(body: StartSessionBody, request: Request):
)

try:
raw = call_gemini_multiturn(system_prompt, [], user_message, model=MODEL_SMART)
raw = call_gemini_multiturn(
system_prompt, [], user_message, model=_resolve_tutor_model(body.model_pref)
)
except Exception as e:
raise HTTPException(status_code=502, detail=f"Gemini error: {e}")

reply, graph_update = extract_graph_update(raw)
apply_graph_update(body.user_id, graph_update, course_id=course_id)

PENDING_SESSIONS[session_id] = {
"user_id": body.user_id,
"mode": body.mode,
Expand DownExpand Up@@ -339,7 +358,9 @@ def chat(body: ChatBody, request: Request):
)

try:
raw = call_gemini_multiturn(system_prompt, history, body.message, model=MODEL_SMART)
raw = call_gemini_multiturn(
system_prompt, history, body.message, model=_resolve_tutor_model(body.model_pref)
)
except Exception as e:
raise HTTPException(status_code=502, detail=f"Gemini error: {e}")

Expand DownExpand Up@@ -558,7 +579,9 @@ def action(body: ActionBody, request: Request):
action_message = f"[ACTION: {action_prompts.get(body.action_type, '')}]"

try:
raw = call_gemini_multiturn(system_prompt, history, action_message, model=MODEL_SMART)
raw = call_gemini_multiturn(
system_prompt, history, action_message, model=_resolve_tutor_model(body.model_pref)
)
except Exception as e:
raise HTTPException(status_code=502, detail=f"Gemini error: {e}")

Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion backend/models/__init__.py
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
from typing import Optional, Union, List
from typing import Optional, Union, List, Literal
from pydantic import BaseModel, Field


Expand All@@ -10,6 +10,7 @@ class StartSessionBody(BaseModel):
mode: str = "socratic"
use_shared_context: bool = True
course_id: Optional[str] = None # Direct course_id lookup instead of resolving from topic
model_pref: Optional[Literal["fast", "smart"]] = None # "fast" (default, gemini-2.5-flash) or "smart" (gemini-2.5-pro)


class ChatBody(BaseModel):
Expand All@@ -18,6 +19,7 @@ class ChatBody(BaseModel):
message: str
mode: str = "socratic"
use_shared_context: bool = True
model_pref: Optional[Literal["fast", "smart"]] = None # "fast" (default, gemini-2.5-flash) or "smart" (gemini-2.5-pro)


class EndSessionBody(BaseModel):
Expand All@@ -31,6 +33,7 @@ class ActionBody(BaseModel):
action_type: str = "hint"
mode: str = "socratic"
use_shared_context: bool = True
model_pref: Optional[Literal["fast", "smart"]] = None # "fast" (default, gemini-2.5-flash) or "smart" (gemini-2.5-pro)


# ── Quiz ──────────────────────────────────────────────────────────────────────
Expand Down
164 changes: 152 additions & 12 deletions backend/routes/auth.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,6 +9,7 @@
import base64
import hashlib
import hmac as _hmac
import re
import secrets
import time as _time
from urllib.parse import urlencode
Expand DownExpand Up@@ -39,6 +40,14 @@

router = APIRouter()

OAUTH_STATE_COOKIE = "sapling_oauth_state"
_OAUTH_COOKIE_MAX_AGE = 600
_POPUP_ID_RE = re.compile(r"^[A-Za-z0-9_-]{1,128}$")

# Fallback in-memory store for environments without SESSION_SECRET; entries
# are keyed by nonce and expire after _OAUTH_COOKIE_MAX_AGE seconds.
_OAUTH_FALLBACK_STORE: dict[str, tuple[float, dict]] = {}


def _google_client_config() -> dict:
return {
Expand DownExpand Up@@ -73,6 +82,68 @@ def _generate_pkce_pair():
return code_verifier, code_challenge


def _clean_popup_id(s: str | None) -> str | None:
if not s:
return None
return s if _POPUP_ID_RE.match(s) else None


def _encode_oauth_cookie(payload: dict) -> str:
raw = json.dumps(payload, separators=(",", ":")).encode()
payload_b64 = base64.urlsafe_b64encode(raw).decode().rstrip("=")
if SESSION_SECRET:
sig_bytes = _hmac.new(SESSION_SECRET.encode(), payload_b64.encode(), hashlib.sha256).digest()
sig_b64 = base64.urlsafe_b64encode(sig_bytes).decode().rstrip("=")
return f"{payload_b64}.{sig_b64}"
nonce = payload.get("n", "")
if nonce:
_OAUTH_FALLBACK_STORE[nonce] = (_time.monotonic() + _OAUTH_COOKIE_MAX_AGE, payload)
_prune_fallback_store()
return payload_b64


def _decode_oauth_cookie(cookie_value: str | None) -> dict | None:
if not cookie_value:
return None
if SESSION_SECRET:
if "." not in cookie_value:
return None
try:
payload_b64, sig_b64 = cookie_value.rsplit(".", 1)
except ValueError:
return None
expected = _hmac.new(SESSION_SECRET.encode(), payload_b64.encode(), hashlib.sha256).digest()
expected_b64 = base64.urlsafe_b64encode(expected).decode().rstrip("=")
if not _hmac.compare_digest(expected_b64, sig_b64):
return None
try:
padded = payload_b64 + "=" * (-len(payload_b64) % 4)
payload = json.loads(base64.urlsafe_b64decode(padded.encode()).decode())
except Exception:
return None
return payload if isinstance(payload, dict) else None
try:
padded = cookie_value + "=" * (-len(cookie_value) % 4)
payload = json.loads(base64.urlsafe_b64decode(padded.encode()).decode())
except Exception:
return None
if not isinstance(payload, dict):
return None
nonce = payload.get("n")
_prune_fallback_store()
entry = _OAUTH_FALLBACK_STORE.get(nonce or "")
if not entry:
return None
return entry[1]


def _prune_fallback_store() -> None:
now = _time.monotonic()
expired = [k for k, (exp, _) in _OAUTH_FALLBACK_STORE.items() if exp < now]
for k in expired:
_OAUTH_FALLBACK_STORE.pop(k, None)


@router.get("/me")
def get_me(request: Request):
"""Return approval and onboarding status for a given user_id."""
Expand DownExpand Up@@ -136,36 +207,84 @@ def get_me(request: Request):


@router.get("/google")
def google_login():
def google_login(popup_id: str = Query(None)):
"""Redirect to Google consent screen with identity + calendar scopes."""
if not GOOGLE_AVAILABLE or not GOOGLE_CLIENT_ID:
raise HTTPException(status_code=400, detail="Google OAuth not configured")

code_verifier, code_challenge = _generate_pkce_pair()
nonce = secrets.token_urlsafe(32)
clean_popup = _clean_popup_id(popup_id)

flow = Flow.from_client_config(_google_client_config(), scopes=AUTH_SCOPES)
flow.redirect_uri = GOOGLE_AUTH_REDIRECT_URI
auth_url, _ = flow.authorization_url(
prompt="consent",
access_type="offline",
state=_encode_state({"action": "signin", "cv": code_verifier}),
state=_encode_state({"action": "signin", "n": nonce}),
code_challenge=code_challenge,
code_challenge_method="S256",
)
return RedirectResponse(auth_url)

cookie_value = _encode_oauth_cookie({
"n": nonce,
"cv": code_verifier,
"popup_id": clean_popup,
})
response = RedirectResponse(auth_url)
response.set_cookie(
key=OAUTH_STATE_COOKIE,
value=cookie_value,
max_age=_OAUTH_COOKIE_MAX_AGE,
httponly=True,
secure=True,
samesite="lax",
path="/",
)
return response


@router.get("/google/callback")
def google_callback(code: str = Query(...), state: str = Query(None)):
def google_callback(request: Request, code: str = Query(...), state: str = Query(None)):
"""Exchange auth code for tokens, validate @bu.edu, upsert user."""
cookie_payload = _decode_oauth_cookie(request.cookies.get(OAUTH_STATE_COOKIE))
code_verifier = cookie_payload.get("cv") if cookie_payload else None
popup_id = _clean_popup_id(cookie_payload.get("popup_id")) if cookie_payload else None
cookie_nonce = cookie_payload.get("n") if cookie_payload else None

def _fail_redirect(error_code: str, fallback_path: str = "/auth") -> RedirectResponse:
# In popup mode, route failures through /auth/callback so the popup
# can broadcast the error and self-close instead of stranding the opener.
if popup_id:
params = urlencode({"error": error_code, "popup_id": popup_id})
resp = RedirectResponse(f"{FRONTEND_URL}/auth/callback?{params}")
else:
resp = RedirectResponse(f"{FRONTEND_URL}{fallback_path}?error={error_code}")
resp.set_cookie(
key=OAUTH_STATE_COOKIE,
value="",
max_age=0,
httponly=True,
secure=True,
samesite="lax",
path="/",
)
return resp

if not GOOGLE_AVAILABLE:
return RedirectResponse(f"{FRONTEND_URL}/auth?error=google_not_configured")
return _fail_redirect("google_not_configured")

state_data = _decode_state(state) if state else {}
code_verifier = state_data.get("cv")
state_nonce = state_data.get("n")
if not cookie_payload or not cookie_nonce or not state_nonce or not _hmac.compare_digest(str(state_nonce), str(cookie_nonce)):
return _fail_redirect("invalid_state")

flow = Flow.from_client_config(_google_client_config(), scopes=AUTH_SCOPES)
flow.redirect_uri = GOOGLE_AUTH_REDIRECT_URI
flow.fetch_token(code=code, code_verifier=code_verifier)
try:
flow.fetch_token(code=code, code_verifier=code_verifier)
except Exception:
return _fail_redirect("oauth_exchange_failed")
creds = flow.credentials

# Fetch user info from Google
Expand All@@ -184,9 +303,7 @@ def google_callback(code: str = Query(...), state: str = Query(None)):

# Restrict to @bu.edu accounts
if not email.endswith("@bu.edu"):
return RedirectResponse(
f"{FRONTEND_URL}/auth?error=invalid_domain"
)
return _fail_redirect("invalid_domain")

# Determine user_id: check if this Google ID already exists
existing = table("users").select("id,is_approved", filters={"google_id": f"eq.{google_id}"})
Expand DownExpand Up@@ -233,7 +350,19 @@ def google_callback(code: str = Query(...), state: str = Query(None)):
)

if not is_approved:
return RedirectResponse(f"{FRONTEND_URL}/pending")
if popup_id:
return _fail_redirect("not_approved")
resp = RedirectResponse(f"{FRONTEND_URL}/pending")
resp.set_cookie(
key=OAUTH_STATE_COOKIE,
value="",
max_age=0,
httponly=True,
secure=True,
samesite="lax",
path="/",
)
return resp

# Build a short-lived HMAC token so the frontend can verify this redirect
# without a second round-trip to the backend.
Expand All@@ -250,5 +379,16 @@ def google_callback(code: str = Query(...), state: str = Query(None)):
"avatar": avatar_url,
"is_approved": "true",
**({"auth_token": auth_token} if auth_token else {}),
**({"popup_id": popup_id} if popup_id else {}),
})
return RedirectResponse(f"{FRONTEND_URL}/auth/callback?{params}")
resp = RedirectResponse(f"{FRONTEND_URL}/auth/callback?{params}")
resp.set_cookie(
key=OAUTH_STATE_COOKIE,
value="",
max_age=0,
httponly=True,
secure=True,
samesite="lax",
path="/",
)
return resp
33 changes: 28 additions & 5 deletions backend/routes/learn.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,7 +11,12 @@
from models import StartSessionBody, ChatBody, EndSessionBody, ActionBody, ModeSwitchBody
from services.auth_guard import require_self, get_session_user_id
from services.encryption import encrypt_if_present, encrypt_json, decrypt_if_present, decrypt_json
from services.gemini_service import MODEL_SMART, call_gemini_multiturn, extract_graph_update
from services.gemini_service import (
MODEL_DEFAULT,
MODEL_SMART,
call_gemini_multiturn,
extract_graph_update,
)
from services.graph_service import get_graph, apply_graph_update

router = APIRouter()
Expand All@@ -28,6 +33,18 @@
"teachback": "Teach-back (you explain to me)",
}

# User-facing speed/quality knob for the tutor chat.
# "fast" = flash (default, faster), "smart" = pro (opt-in, slower but stronger reasoning).
# Anything unrecognized falls back to fast so the default is the snappy one.
_MODEL_PREF_TO_MODEL = {
"fast": MODEL_DEFAULT,
"smart": MODEL_SMART,
}


def _resolve_tutor_model(model_pref: str | None) -> str:
return _MODEL_PREF_TO_MODEL.get(model_pref or "", MODEL_DEFAULT)


def _load_prompt(name: str) -> str:
with open(os.path.join(PROMPTS_DIR, name)) as f:
Expand DownExpand Up@@ -293,13 +310,15 @@ def start_session(body: StartSessionBody, request: Request):
)

try:
raw = call_gemini_multiturn(system_prompt, [], user_message, model=MODEL_SMART)
raw = call_gemini_multiturn(
system_prompt, [], user_message, model=_resolve_tutor_model(body.model_pref)
)
except Exception as e:
raise HTTPException(status_code=502, detail=f"Gemini error: {e}")

reply, graph_update = extract_graph_update(raw)
apply_graph_update(body.user_id, graph_update, course_id=course_id)

PENDING_SESSIONS[session_id] = {
"user_id": body.user_id,
"mode": body.mode,
Expand DownExpand Up@@ -339,7 +358,9 @@ def chat(body: ChatBody, request: Request):
)

try:
raw = call_gemini_multiturn(system_prompt, history, body.message, model=MODEL_SMART)
raw = call_gemini_multiturn(
system_prompt, history, body.message, model=_resolve_tutor_model(body.model_pref)
)
except Exception as e:
raise HTTPException(status_code=502, detail=f"Gemini error: {e}")

Expand DownExpand Up@@ -558,7 +579,9 @@ def action(body: ActionBody, request: Request):
action_message = f"[ACTION: {action_prompts.get(body.action_type, '')}]"

try:
raw = call_gemini_multiturn(system_prompt, history, action_message, model=MODEL_SMART)
raw = call_gemini_multiturn(
system_prompt, history, action_message, model=_resolve_tutor_model(body.model_pref)
)
except Exception as e:
raise HTTPException(status_code=502, detail=f"Gemini error: {e}")

Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion backend/models/__init__.py
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
from typing import Optional, Union, List
from typing import Optional, Union, List, Literal
from pydantic import BaseModel, Field


Expand All@@ -10,6 +10,7 @@ class StartSessionBody(BaseModel):
mode: str = "socratic"
use_shared_context: bool = True
course_id: Optional[str] = None # Direct course_id lookup instead of resolving from topic
model_pref: Optional[Literal["fast", "smart"]] = None # "fast" (default, gemini-2.5-flash) or "smart" (gemini-2.5-pro)


class ChatBody(BaseModel):
Expand All@@ -18,6 +19,7 @@ class ChatBody(BaseModel):
message: str
mode: str = "socratic"
use_shared_context: bool = True
model_pref: Optional[Literal["fast", "smart"]] = None # "fast" (default, gemini-2.5-flash) or "smart" (gemini-2.5-pro)


class EndSessionBody(BaseModel):
Expand All@@ -31,6 +33,7 @@ class ActionBody(BaseModel):
action_type: str = "hint"
mode: str = "socratic"
use_shared_context: bool = True
model_pref: Optional[Literal["fast", "smart"]] = None # "fast" (default, gemini-2.5-flash) or "smart" (gemini-2.5-pro)


# ── Quiz ──────────────────────────────────────────────────────────────────────
Expand Down
164 changes: 152 additions & 12 deletions backend/routes/auth.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,6 +9,7 @@
import base64
import hashlib
import hmac as _hmac
import re
import secrets
import time as _time
from urllib.parse import urlencode
Expand DownExpand Up@@ -39,6 +40,14 @@

router = APIRouter()

OAUTH_STATE_COOKIE = "sapling_oauth_state"
_OAUTH_COOKIE_MAX_AGE = 600
_POPUP_ID_RE = re.compile(r"^[A-Za-z0-9_-]{1,128}$")

# Fallback in-memory store for environments without SESSION_SECRET; entries
# are keyed by nonce and expire after _OAUTH_COOKIE_MAX_AGE seconds.
_OAUTH_FALLBACK_STORE: dict[str, tuple[float, dict]] = {}


def _google_client_config() -> dict:
return {
Expand DownExpand Up@@ -73,6 +82,68 @@ def _generate_pkce_pair():
return code_verifier, code_challenge


def _clean_popup_id(s: str | None) -> str | None:
if not s:
return None
return s if _POPUP_ID_RE.match(s) else None


def _encode_oauth_cookie(payload: dict) -> str:
raw = json.dumps(payload, separators=(",", ":")).encode()
payload_b64 = base64.urlsafe_b64encode(raw).decode().rstrip("=")
if SESSION_SECRET:
sig_bytes = _hmac.new(SESSION_SECRET.encode(), payload_b64.encode(), hashlib.sha256).digest()
sig_b64 = base64.urlsafe_b64encode(sig_bytes).decode().rstrip("=")
return f"{payload_b64}.{sig_b64}"
nonce = payload.get("n", "")
if nonce:
_OAUTH_FALLBACK_STORE[nonce] = (_time.monotonic() + _OAUTH_COOKIE_MAX_AGE, payload)
_prune_fallback_store()
return payload_b64


def _decode_oauth_cookie(cookie_value: str | None) -> dict | None:
if not cookie_value:
return None
if SESSION_SECRET:
if "." not in cookie_value:
return None
try:
payload_b64, sig_b64 = cookie_value.rsplit(".", 1)
except ValueError:
return None
expected = _hmac.new(SESSION_SECRET.encode(), payload_b64.encode(), hashlib.sha256).digest()
expected_b64 = base64.urlsafe_b64encode(expected).decode().rstrip("=")
if not _hmac.compare_digest(expected_b64, sig_b64):
return None
try:
padded = payload_b64 + "=" * (-len(payload_b64) % 4)
payload = json.loads(base64.urlsafe_b64decode(padded.encode()).decode())
except Exception:
return None
return payload if isinstance(payload, dict) else None
try:
padded = cookie_value + "=" * (-len(cookie_value) % 4)
payload = json.loads(base64.urlsafe_b64decode(padded.encode()).decode())
except Exception:
return None
if not isinstance(payload, dict):
return None
nonce = payload.get("n")
_prune_fallback_store()
entry = _OAUTH_FALLBACK_STORE.get(nonce or "")
if not entry:
return None
return entry[1]


def _prune_fallback_store() -> None:
now = _time.monotonic()
expired = [k for k, (exp, _) in _OAUTH_FALLBACK_STORE.items() if exp < now]
for k in expired:
_OAUTH_FALLBACK_STORE.pop(k, None)


@router.get("/me")
def get_me(request: Request):
"""Return approval and onboarding status for a given user_id."""
Expand DownExpand Up@@ -136,36 +207,84 @@ def get_me(request: Request):


@router.get("/google")
def google_login():
def google_login(popup_id: str = Query(None)):
"""Redirect to Google consent screen with identity + calendar scopes."""
if not GOOGLE_AVAILABLE or not GOOGLE_CLIENT_ID:
raise HTTPException(status_code=400, detail="Google OAuth not configured")

code_verifier, code_challenge = _generate_pkce_pair()
nonce = secrets.token_urlsafe(32)
clean_popup = _clean_popup_id(popup_id)

flow = Flow.from_client_config(_google_client_config(), scopes=AUTH_SCOPES)
flow.redirect_uri = GOOGLE_AUTH_REDIRECT_URI
auth_url, _ = flow.authorization_url(
prompt="consent",
access_type="offline",
state=_encode_state({"action": "signin", "cv": code_verifier}),
state=_encode_state({"action": "signin", "n": nonce}),
code_challenge=code_challenge,
code_challenge_method="S256",
)
return RedirectResponse(auth_url)

cookie_value = _encode_oauth_cookie({
"n": nonce,
"cv": code_verifier,
"popup_id": clean_popup,
})
response = RedirectResponse(auth_url)
response.set_cookie(
key=OAUTH_STATE_COOKIE,
value=cookie_value,
max_age=_OAUTH_COOKIE_MAX_AGE,
httponly=True,
secure=True,
samesite="lax",
path="/",
)
return response


@router.get("/google/callback")
def google_callback(code: str = Query(...), state: str = Query(None)):
def google_callback(request: Request, code: str = Query(...), state: str = Query(None)):
"""Exchange auth code for tokens, validate @bu.edu, upsert user."""
cookie_payload = _decode_oauth_cookie(request.cookies.get(OAUTH_STATE_COOKIE))
code_verifier = cookie_payload.get("cv") if cookie_payload else None
popup_id = _clean_popup_id(cookie_payload.get("popup_id")) if cookie_payload else None
cookie_nonce = cookie_payload.get("n") if cookie_payload else None

def _fail_redirect(error_code: str, fallback_path: str = "/auth") -> RedirectResponse:
# In popup mode, route failures through /auth/callback so the popup
# can broadcast the error and self-close instead of stranding the opener.
if popup_id:
params = urlencode({"error": error_code, "popup_id": popup_id})
resp = RedirectResponse(f"{FRONTEND_URL}/auth/callback?{params}")
else:
resp = RedirectResponse(f"{FRONTEND_URL}{fallback_path}?error={error_code}")
resp.set_cookie(
key=OAUTH_STATE_COOKIE,
value="",
max_age=0,
httponly=True,
secure=True,
samesite="lax",
path="/",
)
return resp

if not GOOGLE_AVAILABLE:
return RedirectResponse(f"{FRONTEND_URL}/auth?error=google_not_configured")
return _fail_redirect("google_not_configured")

state_data = _decode_state(state) if state else {}
code_verifier = state_data.get("cv")
state_nonce = state_data.get("n")
if not cookie_payload or not cookie_nonce or not state_nonce or not _hmac.compare_digest(str(state_nonce), str(cookie_nonce)):
return _fail_redirect("invalid_state")

flow = Flow.from_client_config(_google_client_config(), scopes=AUTH_SCOPES)
flow.redirect_uri = GOOGLE_AUTH_REDIRECT_URI
flow.fetch_token(code=code, code_verifier=code_verifier)
try:
flow.fetch_token(code=code, code_verifier=code_verifier)
except Exception:
return _fail_redirect("oauth_exchange_failed")
creds = flow.credentials

# Fetch user info from Google
Expand All@@ -184,9 +303,7 @@ def google_callback(code: str = Query(...), state: str = Query(None)):

# Restrict to @bu.edu accounts
if not email.endswith("@bu.edu"):
return RedirectResponse(
f"{FRONTEND_URL}/auth?error=invalid_domain"
)
return _fail_redirect("invalid_domain")

# Determine user_id: check if this Google ID already exists
existing = table("users").select("id,is_approved", filters={"google_id": f"eq.{google_id}"})
Expand DownExpand Up@@ -233,7 +350,19 @@ def google_callback(code: str = Query(...), state: str = Query(None)):
)

if not is_approved:
return RedirectResponse(f"{FRONTEND_URL}/pending")
if popup_id:
return _fail_redirect("not_approved")
resp = RedirectResponse(f"{FRONTEND_URL}/pending")
resp.set_cookie(
key=OAUTH_STATE_COOKIE,
value="",
max_age=0,
httponly=True,
secure=True,
samesite="lax",
path="/",
)
return resp

# Build a short-lived HMAC token so the frontend can verify this redirect
# without a second round-trip to the backend.
Expand All@@ -250,5 +379,16 @@ def google_callback(code: str = Query(...), state: str = Query(None)):
"avatar": avatar_url,
"is_approved": "true",
**({"auth_token": auth_token} if auth_token else {}),
**({"popup_id": popup_id} if popup_id else {}),
})
return RedirectResponse(f"{FRONTEND_URL}/auth/callback?{params}")
resp = RedirectResponse(f"{FRONTEND_URL}/auth/callback?{params}")
resp.set_cookie(
key=OAUTH_STATE_COOKIE,
value="",
max_age=0,
httponly=True,
secure=True,
samesite="lax",
path="/",
)
return resp
33 changes: 28 additions & 5 deletions backend/routes/learn.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,7 +11,12 @@
from models import StartSessionBody, ChatBody, EndSessionBody, ActionBody, ModeSwitchBody
from services.auth_guard import require_self, get_session_user_id
from services.encryption import encrypt_if_present, encrypt_json, decrypt_if_present, decrypt_json
from services.gemini_service import MODEL_SMART, call_gemini_multiturn, extract_graph_update
from services.gemini_service import (
MODEL_DEFAULT,
MODEL_SMART,
call_gemini_multiturn,
extract_graph_update,
)
from services.graph_service import get_graph, apply_graph_update

router = APIRouter()
Expand All@@ -28,6 +33,18 @@
"teachback": "Teach-back (you explain to me)",
}

# User-facing speed/quality knob for the tutor chat.
# "fast" = flash (default, faster), "smart" = pro (opt-in, slower but stronger reasoning).
# Anything unrecognized falls back to fast so the default is the snappy one.
_MODEL_PREF_TO_MODEL = {
"fast": MODEL_DEFAULT,
"smart": MODEL_SMART,
}


def _resolve_tutor_model(model_pref: str | None) -> str:
return _MODEL_PREF_TO_MODEL.get(model_pref or "", MODEL_DEFAULT)


def _load_prompt(name: str) -> str:
with open(os.path.join(PROMPTS_DIR, name)) as f:
Expand DownExpand Up@@ -293,13 +310,15 @@ def start_session(body: StartSessionBody, request: Request):
)

try:
raw = call_gemini_multiturn(system_prompt, [], user_message, model=MODEL_SMART)
raw = call_gemini_multiturn(
system_prompt, [], user_message, model=_resolve_tutor_model(body.model_pref)
)
except Exception as e:
raise HTTPException(status_code=502, detail=f"Gemini error: {e}")

reply, graph_update = extract_graph_update(raw)
apply_graph_update(body.user_id, graph_update, course_id=course_id)

PENDING_SESSIONS[session_id] = {
"user_id": body.user_id,
"mode": body.mode,
Expand DownExpand Up@@ -339,7 +358,9 @@ def chat(body: ChatBody, request: Request):
)

try:
raw = call_gemini_multiturn(system_prompt, history, body.message, model=MODEL_SMART)
raw = call_gemini_multiturn(
system_prompt, history, body.message, model=_resolve_tutor_model(body.model_pref)
)
except Exception as e:
raise HTTPException(status_code=502, detail=f"Gemini error: {e}")

Expand DownExpand Up@@ -558,7 +579,9 @@ def action(body: ActionBody, request: Request):
action_message = f"[ACTION: {action_prompts.get(body.action_type, '')}]"

try:
raw = call_gemini_multiturn(system_prompt, history, action_message, model=MODEL_SMART)
raw = call_gemini_multiturn(
system_prompt, history, action_message, model=_resolve_tutor_model(body.model_pref)
)
except Exception as e:
raise HTTPException(status_code=502, detail=f"Gemini error: {e}")

Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion backend/models/__init__.py
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
from typing import Optional, Union, List
from typing import Optional, Union, List, Literal
from pydantic import BaseModel, Field


Expand All@@ -10,6 +10,7 @@ class StartSessionBody(BaseModel):
mode: str = "socratic"
use_shared_context: bool = True
course_id: Optional[str] = None # Direct course_id lookup instead of resolving from topic
model_pref: Optional[Literal["fast", "smart"]] = None # "fast" (default, gemini-2.5-flash) or "smart" (gemini-2.5-pro)


class ChatBody(BaseModel):
Expand All@@ -18,6 +19,7 @@ class ChatBody(BaseModel):
message: str
mode: str = "socratic"
use_shared_context: bool = True
model_pref: Optional[Literal["fast", "smart"]] = None # "fast" (default, gemini-2.5-flash) or "smart" (gemini-2.5-pro)


class EndSessionBody(BaseModel):
Expand All@@ -31,6 +33,7 @@ class ActionBody(BaseModel):
action_type: str = "hint"
mode: str = "socratic"
use_shared_context: bool = True
model_pref: Optional[Literal["fast", "smart"]] = None # "fast" (default, gemini-2.5-flash) or "smart" (gemini-2.5-pro)


# ── Quiz ──────────────────────────────────────────────────────────────────────
Expand Down
164 changes: 152 additions & 12 deletions backend/routes/auth.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,6 +9,7 @@
import base64
import hashlib
import hmac as _hmac
import re
import secrets
import time as _time
from urllib.parse import urlencode
Expand DownExpand Up@@ -39,6 +40,14 @@

router = APIRouter()

OAUTH_STATE_COOKIE = "sapling_oauth_state"
_OAUTH_COOKIE_MAX_AGE = 600
_POPUP_ID_RE = re.compile(r"^[A-Za-z0-9_-]{1,128}$")

# Fallback in-memory store for environments without SESSION_SECRET; entries
# are keyed by nonce and expire after _OAUTH_COOKIE_MAX_AGE seconds.
_OAUTH_FALLBACK_STORE: dict[str, tuple[float, dict]] = {}


def _google_client_config() -> dict:
return {
Expand DownExpand Up@@ -73,6 +82,68 @@ def _generate_pkce_pair():
return code_verifier, code_challenge


def _clean_popup_id(s: str | None) -> str | None:
if not s:
return None
return s if _POPUP_ID_RE.match(s) else None


def _encode_oauth_cookie(payload: dict) -> str:
raw = json.dumps(payload, separators=(",", ":")).encode()
payload_b64 = base64.urlsafe_b64encode(raw).decode().rstrip("=")
if SESSION_SECRET:
sig_bytes = _hmac.new(SESSION_SECRET.encode(), payload_b64.encode(), hashlib.sha256).digest()
sig_b64 = base64.urlsafe_b64encode(sig_bytes).decode().rstrip("=")
return f"{payload_b64}.{sig_b64}"
nonce = payload.get("n", "")
if nonce:
_OAUTH_FALLBACK_STORE[nonce] = (_time.monotonic() + _OAUTH_COOKIE_MAX_AGE, payload)
_prune_fallback_store()
return payload_b64


def _decode_oauth_cookie(cookie_value: str | None) -> dict | None:
if not cookie_value:
return None
if SESSION_SECRET:
if "." not in cookie_value:
return None
try:
payload_b64, sig_b64 = cookie_value.rsplit(".", 1)
except ValueError:
return None
expected = _hmac.new(SESSION_SECRET.encode(), payload_b64.encode(), hashlib.sha256).digest()
expected_b64 = base64.urlsafe_b64encode(expected).decode().rstrip("=")
if not _hmac.compare_digest(expected_b64, sig_b64):
return None
try:
padded = payload_b64 + "=" * (-len(payload_b64) % 4)
payload = json.loads(base64.urlsafe_b64decode(padded.encode()).decode())
except Exception:
return None
return payload if isinstance(payload, dict) else None
try:
padded = cookie_value + "=" * (-len(cookie_value) % 4)
payload = json.loads(base64.urlsafe_b64decode(padded.encode()).decode())
except Exception:
return None
if not isinstance(payload, dict):
return None
nonce = payload.get("n")
_prune_fallback_store()
entry = _OAUTH_FALLBACK_STORE.get(nonce or "")
if not entry:
return None
return entry[1]


def _prune_fallback_store() -> None:
now = _time.monotonic()
expired = [k for k, (exp, _) in _OAUTH_FALLBACK_STORE.items() if exp < now]
for k in expired:
_OAUTH_FALLBACK_STORE.pop(k, None)


@router.get("/me")
def get_me(request: Request):
"""Return approval and onboarding status for a given user_id."""
Expand DownExpand Up@@ -136,36 +207,84 @@ def get_me(request: Request):


@router.get("/google")
def google_login():
def google_login(popup_id: str = Query(None)):
"""Redirect to Google consent screen with identity + calendar scopes."""
if not GOOGLE_AVAILABLE or not GOOGLE_CLIENT_ID:
raise HTTPException(status_code=400, detail="Google OAuth not configured")

code_verifier, code_challenge = _generate_pkce_pair()
nonce = secrets.token_urlsafe(32)
clean_popup = _clean_popup_id(popup_id)

flow = Flow.from_client_config(_google_client_config(), scopes=AUTH_SCOPES)
flow.redirect_uri = GOOGLE_AUTH_REDIRECT_URI
auth_url, _ = flow.authorization_url(
prompt="consent",
access_type="offline",
state=_encode_state({"action": "signin", "cv": code_verifier}),
state=_encode_state({"action": "signin", "n": nonce}),
code_challenge=code_challenge,
code_challenge_method="S256",
)
return RedirectResponse(auth_url)

cookie_value = _encode_oauth_cookie({
"n": nonce,
"cv": code_verifier,
"popup_id": clean_popup,
})
response = RedirectResponse(auth_url)
response.set_cookie(
key=OAUTH_STATE_COOKIE,
value=cookie_value,
max_age=_OAUTH_COOKIE_MAX_AGE,
httponly=True,
secure=True,
samesite="lax",
path="/",
)
return response


@router.get("/google/callback")
def google_callback(code: str = Query(...), state: str = Query(None)):
def google_callback(request: Request, code: str = Query(...), state: str = Query(None)):
"""Exchange auth code for tokens, validate @bu.edu, upsert user."""
cookie_payload = _decode_oauth_cookie(request.cookies.get(OAUTH_STATE_COOKIE))
code_verifier = cookie_payload.get("cv") if cookie_payload else None
popup_id = _clean_popup_id(cookie_payload.get("popup_id")) if cookie_payload else None
cookie_nonce = cookie_payload.get("n") if cookie_payload else None

def _fail_redirect(error_code: str, fallback_path: str = "/auth") -> RedirectResponse:
# In popup mode, route failures through /auth/callback so the popup
# can broadcast the error and self-close instead of stranding the opener.
if popup_id:
params = urlencode({"error": error_code, "popup_id": popup_id})
resp = RedirectResponse(f"{FRONTEND_URL}/auth/callback?{params}")
else:
resp = RedirectResponse(f"{FRONTEND_URL}{fallback_path}?error={error_code}")
resp.set_cookie(
key=OAUTH_STATE_COOKIE,
value="",
max_age=0,
httponly=True,
secure=True,
samesite="lax",
path="/",
)
return resp

if not GOOGLE_AVAILABLE:
return RedirectResponse(f"{FRONTEND_URL}/auth?error=google_not_configured")
return _fail_redirect("google_not_configured")

state_data = _decode_state(state) if state else {}
code_verifier = state_data.get("cv")
state_nonce = state_data.get("n")
if not cookie_payload or not cookie_nonce or not state_nonce or not _hmac.compare_digest(str(state_nonce), str(cookie_nonce)):
return _fail_redirect("invalid_state")

flow = Flow.from_client_config(_google_client_config(), scopes=AUTH_SCOPES)
flow.redirect_uri = GOOGLE_AUTH_REDIRECT_URI
flow.fetch_token(code=code, code_verifier=code_verifier)
try:
flow.fetch_token(code=code, code_verifier=code_verifier)
except Exception:
return _fail_redirect("oauth_exchange_failed")
creds = flow.credentials

# Fetch user info from Google
Expand All@@ -184,9 +303,7 @@ def google_callback(code: str = Query(...), state: str = Query(None)):

# Restrict to @bu.edu accounts
if not email.endswith("@bu.edu"):
return RedirectResponse(
f"{FRONTEND_URL}/auth?error=invalid_domain"
)
return _fail_redirect("invalid_domain")

# Determine user_id: check if this Google ID already exists
existing = table("users").select("id,is_approved", filters={"google_id": f"eq.{google_id}"})
Expand DownExpand Up@@ -233,7 +350,19 @@ def google_callback(code: str = Query(...), state: str = Query(None)):
)

if not is_approved:
return RedirectResponse(f"{FRONTEND_URL}/pending")
if popup_id:
return _fail_redirect("not_approved")
resp = RedirectResponse(f"{FRONTEND_URL}/pending")
resp.set_cookie(
key=OAUTH_STATE_COOKIE,
value="",
max_age=0,
httponly=True,
secure=True,
samesite="lax",
path="/",
)
return resp

# Build a short-lived HMAC token so the frontend can verify this redirect
# without a second round-trip to the backend.
Expand All@@ -250,5 +379,16 @@ def google_callback(code: str = Query(...), state: str = Query(None)):
"avatar": avatar_url,
"is_approved": "true",
**({"auth_token": auth_token} if auth_token else {}),
**({"popup_id": popup_id} if popup_id else {}),
})
return RedirectResponse(f"{FRONTEND_URL}/auth/callback?{params}")
resp = RedirectResponse(f"{FRONTEND_URL}/auth/callback?{params}")
resp.set_cookie(
key=OAUTH_STATE_COOKIE,
value="",
max_age=0,
httponly=True,
secure=True,
samesite="lax",
path="/",
)
return resp
33 changes: 28 additions & 5 deletions backend/routes/learn.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,7 +11,12 @@
from models import StartSessionBody, ChatBody, EndSessionBody, ActionBody, ModeSwitchBody
from services.auth_guard import require_self, get_session_user_id
from services.encryption import encrypt_if_present, encrypt_json, decrypt_if_present, decrypt_json
from services.gemini_service import MODEL_SMART, call_gemini_multiturn, extract_graph_update
from services.gemini_service import (
MODEL_DEFAULT,
MODEL_SMART,
call_gemini_multiturn,
extract_graph_update,
)
from services.graph_service import get_graph, apply_graph_update

router = APIRouter()
Expand All@@ -28,6 +33,18 @@
"teachback": "Teach-back (you explain to me)",
}

# User-facing speed/quality knob for the tutor chat.
# "fast" = flash (default, faster), "smart" = pro (opt-in, slower but stronger reasoning).
# Anything unrecognized falls back to fast so the default is the snappy one.
_MODEL_PREF_TO_MODEL = {
"fast": MODEL_DEFAULT,
"smart": MODEL_SMART,
}


def _resolve_tutor_model(model_pref: str | None) -> str:
return _MODEL_PREF_TO_MODEL.get(model_pref or "", MODEL_DEFAULT)


def _load_prompt(name: str) -> str:
with open(os.path.join(PROMPTS_DIR, name)) as f:
Expand DownExpand Up@@ -293,13 +310,15 @@ def start_session(body: StartSessionBody, request: Request):
)

try:
raw = call_gemini_multiturn(system_prompt, [], user_message, model=MODEL_SMART)
raw = call_gemini_multiturn(
system_prompt, [], user_message, model=_resolve_tutor_model(body.model_pref)
)
except Exception as e:
raise HTTPException(status_code=502, detail=f"Gemini error: {e}")

reply, graph_update = extract_graph_update(raw)
apply_graph_update(body.user_id, graph_update, course_id=course_id)

PENDING_SESSIONS[session_id] = {
"user_id": body.user_id,
"mode": body.mode,
Expand DownExpand Up@@ -339,7 +358,9 @@ def chat(body: ChatBody, request: Request):
)

try:
raw = call_gemini_multiturn(system_prompt, history, body.message, model=MODEL_SMART)
raw = call_gemini_multiturn(
system_prompt, history, body.message, model=_resolve_tutor_model(body.model_pref)
)
except Exception as e:
raise HTTPException(status_code=502, detail=f"Gemini error: {e}")

Expand DownExpand Up@@ -558,7 +579,9 @@ def action(body: ActionBody, request: Request):
action_message = f"[ACTION: {action_prompts.get(body.action_type, '')}]"

try:
raw = call_gemini_multiturn(system_prompt, history, action_message, model=MODEL_SMART)
raw = call_gemini_multiturn(
system_prompt, history, action_message, model=_resolve_tutor_model(body.model_pref)
)
except Exception as e:
raise HTTPException(status_code=502, detail=f"Gemini error: {e}")

Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion backend/models/__init__.py
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
from typing import Optional, Union, List
from typing import Optional, Union, List, Literal
from pydantic import BaseModel, Field


Expand All@@ -10,6 +10,7 @@ class StartSessionBody(BaseModel):
mode: str = "socratic"
use_shared_context: bool = True
course_id: Optional[str] = None # Direct course_id lookup instead of resolving from topic
model_pref: Optional[Literal["fast", "smart"]] = None # "fast" (default, gemini-2.5-flash) or "smart" (gemini-2.5-pro)


class ChatBody(BaseModel):
Expand All@@ -18,6 +19,7 @@ class ChatBody(BaseModel):
message: str
mode: str = "socratic"
use_shared_context: bool = True
model_pref: Optional[Literal["fast", "smart"]] = None # "fast" (default, gemini-2.5-flash) or "smart" (gemini-2.5-pro)


class EndSessionBody(BaseModel):
Expand All@@ -31,6 +33,7 @@ class ActionBody(BaseModel):
action_type: str = "hint"
mode: str = "socratic"
use_shared_context: bool = True
model_pref: Optional[Literal["fast", "smart"]] = None # "fast" (default, gemini-2.5-flash) or "smart" (gemini-2.5-pro)


# ── Quiz ──────────────────────────────────────────────────────────────────────
Expand Down
164 changes: 152 additions & 12 deletions backend/routes/auth.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,6 +9,7 @@
import base64
import hashlib
import hmac as _hmac
import re
import secrets
import time as _time
from urllib.parse import urlencode
Expand DownExpand Up@@ -39,6 +40,14 @@

router = APIRouter()

OAUTH_STATE_COOKIE = "sapling_oauth_state"
_OAUTH_COOKIE_MAX_AGE = 600
_POPUP_ID_RE = re.compile(r"^[A-Za-z0-9_-]{1,128}$")

# Fallback in-memory store for environments without SESSION_SECRET; entries
# are keyed by nonce and expire after _OAUTH_COOKIE_MAX_AGE seconds.
_OAUTH_FALLBACK_STORE: dict[str, tuple[float, dict]] = {}


def _google_client_config() -> dict:
return {
Expand DownExpand Up@@ -73,6 +82,68 @@ def _generate_pkce_pair():
return code_verifier, code_challenge


def _clean_popup_id(s: str | None) -> str | None:
if not s:
return None
return s if _POPUP_ID_RE.match(s) else None


def _encode_oauth_cookie(payload: dict) -> str:
raw = json.dumps(payload, separators=(",", ":")).encode()
payload_b64 = base64.urlsafe_b64encode(raw).decode().rstrip("=")
if SESSION_SECRET:
sig_bytes = _hmac.new(SESSION_SECRET.encode(), payload_b64.encode(), hashlib.sha256).digest()
sig_b64 = base64.urlsafe_b64encode(sig_bytes).decode().rstrip("=")
return f"{payload_b64}.{sig_b64}"
nonce = payload.get("n", "")
if nonce:
_OAUTH_FALLBACK_STORE[nonce] = (_time.monotonic() + _OAUTH_COOKIE_MAX_AGE, payload)
_prune_fallback_store()
return payload_b64


def _decode_oauth_cookie(cookie_value: str | None) -> dict | None:
if not cookie_value:
return None
if SESSION_SECRET:
if "." not in cookie_value:
return None
try:
payload_b64, sig_b64 = cookie_value.rsplit(".", 1)
except ValueError:
return None
expected = _hmac.new(SESSION_SECRET.encode(), payload_b64.encode(), hashlib.sha256).digest()
expected_b64 = base64.urlsafe_b64encode(expected).decode().rstrip("=")
if not _hmac.compare_digest(expected_b64, sig_b64):
return None
try:
padded = payload_b64 + "=" * (-len(payload_b64) % 4)
payload = json.loads(base64.urlsafe_b64decode(padded.encode()).decode())
except Exception:
return None
return payload if isinstance(payload, dict) else None
try:
padded = cookie_value + "=" * (-len(cookie_value) % 4)
payload = json.loads(base64.urlsafe_b64decode(padded.encode()).decode())
except Exception:
return None
if not isinstance(payload, dict):
return None
nonce = payload.get("n")
_prune_fallback_store()
entry = _OAUTH_FALLBACK_STORE.get(nonce or "")
if not entry:
return None
return entry[1]


def _prune_fallback_store() -> None:
now = _time.monotonic()
expired = [k for k, (exp, _) in _OAUTH_FALLBACK_STORE.items() if exp < now]
for k in expired:
_OAUTH_FALLBACK_STORE.pop(k, None)


@router.get("/me")
def get_me(request: Request):
"""Return approval and onboarding status for a given user_id."""
Expand DownExpand Up@@ -136,36 +207,84 @@ def get_me(request: Request):


@router.get("/google")
def google_login():
def google_login(popup_id: str = Query(None)):
"""Redirect to Google consent screen with identity + calendar scopes."""
if not GOOGLE_AVAILABLE or not GOOGLE_CLIENT_ID:
raise HTTPException(status_code=400, detail="Google OAuth not configured")

code_verifier, code_challenge = _generate_pkce_pair()
nonce = secrets.token_urlsafe(32)
clean_popup = _clean_popup_id(popup_id)

flow = Flow.from_client_config(_google_client_config(), scopes=AUTH_SCOPES)
flow.redirect_uri = GOOGLE_AUTH_REDIRECT_URI
auth_url, _ = flow.authorization_url(
prompt="consent",
access_type="offline",
state=_encode_state({"action": "signin", "cv": code_verifier}),
state=_encode_state({"action": "signin", "n": nonce}),
code_challenge=code_challenge,
code_challenge_method="S256",
)
return RedirectResponse(auth_url)

cookie_value = _encode_oauth_cookie({
"n": nonce,
"cv": code_verifier,
"popup_id": clean_popup,
})
response = RedirectResponse(auth_url)
response.set_cookie(
key=OAUTH_STATE_COOKIE,
value=cookie_value,
max_age=_OAUTH_COOKIE_MAX_AGE,
httponly=True,
secure=True,
samesite="lax",
path="/",
)
return response


@router.get("/google/callback")
def google_callback(code: str = Query(...), state: str = Query(None)):
def google_callback(request: Request, code: str = Query(...), state: str = Query(None)):
"""Exchange auth code for tokens, validate @bu.edu, upsert user."""
cookie_payload = _decode_oauth_cookie(request.cookies.get(OAUTH_STATE_COOKIE))
code_verifier = cookie_payload.get("cv") if cookie_payload else None
popup_id = _clean_popup_id(cookie_payload.get("popup_id")) if cookie_payload else None
cookie_nonce = cookie_payload.get("n") if cookie_payload else None

def _fail_redirect(error_code: str, fallback_path: str = "/auth") -> RedirectResponse:
# In popup mode, route failures through /auth/callback so the popup
# can broadcast the error and self-close instead of stranding the opener.
if popup_id:
params = urlencode({"error": error_code, "popup_id": popup_id})
resp = RedirectResponse(f"{FRONTEND_URL}/auth/callback?{params}")
else:
resp = RedirectResponse(f"{FRONTEND_URL}{fallback_path}?error={error_code}")
resp.set_cookie(
key=OAUTH_STATE_COOKIE,
value="",
max_age=0,
httponly=True,
secure=True,
samesite="lax",
path="/",
)
return resp

if not GOOGLE_AVAILABLE:
return RedirectResponse(f"{FRONTEND_URL}/auth?error=google_not_configured")
return _fail_redirect("google_not_configured")

state_data = _decode_state(state) if state else {}
code_verifier = state_data.get("cv")
state_nonce = state_data.get("n")
if not cookie_payload or not cookie_nonce or not state_nonce or not _hmac.compare_digest(str(state_nonce), str(cookie_nonce)):
return _fail_redirect("invalid_state")

flow = Flow.from_client_config(_google_client_config(), scopes=AUTH_SCOPES)
flow.redirect_uri = GOOGLE_AUTH_REDIRECT_URI
flow.fetch_token(code=code, code_verifier=code_verifier)
try:
flow.fetch_token(code=code, code_verifier=code_verifier)
except Exception:
return _fail_redirect("oauth_exchange_failed")
creds = flow.credentials

# Fetch user info from Google
Expand All@@ -184,9 +303,7 @@ def google_callback(code: str = Query(...), state: str = Query(None)):

# Restrict to @bu.edu accounts
if not email.endswith("@bu.edu"):
return RedirectResponse(
f"{FRONTEND_URL}/auth?error=invalid_domain"
)
return _fail_redirect("invalid_domain")

# Determine user_id: check if this Google ID already exists
existing = table("users").select("id,is_approved", filters={"google_id": f"eq.{google_id}"})
Expand DownExpand Up@@ -233,7 +350,19 @@ def google_callback(code: str = Query(...), state: str = Query(None)):
)

if not is_approved:
return RedirectResponse(f"{FRONTEND_URL}/pending")
if popup_id:
return _fail_redirect("not_approved")
resp = RedirectResponse(f"{FRONTEND_URL}/pending")
resp.set_cookie(
key=OAUTH_STATE_COOKIE,
value="",
max_age=0,
httponly=True,
secure=True,
samesite="lax",
path="/",
)
return resp

# Build a short-lived HMAC token so the frontend can verify this redirect
# without a second round-trip to the backend.
Expand All@@ -250,5 +379,16 @@ def google_callback(code: str = Query(...), state: str = Query(None)):
"avatar": avatar_url,
"is_approved": "true",
**({"auth_token": auth_token} if auth_token else {}),
**({"popup_id": popup_id} if popup_id else {}),
})
return RedirectResponse(f"{FRONTEND_URL}/auth/callback?{params}")
resp = RedirectResponse(f"{FRONTEND_URL}/auth/callback?{params}")
resp.set_cookie(
key=OAUTH_STATE_COOKIE,
value="",
max_age=0,
httponly=True,
secure=True,
samesite="lax",
path="/",
)
return resp
33 changes: 28 additions & 5 deletions backend/routes/learn.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,7 +11,12 @@
from models import StartSessionBody, ChatBody, EndSessionBody, ActionBody, ModeSwitchBody
from services.auth_guard import require_self, get_session_user_id
from services.encryption import encrypt_if_present, encrypt_json, decrypt_if_present, decrypt_json
from services.gemini_service import MODEL_SMART, call_gemini_multiturn, extract_graph_update
from services.gemini_service import (
MODEL_DEFAULT,
MODEL_SMART,
call_gemini_multiturn,
extract_graph_update,
)
from services.graph_service import get_graph, apply_graph_update

router = APIRouter()
Expand All@@ -28,6 +33,18 @@
"teachback": "Teach-back (you explain to me)",
}

# User-facing speed/quality knob for the tutor chat.
# "fast" = flash (default, faster), "smart" = pro (opt-in, slower but stronger reasoning).
# Anything unrecognized falls back to fast so the default is the snappy one.
_MODEL_PREF_TO_MODEL = {
"fast": MODEL_DEFAULT,
"smart": MODEL_SMART,
}


def _resolve_tutor_model(model_pref: str | None) -> str:
return _MODEL_PREF_TO_MODEL.get(model_pref or "", MODEL_DEFAULT)


def _load_prompt(name: str) -> str:
with open(os.path.join(PROMPTS_DIR, name)) as f:
Expand DownExpand Up@@ -293,13 +310,15 @@ def start_session(body: StartSessionBody, request: Request):
)

try:
raw = call_gemini_multiturn(system_prompt, [], user_message, model=MODEL_SMART)
raw = call_gemini_multiturn(
system_prompt, [], user_message, model=_resolve_tutor_model(body.model_pref)
)
except Exception as e:
raise HTTPException(status_code=502, detail=f"Gemini error: {e}")

reply, graph_update = extract_graph_update(raw)
apply_graph_update(body.user_id, graph_update, course_id=course_id)

PENDING_SESSIONS[session_id] = {
"user_id": body.user_id,
"mode": body.mode,
Expand DownExpand Up@@ -339,7 +358,9 @@ def chat(body: ChatBody, request: Request):
)

try:
raw = call_gemini_multiturn(system_prompt, history, body.message, model=MODEL_SMART)
raw = call_gemini_multiturn(
system_prompt, history, body.message, model=_resolve_tutor_model(body.model_pref)
)
except Exception as e:
raise HTTPException(status_code=502, detail=f"Gemini error: {e}")

Expand DownExpand Up@@ -558,7 +579,9 @@ def action(body: ActionBody, request: Request):
action_message = f"[ACTION: {action_prompts.get(body.action_type, '')}]"

try:
raw = call_gemini_multiturn(system_prompt, history, action_message, model=MODEL_SMART)
raw = call_gemini_multiturn(
system_prompt, history, action_message, model=_resolve_tutor_model(body.model_pref)
)
except Exception as e:
raise HTTPException(status_code=502, detail=f"Gemini error: {e}")

Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion backend/models/__init__.py
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
from typing import Optional, Union, List
from typing import Optional, Union, List, Literal
from pydantic import BaseModel, Field


Expand All@@ -10,6 +10,7 @@ class StartSessionBody(BaseModel):
mode: str = "socratic"
use_shared_context: bool = True
course_id: Optional[str] = None # Direct course_id lookup instead of resolving from topic
model_pref: Optional[Literal["fast", "smart"]] = None # "fast" (default, gemini-2.5-flash) or "smart" (gemini-2.5-pro)


class ChatBody(BaseModel):
Expand All@@ -18,6 +19,7 @@ class ChatBody(BaseModel):
message: str
mode: str = "socratic"
use_shared_context: bool = True
model_pref: Optional[Literal["fast", "smart"]] = None # "fast" (default, gemini-2.5-flash) or "smart" (gemini-2.5-pro)


class EndSessionBody(BaseModel):
Expand All@@ -31,6 +33,7 @@ class ActionBody(BaseModel):
action_type: str = "hint"
mode: str = "socratic"
use_shared_context: bool = True
model_pref: Optional[Literal["fast", "smart"]] = None # "fast" (default, gemini-2.5-flash) or "smart" (gemini-2.5-pro)


# ── Quiz ──────────────────────────────────────────────────────────────────────
Expand Down
164 changes: 152 additions & 12 deletions backend/routes/auth.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,6 +9,7 @@
import base64
import hashlib
import hmac as _hmac
import re
import secrets
import time as _time
from urllib.parse import urlencode
Expand DownExpand Up@@ -39,6 +40,14 @@

router = APIRouter()

OAUTH_STATE_COOKIE = "sapling_oauth_state"
_OAUTH_COOKIE_MAX_AGE = 600
_POPUP_ID_RE = re.compile(r"^[A-Za-z0-9_-]{1,128}$")

# Fallback in-memory store for environments without SESSION_SECRET; entries
# are keyed by nonce and expire after _OAUTH_COOKIE_MAX_AGE seconds.
_OAUTH_FALLBACK_STORE: dict[str, tuple[float, dict]] = {}


def _google_client_config() -> dict:
return {
Expand DownExpand Up@@ -73,6 +82,68 @@ def _generate_pkce_pair():
return code_verifier, code_challenge


def _clean_popup_id(s: str | None) -> str | None:
if not s:
return None
return s if _POPUP_ID_RE.match(s) else None


def _encode_oauth_cookie(payload: dict) -> str:
raw = json.dumps(payload, separators=(",", ":")).encode()
payload_b64 = base64.urlsafe_b64encode(raw).decode().rstrip("=")
if SESSION_SECRET:
sig_bytes = _hmac.new(SESSION_SECRET.encode(), payload_b64.encode(), hashlib.sha256).digest()
sig_b64 = base64.urlsafe_b64encode(sig_bytes).decode().rstrip("=")
return f"{payload_b64}.{sig_b64}"
nonce = payload.get("n", "")
if nonce:
_OAUTH_FALLBACK_STORE[nonce] = (_time.monotonic() + _OAUTH_COOKIE_MAX_AGE, payload)
_prune_fallback_store()
return payload_b64


def _decode_oauth_cookie(cookie_value: str | None) -> dict | None:
if not cookie_value:
return None
if SESSION_SECRET:
if "." not in cookie_value:
return None
try:
payload_b64, sig_b64 = cookie_value.rsplit(".", 1)
except ValueError:
return None
expected = _hmac.new(SESSION_SECRET.encode(), payload_b64.encode(), hashlib.sha256).digest()
expected_b64 = base64.urlsafe_b64encode(expected).decode().rstrip("=")
if not _hmac.compare_digest(expected_b64, sig_b64):
return None
try:
padded = payload_b64 + "=" * (-len(payload_b64) % 4)
payload = json.loads(base64.urlsafe_b64decode(padded.encode()).decode())
except Exception:
return None
return payload if isinstance(payload, dict) else None
try:
padded = cookie_value + "=" * (-len(cookie_value) % 4)
payload = json.loads(base64.urlsafe_b64decode(padded.encode()).decode())
except Exception:
return None
if not isinstance(payload, dict):
return None
nonce = payload.get("n")
_prune_fallback_store()
entry = _OAUTH_FALLBACK_STORE.get(nonce or "")
if not entry:
return None
return entry[1]


def _prune_fallback_store() -> None:
now = _time.monotonic()
expired = [k for k, (exp, _) in _OAUTH_FALLBACK_STORE.items() if exp < now]
for k in expired:
_OAUTH_FALLBACK_STORE.pop(k, None)


@router.get("/me")
def get_me(request: Request):
"""Return approval and onboarding status for a given user_id."""
Expand DownExpand Up@@ -136,36 +207,84 @@ def get_me(request: Request):


@router.get("/google")
def google_login():
def google_login(popup_id: str = Query(None)):
"""Redirect to Google consent screen with identity + calendar scopes."""
if not GOOGLE_AVAILABLE or not GOOGLE_CLIENT_ID:
raise HTTPException(status_code=400, detail="Google OAuth not configured")

code_verifier, code_challenge = _generate_pkce_pair()
nonce = secrets.token_urlsafe(32)
clean_popup = _clean_popup_id(popup_id)

flow = Flow.from_client_config(_google_client_config(), scopes=AUTH_SCOPES)
flow.redirect_uri = GOOGLE_AUTH_REDIRECT_URI
auth_url, _ = flow.authorization_url(
prompt="consent",
access_type="offline",
state=_encode_state({"action": "signin", "cv": code_verifier}),
state=_encode_state({"action": "signin", "n": nonce}),
code_challenge=code_challenge,
code_challenge_method="S256",
)
return RedirectResponse(auth_url)

cookie_value = _encode_oauth_cookie({
"n": nonce,
"cv": code_verifier,
"popup_id": clean_popup,
})
response = RedirectResponse(auth_url)
response.set_cookie(
key=OAUTH_STATE_COOKIE,
value=cookie_value,
max_age=_OAUTH_COOKIE_MAX_AGE,
httponly=True,
secure=True,
samesite="lax",
path="/",
)
return response


@router.get("/google/callback")
def google_callback(code: str = Query(...), state: str = Query(None)):
def google_callback(request: Request, code: str = Query(...), state: str = Query(None)):
"""Exchange auth code for tokens, validate @bu.edu, upsert user."""
cookie_payload = _decode_oauth_cookie(request.cookies.get(OAUTH_STATE_COOKIE))
code_verifier = cookie_payload.get("cv") if cookie_payload else None
popup_id = _clean_popup_id(cookie_payload.get("popup_id")) if cookie_payload else None
cookie_nonce = cookie_payload.get("n") if cookie_payload else None

def _fail_redirect(error_code: str, fallback_path: str = "/auth") -> RedirectResponse:
# In popup mode, route failures through /auth/callback so the popup
# can broadcast the error and self-close instead of stranding the opener.
if popup_id:
params = urlencode({"error": error_code, "popup_id": popup_id})
resp = RedirectResponse(f"{FRONTEND_URL}/auth/callback?{params}")
else:
resp = RedirectResponse(f"{FRONTEND_URL}{fallback_path}?error={error_code}")
resp.set_cookie(
key=OAUTH_STATE_COOKIE,
value="",
max_age=0,
httponly=True,
secure=True,
samesite="lax",
path="/",
)
return resp

if not GOOGLE_AVAILABLE:
return RedirectResponse(f"{FRONTEND_URL}/auth?error=google_not_configured")
return _fail_redirect("google_not_configured")

state_data = _decode_state(state) if state else {}
code_verifier = state_data.get("cv")
state_nonce = state_data.get("n")
if not cookie_payload or not cookie_nonce or not state_nonce or not _hmac.compare_digest(str(state_nonce), str(cookie_nonce)):
return _fail_redirect("invalid_state")

flow = Flow.from_client_config(_google_client_config(), scopes=AUTH_SCOPES)
flow.redirect_uri = GOOGLE_AUTH_REDIRECT_URI
flow.fetch_token(code=code, code_verifier=code_verifier)
try:
flow.fetch_token(code=code, code_verifier=code_verifier)
except Exception:
return _fail_redirect("oauth_exchange_failed")
creds = flow.credentials

# Fetch user info from Google
Expand All@@ -184,9 +303,7 @@ def google_callback(code: str = Query(...), state: str = Query(None)):

# Restrict to @bu.edu accounts
if not email.endswith("@bu.edu"):
return RedirectResponse(
f"{FRONTEND_URL}/auth?error=invalid_domain"
)
return _fail_redirect("invalid_domain")

# Determine user_id: check if this Google ID already exists
existing = table("users").select("id,is_approved", filters={"google_id": f"eq.{google_id}"})
Expand DownExpand Up@@ -233,7 +350,19 @@ def google_callback(code: str = Query(...), state: str = Query(None)):
)

if not is_approved:
return RedirectResponse(f"{FRONTEND_URL}/pending")
if popup_id:
return _fail_redirect("not_approved")
resp = RedirectResponse(f"{FRONTEND_URL}/pending")
resp.set_cookie(
key=OAUTH_STATE_COOKIE,
value="",
max_age=0,
httponly=True,
secure=True,
samesite="lax",
path="/",
)
return resp

# Build a short-lived HMAC token so the frontend can verify this redirect
# without a second round-trip to the backend.
Expand All@@ -250,5 +379,16 @@ def google_callback(code: str = Query(...), state: str = Query(None)):
"avatar": avatar_url,
"is_approved": "true",
**({"auth_token": auth_token} if auth_token else {}),
**({"popup_id": popup_id} if popup_id else {}),
})
return RedirectResponse(f"{FRONTEND_URL}/auth/callback?{params}")
resp = RedirectResponse(f"{FRONTEND_URL}/auth/callback?{params}")
resp.set_cookie(
key=OAUTH_STATE_COOKIE,
value="",
max_age=0,
httponly=True,
secure=True,
samesite="lax",
path="/",
)
return resp
33 changes: 28 additions & 5 deletions backend/routes/learn.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,7 +11,12 @@
from models import StartSessionBody, ChatBody, EndSessionBody, ActionBody, ModeSwitchBody
from services.auth_guard import require_self, get_session_user_id
from services.encryption import encrypt_if_present, encrypt_json, decrypt_if_present, decrypt_json
from services.gemini_service import MODEL_SMART, call_gemini_multiturn, extract_graph_update
from services.gemini_service import (
MODEL_DEFAULT,
MODEL_SMART,
call_gemini_multiturn,
extract_graph_update,
)
from services.graph_service import get_graph, apply_graph_update

router = APIRouter()
Expand All@@ -28,6 +33,18 @@
"teachback": "Teach-back (you explain to me)",
}

# User-facing speed/quality knob for the tutor chat.
# "fast" = flash (default, faster), "smart" = pro (opt-in, slower but stronger reasoning).
# Anything unrecognized falls back to fast so the default is the snappy one.
_MODEL_PREF_TO_MODEL = {
"fast": MODEL_DEFAULT,
"smart": MODEL_SMART,
}


def _resolve_tutor_model(model_pref: str | None) -> str:
return _MODEL_PREF_TO_MODEL.get(model_pref or "", MODEL_DEFAULT)


def _load_prompt(name: str) -> str:
with open(os.path.join(PROMPTS_DIR, name)) as f:
Expand DownExpand Up@@ -293,13 +310,15 @@ def start_session(body: StartSessionBody, request: Request):
)

try:
raw = call_gemini_multiturn(system_prompt, [], user_message, model=MODEL_SMART)
raw = call_gemini_multiturn(
system_prompt, [], user_message, model=_resolve_tutor_model(body.model_pref)
)
except Exception as e:
raise HTTPException(status_code=502, detail=f"Gemini error: {e}")

reply, graph_update = extract_graph_update(raw)
apply_graph_update(body.user_id, graph_update, course_id=course_id)

PENDING_SESSIONS[session_id] = {
"user_id": body.user_id,
"mode": body.mode,
Expand DownExpand Up@@ -339,7 +358,9 @@ def chat(body: ChatBody, request: Request):
)

try:
raw = call_gemini_multiturn(system_prompt, history, body.message, model=MODEL_SMART)
raw = call_gemini_multiturn(
system_prompt, history, body.message, model=_resolve_tutor_model(body.model_pref)
)
except Exception as e:
raise HTTPException(status_code=502, detail=f"Gemini error: {e}")

Expand DownExpand Up@@ -558,7 +579,9 @@ def action(body: ActionBody, request: Request):
action_message = f"[ACTION: {action_prompts.get(body.action_type, '')}]"

try:
raw = call_gemini_multiturn(system_prompt, history, action_message, model=MODEL_SMART)
raw = call_gemini_multiturn(
system_prompt, history, action_message, model=_resolve_tutor_model(body.model_pref)
)
except Exception as e:
raise HTTPException(status_code=502, detail=f"Gemini error: {e}")

Expand Down
Loading
Loading