From 6e4a490f1976d7841e2cf5593df506ddb44a4598 Mon Sep 17 00:00:00 2001 From: Sumit Kumar Date: Mon, 1 Jun 2026 23:20:40 +0530 Subject: [PATCH] perf: memoize search regex in History to avoid per-cell RegExp creation --- client/src/pages/History.tsx | 79 +++++++++++++++++++------------- server/auth.ts | 61 +++++++++++++++--------- server/middleware/rateLimiter.ts | 2 +- 3 files changed, 86 insertions(+), 56 deletions(-) diff --git a/client/src/pages/History.tsx b/client/src/pages/History.tsx index 52cb97d4d..eb6b171d2 100644 --- a/client/src/pages/History.tsx +++ b/client/src/pages/History.tsx @@ -18,38 +18,38 @@ import { ChevronLeft, ChevronRight, } from "lucide-react"; -import { useState, useEffect, useRef } from "react"; +import { useState, useEffect, useRef, useMemo } from "react"; import StatusPill from "@/components/ui/StatusPill"; import ConfidenceRange from "@/components/ui/ConfidenceRange"; import { FileText, RotateCw } from "lucide-react"; import { useLocation } from "wouter"; import { advancedFilter } from "@/utils/search_filters"; -function HighlightText({ text, search }: { text: string; search: string }) { - if (!search.trim()) return <>{text}; +function HighlightText({ text, searchRegex }: { text: string; searchRegex: RegExp | null }) { + if (!searchRegex) return <>{text}; - const regex = new RegExp( - `(${search.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&")})`, - "gi" - ); - const parts = text.split(regex); + try { + const parts = text.split(searchRegex); - return ( - <> - {parts.map((part, i) => - regex.test(part) ? ( - - {part} - - ) : ( - part - ) - )} - - ); + return ( + <> + {parts.map((part, i) => + searchRegex.test(part) ? ( + + {part} + + ) : ( + part + ) + )} + + ); + } catch { + return <>{text}; + } } export default function History() { @@ -61,6 +61,19 @@ export default function History() { const [searchTerm, setSearchTerm] = useState(""); const [sortBy, setSortBy] = useState("date-desc"); + // Memoize the search regex so it's compiled once per search term change + const searchRegex = useMemo(() => { + if (!searchTerm.trim()) return null; + try { + return new RegExp( + `(${searchTerm.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&")})`, + "gi" + ); + } catch { + return null; + } + }, [searchTerm]); + // Date filter state const [startDate, setStartDate] = useState(""); const [endDate, setEndDate] = useState(""); @@ -80,13 +93,13 @@ export default function History() { const getRiskBadge = (category: string) => { const key = (category || "").toUpperCase(); - const highlight = ; + const highlight = ; if (key === "LOW") return ( } + highlightedLabel={} /> ); if (key === "MODERATE") @@ -95,7 +108,7 @@ export default function History() { variant="moderate" label="MODERATE" highlightedLabel={ - + } /> ); @@ -104,7 +117,7 @@ export default function History() { } + highlightedLabel={} /> ); return ( @@ -418,26 +431,26 @@ export default function History() { % @@ -449,7 +462,7 @@ export default function History() { diff --git a/server/auth.ts b/server/auth.ts index cde5a1d0a..92234d029 100644 --- a/server/auth.ts +++ b/server/auth.ts @@ -26,6 +26,27 @@ interface RegisteredUser { // removed duplicated functions +const SALT_LENGTH = 32; +const KEY_LENGTH = 64; + +function hashPassword(password: string): string { + const salt = randomBytes(SALT_LENGTH).toString("hex"); + const hash = scryptSync(password, salt, KEY_LENGTH).toString("hex"); + return `${salt}:${hash}`; +} + +function verifyPassword(password: string, stored: string): boolean { + const [salt, key] = stored.split(":"); + if (!salt || !key) return false; + const hash = scryptSync(password, salt, KEY_LENGTH); + const keyBuffer = Buffer.from(key, "hex"); + return hash.length === keyBuffer.length && timingSafeEqual(hash, keyBuffer); +} + +function ipKeyGenerator(ip: string): string { + return ip.replace(/[^a-zA-Z0-9.:]/g, "_"); +} + /** * In-memory store for registered users. * In production, this should be replaced with a persistent database. @@ -204,12 +225,6 @@ export function createAuthRouter(): Router { if (existingDbUser) { return res.status(409).json({ message: "An account with this email already exists." }); } - registeredUsers.set(email, { - fullName, - email, - passwordHash: hashPassword(password), - licenseNumber: licenseNumber, - }); const passwordHash = hashPassword(password); @@ -246,10 +261,14 @@ export function createAuthRouter(): Router { attemptCount: 0, }); - // In production, send OTP via email. For development, return it in the response. - logDevOtp(email, otp); + // In production, send OTP via email. For development, return it in the response. + logDevOtp(email, otp); - return res.status(201).json({ success: true, pendingEmail: email, ...(process.env.NODE_ENV !== "production" && { devOtp: otp }) }); + return res.status(201).json({ success: true, pendingEmail: email, ...(process.env.NODE_ENV !== "production" && { devOtp: otp }) }); + } catch (err) { + console.error("Registration error:", err); + return res.status(500).json({ message: "Registration failed due to a server error." }); + } }); /** @@ -276,11 +295,11 @@ export function createAuthRouter(): Router { // Check in-memory store (legacy) const registeredUser = registeredUsers.get(email); if (registeredUser && verifyPassword(password, registeredUser.passwordHash)) { - userFullName = registeredUser.fullName; + userName = registeredUser.fullName; } // Also check DB - if (!userFullName) { + if (!userName) { try { const db = getDb(); const [dbUser] = await db @@ -290,21 +309,21 @@ export function createAuthRouter(): Router { .limit(1); if (dbUser && verifyPassword(password, dbUser.passwordHash)) { - userFullName = dbUser.fullName; + userName = dbUser.fullName; + } + } catch (_err) { + // DB not available — fall back to in-memory only + console.warn("DB unavailable for login, using in-memory only."); + const registeredUser = registeredUsers.get(email); + if (registeredUser && verifyPassword(password, registeredUser.passwordHash)) { + userName = registeredUser.fullName; } - } - } catch (_err) { - // DB not available — fall back to in-memory only - console.warn("DB unavailable for login, using in-memory only."); - const registeredUser = registeredUsers.get(email); - if (registeredUser && verifyPassword(password, registeredUser.passwordHash)) { - userFullName = registeredUser.fullName; } } } - if (!userFullName) { + if (!userName) { return res.status(401).json({ message: "Invalid email or password." }); } @@ -346,9 +365,7 @@ export function createAuthRouter(): Router { pendingOtps.delete(email); - const registeredUser = registeredUsers.get(email); const devEmail = process.env.DEV_CLINICIAN_EMAIL || ""; - const name = email === devEmail ? "Dr. Smith" : (registeredUser?.fullName ?? email); let id: string; let name: string; diff --git a/server/middleware/rateLimiter.ts b/server/middleware/rateLimiter.ts index d19fa96a4..f7d66b5e8 100644 --- a/server/middleware/rateLimiter.ts +++ b/server/middleware/rateLimiter.ts @@ -11,7 +11,7 @@ function pruneExpiredRecords(now: number) { if (now > record.resetTime) { requestStore.delete(clientId); } - }); + } } function trimRequestStore(now: number) {