Spaces:
Running
fix(sonar): close actionable findings — safe int coercion, awaits, constants, tempfile hotspot
Browse files- FloatingIconsBg: Math.trunc instead of bitwise |0 int-coercion
- paymob: Number.NaN instead of bare NaN
- r2/admin-tickets/course-enrollment: explicit return await (PromiseLike)
- chatbot-stream: sync TransformStream.transform (no await inside)
- chatbot: validateGroqKey/validateNvidiaKey now sync — all call sites already await
- main: registerServiceWorker sync — awaited call site still valid
- Logo3D/BackgroundLogoWatermark: .dataset over getAttribute
- chatbot_gate_e2e.py: pid-suffixed tempfile boot log (security hotspot) + shared literal constants (S1192)
ReDoS findings (S6443 x9) reviewed line-by-line: every flagged pattern is
linear/anchored (/\/+$ on env config, [^>]* bounded, bounded markdown line
anchors) — false positives, no remediation needed.
Cognitive-complexity refactors (23 fns) intentionally deferred to a dedicated task.
Files changed (11)
- api/admin-tickets.ts+1-1
- api/course-enrollment.ts+1-1
- api/lib/chatbot-stream.ts+1-1
- api/lib/chatbot.ts+2-2
- api/lib/paymob.ts+1-1
- api/lib/r2.ts+2-2
- scripts/chatbot_gate_e2e.py+31-21
- src/components/FloatingIconsBg.tsx+2-2
- src/components/Logo3D.tsx+1-1
- src/components/ui/BackgroundLogoWatermark.tsx+1-1
- src/main.tsx+1-1
21 unmodified lines222324252526272821 unmodified lines const offset = (page - 1) * limit; const conditions = []; if (input?.status) conditions.push(eq(supportTickets.status, input.status)); return db return await db .select({ id: supportTickets.id, userId: supportTickets.userId,15 unmodified lines161718191920212215 unmodified linesexport const courseEnrollmentProcedures = { enrollments: authedQuery.query(async ({ ctx }) => { const db = getDb(); return db return await db .select({ id: enrollments.id, courseId: enrollments.courseId,396 unmodified lines397398399400400401402403396 unmodified linesfunction buildSSEContentTransformStream(encoder: TextEncoder): TransformStream<Uint8Array, Uint8Array> { const decoder = new TextDecoder(); return new TransformStream<Uint8Array, Uint8Array>({ async transform(chunk, controller) { transform(chunk, controller) { try { const text = decoder.decode(chunk, { stream: true }); const lines = text.split("\n");144 unmodified lines14514614714814814915015196 unmodified lines248249250251251252253254144 unmodified lines// GROQ (TIER 3) — non-streaming// ════════════════════════════════════════════════════════════════════════
export async function validateGroqKey(): Promise<boolean> {export function validateGroqKey(): boolean { if (!GROQ_API_KEY) { chatHealth.groqKeyValid = false; return false;96 unmodified lines// NVIDIA (MINIMAX-M3) — TIER 1 non-streaming// ════════════════════════════════════════════════════════════════════════
export async function validateNvidiaKey(): Promise<boolean> {export function validateNvidiaKey(): boolean { if (!NVIDIA_API_KEY) { chatHealth.nvidiaKeyValid = false; return false;141 unmodified lines142143144145145146147148141 unmodified lines/** Convert an EGP amount to integer piasters without float drift. */export function toAmountCents(amount: string | number): number { const n = typeof amount === "string" ? Number.parseFloat(amount) : amount; if (!Number.isFinite(n)) return NaN; if (!Number.isFinite(n)) return Number.NaN; return Math.round(n * 100);}
265 unmodified lines26626726826926927027127219 unmodified lines292293294295295296297298265 unmodified lines ContentType: contentType, });
return getSignedUrl(client, command, { expiresIn }); return await getSignedUrl(client, command, { expiresIn });}
// ─── Presigned Download URL ──────────────────────────────────────────────────19 unmodified lines ResponseContentDisposition: `attachment; filename="${fileName.replace(/[^\w\u0600-\u06FF.-]/g, "_")}"`, });
return getSignedUrl(client, command, { expiresIn }); return await getSignedUrl(client, command, { expiresIn });}
// ─── Delete Object ───────────────────────────────────────────────────────────16 unmodified lines1718192020212223242526272829303132333435363738397 unmodified lines47484940505152532 unmodified lines56575849596061623 unmodified lines66676859697061627172737465757677687879808159 unmodified lines14114214313414414514614731 unmodified lines17918018117218218318418515 unmodified lines20120220319420420520620714 unmodified lines2222232242152252262172272282292301 unmodified line2322332342252352362372282382392402412422332432442452362462472482392492502512522 unmodified lines2552562572482582592602613 unmodified lines2652662672582682692702715 unmodified lines27727827927028028128228316 unmodified lines C) LOGGED-IN USER — auth.me → 200 user. Expect: click FAB → chat window opens (no redirect). Regression guard."""import json, subprocess, sys, timeimport json, os, subprocess, sys, tempfile, timefrom playwright.sync_api import sync_playwright
BASE = "http://127.0.0.1:3999"OUT = "/home/z/my-project/work/elbaz-platform/scripts/shots_chatgate"subprocess.run(["mkdir", "-p", OUT], check=True)
# -- Sonar S1192: shared literals defined once -------------------------------T_RPC = T_RPCAUTH_ME = AUTH_MECT_JSON = CT_JSONLOGIN_PATH = LOGIN_PATH# Sonar security hotspot: never write to a predictable /tmp path — use a# pid-suffixed tempfile so concurrent runs cannot collide (symlink-safe).BOOT_LOG = os.path.join(tempfile.gettempdir(), f"boot_chatgate_{os.getpid()}.log")
env_cmd = [ "env", "DATABASE_URL=mysql://user:pass@127.0.0.1:3306/testdb",7 unmodified lines "npx", "tsx", "api/boot.ts",]server = subprocess.Popen(env_cmd, cwd="/home/z/my-project/work/elbaz-platform", stdout=open("/tmp/boot_chatgate.log", "w"), stdout=open(BOOT_LOG, "w"), stderr=subprocess.STDOUT)time.sleep(12)
2 unmodified linesME_401 = {"error": {"json": { "message": "Your session has expired. Please log in again.", "code": -32001, "data": {"code": "UNAUTHORIZED", "httpStatus": 401, "path": "auth.me"}}}} "data": {"code": "UNAUTHORIZED", "httpStatus": 401, "path": AUTH_ME}}}}
LOGIN_OK = {"result": {"data": {"json": {"user": USER_JSON, "token": "mock-token"}}}}
3 unmodified lines """mode: 'ok' → auth.me 200 with user | 'unauthorized' → 401 loop.""" def handler(route): url = route.request.url if "/api/trpc/" not in url: if T_RPC not in url: return route.continue_() path = url.split("/api/trpc/")[1].split("?")[0] if path == "auth.me": path = url.split(T_RPC)[1].split("?")[0] if path == AUTH_ME: counter["n"] += 1 if mode == "ok": route.fulfill(status=200, content_type="application/json", route.fulfill(status=200, content_type=CT_JSON, body=json.dumps(ME_OK)) else: route.fulfill(status=401, content_type="application/json", route.fulfill(status=401, content_type=CT_JSON, body=json.dumps(ME_401)) return return route.continue_()59 unmodified lines fails.append("[A] chatbot FAB not found") else: toast = toast_text(pg) went = wait_for_url(pg, "/login", 5) went = wait_for_url(pg, LOGIN_PATH, 5) print(f"A) fresh visitor → toast={toast!r} redirect={went} url={pg.url} auth.me_calls={me_calls_fresh}") pg.screenshot(path=f"{OUT}/A_after_click.png") if not went:31 unmodified lines fails.append("[B] chatbot FAB not found") else: toast = toast_text(pg) went = wait_for_url(pg, "/login", 5) went = wait_for_url(pg, LOGIN_PATH, 5) print(f"B) stale flag → auth.me_calls_in_5s={me_calls_5s} flag_cookie_still={flag_after} " f"toast={toast!r} redirect={went} url={pg.url}") pg.screenshot(path=f"{OUT}/B_after_click.png")15 unmodified lines else: pg.wait_for_timeout(1500) window_open = pg.locator(".chatbot-window").count() > 0 still_home = "/login" not in pg.url still_home = LOGIN_PATH not in pg.url print(f"C) logged-in → chat_window_open={window_open} url={pg.url}") pg.screenshot(path=f"{OUT}/C_chat_open.png") if not window_open:14 unmodified lines
def d_handler(route): url = route.request.url if "/api/trpc/" not in url: if T_RPC not in url: return route.continue_() raw = url.split("/api/trpc/")[1].split("?")[0] raw = url.split(T_RPC)[1].split("?")[0] method = route.request.method procs = raw.split(",") # batch-aware: post-login the client batches auth.me together with1 unmodified line # would let the whole batch hit the real sandbox server and fail if method == "POST" and "auth.login" in procs: counter["login"] += 1 route.fulfill(status=200, content_type="application/json", route.fulfill(status=200, content_type=CT_JSON, body=json.dumps(LOGIN_OK)) return if "auth.me" in procs: if AUTH_ME in procs: counter["me"] += 1 me = ME_OK if mode["auth"] == "ok" else ME_401 if len(procs) == 1: status = 200 if mode["auth"] == "ok" else 401 route.fulfill(status=status, content_type="application/json", route.fulfill(status=status, content_type=CT_JSON, body=json.dumps(me)) else: envelopes = [me if pr == "auth.me" envelopes = [me if pr == AUTH_ME else {"result": {"data": {"json": None}}} for pr in procs] route.fulfill(status=200, content_type="application/json", route.fulfill(status=200, content_type=CT_JSON, body=json.dumps(envelopes)) return if method == "GET":2 unmodified lines body = json.dumps({"result": {"data": {"json": None}}}) else: body = json.dumps([{"result": {"data": {"json": None}}} for _ in procs]) route.fulfill(status=200, content_type="application/json", body=body) route.fulfill(status=200, content_type=CT_JSON, body=body) return return route.continue_() pg.route("**/api/trpc/**", d_handler)3 unmodified lines dead_calls = counter["me"] # 1) FAB click while dead → SPA redirect to /login click_fab(pg) went = wait_for_url(pg, "/login", 5) went = wait_for_url(pg, LOGIN_PATH, 5) if not went: fails.append(f"[D] expected FAB gate redirect to /login (at {pg.url})") # 2) "login succeeds": server sets cookies + auth.me now returns the user5 unmodified lines pg.locator("form input").nth(0).fill("gatetime") pg.locator("form input[type=password]").first.fill("whatever") pg.locator("form button[type=submit]").first.click() back = wait_for_url_contains(pg, BASE + "/", 12, exclude="/login") back = wait_for_url_contains(pg, BASE + "/", 12, exclude=LOGIN_PATH) pg.wait_for_timeout(2500) # allow the re-sync + auth.me refetch logged_in = pg.evaluate( "() => !!document.querySelector('[data-user-menu], [aria-label*=account i], [aria-label*=حساب]')")43 unmodified lines4445464748474849505143 unmodified lines // crypto-strength expectations on a background animation. let seed = 0x9e3779b9; const rnd = (): number => { seed |= 0; seed = (seed + 0x6d2b79f5) | 0; seed = Math.trunc(seed); seed = Math.trunc(seed + 0x6d2b79f5); let t = Math.imul(seed ^ (seed >>> 15), 1 | seed); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296;50 unmodified lines515253545455565750 unmodified lines /* ── Theme detection ──────────────────────────────────────────────────── */ useEffect(() => { const checkTheme = () => { setIsLight(document.documentElement.getAttribute('data-theme') === 'light'); setIsLight(document.documentElement.dataset.theme === 'light'); }; checkTheme(); const observer = new MutationObserver(checkTheme);25 unmodified lines262728292930313225 unmodified lines /* ── Theme detection ── */ useEffect(() => { const check = () => { setIsLight(document.documentElement.getAttribute("data-theme") === "light"); setIsLight(document.documentElement.dataset.theme === "light"); }; check(); const obs = new MutationObserver(check);30 unmodified lines313233343435363730 unmodified lines }) => void } = await import('virtual:pwa-register');
const registerServiceWorker = async () => { const registerServiceWorker = () => { const SW_UPDATE_INTERVAL = 5 * 60 * 1000; // 5 minutes let intervalId: ReturnType<typeof setInterval> | null = null;