Stormcom Comprehensive Audit Implementations#336
Stormcom Comprehensive Audit Implementations#336rezwana-karim wants to merge 16 commits intomainfrom
Conversation
Prisma: make ProductVariant.sku scoped to a product by replacing the global @unique on sku with @@unique([productId, sku]) (SR-002). Middleware: add Content-Security-Policy header with a relaxed policy for /store/* (allows inline scripts/styles for theme flexibility and external integrations) and a stricter policy for admin/dashboard routes; set the header on responses and add "/admin" to protectedPaths. UI: add admin pages (security dashboard, error and not-found handlers), many dashboard error pages and a DashboardErrorBoundary component to standardize error UI. Other: include build output artifacts (build-final.txt, build-output-latest.txt) and multiple API/component updates referenced in the changeset.
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
There was a problem hiding this comment.
Pull request overview
This PR bundles several “audit” hardening changes across auth/session behavior, API authorization/IDOR prevention, admin routing, and UI resiliency, plus commits updated build output artifacts.
Changes:
- Adds/updates security controls: middleware CSP, expands protected routes to include
/admin, adds permission/store-access checks across multiple APIs. - Improves UX robustness: introduces reusable dashboard error boundary + many route-segment
error.tsx/not-found.tsxpages; updates nav to mark placeholder items as “Soon”. - Normalizes subscription plan endpoint usage by switching clients to
/api/subscriptions/plansand deprecating older plan endpoints.
Reviewed changes
Copilot reviewed 40 out of 40 changed files in this pull request and generated 9 comments.
Show a summary per file
| File | Description |
|---|---|
| src/lib/auth.ts | Sets JWT session maxAge to 24 hours. |
| src/components/subscription/trial-expiration-guard.tsx | Updates plan fetch endpoint to /api/subscriptions/plans. |
| src/components/subscription/admin/subscriptions-table.tsx | Updates plan fetch endpoint to /api/subscriptions/plans. |
| src/components/nav-secondary.tsx | Disables placeholder nav items and adds “Soon” badge/tooltip. |
| src/components/nav-documents.tsx | Disables placeholder nav items and adds “Soon” badge. |
| src/components/dashboard-error-boundary.tsx | Adds reusable client error UI for dashboard/admin segments. |
| src/components/app-sidebar.tsx | Removes unused nav config and adjusts placeholder icon. |
| src/app/not-found.tsx | Adds app-level 404 page. |
| src/app/dashboard/webhooks/error.tsx | Adds route-segment error UI. |
| src/app/dashboard/subscriptions/error.tsx | Adds route-segment error UI. |
| src/app/dashboard/stores/error.tsx | Adds route-segment error UI. |
| src/app/dashboard/settings/error.tsx | Adds route-segment error UI. |
| src/app/dashboard/reviews/error.tsx | Adds route-segment error UI. |
| src/app/dashboard/notifications/error.tsx | Adds route-segment error UI. |
| src/app/dashboard/not-found.tsx | Adds dashboard-scoped 404 page. |
| src/app/dashboard/integrations/error.tsx | Adds route-segment error UI. |
| src/app/dashboard/emails/error.tsx | Adds route-segment error UI. |
| src/app/dashboard/coupons/error.tsx | Adds route-segment error UI. |
| src/app/dashboard/brands/error.tsx | Adds route-segment error UI. |
| src/app/dashboard/attributes/error.tsx | Adds route-segment error UI. |
| src/app/dashboard/analytics/error.tsx | Adds route-segment error UI. |
| src/app/api/subscription/plans/route.ts | Deprecates old plans route and proxies to shared getAvailablePlans(). |
| src/app/api/subscription-plans/route.ts | Deprecates old plans route and proxies to shared getAvailablePlans(). |
| src/app/api/stores/[id]/stats/route.ts | Adds requireStoreAccessCheck() for IDOR prevention. |
| src/app/api/stores/[id]/settings/route.ts | Adds requireStoreAccessCheck() for IDOR prevention. |
| src/app/api/stores/[id]/route.ts | Adds requireStoreAccessCheck() for IDOR prevention. |
| src/app/api/stores/[id]/role-requests/route.ts | Adds requireStoreAccessCheck() for IDOR prevention. |
| src/app/api/stores/[id]/role-requests/[requestId]/route.ts | Adds requireStoreAccessCheck() for IDOR prevention. |
| src/app/api/stores/[id]/domain/verify/route.ts | Adds requireStoreAccessCheck() for IDOR prevention. |
| src/app/api/stores/[id]/domain/route.ts | Adds requireStoreAccessCheck() for POST/DELETE domain ops. |
| src/app/api/payments/configurations/toggle/route.ts | Adds permission check (settings:update) for toggling gateways. |
| src/app/api/payments/configurations/route.ts | Adds permission checks (settings:read/settings:update) for configs. |
| src/app/api/admin/fix-broken-trials/route.ts | Hardens endpoint with auth + super-admin + optional token gate. |
| src/app/admin/security/page.tsx | Adds admin security dashboard page (stats + recent activity). |
| src/app/admin/not-found.tsx | Adds admin-scoped 404 page. |
| src/app/admin/error.tsx | Adds admin-scoped error UI. |
| prisma/schema.prisma | Changes ProductVariant SKU uniqueness to be scoped per product. |
| middleware.ts | Adds CSP logic and protects /admin route. |
| build-output-latest.txt | Updates stored build output/log snapshot. |
| build-final.txt | Adds stored build output/log snapshot. |
| : [ | ||
| "default-src 'self'", | ||
| "script-src 'self' 'unsafe-inline' 'unsafe-eval'", | ||
| "style-src 'self' 'unsafe-inline' https://fonts.googleapis.com", | ||
| "img-src 'self' data: blob: https: http:", | ||
| "font-src 'self' https://fonts.gstatic.com", |
There was a problem hiding this comment.
The “stricter” (non-store) CSP still includes both 'unsafe-inline' and 'unsafe-eval', which largely defeats the XSS protections CSP is meant to provide. Either tighten this policy (prefer nonces/hashes; at minimum avoid 'unsafe-eval' in production) or adjust the comment/documentation so it doesn’t claim to be stricter than the store policy.
| return ( | ||
| <div className="flex items-center justify-center min-h-100"> | ||
| <Card className="max-w-lg"> |
There was a problem hiding this comment.
min-h-100 isn’t a valid default Tailwind class (and differs from the existing dashboard error UI which uses min-h-[600px]). This will likely render without the intended minimum height. Use a valid Tailwind min-height utility (e.g. min-h-screen or min-h-[600px]).
| /** | ||
| * @deprecated Use GET /api/subscriptions/plans instead | ||
| * | ||
| * This route is deprecated. Frontend consumers have been updated to use | ||
| * the canonical /api/subscriptions/plans endpoint. This remains as a | ||
| * backwards-compatible redirect for any external consumers. | ||
| * | ||
| * DUP-001: Consolidated to /api/subscriptions/plans |
There was a problem hiding this comment.
The header comment says this endpoint is a “backwards-compatible redirect”, but the implementation returns 200 JSON and only sets X-Redirect-To (no HTTP redirect status / Location header). Either implement an actual redirect (e.g. 307/308 with Location) or update the comment to reflect that this is a compatibility alias that returns the same payload.
| /** | ||
| * GET /api/subscription-plans | ||
| * Fetch all available subscription plans for plan selection | ||
| * @deprecated Use GET /api/subscriptions/plans instead | ||
| * | ||
| * This route is deprecated. Frontend consumers have been updated to use | ||
| * the canonical /api/subscriptions/plans endpoint. This remains as a | ||
| * backwards-compatible redirect for any external consumers. | ||
| * | ||
| * DUP-001: Consolidated to /api/subscriptions/plans | ||
| */ |
There was a problem hiding this comment.
The header comment says this endpoint is a “backwards-compatible redirect”, but the implementation returns 200 JSON and only sets X-Redirect-To (no HTTP redirect status / Location header). Either implement an actual redirect (e.g. 307/308 with Location) or update the comment to reflect that this is a compatibility alias that returns the same payload.
| Ôû▓ Next.js 16.1.6 (Turbopack) | ||
| - Environments: .env.production.local, .env.local, .env | ||
| - Experiments (use with caution): | ||
| ┬À optimizePackageImports | ||
|
|
||
| > stormcom@0.1.0 build | ||
| > node scripts/build.js | ||
| Creating an optimized production build ... | ||
| Ô£ô Compiled successfully in 117s |
There was a problem hiding this comment.
These committed build logs include terminal-encoding glyphs (e.g. Ôû▓, Ô£ô) and non-deterministic data (timings, PIDs). This makes diffs noisy and can be hard to read across environments. If these logs must live in-repo, consider normalizing them to plain UTF-8 text (or capturing a summarized/curated excerpt) to avoid churn.
| // Content Security Policy | ||
| // Store routes allow inline styles/scripts for theme flexibility; | ||
| // admin/dashboard routes use a stricter policy. | ||
| const isStorePage = pathname.startsWith("/store/"); | ||
| const csp = isStorePage |
There was a problem hiding this comment.
applySecurityHeaders() is only called for NextResponse.next() responses. The early-return path that rewrites subdomain/custom-domain storefront traffic (NextResponse.rewrite(storeUrl)) bypasses these headers entirely, so CSP/XFO/etc won’t be applied for most real storefront requests. Apply applySecurityHeaders to the rewrite response as well, and compute store/admin detection from the rewritten path (or otherwise ensure store pages reached via subdomain still get the intended store CSP).
| // Check if route needs authentication | ||
| const protectedPaths = [ | ||
| "/admin", | ||
| "/dashboard", | ||
| "/settings", | ||
| "/team", |
There was a problem hiding this comment.
/admin was added to protectedPaths, but shouldSkipSubdomainRouting() still doesn’t treat /admin as a skip route. On store subdomains/custom domains, requests to /admin/* may get rewritten into /store/{slug}/admin/* instead of hitting the admin area (and therefore won’t be protected/handled as intended). Add /admin to the skip list alongside the other protected routes.
| const params = await (context as RouteContext).params; | ||
| const { storeId } = storeIdSchema.parse({ storeId: params.id }); | ||
|
|
||
| // IDOR prevention — verify user belongs to THIS store | ||
| const storeAccessError = await requireStoreAccessCheck(storeId); | ||
| if (storeAccessError) return storeAccessError; | ||
|
|
There was a problem hiding this comment.
This file adds requireStoreAccessCheck() for POST/DELETE, but the GET handler still fetches domain/subdomain details for any storeId without verifying store access. Since permission: 'stores:read' alone doesn’t guarantee the requested storeId matches the caller’s store context, this remains an IDOR risk. Apply the same requireStoreAccessCheck(storeId) in GET before reading/returning store domain data.
| model ProductVariant { | ||
| id String @id @default(cuid()) | ||
| productId String | ||
| name String | ||
| sku String @unique | ||
| sku String | ||
| barcode String? | ||
| price Int? | ||
| compareAtPrice Int? | ||
| inventoryQty Int @default(0) | ||
| lowStockThreshold Int @default(5) | ||
| weight Float? | ||
| image String? | ||
| options String | ||
| isDefault Boolean @default(false) | ||
|
|
||
| // Variant-level discount fields | ||
| discountType DiscountType @default(NONE) | ||
| discountValue Int? // Percentage (e.g. 10 = 10%) or minor units (paisa) for FIXED | ||
| discountStartDate DateTime? | ||
| discountEndDate DateTime? | ||
|
|
||
| createdAt DateTime @default(now()) | ||
| updatedAt DateTime @updatedAt | ||
| inventoryLogs InventoryLog[] @relation("VariantInventoryLogs") | ||
| inventoryReservations InventoryReservation[] | ||
| orderItems OrderItem[] | ||
| product Product @relation(fields: [productId], references: [id], onDelete: Cascade) | ||
|
|
||
| @@index([productId]) | ||
| @@index([productId, isDefault]) | ||
| @@unique([productId, sku]) // SR-002: SKU scoped to product (not globally unique) | ||
| } |
There was a problem hiding this comment.
This changes ProductVariant.sku from globally unique to @@unique([productId, sku]). This requires a Prisma migration (dropping the old unique index and creating the composite unique), and the migration will fail if there are existing duplicate (productId, sku) pairs. Add/commit the corresponding migration and consider a pre-migration cleanup/backfill strategy if duplicates already exist.
Revise comprehensive audit docs to reflect remediation work completed: mark multiple security findings (SEC-001..SEC-011), navigation fixes (NAV-001/NAV-002), error/not-found handlers (ERR-001/ERR-002), duplication and schema items (DUP-001, SR-002) as implemented or deferred. Added remediation summary and completion record with validation status (TypeScript, ESLint, production build). Document implementation details: CSP header added to middleware, /admin added to protectedPaths, requireSuperAdmin/permission checks added to affected APIs, requireStoreAccessCheck applied to stores routes, session maxAge reduced to 24 hours, consolidated subscription plans endpoint, and created /admin/security page. Also update DB schema map to scope ProductVariant SKU to product (@@unique([productId, sku])). Added lint-err.txt.
Add a fresh StormCom comprehensive-audit artifact set under docs/stormcom-comprehensive-audit-2026-03-10-fresh-start (index, charter, best-practices, DB schema map, API inventory, page/route map, sidebar audit, feature inventory, gap matrix, UI/UX audit, remediation backlog, execution checklist, plus staging files). Also apply updates to multiple server handlers and related pages: various src/app/api/* route.ts files (admin, plans, role-requests, store-requests, stores/[storeId]/pathao/configure, subscriptions, system, users, auth/signup) and frontend pages (dashboard/integrations/pathao, settings/billing). These changes add audit documentation and adjust API/dashboard handlers to align with the current codebase and audit needs.
Fixes and improvements across UI, hooks, API route, and docs: - AppSidebar: rewrite nav filtering to correctly exclude items when permissioned children are empty (map/filter + TS narrowing) to fix sidebar child-filter bug. - API route: remove unused audit-logger import (deleted logUpdate import). - Storefront AddToCartButton: add aria-labels for increment/decrement and make quantity span aria-live for screen reader updates. - PwaInstallPrompt: remove noisy console logs, handle install-prompt errors silently, and adjust layout utility classes (shrink-0 fixes). - UI Button: replace transition-all with transition-colors to reduce layout thrashing. - useRenderPerformance: replace renderCount state with a ref and expose a getter to avoid extra re-renders while preserving metrics. - Docs: expand audit findings and feature/gap matrices (sidebar, onboarding, billing, routes, tenant/auth gaps) and add minimal lint output. These changes address a visible permission-filtering bug, improve accessibility and runtime noise, and reduce unnecessary renders while adding documentation updates from the audit.
Update the fresh-start StormCom audit artifacts: mark phases and artifact statuses complete, add critical findings, workstreams, sequenced remediation plan, verification/acceptance criteria, and an expanded execution checklist. Add staged Phase 4 runtime audit notes for storefront checkout, dashboard UX, and admin/auth UX. Also small code cleanups to silence unused-variable lint warnings by renaming `session` to `_session` in Pathao integration and billing pages. These changes consolidate runtime findings and prepare the repo for remediation tasks and browser verification.
Add generated ESLint reports to docs/stormcom-comprehensive-audit-2026-03-10-fresh-start/_staging (eslint-direct.json, eslint-json.log, lint-continuation.log) containing aggregated lint results and suppressions. Remove prisma/prisma/dev.db (local development database) to avoid committing a binary dev DB to the repo.
Document a high-risk store-management authoring/permission mismatch and build-time DB/schema drift across the audit. Added findings to index, API inventory, DB/API/UI gap matrix, UI/UX audit, remediation backlog (T12b, T14b), and execution checklist. Calls for investigating /api/stores and StoreService.list() user-context filtering, aligning super-admin access or hiding quick actions, and resolving Prisma/schema drift that triggers a prisma.store.findMany() missing-column error during build.
Add a new comprehensive architectural review and marketing collateral, and apply a rerun addendum across audit docs. - Added ARCHITECTURAL_REVIEW_SUMMARY.md containing the 2026-03-11 audit findings and remediation recommendations. - Added MARKETING_EXECUTION_PLAN.md and MARKETING_SCRIPTS_DETAILED.md with go-to-market plans and ad scripts. - Updated multiple docs under docs/stormcom-comprehensive-audit-2026-03-10-fresh-start to include a 2026-03-11 rerun addendum (index, charter, best-practices, db-schema-map, api-inventory, page-route-map, sidebar-navigation-audit, feature-inventory, gap-matrix, ui-ux-audit, agentic-remediation-backlog, execution-checklist). - Updated .gitignore to ignore /marketing and scripts/record-marketing-video.mjs. Purpose: capture fresh validation evidence from the rerun and add marketing materials to support launch and remediation planning.
Add two new audit supplements: docs/stormcom-comprehensive-audit-2026-03-10-fresh-start/12-live-browser-route-coverage.md and 13-live-browser-ui-ux-review.md, which capture browser-verified route coverage and a detailed UI/UX review from the 2026-03-11 live audit (sessions, seeded data, interactions, findings, and recommendations). Update 00-index.md to include links to the new files and add execution-table entries marking them complete on 2026-03-11. These documents provide real-session evidence, stability notes, and prioritized remediation guidance for storefront, dashboard, admin, and checkout flows.
Add a comprehensive UI/UX review for StormCom (executive summary, findings, recommendations, user flows and related audit docs) and several StormCom UX reference files. Introduce error pages (error.tsx, global-error.tsx) and a new discount type, plus lint outputs. Update VSCode settings (bump chat.planAgent.defaultModel to GPT-5.4). Apply miscellaneous fixes/changes across middleware, API routes (stores, subscriptions), store UI components (product card/grid, variant selector) and supporting libs (auth-helpers, api-middleware, discount-utils, get-current-user, store.service) to improve auth, subscription and store handling.
Add a full UI/UX audit (COMPREHENSIVE_UI_UX_REVIEW.md) for the StormCom multi-tenant SaaS platform. The report (dated Mar 11, 2025) documents test matrix, 4 critical P0 bugs (middleware RBAC bypass, orders RSC infinite loop, missing order detail action/page, broken /dashboard/marketing), P1–P3 issues, page-by-page findings, RBAC recommendations, accessibility/perf fixes, and a suggested remediation roadmap. Use this as a single-source reference for prioritized fixes and implementation planning.
Add extensive skill documentation, rules, and resources for multiple agent namespaces (.agent, .agents, .claude, .qwen). Introduces deploy-to-vercel scripts and archives, Next.js/React/React Native best-practices, Vercel composition patterns, and many rule markdowns under each skill set. Also updates a few SKILL.md and AGENTS.md files and adjusts .gitignore.
Replaced the object return ({ from, to }) in getDateRange with a JSX ResponsiveContainer element (width/height/minWidth/minHeight) in src/components/analytics/revenue-chart.tsx. This change makes getDateRange return a React element instead of the expected date range object and will break callers that rely on { from, to }; likely unintended and should be reviewed/fixed.
Add loading skeleton components for multiple dashboard sections (admin, attributes, emails, integrations, landing-pages, notifications, reviews, stores, webhooks) and introduce standardized client-side error components that use DashboardErrorBoundary for consistent error UI. Refactor orders/[id]/page.tsx: rename to OrderDetailsPage, add server-side auth and permission checks, implement super-admin store fallback (querying prisma for order.storeId), validate order existence (notFound/redirects), and adjust layout (SidebarProvider styles and container structure). Also import prisma and clean up component typings and formatting.
|
Automated review (GitHub Models): The main features and fixes described in PR #336—including improved error boundaries, Confidence: 0.95 Evidence:
|
This pull request updates build output and audit documentation to reflect recent improvements in error handling and route protection for the StormCom multi-tenant SaaS application. The most important changes are the addition of error boundary files, inclusion of
/adminin protected middleware paths, and alignment of build logs with the current application structure.Error handling and route protection improvements:
/adminto the list of middleware-protected paths, ensuring admin routes are now secured at the middleware level and not just via layout/page-level authentication.Build output alignment:
build-final.txtandbuild-output-latest.txtto reflect the current Next.js version, build process, and route structure, including new static and dynamic routes and middleware proxy details. [1] [2]Security and developer experience:
Build process and output improvements:
build-final.txtandbuild-output-latest.txtto include detailed logs for Next.js build, Prisma errors, and PostgreSQL SSL warnings, making it easier to spot database issues and security warnings during deployment. [1] [2]Security enhancements:
applySecurityHeadersfunction inmiddleware.ts, applying a more permissive policy for store pages (to allow theme flexibility) and a stricter policy for admin/dashboard routes. This helps mitigate XSS risks while supporting required frontend features.Please let me know if you want more details on any specific change or need guidance on how these improvements affect development and deployment!