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 lines2223242526272821 unmodified linesconst offset = (page - 1) * limit;const conditions = [];if (input?.status) conditions.push(eq(supportTickets.status, input.status));return db.select({id: supportTickets.id,userId: supportTickets.userId,21 unmodified lines2223242526272821 unmodified linesconst offset = (page - 1) * limit;const conditions = [];if (input?.status) conditions.push(eq(supportTickets.status, input.status));return await db.select({id: supportTickets.id,userId: supportTickets.userId,
15 unmodified lines1617181920212215 unmodified linesexport const courseEnrollmentProcedures = {enrollments: authedQuery.query(async ({ ctx }) => {const db = getDb();return db.select({id: enrollments.id,courseId: enrollments.courseId,15 unmodified lines1617181920212215 unmodified linesexport const courseEnrollmentProcedures = {enrollments: authedQuery.query(async ({ ctx }) => {const db = getDb();return await db.select({id: enrollments.id,courseId: enrollments.courseId,
396 unmodified lines397398399400401402403396 unmodified linesfunction buildSSEContentTransformStream(encoder: TextEncoder): TransformStream<Uint8Array, Uint8Array> {const decoder = new TextDecoder();return new TransformStream<Uint8Array, Uint8Array>({async transform(chunk, controller) {try {const text = decoder.decode(chunk, { stream: true });const lines = text.split("\n");396 unmodified lines397398399400401402403396 unmodified linesfunction buildSSEContentTransformStream(encoder: TextEncoder): TransformStream<Uint8Array, Uint8Array> {const decoder = new TextDecoder();return new TransformStream<Uint8Array, Uint8Array>({transform(chunk, controller) {try {const text = decoder.decode(chunk, { stream: true });const lines = text.split("\n");
144 unmodified lines14514614714814915015196 unmodified lines248249250251252253254144 unmodified lines// GROQ (TIER 3) — non-streaming// ════════════════════════════════════════════════════════════════════════export async function validateGroqKey(): Promise<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> {if (!NVIDIA_API_KEY) {chatHealth.nvidiaKeyValid = false;return false;144 unmodified lines14514614714814915015196 unmodified lines248249250251252253254144 unmodified lines// GROQ (TIER 3) — non-streaming// ════════════════════════════════════════════════════════════════════════export function validateGroqKey(): boolean {if (!GROQ_API_KEY) {chatHealth.groqKeyValid = false;return false;96 unmodified lines// NVIDIA (MINIMAX-M3) — TIER 1 non-streaming// ════════════════════════════════════════════════════════════════════════export function validateNvidiaKey(): boolean {if (!NVIDIA_API_KEY) {chatHealth.nvidiaKeyValid = false;return false;
141 unmodified lines142143144145146147148141 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;return Math.round(n * 100);}141 unmodified lines142143144145146147148141 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 Number.NaN;return Math.round(n * 100);}
265 unmodified lines26626726826927027127219 unmodified lines292293294295296297298265 unmodified linesContentType: contentType,});return getSignedUrl(client, command, { expiresIn });}// ─── Presigned Download URL ──────────────────────────────────────────────────19 unmodified linesResponseContentDisposition: `attachment; filename="${fileName.replace(/[^\w\u0600-\u06FF.-]/g, "_")}"`,});return getSignedUrl(client, command, { expiresIn });}// ─── Delete Object ───────────────────────────────────────────────────────────265 unmodified lines26626726826927027127219 unmodified lines292293294295296297298265 unmodified linesContentType: contentType,});return await getSignedUrl(client, command, { expiresIn });}// ─── Presigned Download URL ──────────────────────────────────────────────────19 unmodified linesResponseContentDisposition: `attachment; filename="${fileName.replace(/[^\w\u0600-\u06FF.-]/g, "_")}"`,});return await getSignedUrl(client, command, { expiresIn });}// ─── Delete Object ───────────────────────────────────────────────────────────
16 unmodified lines171819202122232425262728297 unmodified lines373839404142432 unmodified lines464748495051523 unmodified lines5657585960616263646566676869707159 unmodified lines13113213313413513613731 unmodified lines16917017117217317417515 unmodified lines19119219319419519619714 unmodified lines2122132142152162172182192201 unmodified line2222232242252262272282292302312322332342352362372382392402412422 unmodified lines2452462472482492502513 unmodified lines2552562572582592602615 unmodified lines26726826927027127227316 unmodified linesC) LOGGED-IN USER — auth.me → 200 user. Expect: click FAB → chat windowopens (no redirect). Regression guard."""import json, subprocess, sys, timefrom playwright.sync_api import sync_playwrightBASE = "http://127.0.0.1:3999"OUT = "/home/z/my-project/work/elbaz-platform/scripts/shots_chatgate"subprocess.run(["mkdir", "-p", OUT], check=True)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"),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"}}}}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.urlif "/api/trpc/" not in url:return route.continue_()path = url.split("/api/trpc/")[1].split("?")[0]if path == "auth.me":counter["n"] += 1if mode == "ok":route.fulfill(status=200, content_type="application/json",body=json.dumps(ME_OK))else:route.fulfill(status=401, content_type="application/json",body=json.dumps(ME_401))returnreturn route.continue_()59 unmodified linesfails.append("[A] chatbot FAB not found")else:toast = toast_text(pg)went = wait_for_url(pg, "/login", 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 linesfails.append("[B] chatbot FAB not found")else:toast = toast_text(pg)went = wait_for_url(pg, "/login", 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 lineselse:pg.wait_for_timeout(1500)window_open = pg.locator(".chatbot-window").count() > 0still_home = "/login" not in pg.urlprint(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 linesdef d_handler(route):url = route.request.urlif "/api/trpc/" not in url:return route.continue_()raw = url.split("/api/trpc/")[1].split("?")[0]method = route.request.methodprocs = 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 failif method == "POST" and "auth.login" in procs:counter["login"] += 1route.fulfill(status=200, content_type="application/json",body=json.dumps(LOGIN_OK))returnif "auth.me" in procs:counter["me"] += 1me = ME_OK if mode["auth"] == "ok" else ME_401if len(procs) == 1:status = 200 if mode["auth"] == "ok" else 401route.fulfill(status=status, content_type="application/json",body=json.dumps(me))else:envelopes = [me if pr == "auth.me"else {"result": {"data": {"json": None}}}for pr in procs]route.fulfill(status=200, content_type="application/json",body=json.dumps(envelopes))returnif method == "GET":2 unmodified linesbody = 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)returnreturn route.continue_()pg.route("**/api/trpc/**", d_handler)3 unmodified linesdead_calls = counter["me"]# 1) FAB click while dead → SPA redirect to /loginclick_fab(pg)went = wait_for_url(pg, "/login", 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 linespg.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")pg.wait_for_timeout(2500) # allow the re-sync + auth.me refetchlogged_in = pg.evaluate("() => !!document.querySelector('[data-user-menu], [aria-label*=account i], [aria-label*=حساب]')")16 unmodified lines17181920212223242526272829303132333435363738397 unmodified lines474849505152532 unmodified lines565758596061623 unmodified lines6667686970717273747576777879808159 unmodified lines14114214314414514614731 unmodified lines17918018118218318418515 unmodified lines20120220320420520620714 unmodified lines2222232242252262272282292301 unmodified line2322332342352362372382392402412422432442452462472482492502512522 unmodified lines2552562572582592602613 unmodified lines2652662672682692702715 unmodified lines27727827928028128228316 unmodified linesC) LOGGED-IN USER — auth.me → 200 user. Expect: click FAB → chat windowopens (no redirect). Regression guard."""import json, os, subprocess, sys, tempfile, timefrom playwright.sync_api import sync_playwrightBASE = "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(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}}}}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.urlif T_RPC not in url:return route.continue_()path = url.split(T_RPC)[1].split("?")[0]if path == AUTH_ME:counter["n"] += 1if mode == "ok":route.fulfill(status=200, content_type=CT_JSON,body=json.dumps(ME_OK))else:route.fulfill(status=401, content_type=CT_JSON,body=json.dumps(ME_401))returnreturn route.continue_()59 unmodified linesfails.append("[A] chatbot FAB not found")else:toast = toast_text(pg)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 linesfails.append("[B] chatbot FAB not found")else:toast = toast_text(pg)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 lineselse:pg.wait_for_timeout(1500)window_open = pg.locator(".chatbot-window").count() > 0still_home = LOGIN_PATH not in pg.urlprint(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 linesdef d_handler(route):url = route.request.urlif T_RPC not in url:return route.continue_()raw = url.split(T_RPC)[1].split("?")[0]method = route.request.methodprocs = 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 failif method == "POST" and "auth.login" in procs:counter["login"] += 1route.fulfill(status=200, content_type=CT_JSON,body=json.dumps(LOGIN_OK))returnif AUTH_ME in procs:counter["me"] += 1me = ME_OK if mode["auth"] == "ok" else ME_401if len(procs) == 1:status = 200 if mode["auth"] == "ok" else 401route.fulfill(status=status, content_type=CT_JSON,body=json.dumps(me))else:envelopes = [me if pr == AUTH_MEelse {"result": {"data": {"json": None}}}for pr in procs]route.fulfill(status=200, content_type=CT_JSON,body=json.dumps(envelopes))returnif method == "GET":2 unmodified linesbody = json.dumps({"result": {"data": {"json": None}}})else:body = json.dumps([{"result": {"data": {"json": None}}} for _ in procs])route.fulfill(status=200, content_type=CT_JSON, body=body)returnreturn route.continue_()pg.route("**/api/trpc/**", d_handler)3 unmodified linesdead_calls = counter["me"]# 1) FAB click while dead → SPA redirect to /loginclick_fab(pg)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 linespg.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_PATH)pg.wait_for_timeout(2500) # allow the re-sync + auth.me refetchlogged_in = pg.evaluate("() => !!document.querySelector('[data-user-menu], [aria-label*=account i], [aria-label*=حساب]')")
43 unmodified lines444546474849505143 unmodified lines// crypto-strength expectations on a background animation.let seed = 0x9e3779b9;const rnd = (): number => {seed |= 0;seed = (seed + 0x6d2b79f5) | 0;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;43 unmodified lines444546474849505143 unmodified lines// crypto-strength expectations on a background animation.let seed = 0x9e3779b9;const rnd = (): number => {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 lines5152535455565750 unmodified lines/* ── Theme detection ──────────────────────────────────────────────────── */useEffect(() => {const checkTheme = () => {setIsLight(document.documentElement.getAttribute('data-theme') === 'light');};checkTheme();const observer = new MutationObserver(checkTheme);50 unmodified lines5152535455565750 unmodified lines/* ── Theme detection ──────────────────────────────────────────────────── */useEffect(() => {const checkTheme = () => {setIsLight(document.documentElement.dataset.theme === 'light');};checkTheme();const observer = new MutationObserver(checkTheme);
25 unmodified lines2627282930313225 unmodified lines/* ── Theme detection ── */useEffect(() => {const check = () => {setIsLight(document.documentElement.getAttribute("data-theme") === "light");};check();const obs = new MutationObserver(check);25 unmodified lines2627282930313225 unmodified lines/* ── Theme detection ── */useEffect(() => {const check = () => {setIsLight(document.documentElement.dataset.theme === "light");};check();const obs = new MutationObserver(check);
30 unmodified lines3132333435363730 unmodified lines}) => void} = await import('virtual:pwa-register');const registerServiceWorker = async () => {const SW_UPDATE_INTERVAL = 5 * 60 * 1000; // 5 minuteslet intervalId: ReturnType<typeof setInterval> | null = null;30 unmodified lines3132333435363730 unmodified lines}) => void} = await import('virtual:pwa-register');const registerServiceWorker = () => {const SW_UPDATE_INTERVAL = 5 * 60 * 1000; // 5 minuteslet intervalId: ReturnType<typeof setInterval> | null = null;