WINTER4000 commited on
Commit
bfa71a2
Β·
verified Β·
1 Parent(s): 5ddc4d7

Trial timer: 5-min anonymous window + in-engine sign-in modal

Browse files
Files changed (1) hide show
  1. dee/auth.py +423 -0
dee/auth.py ADDED
@@ -0,0 +1,423 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Auth + anonymous-quota middleware for TuringDNA.
2
+
3
+ Two responsibilities, glued together because the endpoints that need them
4
+ overlap completely:
5
+
6
+ 1. Verify Supabase access tokens on /api/run (and any future protected
7
+ endpoint). The token rides in the `Authorization: Bearer <jwt>`
8
+ header. We validate signature + expiry against the Supabase JWT
9
+ secret, then expose the resulting claims via flask.g.user.
10
+
11
+ 2. Enforce the one-free-anonymous-run quota. Anonymous users get exactly
12
+ one /api/run before they need an account. We track this server-side
13
+ via a signed cookie (`td_anon_runs`) so a sophisticated user clearing
14
+ localStorage in the iframe wrapper still hits the wall here.
15
+
16
+ Both are best-effort: missing/invalid auth degrades to anonymous-mode
17
+ processing rather than 401, EXCEPT when require_auth_or_quota() rejects
18
+ the call because the user has used their free run AND has no valid JWT.
19
+
20
+ Env vars (set on the HF Space):
21
+ SUPABASE_URL e.g. https://abcdefg.supabase.co
22
+ SUPABASE_JWT_SECRET The "JWT Secret" from Supabase Settings β†’ API
23
+ SUPABASE_SERVICE_KEY Service-role key (for inserting runs)
24
+ TURINGDNA_ANON_SECRET Random 32+ byte string for cookie signing
25
+ (any reasonably-strong value, doesn't need
26
+ to match Supabase). Generate with:
27
+ python -c "import secrets; print(secrets.token_urlsafe(48))"
28
+
29
+ If env vars are missing, auth is OFF and every request is treated as
30
+ anonymous with unlimited runs β€” keeps local dev easy. The startup log
31
+ warns visibly so this isn't accidental in production.
32
+ """
33
+
34
+ from __future__ import annotations
35
+
36
+ import hashlib
37
+ import hmac
38
+ import json
39
+ import logging
40
+ import os
41
+ import time
42
+ from dataclasses import dataclass
43
+ from typing import Any, Dict, Optional
44
+
45
+ from flask import Flask, Response, g, jsonify, make_response, request
46
+
47
+ logger = logging.getLogger("dee.auth")
48
+
49
+ # ─── Config ────────────────────────────────────────────────────────────
50
+ SUPABASE_URL = os.environ.get("SUPABASE_URL", "").rstrip("/")
51
+ SUPABASE_JWT_SECRET = os.environ.get("SUPABASE_JWT_SECRET", "")
52
+ SUPABASE_SERVICE_KEY = os.environ.get("SUPABASE_SERVICE_KEY", "")
53
+ ANON_SECRET = os.environ.get("TURINGDNA_ANON_SECRET", "")
54
+
55
+ # Cookie name + lifetime for the anonymous-trial tracker. 365d is fine β€”
56
+ # the cookie records "this browser started a trial at timestamp X" and
57
+ # is replaced on sign-in.
58
+ ANON_COOKIE_NAME = "td_anon_runs"
59
+ ANON_COOKIE_MAX_AGE_S = 365 * 24 * 3600
60
+
61
+ # Length of the anonymous trial window, in seconds. The user can run
62
+ # however many sequences they want during this window β€” when it expires,
63
+ # /api/run returns 402 and the frontend pops the sign-in modal.
64
+ #
65
+ # Lean-startup framing: 5 minutes is plenty to feel the magic but not
66
+ # enough to do real exploratory work. Catches users while they're still
67
+ # engaged. Was previously a count-based "1 free run" hard wall, swapped
68
+ # for time-based per user request 2026-05-26.
69
+ ANON_TRIAL_SECONDS = int(os.environ.get("TURINGDNA_ANON_TRIAL_SECONDS", "300"))
70
+
71
+ # Whether auth is configured. If False, every request is anonymous and
72
+ # unlimited β€” we log a warning at startup so production doesn't silently
73
+ # ship without auth.
74
+ AUTH_ENABLED = bool(SUPABASE_JWT_SECRET and ANON_SECRET)
75
+
76
+
77
+ # ─── User context exposed to handlers ─────────────────────────────────
78
+ @dataclass
79
+ class AuthContext:
80
+ """What we know about the requester. Exactly one of (user_id, anon_id)
81
+ is populated. anonymous=True is the catch-all for "no JWT, treat as
82
+ anon" β€” and anon_runs counts how many free runs this anon has used."""
83
+ user_id: Optional[str] = None # Supabase auth.users.id
84
+ email: Optional[str] = None
85
+ anonymous: bool = True
86
+ # Unix timestamp when this anon visitor's trial started (i.e., when
87
+ # they kicked off their first /api/run). 0 means "trial hasn't begun".
88
+ anon_first_at: int = 0
89
+ # Count of anon runs in the trial, informational only β€” gate is
90
+ # time-based, not count-based.
91
+ anon_runs: int = 0
92
+
93
+
94
+ def get_auth() -> AuthContext:
95
+ """Convenience: returns the AuthContext attached to the current Flask
96
+ request by load_auth_into_g(). Returns a fresh anonymous one if no
97
+ middleware ran yet (defensive)."""
98
+ return getattr(g, "auth", AuthContext())
99
+
100
+
101
+ # ─── JWT verification (no external deps) ──────────────────────────────
102
+ # We use PyJWT when available (clean signature/expiry handling), and fall
103
+ # back to a tiny in-house verifier so the auth module works even if PyJWT
104
+ # isn't installed yet. Supabase signs with HS256 (HMAC-SHA256) using the
105
+ # JWT Secret β€” straightforward to verify by hand.
106
+
107
+ def _b64url_decode(data: str) -> bytes:
108
+ # JWT base64url: '-' '_' instead of '+' '/', no padding.
109
+ pad = '=' * (-len(data) % 4)
110
+ return _b64_translate(data + pad)
111
+
112
+
113
+ def _b64_translate(data: str) -> bytes:
114
+ import base64
115
+ return base64.urlsafe_b64decode(data.encode("ascii"))
116
+
117
+
118
+ def _verify_jwt_hs256(token: str, secret: str) -> Optional[Dict[str, Any]]:
119
+ """Verify an HS256-signed JWT and return its claims, or None on failure.
120
+
121
+ Validates: signature, exp (expiry), nbf (not-before if present), and
122
+ iat (issued-at, sanity-checks not-in-future-by-more-than-60s). Does
123
+ not strictly verify `aud` or `iss` β€” Supabase JWTs have iss=supabase
124
+ and aud=authenticated, which we treat as informational only. If the
125
+ deployment exposes the JWT to attackers who can mint tokens with the
126
+ same secret, those tokens are valid by design.
127
+ """
128
+ try:
129
+ header_b64, payload_b64, sig_b64 = token.split(".")
130
+ except ValueError:
131
+ return None
132
+
133
+ try:
134
+ # Verify signature first β€” constant-time compare.
135
+ signing_input = (header_b64 + "." + payload_b64).encode("ascii")
136
+ expected = hmac.new(secret.encode("utf-8"), signing_input, hashlib.sha256).digest()
137
+ actual = _b64url_decode(sig_b64)
138
+ if not hmac.compare_digest(expected, actual):
139
+ return None
140
+
141
+ # Parse claims.
142
+ claims = json.loads(_b64url_decode(payload_b64).decode("utf-8"))
143
+ now = int(time.time())
144
+
145
+ exp = claims.get("exp")
146
+ if isinstance(exp, (int, float)) and now > int(exp):
147
+ return None
148
+
149
+ nbf = claims.get("nbf")
150
+ if isinstance(nbf, (int, float)) and now < int(nbf):
151
+ return None
152
+
153
+ iat = claims.get("iat")
154
+ # Allow some clock skew on iat β€” 5 minutes is generous.
155
+ if isinstance(iat, (int, float)) and int(iat) > now + 300:
156
+ return None
157
+
158
+ return claims
159
+ except Exception:
160
+ return None
161
+
162
+
163
+ # ─── Signed anon cookie ───────────────────────────────────────────────
164
+ # Format: "<first_at>.<runs>.<issued_at>.<hex_hmac>"
165
+ #
166
+ # first_at = unix seconds when this visitor's trial began (0 if first
167
+ # request hasn't happened yet β€” gate not yet armed)
168
+ # runs = informational run count (gate is time-based, this is for
169
+ # analytics convenience)
170
+ # issued_at = cookie issuance time (for max-age sanity check)
171
+ #
172
+ # We sign with ANON_SECRET so the client can't reset first_at to 0 by
173
+ # editing the cookie. They CAN clear the cookie entirely β€” at which
174
+ # point they get a fresh trial β€” so cookie-clearing remains a free path
175
+ # around the wall. Tightening further (server-side IP fingerprint) is
176
+ # a deliberate later choice, not done here.
177
+
178
+ def _sign_anon_value(first_at: int, runs: int, issued: int) -> str:
179
+ body = f"{first_at}.{runs}.{issued}"
180
+ mac = hmac.new(
181
+ ANON_SECRET.encode("utf-8"),
182
+ body.encode("ascii"),
183
+ hashlib.sha256,
184
+ ).hexdigest()
185
+ return f"{body}.{mac}"
186
+
187
+
188
+ def _parse_anon_cookie(raw: Optional[str]) -> tuple[int, int]:
189
+ """Returns (first_at, runs). Both 0 if cookie missing/forged. Also
190
+ rejects cookies issued more than ANON_COOKIE_MAX_AGE_S ago."""
191
+ if not raw or not ANON_SECRET:
192
+ return (0, 0)
193
+ try:
194
+ first_s, runs_s, issued_s, mac = raw.split(".")
195
+ first_at = int(first_s)
196
+ runs = int(runs_s)
197
+ issued = int(issued_s)
198
+ except (ValueError, AttributeError):
199
+ return (0, 0)
200
+ if runs < 0 or runs > 1_000_000:
201
+ return (0, 0)
202
+ if first_at < 0 or first_at > 4_000_000_000:
203
+ return (0, 0)
204
+ if int(time.time()) - issued > ANON_COOKIE_MAX_AGE_S:
205
+ return (0, 0)
206
+ expected = _sign_anon_value(first_at, runs, issued)
207
+ if not hmac.compare_digest(expected, raw):
208
+ return (0, 0)
209
+ return (first_at, runs)
210
+
211
+
212
+ def _set_anon_cookie(response: Response, first_at: int, runs: int) -> None:
213
+ if not ANON_SECRET:
214
+ return
215
+ issued = int(time.time())
216
+ response.set_cookie(
217
+ ANON_COOKIE_NAME,
218
+ _sign_anon_value(first_at, runs, issued),
219
+ max_age=ANON_COOKIE_MAX_AGE_S,
220
+ httponly=True,
221
+ secure=True,
222
+ # Cross-site (iframe β‰  landing origin) requires SameSite=None +
223
+ # Secure. Lax used to work because /app was same-origin in dev,
224
+ # but in production the engine lives at *.hf.space inside an
225
+ # iframe at turingdna.com, so the cookie has to cross sites.
226
+ samesite="None",
227
+ )
228
+
229
+
230
+ # ─── Flask integration ─────────────────────────────────────────────────
231
+ def load_auth_into_g() -> None:
232
+ """before_request hook. Parses Authorization header + anon cookie and
233
+ populates g.auth. Always populates something β€” handlers should read
234
+ g.auth and decide what to do; this hook never returns a response."""
235
+ auth = AuthContext()
236
+
237
+ # 1) Try Authorization: Bearer <jwt>
238
+ auth_header = request.headers.get("Authorization", "")
239
+ if AUTH_ENABLED and auth_header.lower().startswith("bearer "):
240
+ token = auth_header[7:].strip()
241
+ claims = _verify_jwt_hs256(token, SUPABASE_JWT_SECRET)
242
+ if claims:
243
+ auth.user_id = claims.get("sub")
244
+ auth.email = claims.get("email")
245
+ auth.anonymous = False
246
+ else:
247
+ logger.info("Invalid or expired JWT received; treating as anon.")
248
+
249
+ # 2) If still anonymous, read the signed trial cookie.
250
+ if auth.anonymous:
251
+ first_at, runs = _parse_anon_cookie(request.cookies.get(ANON_COOKIE_NAME))
252
+ auth.anon_first_at = first_at
253
+ auth.anon_runs = runs
254
+
255
+ g.auth = auth
256
+
257
+
258
+ def require_auth_or_quota() -> Optional[Response]:
259
+ """Call from a route handler BEFORE doing any work. Returns a 402 JSON
260
+ response (intercept) if the user is anonymous AND their trial window
261
+ has expired. Returns None to let the handler proceed.
262
+
263
+ The gate is **time-based**: from the moment of the first anon /api/run,
264
+ the user has ANON_TRIAL_SECONDS of unlimited access. After that,
265
+ further /api/run calls 402 until they sign in.
266
+
267
+ 402 instead of 401 because the user IS welcome to use this β€” they
268
+ just need to sign up. The frontend interprets 402 specifically as
269
+ "show the sign-up gate" rather than a hard auth error."""
270
+ if not AUTH_ENABLED:
271
+ return None # local dev β€” never block
272
+
273
+ auth = get_auth()
274
+ if not auth.anonymous:
275
+ return None # signed in, proceed
276
+
277
+ if not auth.anon_first_at:
278
+ return None # trial hasn't started yet β€” first run is always free
279
+
280
+ elapsed = int(time.time()) - auth.anon_first_at
281
+ if elapsed >= ANON_TRIAL_SECONDS:
282
+ return jsonify({
283
+ "error": (
284
+ f"Your {ANON_TRIAL_SECONDS // 60}-minute free trial has "
285
+ "ended. Sign in to keep going β€” no password, just an "
286
+ "emailed link."
287
+ ),
288
+ "kind": "auth_required",
289
+ "signup_url": "https://turingdna.com/signup/?from=app",
290
+ "trial_seconds": ANON_TRIAL_SECONDS,
291
+ "trial_started_at": auth.anon_first_at,
292
+ }), 402
293
+
294
+ return None
295
+
296
+
297
+ def increment_anon_runs_on_response(response: Response) -> Response:
298
+ """Called from inside a /api/run handler that has decided to start a
299
+ pipeline FOR an anonymous user. Stamps the first_at timestamp on the
300
+ cookie if this is their first run; otherwise just bumps the
301
+ informational run count without resetting the trial timer.
302
+
303
+ Idempotent against being called twice on the same request β€” the
304
+ response cookie just gets overwritten with the same data.
305
+ """
306
+ auth = get_auth()
307
+ if not (auth.anonymous and AUTH_ENABLED):
308
+ return response
309
+
310
+ now = int(time.time())
311
+ first_at = auth.anon_first_at or now
312
+ runs = auth.anon_runs + 1
313
+ _set_anon_cookie(response, first_at, runs)
314
+
315
+ # Also surface the trial state in a custom response header so the
316
+ # frontend can read it without parsing the cookie itself. The frontend
317
+ # uses this to start its own client-side countdown to the in-session
318
+ # "sign in to keep going" modal.
319
+ elapsed = now - first_at
320
+ remaining = max(0, ANON_TRIAL_SECONDS - elapsed)
321
+ response.headers["X-TD-Trial-Remaining-S"] = str(remaining)
322
+ response.headers["X-TD-Trial-Started-At"] = str(first_at)
323
+ return response
324
+
325
+
326
+ # ─── Run logging (best-effort) ────────────────────────────────────────
327
+ # After a /api/run starts we POST a row into Supabase public.runs via the
328
+ # REST API using the service-role key. Never blocks the user's request β€”
329
+ # fire-and-forget in a daemon thread, log on error.
330
+
331
+ def log_run_async(
332
+ *,
333
+ job_id: str,
334
+ sequence_hash: str,
335
+ sequence_length: int,
336
+ model: Optional[str],
337
+ host_organism: Optional[str],
338
+ ) -> None:
339
+ """Fire-and-forget insert into public.runs. Captures user_id from
340
+ g.auth if signed in; otherwise stores anon_fingerprint = IP+UA hash."""
341
+ if not (SUPABASE_URL and SUPABASE_SERVICE_KEY):
342
+ return # not configured; skip silently
343
+
344
+ auth = get_auth()
345
+ user_id = auth.user_id
346
+ anon_fingerprint = None
347
+ if auth.anonymous:
348
+ anon_fingerprint = _anon_fingerprint()
349
+
350
+ request_ip = request.headers.get("X-Forwarded-For", request.remote_addr or "").split(",")[0].strip()
351
+ request_ua = request.headers.get("User-Agent", "")[:512]
352
+
353
+ payload = {
354
+ "user_id": user_id,
355
+ "anon_fingerprint": anon_fingerprint,
356
+ "job_id": job_id,
357
+ "sequence_hash": sequence_hash,
358
+ "sequence_length": sequence_length,
359
+ "model": model,
360
+ "host_organism": host_organism,
361
+ "status": "started",
362
+ "request_ip": request_ip or None,
363
+ "request_ua": request_ua or None,
364
+ }
365
+
366
+ import threading
367
+ threading.Thread(
368
+ target=_post_run_row, args=(payload,), daemon=True,
369
+ ).start()
370
+
371
+
372
+ def _post_run_row(payload: Dict[str, Any]) -> None:
373
+ try:
374
+ import urllib.request
375
+ import urllib.error
376
+ req = urllib.request.Request(
377
+ f"{SUPABASE_URL}/rest/v1/runs",
378
+ data=json.dumps(payload).encode("utf-8"),
379
+ method="POST",
380
+ headers={
381
+ "Content-Type": "application/json",
382
+ "apikey": SUPABASE_SERVICE_KEY,
383
+ "Authorization": f"Bearer {SUPABASE_SERVICE_KEY}",
384
+ "Prefer": "return=minimal",
385
+ },
386
+ )
387
+ with urllib.request.urlopen(req, timeout=4.0) as resp:
388
+ if resp.status not in (200, 201, 204):
389
+ logger.warning("Supabase runs insert returned %s", resp.status)
390
+ except Exception as exc: # noqa: BLE001
391
+ logger.warning("Could not log run to Supabase: %s", exc)
392
+
393
+
394
+ def _anon_fingerprint() -> str:
395
+ """Stable-ish hash of IP + UA, salted with ANON_SECRET. Used only to
396
+ rough-deduplicate anonymous runs in analytics. Not identity-grade β€”
397
+ same household + same browser β†’ same fingerprint."""
398
+ ip = request.headers.get("X-Forwarded-For", request.remote_addr or "").split(",")[0].strip()
399
+ ua = request.headers.get("User-Agent", "")[:512]
400
+ data = f"{ip}|{ua}".encode("utf-8")
401
+ return hmac.new(
402
+ (ANON_SECRET or "no-secret").encode("utf-8"),
403
+ data,
404
+ hashlib.sha256,
405
+ ).hexdigest()[:32]
406
+
407
+
408
+ # ─── App registration ─────────────────────────────────────────────────
409
+ def init_app(app: Flask) -> None:
410
+ """Wire up the before_request hook on the Flask app."""
411
+ app.before_request(load_auth_into_g)
412
+
413
+ if AUTH_ENABLED:
414
+ logger.info(
415
+ "Auth enabled: Supabase JWT + anon trial timer (%ds free window).",
416
+ ANON_TRIAL_SECONDS,
417
+ )
418
+ else:
419
+ logger.warning(
420
+ "AUTH IS OFF β€” set SUPABASE_JWT_SECRET + TURINGDNA_ANON_SECRET "
421
+ "as env vars to enable. All requests will be treated as "
422
+ "anonymous with unlimited quota."
423
+ )