Hussien Haider commited on
Commit
082c217
Β·
1 Parent(s): bef7f19
app/api/onevone.py CHANGED
@@ -30,7 +30,6 @@ Real-time:
30
 
31
  from __future__ import annotations
32
 
33
- import os
34
  import sys
35
  import asyncio
36
  import json
@@ -54,8 +53,7 @@ sys.stdout.reconfigure(encoding="utf-8")
54
  router = APIRouter(prefix="/api/onevone", tags=["onevone"])
55
 
56
  # ---- env (mirror main.py) ----
57
- SUPABASE_URL = os.environ.get("SUPABASE_URL", "https://yevtnyokixocpihpdwqu.supabase.co")
58
- SUPABASE_ANON_KEY = os.environ.get("SUPABASE_ANON_KEY", "")
59
  SUPABASE_HEADERS = {
60
  "apikey": SUPABASE_ANON_KEY,
61
  "Authorization": f"Bearer {SUPABASE_ANON_KEY}",
 
30
 
31
  from __future__ import annotations
32
 
 
33
  import sys
34
  import asyncio
35
  import json
 
53
  router = APIRouter(prefix="/api/onevone", tags=["onevone"])
54
 
55
  # ---- env (mirror main.py) ----
56
+ from app.core.config import SUPABASE_URL, SUPABASE_ANON_KEY
 
57
  SUPABASE_HEADERS = {
58
  "apikey": SUPABASE_ANON_KEY,
59
  "Authorization": f"Bearer {SUPABASE_ANON_KEY}",
app/core/auth.py CHANGED
@@ -4,26 +4,117 @@ Validates Supabase JWT tokens from the Authorization header and
4
  extracts the authenticated user_id. This prevents user ID spoofing.
5
  """
6
 
7
- import jwt
8
  import logging
 
9
  from typing import Optional
10
 
 
 
 
 
11
  from fastapi import Request, HTTPException, status
12
 
13
- from app.core.config import SUPABASE_ANON_KEY, SUPABASE_JWT_SECRET
14
 
15
  log = logging.getLogger("auth")
16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
- def _validate_jwt(token: str) -> Optional[dict]:
 
19
  """Validate JWT and return payload if valid."""
 
 
20
  if not SUPABASE_JWT_SECRET:
21
- log.warning("SUPABASE_JWT_SECRET not configured - using insecure fallback (DEV ONLY)")
22
  try:
23
  payload = jwt.decode(
24
  token,
25
  options={"verify_signature": False, "verify_aud": False},
26
- algorithms=["HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "ES256", "ES384", "ES512", "EdDSA"],
 
 
27
  )
28
  return payload
29
  except jwt.ExpiredSignatureError:
@@ -32,20 +123,78 @@ def _validate_jwt(token: str) -> Optional[dict]:
32
  except jwt.InvalidTokenError as exc:
33
  log.warning("JWT decode failed (insecure fallback): %s", exc)
34
  return None
35
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
  try:
37
  payload = jwt.decode(
38
  token,
39
- SUPABASE_JWT_SECRET,
40
- algorithms=["HS256"],
41
- options={"verify_aud": False},
 
42
  )
43
  return payload
44
  except jwt.ExpiredSignatureError:
45
- log.warning("JWT expired - user may need to refresh or re-authenticate")
46
  return None
47
  except jwt.InvalidTokenError as exc:
48
- log.warning("JWT decode failed: %s", exc)
49
  return None
50
 
51
 
@@ -68,7 +217,7 @@ async def get_current_user(request: Request) -> dict:
68
  if request.method in ["GET", "HEAD", "OPTIONS"]:
69
  token = extract_token_from_request(request)
70
  if token:
71
- payload = _validate_jwt(token)
72
  if payload:
73
  user_id = payload.get("sub", "")
74
  if user_id:
@@ -84,7 +233,6 @@ async def get_current_user(request: Request) -> dict:
84
  try:
85
  body_bytes = await request.body()
86
  if body_bytes:
87
- import json
88
  body = json.loads(body_bytes)
89
  user_id = body.get("user_id", "") or body.get("userId", "")
90
  if user_id:
@@ -96,7 +244,7 @@ async def get_current_user(request: Request) -> dict:
96
  # For remaining cases, try Authorization header (JWT)
97
  token = extract_token_from_request(request)
98
  if token:
99
- payload = _validate_jwt(token)
100
  if payload:
101
  user_id = payload.get("sub", "")
102
  if user_id:
 
4
  extracts the authenticated user_id. This prevents user ID spoofing.
5
  """
6
 
7
+ import json
8
  import logging
9
+ from datetime import datetime, timedelta
10
  from typing import Optional
11
 
12
+ import httpx
13
+ import jwt
14
+ from cryptography.hazmat.primitives import serialization
15
+ from cryptography.hazmat.primitives.asymmetric import rsa
16
  from fastapi import Request, HTTPException, status
17
 
18
+ from app.core.config import SUPABASE_ANON_KEY, SUPABASE_JWT_SECRET, SUPABASE_URL
19
 
20
  log = logging.getLogger("auth")
21
 
22
+ # ── JWK cache ──────────────────────────────────────────────────────────
23
+ _jwk_cache: dict | None = None
24
+ _jwk_cache_at: datetime | None = None
25
+ _JWK_TTL = timedelta(hours=1)
26
+
27
+
28
+ def _get_jwks_url() -> str | None:
29
+ if not SUPABASE_URL:
30
+ return None
31
+ base = SUPABASE_URL.rstrip("/")
32
+ return f"{base}/auth/v1/.well-known/jwks.json"
33
+
34
+
35
+ async def _fetch_jwks() -> dict | None:
36
+ url = _get_jwks_url()
37
+ if not url:
38
+ return None
39
+ try:
40
+ async with httpx.AsyncClient(timeout=5) as cl:
41
+ r = await cl.get(url)
42
+ r.raise_for_status()
43
+ return r.json()
44
+ except Exception as exc:
45
+ log.warning("Failed to fetch JWKs from %s: %s", url, exc)
46
+ return None
47
+
48
+
49
+ async def _get_jwks() -> dict | None:
50
+ global _jwk_cache, _jwk_cache_at
51
+ now = datetime.utcnow()
52
+ if _jwk_cache is not None and _jwk_cache_at is not None and now - _jwk_cache_at < _JWK_TTL:
53
+ return _jwk_cache
54
+ jwks = await _fetch_jwks()
55
+ _jwk_cache = jwks
56
+ _jwk_cache_at = now if jwks else _jwk_cache_at
57
+ return jwks
58
+
59
+
60
+ def _b64u(s: str) -> bytes:
61
+ """Decode URL-safe base64 with missing padding."""
62
+ import base64
63
+ s = s.strip().replace("-", "+").replace("_", "/")
64
+ pad = 4 - len(s) % 4
65
+ if pad != 4:
66
+ s += "=" * pad
67
+ return base64.b64decode(s)
68
+
69
+
70
+ def _jwk_to_pem(jwk_key: dict) -> bytes | None:
71
+ """Convert a JWK (RSA or EC) to a PEM-encoded public key."""
72
+ from cryptography.hazmat.primitives.asymmetric import ec
73
+ try:
74
+ kty = jwk_key.get("kty", "")
75
+ if kty == "RSA":
76
+ n = int.from_bytes(_b64u(jwk_key["n"]), byteorder="big")
77
+ e = int.from_bytes(_b64u(jwk_key["e"]), byteorder="big")
78
+ pub_key = rsa.RSAPublicNumbers(e, n).public_key()
79
+ elif kty == "EC":
80
+ crv = jwk_key.get("crv", "")
81
+ x = int.from_bytes(_b64u(jwk_key["x"]), byteorder="big")
82
+ y = int.from_bytes(_b64u(jwk_key["y"]), byteorder="big")
83
+ if crv == "P-256":
84
+ curve = ec.SECP256R1()
85
+ elif crv == "P-384":
86
+ curve = ec.SECP384R1()
87
+ elif crv == "P-521":
88
+ curve = ec.SECP521R1()
89
+ else:
90
+ raise ValueError(f"Unsupported EC curve: {crv}")
91
+ pub_key = ec.EllipticCurvePublicNumbers(x, y, curve).public_key()
92
+ else:
93
+ log.warning("Unsupported JWK kty=%s", kty)
94
+ return None
95
+ pem = pub_key.public_bytes(
96
+ encoding=serialization.Encoding.PEM,
97
+ format=serialization.PublicFormat.SubjectPublicKeyInfo,
98
+ )
99
+ return pem
100
+ except Exception as exc:
101
+ log.warning("JWK β†’ PEM conversion failed: %s", exc)
102
+ return None
103
 
104
+
105
+ async def _validate_jwt(token: str) -> Optional[dict]:
106
  """Validate JWT and return payload if valid."""
107
+
108
+ # ── 1. No secret configured ──
109
  if not SUPABASE_JWT_SECRET:
110
+ log.warning("SUPABASE_JWT_SECRET not configured β€” using insecure fallback (DEV ONLY)")
111
  try:
112
  payload = jwt.decode(
113
  token,
114
  options={"verify_signature": False, "verify_aud": False},
115
+ algorithms=["HS256", "HS384", "HS512",
116
+ "RS256", "RS384", "RS512",
117
+ "ES256", "ES384", "ES512", "EdDSA"],
118
  )
119
  return payload
120
  except jwt.ExpiredSignatureError:
 
123
  except jwt.InvalidTokenError as exc:
124
  log.warning("JWT decode failed (insecure fallback): %s", exc)
125
  return None
126
+
127
+ # ── 2. Determine algorithm from token header ──
128
+ try:
129
+ unverified_header = jwt.get_unverified_header(token)
130
+ except Exception as exc:
131
+ log.warning("Could not read JWT header: %s", exc)
132
+ return None
133
+
134
+ alg = (unverified_header or {}).get("alg", "")
135
+
136
+ # ── 3. Symmetric (HS*) ──
137
+ if alg.startswith("HS"):
138
+ try:
139
+ payload = jwt.decode(
140
+ token,
141
+ SUPABASE_JWT_SECRET,
142
+ algorithms=["HS256", "HS384", "HS512"],
143
+ options={"verify_aud": False},
144
+ )
145
+ return payload
146
+ except jwt.ExpiredSignatureError:
147
+ log.warning("JWT expired (symmetric)")
148
+ return None
149
+ except jwt.InvalidTokenError as exc:
150
+ log.warning("JWT decode failed (symmetric): %s", exc)
151
+ return None
152
+
153
+ # ── 4. Asymmetric (RS*, ES*, EdDSA) β€” fetch JWKs ──
154
+ kid = (unverified_header or {}).get("kid", "")
155
+ jwks = await _get_jwks()
156
+ if jwks:
157
+ keys = jwks.get("keys", [])
158
+ # If we have a kid, find matching key; otherwise try all
159
+ candidates = [k for k in keys if k.get("kid") == kid] if kid else keys
160
+ if not candidates:
161
+ candidates = keys # fallback to any key
162
+ for jwk_key in candidates:
163
+ pem = _jwk_to_pem(jwk_key)
164
+ if pem is None:
165
+ continue
166
+ try:
167
+ payload = jwt.decode(
168
+ token,
169
+ pem,
170
+ algorithms=["RS256", "RS384", "RS512",
171
+ "ES256", "ES384", "ES512", "EdDSA"],
172
+ options={"verify_aud": False},
173
+ )
174
+ log.info("JWT validated via JWKs (alg=%s kid=%s)", alg, kid)
175
+ return payload
176
+ except jwt.ExpiredSignatureError:
177
+ log.warning("JWT expired (asymmetric)")
178
+ return None
179
+ except jwt.InvalidTokenError:
180
+ continue # try next key
181
+
182
+ # ── 5. Last resort β€” unverified decode (handles unusual algs) ──
183
+ log.warning("JWT fallback: decoding without signature verification for alg=%s", alg)
184
  try:
185
  payload = jwt.decode(
186
  token,
187
+ options={"verify_signature": False, "verify_aud": False},
188
+ algorithms=["HS256", "HS384", "HS512",
189
+ "RS256", "RS384", "RS512",
190
+ "ES256", "ES384", "ES512", "EdDSA"],
191
  )
192
  return payload
193
  except jwt.ExpiredSignatureError:
194
+ log.warning("JWT expired (fallback)")
195
  return None
196
  except jwt.InvalidTokenError as exc:
197
+ log.warning("JWT decode failed (fallback): %s", exc)
198
  return None
199
 
200
 
 
217
  if request.method in ["GET", "HEAD", "OPTIONS"]:
218
  token = extract_token_from_request(request)
219
  if token:
220
+ payload = await _validate_jwt(token)
221
  if payload:
222
  user_id = payload.get("sub", "")
223
  if user_id:
 
233
  try:
234
  body_bytes = await request.body()
235
  if body_bytes:
 
236
  body = json.loads(body_bytes)
237
  user_id = body.get("user_id", "") or body.get("userId", "")
238
  if user_id:
 
244
  # For remaining cases, try Authorization header (JWT)
245
  token = extract_token_from_request(request)
246
  if token:
247
+ payload = await _validate_jwt(token)
248
  if payload:
249
  user_id = payload.get("sub", "")
250
  if user_id:
app/core/config.py CHANGED
@@ -14,10 +14,7 @@ import os
14
  # Supabase #
15
  # --------------------------------------------------------------------------- #
16
 
17
- SUPABASE_URL = os.environ.get(
18
- "SUPABASE_URL",
19
- "https://yevtnyokixocpihpdwqu.supabase.co",
20
- )
21
  SUPABASE_ANON_KEY = os.environ.get("SUPABASE_ANON_KEY", "")
22
  SUPABASE_JWT_SECRET = os.environ.get("SUPABASE_JWT_SECRET", "")
23
 
@@ -26,16 +23,26 @@ SUPABASE_JWT_SECRET = os.environ.get("SUPABASE_JWT_SECRET", "")
26
  # AI providers β€” endpoints, model names, keys #
27
  # --------------------------------------------------------------------------- #
28
 
29
- # Cloudflare Workers AI is the primary tier in the three-tier fallback
30
- # chain documented in AGENTS.md. It's only used inside individual
31
- # generators; the main backend talks to Groq / Mistral directly.
 
 
 
 
 
32
 
33
- # Groq (secondary AI, also the legacy scenario/eval backend).
34
  GROQ_API_KEY = os.environ.get("GROQ_API_KEY", "")
35
  GROQ_API_URL = "https://api.groq.com/openai/v1/chat/completions"
36
- GROQ_DEFAULT_MODEL = os.environ.get("GROQ_MODEL", "llama-3.1-8b-instant")
 
 
 
 
 
37
 
38
- # Mistral β€” used for log-analysis Arabic feedback only.
39
  MISTRAL_API_KEY = os.environ.get("MISTRAL_API_KEY", "")
40
  MISTRAL_MODEL = os.environ.get("MISTRAL_MODEL", "mistral-large-latest")
41
  MISTRAL_API_URL = os.environ.get(
 
14
  # Supabase #
15
  # --------------------------------------------------------------------------- #
16
 
17
+ SUPABASE_URL = os.environ.get("SUPABASE_URL", "")
 
 
 
18
  SUPABASE_ANON_KEY = os.environ.get("SUPABASE_ANON_KEY", "")
19
  SUPABASE_JWT_SECRET = os.environ.get("SUPABASE_JWT_SECRET", "")
20
 
 
23
  # AI providers β€” endpoints, model names, keys #
24
  # --------------------------------------------------------------------------- #
25
 
26
+ # Cloudflare Workers AI β€” secondary tier in the fallback chain.
27
+ CLOUDFLARE_API_TOKEN = os.environ.get("CLOUDFLARE_API_TOKEN", "")
28
+ CLOUDFLARE_ACCOUNT_ID = os.environ.get("CLOUDFLARE_ACCOUNT_ID", "")
29
+ CLOUDFLARE_MODEL = os.environ.get("CLOUDFLARE_MODEL", "@cf/meta/llama-3.1-8b-instruct")
30
+ CLOUDFLARE_URL = (
31
+ f"https://api.cloudflare.com/client/v4/accounts/{CLOUDFLARE_ACCOUNT_ID}/ai/run/{CLOUDFLARE_MODEL}"
32
+ if CLOUDFLARE_ACCOUNT_ID else ""
33
+ )
34
 
35
+ # Groq β€” secondary AI, also the legacy scenario/eval backend.
36
  GROQ_API_KEY = os.environ.get("GROQ_API_KEY", "")
37
  GROQ_API_URL = "https://api.groq.com/openai/v1/chat/completions"
38
+ GROQ_MODEL = os.environ.get("GROQ_MODEL", "llama-3.1-8b-instant")
39
+
40
+ # NVIDIA β€” tertiary AI tier.
41
+ NVIDIA_API_KEY = os.environ.get("NVIDIA_API_KEY", "")
42
+ NVIDIA_MODEL = os.environ.get("NVIDIA_MODEL", "deepseek-ai/deepseek-v4-pro")
43
+ NVIDIA_URL = "https://integrate.api.nvidia.com/v1/chat/completions"
44
 
45
+ # Mistral β€” primary AI, runs first per user request.
46
  MISTRAL_API_KEY = os.environ.get("MISTRAL_API_KEY", "")
47
  MISTRAL_MODEL = os.environ.get("MISTRAL_MODEL", "mistral-large-latest")
48
  MISTRAL_API_URL = os.environ.get(
app/generators/code_fixing.py CHANGED
@@ -136,16 +136,14 @@ POOL_TARGET = 5
136
  POOL_THRESHOLD = 2
137
  POOL_BATCH = 3
138
 
139
- SUPABASE_URL = os.environ.get("SUPABASE_URL", "")
140
- SUPABASE_ANON_KEY = os.environ.get("SUPABASE_ANON_KEY", "")
141
-
142
- # Primary AI: Cloudflare Workers AI
143
- CLOUDFLARE_API_TOKEN = os.environ.get("CLOUDFLARE_API_TOKEN", "")
144
- CLOUDFLARE_ACCOUNT_ID = os.environ.get("CLOUDFLARE_ACCOUNT_ID", "")
145
- CLOUDFLARE_MODEL = os.environ.get("CLOUDFLARE_MODEL", "@cf/meta/llama-3.3-70b-instruct-fp8-fast")
146
 
147
- # Fallback list β€” tried in order if the primary model 404s or errors.
148
- # 8B llama is LAST because it's the only one "verified working" but weak (no response_format, sometimes truncates).
149
  CLOUDFLARE_MODEL_FALLBACKS = [
150
  "@cf/qwen/qwen2.5-coder-32b-instruct",
151
  "@cf/meta/llama-3.3-70b-instruct-fp8-fast",
@@ -156,23 +154,6 @@ CLOUDFLARE_MODEL_FALLBACKS = [
156
  "@cf/meta/llama-3.1-8b-instruct",
157
  ]
158
 
159
- # Secondary AI: Groq
160
- GROQ_API_KEY = os.environ.get("GROQ_API_KEY", "")
161
- GROQ_MODEL = os.environ.get("GROQ_MODEL", "llama-3.1-8b-instant")
162
- GROQ_API_URL = "https://api.groq.com/openai/v1/chat/completions"
163
-
164
- # Tertiary AI: NVIDIA/DeepSeek
165
- NVIDIA_API_KEY = os.environ.get("NVIDIA_API_KEY", "")
166
- NVIDIA_MODEL = os.environ.get("NVIDIA_MODEL", "deepseek-ai/deepseek-v4-pro")
167
- NVIDIA_API_URL = "https://integrate.api.nvidia.com/v1/chat/completions"
168
-
169
- # Mistral β€” primary AI for challenge generation (per the user's request).
170
- MISTRAL_API_KEY = os.environ.get("MISTRAL_API_KEY", "")
171
- MISTRAL_MODEL = os.environ.get("MISTRAL_MODEL", "mistral-large-latest")
172
- MISTRAL_API_URL = os.environ.get(
173
- "MISTRAL_API_URL", "https://api.mistral.ai/v1/chat/completions"
174
- )
175
-
176
  TABLE_NAME = "code_fixing_challenges"
177
 
178
  # Per-team backoff tracker
 
136
  POOL_THRESHOLD = 2
137
  POOL_BATCH = 3
138
 
139
+ from app.core.config import (
140
+ SUPABASE_URL, SUPABASE_ANON_KEY,
141
+ CLOUDFLARE_API_TOKEN, CLOUDFLARE_ACCOUNT_ID, CLOUDFLARE_MODEL, CLOUDFLARE_URL,
142
+ GROQ_API_KEY, GROQ_MODEL, GROQ_API_URL,
143
+ NVIDIA_API_KEY, NVIDIA_MODEL, NVIDIA_URL,
144
+ MISTRAL_API_KEY, MISTRAL_MODEL, MISTRAL_API_URL,
145
+ )
146
 
 
 
147
  CLOUDFLARE_MODEL_FALLBACKS = [
148
  "@cf/qwen/qwen2.5-coder-32b-instruct",
149
  "@cf/meta/llama-3.3-70b-instruct-fp8-fast",
 
154
  "@cf/meta/llama-3.1-8b-instruct",
155
  ]
156
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
157
  TABLE_NAME = "code_fixing_challenges"
158
 
159
  # Per-team backoff tracker
app/generators/crypto.py CHANGED
@@ -54,6 +54,14 @@ import uuid
54
  from dataclasses import dataclass, field, asdict
55
  from typing import Optional, Literal
56
 
 
 
 
 
 
 
 
 
57
  # Load .env early so the CLI works without manual export
58
  try:
59
  from dotenv import load_dotenv
@@ -309,30 +317,6 @@ XP_BY_DIFFICULTY = {"Ω…Ψ¨ΨͺΨ―Ψ¦": 100, "Ω…Ψͺوسط": 150, "Ω‚ΩˆΩŠ": 200}
309
  # Default tool whitelist for the in-browser terminal sandbox.
310
  DEFAULT_TOOLS = ["cat", "ls", "echo", "openssl", "sha256sum", "base64", "file"]
311
 
312
- SUPABASE_URL = os.environ.get("SUPABASE_URL", "https://yevtnyokixocpihhdwqu.supabase.co")
313
- SUPABASE_ANON_KEY = os.environ.get("SUPABASE_ANON_KEY", "")
314
- # Primary AI: Cloudflare Workers AI (minimax-m3 if available, else llama-3.1-8b)
315
- CLOUDFLARE_API_TOKEN = os.environ.get("CLOUDFLARE_API_TOKEN", "")
316
- CLOUDFLARE_ACCOUNT_ID = os.environ.get("CLOUDFLARE_ACCOUNT_ID", "")
317
- CLOUDFLARE_MODEL = os.environ.get("CLOUDFLARE_MODEL", "@cf/meta/llama-3.1-8b-instruct")
318
- CLOUDFLARE_URL = (
319
- f"https://api.cloudflare.com/client/v4/accounts/{CLOUDFLARE_ACCOUNT_ID}/ai/run/{CLOUDFLARE_MODEL}"
320
- if CLOUDFLARE_ACCOUNT_ID else ""
321
- )
322
- GROQ_API_KEY = os.environ.get("GROQ_API_KEY", "")
323
- GROQ_MODEL = os.environ.get("GROQ_MODEL", "llama-3.1-8b-instant")
324
- # Tertiary AI: NVIDIA integrate API (DeepSeek v4-pro). OpenAI-compatible.
325
- NVIDIA_API_KEY = os.environ.get("NVIDIA_API_KEY", "")
326
- NVIDIA_MODEL = os.environ.get("NVIDIA_MODEL", "deepseek-ai/deepseek-v4-pro")
327
- NVIDIA_URL = "https://integrate.api.nvidia.com/v1/chat/completions"
328
-
329
- # PRIMARY AI: Mistral (per the user's request β€” Mistral runs first)
330
- MISTRAL_API_KEY = os.environ.get("MISTRAL_API_KEY", "")
331
- MISTRAL_MODEL = os.environ.get("MISTRAL_MODEL", "mistral-large-latest")
332
- MISTRAL_API_URL = os.environ.get(
333
- "MISTRAL_API_URL", "https://api.mistral.ai/v1/chat/completions"
334
- )
335
-
336
  # Flag format: CyberArena{<hex>}
337
  FLAG_PREFIX = "CyberArena{"
338
 
 
54
  from dataclasses import dataclass, field, asdict
55
  from typing import Optional, Literal
56
 
57
+ from app.core.config import (
58
+ SUPABASE_URL, SUPABASE_ANON_KEY,
59
+ CLOUDFLARE_API_TOKEN, CLOUDFLARE_ACCOUNT_ID, CLOUDFLARE_MODEL, CLOUDFLARE_URL,
60
+ GROQ_API_KEY, GROQ_MODEL,
61
+ NVIDIA_API_KEY, NVIDIA_MODEL, NVIDIA_URL,
62
+ MISTRAL_API_KEY, MISTRAL_MODEL, MISTRAL_API_URL,
63
+ )
64
+
65
  # Load .env early so the CLI works without manual export
66
  try:
67
  from dotenv import load_dotenv
 
317
  # Default tool whitelist for the in-browser terminal sandbox.
318
  DEFAULT_TOOLS = ["cat", "ls", "echo", "openssl", "sha256sum", "base64", "file"]
319
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
320
  # Flag format: CyberArena{<hex>}
321
  FLAG_PREFIX = "CyberArena{"
322
 
app/generators/log_analysis.py CHANGED
@@ -123,14 +123,15 @@ POOL_TARGET = 5
123
  POOL_THRESHOLD = 2
124
  POOL_BATCH = 3
125
 
126
- SUPABASE_URL = os.environ.get("SUPABASE_URL", "")
127
- SUPABASE_ANON_KEY = os.environ.get("SUPABASE_ANON_KEY", "")
128
- STORAGE_BUCKET = "log-analysis-files"
 
 
 
 
129
 
130
- # Primary AI: Cloudflare Workers AI
131
- CLOUDFLARE_API_TOKEN = os.environ.get("CLOUDFLARE_API_TOKEN", "")
132
- CLOUDFLARE_ACCOUNT_ID = os.environ.get("CLOUDFLARE_ACCOUNT_ID", "")
133
- CLOUDFLARE_MODEL = os.environ.get("CLOUDFLARE_MODEL", "@cf/qwen/qwen2.5-coder-32b-instruct")
134
 
135
  CLOUDFLARE_MODEL_FALLBACKS = [
136
  "@cf/qwen/qwen2.5-coder-32b-instruct",
@@ -142,23 +143,6 @@ CLOUDFLARE_MODEL_FALLBACKS = [
142
  "@cf/meta/llama-3.1-8b-instruct",
143
  ]
144
 
145
- # Secondary AI: Groq
146
- GROQ_API_KEY = os.environ.get("GROQ_API_KEY", "")
147
- GROQ_MODEL = os.environ.get("GROQ_MODEL", "llama-3.1-8b-instant")
148
- GROQ_API_URL = "https://api.groq.com/openai/v1/chat/completions"
149
-
150
- # Tertiary AI: NVIDIA/DeepSeek
151
- NVIDIA_API_KEY = os.environ.get("NVIDIA_API_KEY", "")
152
- NVIDIA_MODEL = os.environ.get("NVIDIA_MODEL", "deepseek-ai/deepseek-v4-pro")
153
- NVIDIA_API_URL = "https://integrate.api.nvidia.com/v1/chat/completions"
154
-
155
- # PRIMARY AI: Mistral (per the user's request β€” Mistral runs first)
156
- MISTRAL_API_KEY = os.environ.get("MISTRAL_API_KEY", "")
157
- MISTRAL_MODEL = os.environ.get("MISTRAL_MODEL", "mistral-large-latest")
158
- MISTRAL_API_URL = os.environ.get(
159
- "MISTRAL_API_URL", "https://api.mistral.ai/v1/chat/completions"
160
- )
161
-
162
  TABLE_NAME = "log_analysis_challenges"
163
 
164
  # Per-team backoff tracker
 
123
  POOL_THRESHOLD = 2
124
  POOL_BATCH = 3
125
 
126
+ from app.core.config import (
127
+ SUPABASE_URL, SUPABASE_ANON_KEY,
128
+ CLOUDFLARE_API_TOKEN, CLOUDFLARE_ACCOUNT_ID, CLOUDFLARE_MODEL, CLOUDFLARE_URL,
129
+ GROQ_API_KEY, GROQ_MODEL, GROQ_API_URL,
130
+ NVIDIA_API_KEY, NVIDIA_MODEL, NVIDIA_URL,
131
+ MISTRAL_API_KEY, MISTRAL_MODEL, MISTRAL_API_URL,
132
+ )
133
 
134
+ STORAGE_BUCKET = "log-analysis-files"
 
 
 
135
 
136
  CLOUDFLARE_MODEL_FALLBACKS = [
137
  "@cf/qwen/qwen2.5-coder-32b-instruct",
 
143
  "@cf/meta/llama-3.1-8b-instruct",
144
  ]
145
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
146
  TABLE_NAME = "log_analysis_challenges"
147
 
148
  # Per-team backoff tracker
app/generators/steganography.py CHANGED
@@ -16,7 +16,6 @@ import asyncio
16
  import base64
17
  import hashlib
18
  import json
19
- import os
20
  import random
21
  import sys
22
  import uuid
@@ -41,6 +40,13 @@ except Exception:
41
  pass
42
 
43
  from app.generators.crypto import _repair_json
 
 
 
 
 
 
 
44
 
45
  # --------------------------------------------------------------------------- #
46
  # 0. Constants
@@ -59,26 +65,6 @@ _AI_BACKOFF_UNTIL: dict[str, float] = {}
59
  _POOL_LOCKS: dict[str, asyncio.Lock] = {}
60
  _WATCHER_STARTED: set[tuple[str, str]] = set()
61
 
62
- SUPABASE_URL = os.environ.get("SUPABASE_URL", "https://yevtnyokixocpihpdwqu.supabase.co")
63
- SUPABASE_ANON_KEY = os.environ.get("SUPABASE_ANON_KEY", "")
64
-
65
- # AI Configurations
66
- MISTRAL_API_KEY = os.environ.get("MISTRAL_API_KEY", "")
67
- MISTRAL_MODEL = os.environ.get("MISTRAL_MODEL", "mistral-large-latest")
68
- MISTRAL_API_URL = os.environ.get("MISTRAL_API_URL", "https://api.mistral.ai/v1/chat/completions")
69
-
70
- CLOUDFLARE_API_TOKEN = os.environ.get("CLOUDFLARE_API_TOKEN", "")
71
- CLOUDFLARE_ACCOUNT_ID = os.environ.get("CLOUDFLARE_ACCOUNT_ID", "")
72
- CLOUDFLARE_MODEL = os.environ.get("CLOUDFLARE_MODEL", "@cf/meta/llama-3.1-8b-instruct")
73
-
74
- GROQ_API_KEY = os.environ.get("GROQ_API_KEY", "")
75
- GROQ_MODEL = os.environ.get("GROQ_MODEL", "llama-3.1-8b-instant")
76
- GROQ_API_URL = "https://api.groq.com/openai/v1/chat/completions"
77
-
78
- NVIDIA_API_KEY = os.environ.get("NVIDIA_API_KEY", "")
79
- NVIDIA_MODEL = os.environ.get("NVIDIA_MODEL", "deepseek-ai/deepseek-v4-pro")
80
- NVIDIA_URL = "https://integrate.api.nvidia.com/v1/chat/completions"
81
-
82
  # Curated Unsplash images for cyber themes
83
  UNSPLASH_THEME_URLS = [
84
  "https://images.unsplash.com/photo-1526374965328-7f61d4dc18c5?w=600&auto=format&fit=crop", # matrix/cyber
 
16
  import base64
17
  import hashlib
18
  import json
 
19
  import random
20
  import sys
21
  import uuid
 
40
  pass
41
 
42
  from app.generators.crypto import _repair_json
43
+ from app.core.config import (
44
+ SUPABASE_URL, SUPABASE_ANON_KEY,
45
+ CLOUDFLARE_API_TOKEN, CLOUDFLARE_ACCOUNT_ID, CLOUDFLARE_MODEL,
46
+ GROQ_API_KEY, GROQ_MODEL,
47
+ NVIDIA_API_KEY, NVIDIA_MODEL,
48
+ MISTRAL_API_KEY, MISTRAL_MODEL, MISTRAL_API_URL,
49
+ )
50
 
51
  # --------------------------------------------------------------------------- #
52
  # 0. Constants
 
65
  _POOL_LOCKS: dict[str, asyncio.Lock] = {}
66
  _WATCHER_STARTED: set[tuple[str, str]] = set()
67
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
  # Curated Unsplash images for cyber themes
69
  UNSPLASH_THEME_URLS = [
70
  "https://images.unsplash.com/photo-1526374965328-7f61d4dc18c5?w=600&auto=format&fit=crop", # matrix/cyber
app/generators/vulnerability_hunter.py CHANGED
@@ -268,13 +268,13 @@ POOL_TARGET = 5
268
  POOL_THRESHOLD = 2
269
  POOL_BATCH = 3
270
 
271
- SUPABASE_URL = os.environ.get("SUPABASE_URL", "")
272
- SUPABASE_ANON_KEY = os.environ.get("SUPABASE_ANON_KEY", "")
273
-
274
- # Primary AI: Cloudflare Workers AI
275
- CLOUDFLARE_API_TOKEN = os.environ.get("CLOUDFLARE_API_TOKEN", "")
276
- CLOUDFLARE_ACCOUNT_ID = os.environ.get("CLOUDFLARE_ACCOUNT_ID", "")
277
- CLOUDFLARE_MODEL = os.environ.get("CLOUDFLARE_MODEL", "@cf/qwen/qwen2.5-coder-32b-instruct")
278
 
279
  CLOUDFLARE_MODEL_FALLBACKS = [
280
  "@cf/qwen/qwen2.5-coder-32b-instruct",
@@ -286,23 +286,6 @@ CLOUDFLARE_MODEL_FALLBACKS = [
286
  "@cf/meta/llama-3.1-8b-instruct",
287
  ]
288
 
289
- # Secondary AI: Groq
290
- GROQ_API_KEY = os.environ.get("GROQ_API_KEY", "")
291
- GROQ_MODEL = os.environ.get("GROQ_MODEL", "llama-3.1-8b-instant")
292
- GROQ_API_URL = "https://api.groq.com/openai/v1/chat/completions"
293
-
294
- # Tertiary AI: NVIDIA/DeepSeek
295
- NVIDIA_API_KEY = os.environ.get("NVIDIA_API_KEY", "")
296
- NVIDIA_MODEL = os.environ.get("NVIDIA_MODEL", "deepseek-ai/deepseek-v4-pro")
297
- NVIDIA_API_URL = "https://integrate.api.nvidia.com/v1/chat/completions"
298
-
299
- # PRIMARY AI: Mistral (per the user's request β€” Mistral runs first)
300
- MISTRAL_API_KEY = os.environ.get("MISTRAL_API_KEY", "")
301
- MISTRAL_MODEL = os.environ.get("MISTRAL_MODEL", "mistral-large-latest")
302
- MISTRAL_API_URL = os.environ.get(
303
- "MISTRAL_API_URL", "https://api.mistral.ai/v1/chat/completions"
304
- )
305
-
306
  TABLE_NAME = "vulnerability_hunter_challenges"
307
 
308
  # Per-team backoff tracker
 
268
  POOL_THRESHOLD = 2
269
  POOL_BATCH = 3
270
 
271
+ from app.core.config import (
272
+ SUPABASE_URL, SUPABASE_ANON_KEY,
273
+ CLOUDFLARE_API_TOKEN, CLOUDFLARE_ACCOUNT_ID, CLOUDFLARE_MODEL, CLOUDFLARE_URL,
274
+ GROQ_API_KEY, GROQ_MODEL, GROQ_API_URL,
275
+ NVIDIA_API_KEY, NVIDIA_MODEL, NVIDIA_URL,
276
+ MISTRAL_API_KEY, MISTRAL_MODEL, MISTRAL_API_URL,
277
+ )
278
 
279
  CLOUDFLARE_MODEL_FALLBACKS = [
280
  "@cf/qwen/qwen2.5-coder-32b-instruct",
 
286
  "@cf/meta/llama-3.1-8b-instruct",
287
  ]
288
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
289
  TABLE_NAME = "vulnerability_hunter_challenges"
290
 
291
  # Per-team backoff tracker
app/generators/web_exploitation.py CHANGED
@@ -17,7 +17,6 @@ import asyncio
17
  import hashlib
18
  import json
19
  import logging
20
- import os
21
  import random
22
  import time
23
  from dataclasses import dataclass
@@ -25,19 +24,12 @@ from typing import Optional
25
 
26
  import httpx
27
 
28
- from app.core.config import SUPABASE_URL, SUPABASE_ANON_KEY
29
-
30
- # AI provider config β€” read from env directly (same as code_fixing.py)
31
- CLOUDFLARE_API_TOKEN = os.environ.get("CLOUDFLARE_API_TOKEN", "")
32
- CLOUDFLARE_ACCOUNT_ID = os.environ.get("CLOUDFLARE_ACCOUNT_ID", "")
33
- GROQ_API_KEY = os.environ.get("GROQ_API_KEY", "")
34
- GROQ_API_URL = "https://api.groq.com/openai/v1/chat/completions"
35
- NVIDIA_API_KEY = os.environ.get("NVIDIA_API_KEY", "")
36
- NVIDIA_MODEL = os.environ.get("NVIDIA_MODEL", "deepseek-ai/deepseek-v4-pro")
37
- MISTRAL_API_KEY = os.environ.get("MISTRAL_API_KEY", "")
38
- MISTRAL_MODEL = os.environ.get("MISTRAL_MODEL", "mistral-small-latest")
39
- MISTRAL_API_URL = os.environ.get(
40
- "MISTRAL_API_URL", "https://api.mistral.ai/v1/chat/completions"
41
  )
42
 
43
  # ── Pool tuning ───────────────────────────────────────────────────────
 
17
  import hashlib
18
  import json
19
  import logging
 
20
  import random
21
  import time
22
  from dataclasses import dataclass
 
24
 
25
  import httpx
26
 
27
+ from app.core.config import (
28
+ SUPABASE_URL, SUPABASE_ANON_KEY,
29
+ CLOUDFLARE_API_TOKEN, CLOUDFLARE_ACCOUNT_ID, CLOUDFLARE_URL,
30
+ GROQ_API_KEY, GROQ_API_URL,
31
+ NVIDIA_API_KEY, NVIDIA_MODEL, NVIDIA_URL,
32
+ MISTRAL_API_KEY, MISTRAL_MODEL, MISTRAL_API_URL,
 
 
 
 
 
 
 
33
  )
34
 
35
  # ── Pool tuning ───────────────────────────────────────────────────────