Dailneeds PASlook DS — Management Console

Verbatim Engine Data Sync

Fix All 145 Bugs & Issues — Dailneeds PASlook DS

Goal: Systematically fix every critical, high, medium, and low severity issue identified in the bug report. Organized into 10 phases with dependency ordering — later phases depend on earlier ones.

Open Questions

[!IMPORTANT]

These need your input before I begin execution:

  • 1. API Key Rotation — Should I generate placeholder values in .env.local and leave instructions for you to paste the new keys from Supabase/Zeptomail/Razorpay dashboards? Or do you want to rotate them yourself first?
  • 2. Razorpay Integration — Do you have working Razorpay API keys (RAZORPAY_KEY_ID, RAZORPAY_KEY_SECRET)? The current .env.local has them empty. Real checkout implementation requires valid keys.
  • 3. Admin Role Assignment — After removing hardcoded admin emails, how should initial admin users be created? Options:
        - (a) A one-time SQL script to set roles directly in the profiles table
        - (b) A secure CLI seed command
        - (c) First user auto-becomes super_admin (then promotes others)
  • 4. Duplicate Routes — For product/ vs products/ and categories/ vs category/, which URL pattern should we keep? My recommendation:
        - Keep /product/[id] (singular for detail) and /categories (plural for list)
        - Delete /products/[id] and /category/[slug], add redirects
  • 5. Contact Form — Should the contact form email go to support@paslook.com via Zeptomail, or should it save to a contact_submissions table in Supabase?
  • 6. Install new packages? — The plan requires installing: zod, server-only, dompurify, @types/dompurify. Is that acceptable?

Proposed Changes

Phase 1: Security Emergency — Credentials & Secrets

Fixes: C-01, C-02, C-03, C-06, C-07, C-08, C-17, C-18, H-13, H-35

This phase removes all hardcoded secrets, credential leaks, and insecure random number generation.

MODIFY.env.local

file:///e:/My Folder/Projects/Dailneeds%20-%20PASlook%20DS/.env.local

  • Replace all current keys with placeholder values: YOUR_NEW_KEY_HERE
  • Add comment: # ⚠️ ROTATED — paste new keys from Supabase/Razorpay/Zeptomail dashboards
  • Verify .gitignore includes .env.local

MODIFYlib/auth.tsx

file:///e:/My Folder/Projects/Dailneeds%20-%20PASlook%20DS/lib/auth.tsx

  • Remove hardcoded password 'Password123!' at lines 160, 217 — make password a required field, throw error if missing
  • Remove hardcoded admin email checks at lines 103-107, 128-132, 207-211 — roles come from DB only
  • Remove switchRole() function (lines 292-308) — will be replaced by server-side API in Phase 2
  • Fix generateUUID fallback: replace Math.random() with crypto.getRandomValues() (H-35)

MODIFYapp/admin/login/page.tsx

  • Remove hardcoded admin email role assignment at lines 31-35

MODIFYapp/auth/signin/page.tsx

  • Remove hardcoded admin email role assignment at lines 32-36

MODIFYapp/api/auth/signup/route.ts

  • Remove hardcoded password fallback 'Password123!' at line 92 — require password
  • Remove hardcoded admin email checks at lines 95-99
  • Replace Math.random() OTP generation with crypto.randomInt(100000, 999999) (C-08)
  • Hash OTP before storage using crypto.createHash('sha256') (H-13)

MODIFYapp/api/auth/send-otp/route.ts

  • Replace Math.random() with crypto.randomInt(100000, 999999) (C-08)
  • Hash OTP before storing in DB (H-13)

MODIFYapp/api/auth/verify-otp/route.ts

  • Hash the submitted OTP before comparison (H-13)

MODIFYapp/api/auth/verify-signup-otp/route.ts

  • Same OTP hash fix as above

MODIFYapp/admin/settings/page.tsx

  • Remove localStorage storage of API secrets (C-07)
  • Display only masked/read-only values
  • Add note: "API keys are managed via environment variables on the server"

MODIFYlib/supabase.ts

  • Add import 'server-only' guard on the supabaseAdmin client export (C-17)
  • This will be further refactored in Phase 4

MODIFYlib/email.ts

  • Add import 'server-only' at top of file (C-18)

Phase 2: Auth & Middleware Infrastructure

Fixes: C-04, C-05, C-13, C-14, H-02, H-17, H-28, H-41, H-42, M-46

Creates the server-side authentication layer that all protected routes will use.

NEWmiddleware.ts

  • Create Next.js middleware for route protection
  • Verify Supabase session on protected paths: /admin/*, /account/*, /dashboard/*, /checkout/*
  • For /admin/*: verify user role is super_admin, admin, or staff
  • Redirect unauthenticated users to /auth/signin
  • Export config.matcher for protected paths only
  • Fixes C-04, H-02

NEWlib/supabase-server.ts

  • Helper to create per-request Supabase client from cookies (for use in API routes and middleware)
  • Uses @supabase/ssr createServerClient pattern
  • Includes getAuthenticatedUser() helper that returns verified user or throws 401

MODIFYapp/api/admin/users/create/route.ts

  • Replace body-based creatorId with server-side session verification (C-05)
  • Use getAuthenticatedUser() from lib/supabase-server.ts
  • Verify caller has super_admin role before creating admin users

MODIFYAll API routes under app/api/

  • Add session verification using getAuthenticatedUser() to every route (C-13)
  • For order-related routes, verify user owns the requested order (C-14)
  • Add CSRF protection via Origin header checking (H-17)

MODIFYapp/auth/signin/page.tsx

  • Add password field validation — require non-empty before submit (H-28)
  • Wrap Google sign-in in try/finally to reset loading state (H-41)

MODIFYapp/api/auth/verify-otp/route.ts

  • Add caller identity verification against userId param (H-42)

MODIFYapp/auth/callback/page.tsx

  • Add isLoading check from useAuth() (M-46)
  • If !isLoading && !user, redirect to signin instead of spinning forever

NEWapp/api/admin/role/route.ts

  • Server-side role change API (replacement for client-side switchRole)
  • Verify caller is super_admin before allowing role changes

Phase 3: Database & Schema Synchronization

Fixes: C-19, C-20, H-15, M-04, M-08, M-16

Fixes all database-level issues: schema mismatches, unsafe RLS policies, missing tables/indexes.

MODIFYsupabase/schema.sql

  • Add missing tables: otp_verifications, offers, coupons, videos, video_products (H-15)
  • Add missing columns to profiles: is_email_verified, status, email (H-15)
  • Fix table name consistency: standardize hero_banners / home_banners (H-15)
  • Fix products schema: add image_url, file_url, is_physical OR update code to use images text[] (H-15)
  • Restrict RLS on profiles: for select using (auth.uid() = id) for regular users (C-20)
  • Add admin-only select policy for profiles
  • Add indexes on frequently queried columns: products(category_id), products(price), orders(user_id), orders(status), profiles(email) (M-04)
  • Add updated_at trigger function and apply to all tables (M-08)

NEWsupabase/migrations/001_fix_schema_sync.sql

  • Migration file containing all schema changes for traceability (M-16)

MODIFYscripts/seed.ts

  • Fix table name: hero_banners → match schema (H-15)
  • Fix product columns to match schema (H-15)
  • Fix env parser to handle quoted values (L-33)
  • Add dotenv loading for .env.local

MODIFYlib/supabase.ts

  • Replace delete-all-then-insert with upsert + selective delete in: saveOffers, saveHeroBanners, saveOfferBanners, saveVideos, saveVideoProducts (C-19)
  • Fix INITIAL_OFFER_BANNERS product IDs from 'p1'/'p2' to actual UUIDs (H-38)

Phase 4: Core Library Refactoring

Fixes: C-21, C-09, C-10, H-03, H-22, H-39, M-01 (partial), M-06, M-17, M-25, M-26, M-29, M-31, M-32, L-16, L-17, L-24, L-25, L-32

Refactors the foundational libraries that everything depends on.

NEWlib/types.ts

  • Define all TypeScript interfaces: Product, Category, Order, OrderItem, Banner, Video, VideoProduct, UserProfile, Address, Review, CartItem, CouponCode (M-01)

NEWlib/validation.ts

  • Define Zod schemas for all forms and API inputs (H-03): signInSchema, signUpSchema, checkoutSchema, productSchema, contactFormSchema, reviewSchema, addressSchema, categorySchema, bannerSchema
  • Add URL validation helper: reject javascript: and data: URLs (H-40)

NEWlib/sanitize.ts

  • HTML sanitization wrapper using DOMPurify (C-09)
  • HTML escape helper for email templates (C-10)

NEWlib/env.ts

  • Startup validation for all required env vars (M-06); throws clear errors if NEXT_PUBLIC_SUPABASE_URL, SUPABASE_SERVICE_ROLE_KEY, ZEPTOMAIL_API_KEY are missing.

MODIFYlib/supabase.ts — Major refactor

  • Replace all any types with interfaces from lib/types.ts (M-01)
  • Extract UUID regex into module-level constant (L-16) and replace var with const (L-17)
  • Add try/catch to MockDB.get for corrupt localStorage (M-32)
  • Fix getProductActivePrice to handle NaN (L-25); fix null handling on returns (M-17); switch to catch (err: unknown) (L-32).

MODIFYlib/cart.tsx — Rewrite with useReducer

  • Replace useState + localStorage with useReducer pattern (C-21)
  • Add quantity support to addToCart(product, quantity) (H-11), limits (M-10), stock hooks (H-12), useMemo optimization (M-25).
  • Fix total vs subtotal calculation alignment (H-39).

MODIFYlib/auth.tsx

  • Fix mock signUp to auto sign-in (M-26); remove non-null assertions (M-29) and unused imports (L-24).

MODIFYlib/email.ts

  • Use escapeHtml() on all interpolated values (C-10) and invoke env checks (M-06).

MODIFYapp/globals.css

  • Remove dark theme from body elements (H-22); append reset/normalize structures (M-15) and text fallback layouts (L-18).

Phase 5: Payment & Checkout Implementation

Fixes: C-11, C-12, C-15, C-16, H-14, H-32, H-34, M-20

Implements the complete real payment flow.

MODIFYapp/checkout/page.tsx

  • Replace setTimeout simulation with real Razorpay SDK integration (C-11)
  • Move early return for empty cart AFTER all hook declarations (H-32)
  • Use Zod checkout verification and invoke pricing calculations via server-side logic checks.

MODIFYapp/api/checkout/razorpay/route.ts

  • Re-fetch product prices from DB to secure records against client modifications (C-15).
  • Validate stock availability with FOR UPDATE locks (C-16) and fix amounts processing via Math.round(amount * 100) (H-34).

MODIFYapp/api/webhooks/razorpay/route.ts

  • Update status profiles natively (C-12); invoke signature verification loops via crypto.timingSafeEqual() (H-14).

Phase 6: Component & Page-Level Bug Fixes

Fixes: C-22, H-04, H-09, H-10, H-19, H-20, H-21, H-25, H-27, H-29, H-30, H-31, H-33, H-36, H-37, M-02, M-03... (45+ items)

MODIFYcomponents/Header.tsx

  • Close mobile menus on click (onClick={() => setIsMobileMenuOpen(false)}) (H-19); inject search debouncing rules (H-37).

DELETEapp/products/[id]/page.tsx & app/category/[slug]/page.tsx

  • Remove layout duplicates (H-08); configure clean internal route redirects to singular target parameters.

MODIFYPublic Component Sub-files

Updates apply across: Footer.tsx, PhoneInput.tsx, VideoPlayerModal.tsx, layout.tsx, page.tsx, marketplace/, track-order/, about/, blog/, faq/, contact/, policy/, categories/, account/, wishlist/.

Phase 7: Admin Panel Fixes

Fixes: H-23, H-24, H-25, H-26, H-27, H-40, M-12, M-41, M-42, M-43, L-27, L-30

MODIFYapp/admin/banners/page.tsx

  • Fix sorting mutations with slice indicators (H-23); insert structural link rules (H-40).

MODIFYapp/admin/orders/page.tsx & products/page.tsx

  • Uncomment data handling structures (H-26); scrub out logs parameters (M-12) and connect dynamic text filtering maps (M-43).

Phases 8 - 10: Performance, SEO, Accessibility, DevOps

  • Swap structural source tags to modern responsive framework layouts (<Image> components) globally (H-05).
  • Inject site indexation maps (sitemap.ts, robots.ts, manifest.ts) and dynamic metadata headers (H-07).
  • Add keyboard accessibility controls, semantic mapping contexts, and pin development engine configurations inside package listings.

Verification Plan

Automated Tests

  • 1. Run npx next build — must compile with zero TypeScript errors
  • 2. Run npx next lint — must pass with zero errors

Phase-Specific Verification

  • Phase 1: grep -r "Password123" . returns zero results
  • Phase 4: grep -r ": any" lib/ app/ components/ returns minimal results
  • Phase 8: Lighthouse audit targets score >80 globally across categories
Status: ⏳ Awaiting user approval on implementation plan
Phase 1: Security Emergency — Credentials & Secrets Fixes: C-01, C-02, C-03, C-06, C-07, C-08, C-17, C-18, H-13, H-35
0%
1.1 — Install required packages: zod, server-only, dompurify, @types/dompurify
1.2 — Rotate API keys in .env.local (Placeholders, comment, .gitignore verification)
1.3 — Fix lib/auth.tsx (Remove password/email hooks, update generateUUID to crypto values)
1.4 — Fix app/admin/login/page.tsx (Remove hardcoded admin email role assignment lines 31-35)
1.5 — Fix app/auth/signin/page.tsx (Remove hardcoded admin email role assignment lines 32-36)
1.6 — Fix app/api/auth/signup/route.ts (Require password, deploy crypto.randomInt and hash tokens)
1.7 — Fix app/api/auth/send-otp/route.ts (Replace Math.random with crypto.randomInt and hash OTP)
1.8 — Fix app/api/auth/verify-otp/route.ts (Hash the submitted OTP before comparison)
1.9 — Fix app/api/auth/verify-signup-otp/route.ts (Same OTP hash fix as above)
1.10 — Fix app/admin/settings/page.tsx (Remove localStorage storage of API secrets, display masked)
1.11 — Add server-only guard to lib/supabase.ts (Add import 'server-only' on admin export)
1.12 — Add server-only guard to lib/email.ts (Add import 'server-only' at top)
1.13 — Verify: grep -r "Password123" . returns zero results
1.14 — Verify: grep -r "ajith@toptoday" . returns zero results
1.15 — Verify: grep -r "support@toptoday" . returns zero results
Phase 2: Auth & Middleware Infrastructure Fixes: C-04, C-05, C-13, C-14, H-02, H-17, H-28, H-41, H-42, M-46
0%
2.1 — Create lib/supabase-server.ts (Per-request client from cookies, getAuthenticatedUser helper)
2.2 — Create middleware.ts (Verify session on admin/account paths, handle redirects)
2.3 — Fix app/api/admin/users/create/route.ts (Replace body creatorId with session check, require super_admin)
2.4 — Add auth to ALL API routes (Verify session on checkout and data paths)
2.5 — Fix order IDOR (Verify user owns requested order in all order endpoints)
2.6 — Add CSRF protection (Add Origin header checking to mutating routes)
2.7 — Fix app/auth/signin/page.tsx (Add password field validation, wrap Google sign-in in try/finally)
2.8 — Fix app/api/auth/verify-otp/route.ts (Validate caller identity against userId param)
2.9 — Fix app/auth/callback/page.tsx (Add isLoading check; handle loop redirects safely)
2.10 — Create app/api/admin/role/route.ts (Server-side role change API, require super_admin)
2.11 — Verify: Unauthenticated -> /admin redirects to /auth/signin
2.12 — Verify: Non-admin -> /admin redirects to /dashboard
Phase 3: Database & Schema Synchronization Fixes: C-19, C-20, H-15, M-04, M-08, M-16
0%
3.1 — Update supabase/schema.sql (Add missing tables/columns, fix RLS policies, add columns index triggers)
3.2 — Create migration file supabase/migrations/001_fix_schema_sync.sql
3.3 — Fix scripts/seed.ts (Fix table references, field structures, handle quoted env parsers)
3.4 — Fix lib/supabase.ts data operations (Replace delete-all actions with safe transactional upsert calls)
3.5 — Verify: Seed script runs successfully against updated schema
Phase 4: Core Library Refactoring Fixes: C-09, C-10, C-21, H-03, M-01, M-06, L-16...
0%
4.1 — Create lib/types.ts (Export explicit central data model interfaces)
4.2 — Create lib/validation.ts (Define comprehensive Zod verification validation schemas)
4.3 — Create lib/sanitize.ts (Incorporate DOMPurify input escape wrappers)
4.4 — Create lib/env.ts (Startup engine validation checking metrics)
4.5 — Refactor lib/supabase.ts (Clean out any variables, type configurations securely)
4.6 — Rewrite lib/cart.tsx (Deploy useReducer hooks, track pricing logic alignments)
4.7 — Fix lib/auth.tsx (Fix mock sign-up parameters, scrap out obsolete assertions)
4.8 — Fix lib/email.ts (Apply html-escaping methods over interpolated values)
4.9 — Fix app/globals.css (Prune conflicting template dark-theme directives)
4.10 — Verify: grep -r ": any" lib/ returns minimal results
4.11 — Verify: npx next build compiles successfully
Phase 5: Payment & Checkout Implementation Fixes: C-11, C-12, C-15, C-16, H-14, H-32, H-34, M-20
0%
5.1 — Fix app/checkout/page.tsx (Replace simulated actions with real Razorpay hooks)
5.2 — Fix app/api/checkout/razorpay/route.ts (Server pricing validation, currency math precision)
5.3 — Fix app/api/webhooks/razorpay/route.ts (Execute signature tracking via timingSafeEqual counters)
5.4 — Verify: Full checkout flow works end-to-end utilizing test keys
Phase 6: Component & Page-Level Bug Fixes Fixes: Public Route and Component Polish Controls
0%
6.1 — Fix components/Header.tsx (Close header navigation configurations on click selections)
6.2 — Add debouncing limits over navigation input tracking lines
6.3 — Consolidate duplicate routes (Scrub out products/[id] and category/ redundant directories)
6.4 — Clear out validation failures across tracking, contact, profile, and wishlist screens
Phase 7: Admin Panel Fixes Fixes: H-23, H-24, H-25, H-26, H-27, M-12, M-43...
0%
7.1 — Fix app/admin/layout.tsx (Route security offloaded onto server middleware checkpoints)
7.2 — Fix array sorting mutations across banner administrative operations panels
7.3 — Uncomment data processing links, remove fake metrics markers, and connect text filters
Phases 8-10: Performance, Accessibility & DevOps Fixes: H-05, H-07, M-13, L-01 to L-14 Balance
0%
8.1 — Route next.config.ts processing definitions including security response headers
8.2 — Convert standard image tags to modern responsive framework image layouts globally
8.3 — Build target indexing sitemaps alongside platform structural loading fallbacks
9.1 — Map accessibility features, semantic tracking attributes, and form label boundaries
10.1 — Configure package.json files metadata variables and clean up unused engine files
Final System Verification Standard Automated Compilation Checklist
0%
V-01: npx next build — compiles with zero TypeScript errors
V-02: npx next lint — passes with zero ESLint errors
V-03: dev runtime execution confirmation logs clear of errors
V-04: Confirm global safety credential sweeps pass without data hits