Secure CRM System Architecture & Development Ruleset
Laravel + Cursor AI (Vibe Coding) Development Blueprint
Prepared for: The Colors Pvt Ltd Technology Stack: Laravel Framework Purpose: Secure CRM platform for customer management, invoicing, reporting, and search functionality.
1. Project Overview
This CRM system is intended for secure customer management, invoicing, reporting, and operational tracking.
The system will:
Manage customer profiles
Generate invoices
Track payments
Provide reporting dashboards
Allow advanced searching
Maintain audit logs
Protect sensitive customer data
Provide scalable architecture for future modules
The development will be assisted using Cursor AI (Vibe Coding), therefore this document also acts as a strict AI coding instruction policy.
2. Recommended Technology Stack
Backend
Laravel 12+
PHP 8.3+
Laravel Sanctum (API Authentication)
Laravel Queue
Laravel Horizon
Laravel Scheduler
Laravel Policies & Gates
Laravel Events & Listeners
Laravel Notifications
Laravel Cashier (Optional future billing)
Database
MySQL 
3. CRM Core Modules
3.1 Authentication Module
Features:
Login
Logout
Password Reset
Email Verification
Two Factor Authentication (2FA)
Session Management
Role Based Access Control
Super Admin Rules
Super Admin MUST have:
Full unrestricted access
Access to all modules
Access to all settings
Access to all reports
Access to audit logs
Access to user activity tracking
Access to role management
Access to permission management
Access to payment gateway configuration
Access to module management
Super Admin MUST be able to:
Create any user role
Create Super Users
Assign permissions dynamically
Restrict any system area
Activate/deactivate features
Suspend users
Reset passwords
Monitor all activities
Configure system-wide settings
Permissions MUST be manageable through dashboard-based user management.
Roles and permissions MUST NOT be hardcoded.
Use database-driven dynamic permission management.
Roles:
Super Admin
Admin
Staff
Finance
Viewer
3.2 Customer Management Module
Fields:
First Name
Last Name
Company Name
Email
Address
City
State
Country
Postcode
Phone Number
Customer Status
Signup Date
Features:
Add customer
Edit customer
Soft delete customer
Customer activity timeline
Attach documents
Customer tags
Notes system
Search filters
3.3 Invoice Management Module
Fields:
Invoice Number
Invoice Date
Due Date
Status
Tax Rate
Invoice Items
Bank Details
Disclaimers
Features:
Create invoice
Generate PDF invoice
Email invoice
Mark paid/unpaid/cancelled
Export invoices
Payment tracking
Invoice audit history
Recurring invoice support
3.4 Reporting Module
Reports:
Daily
Weekly
Monthly
Yearly
Custom Date Range
Metrics:
Paid invoices
Unpaid invoices
Cancelled invoices
Revenue summaries
Outstanding balances
Exports:
CSV
Excel
PDF
3.5 User Journey Management Module
Purpose
The CRM MUST include a dedicated module called:
“User Journey”
This module is intended to visually track and manage the complete progress lifecycle of a customer.
The module MUST be fully integrated with the customer profile system.
User Journey Core Features
The system MUST allow:
Journey creation
Journey assignment
Journey stage tracking
Progress percentage tracking
Tree/progress visualization
Remarks & issue tracking
Timeline monitoring
User collaboration
Status analysis
Completion tracking
User Journey UI Requirements
The UI MUST support:
Tree view progress tracking
Step-by-step workflow view
Percentage-based progress bars
Color-coded statuses
Expandable journey stages
Timeline visualization
Issue indicators
Delayed step highlighting
Completion statistics
Assigned staff visibility
Example UI Structure:
Customer Profile └── User Journey ├── Registration Stage (20%) ├── Documentation Stage (45%) ├── Verification Stage (70%) ├── Payment Stage (85%) └── Completion Stage (100%)
Customer Profile Integration
The User Journey MUST be directly connected to:
Customer Profile
Assigned Staff
Invoice Records
Uploaded Documents
Remarks System
Activity Timeline
From the customer profile page, users MUST be able to:
Assign a journey
Select journey templates
Update progress
Add remarks
Upload supporting files
Assign responsible staff
Escalate issues
Monitor completion percentage
Dynamic Journey Builder
Super Admin MUST be able to:
Create custom journey templates
Add/remove journey stages
Reorder workflow stages
Configure percentage weightage
Configure completion conditions
Activate/deactivate journey templates
The system MUST support:
Multiple journey types
Different workflows per department
Future workflow expansion
User Assignment Rules
Super Admin MUST see all journeys by default.
Super Admin MUST be able to:
Assign journeys to users
Restrict journey visibility
Assign stage ownership
Configure role-based access
Transfer journey ownership
Assigned users MUST be able to:
View assigned customer journeys
Update progress stages
Add remarks/comments
Report issues encountered
Upload proof/documents
Change journey status
Request escalation
Journey Status System
Each stage MUST support:
Pending
In Progress
Waiting
Issue Encountered
Rejected
Completed
Escalated
The progress percentage MUST automatically update based on:
Completed stages
Weight allocation
Mandatory step completion
Remarks & Issue Tracking
Assigned users MUST be able to:
Add remarks
Add internal notes
Mention team members
Report blockers/issues
Upload evidence files
Tag priority levels
Issue tracking MUST support:
Open issues
Resolved issues
Escalated issues
Delayed workflow detection
Analytics & Reporting
The User Journey module MUST provide:
Customer completion analytics
Delayed journey reports
Staff performance tracking
Average completion duration
Workflow bottleneck detection
Pending stage reports
Escalation reports
Security & Permission Rules
User Journey permissions MUST use:
Policies
Middleware
Role-based restrictions
Ownership validation
Only authorized users MUST be able to:
Modify progress
View restricted journeys
Access sensitive remarks
Assign journey ownership
Technical Architecture Rules
Cursor AI MUST:
Develop User Journey as a separate module
Use reusable workflow components
Use dynamic stage configuration
Use database-driven workflow management
Use UUIDs for journeys and stages
Log all stage changes
Log all progress modifications
Use event-driven updates
Use notifications for stage updates
Recommended Tables:
journeys
journey_templates
journey_stages
customer_journeys
customer_journey_progress
journey_remarks
journey_issues
journey_assignments
Future Scalability Requirements
The architecture MUST support future additions such as:
Automated workflow triggers
AI journey recommendations
WhatsApp notifications
Email automation
SLA tracking
Deadline reminders
Mobile app support
Multi-branch workflows
ERP workflow integrations
3.6 Search Module
Search By:
Customer Name
Customer ID
Company Name
Mobile Number
Invoice Number
Invoice Amount
Requirements:
Indexed database queries
Search throttling
Pagination
Query optimization
3.6 System Scalability & Modular Architecture
Modular Expansion Requirement
This CRM MUST be developed as a scalable modular system.
Future requirements requested by customers MUST be able to be developed and integrated as:
Independent modules
Reusable components
Plug-and-play services
API driven features
Tenant-ready extensions
The architecture MUST support:
Dynamic module loading
Independent feature activation
Permission-based feature visibility
Reusable UI components
Reusable backend services
Microservice migration capability in future
API-first architecture preparation
Recommended Modular Structure
/modules /CustomerManagement /InvoiceManagement /Reports /Payments /UserManagement /AuditLogs /Settings /FutureModules
Each module MUST contain:
Controllers
Services
Repositories
Routes
Policies
Requests
Migrations
Views/Components
Tests
Module Activation Rules
Super Admin MUST be able to:
Enable modules
Disable modules
Restrict module access
Assign module permissions
Activate modules per user role
Hide modules from navigation dynamically
Modules MUST NOT require core system modification during installation.
4. High Level System Architecture
Recommended Architecture Pattern
Use:
MVC Architecture
Service Layer Pattern
Repository Pattern
Event Driven Architecture where applicable
Folder Structure Recommendation
/app /Services /Repositories /Actions /DTOs /Policies /Traits /Observers /Events /Listeners /Enums /Http /Controllers /Middleware /Requests
5. SECURITY ARCHITECTURE (CRITICAL)
This section MUST be strictly followed by Cursor AI.
The AI assistant MUST NEVER bypass these security instructions.
6. Cursor AI Development Rules (MANDATORY)
Global Rules for Cursor AI
Cursor AI MUST:
Use Laravel best practices only
Never disable middleware
Never store passwords in plain text
Never expose environment variables
Never expose stack traces in production
Never use raw SQL unless absolutely required
Never trust user input
Never create routes without authentication
Never create admin routes without authorization
Never hardcode credentials
Never bypass CSRF protection
Never disable rate limiting
Never store secrets inside repositories
Never return sensitive debug information in API responses
Never use eval()
Never use unserialize() on user input
Never use mass assignment without fillable protection
Never expose internal IDs publicly where UUID can be used
Cursor AI MUST:
Generate Form Requests for validation
Generate Policies for authorization
Generate Middleware for access protection
Use DTOs for clean data transfer
Use queued jobs for heavy tasks
Use transactions for critical DB operations
Use HTTPS-only cookies
Use encrypted storage where applicable
Use prepared statements only
Use Laravel Eloquent ORM safely
Sanitize all request data
Log all critical actions
Implement audit logging
Implement API throttling
Implement login throttling
7. Middleware Security Rules
Mandatory Middleware Stack
Every protected route MUST include:
Route::middleware([
    
'auth:sanctum'
,
    
'verified'
,
    
'throttle:api'
,
    
'security.headers'
,
    
'activity.logger'
,
])->group(
function
 () {
})
;
Custom Middleware Requirements
Create the following middleware:
7.1 SecurityHeadersMiddleware
Must inject:
X
-
Frame
-
Options
:
 
DENY
X
-
Content
-
Type
-
Options
:
 nosniff
Referrer
-
Policy
:
 strict
-
origin
Permissions
-
Policy
Content
-
Security
-
Policy
Strict
-
Transport
-
Security
7.2 ActivityLoggerMiddleware
Must log:
User ID
IP Address
Route Accessed
Request Method
Device Information
Login attempts
Failed requests
Sensitive modifications
7.3 ForcePasswordRotationMiddleware
Requirements:
Force password reset every 90 days
Block reused passwords
Require strong password policy
7.4 IPWhitelistMiddleware (Optional for Admin Panel)
Allow admin access only from approved IP ranges.
 (Should have an option and not a mandatory feature)
7.5 SessionSecurityMiddleware
Requirements:
Regenerate session after login
Auto logout inactive sessions
Detect concurrent sessions
Force secure cookies
Detect session hijacking patterns
8. Input Sanitization Rules
ABSOLUTE REQUIREMENT
ALL user inputs MUST be sanitized BEFORE processing.
Required Sanitization
String Sanitization
strip_tags
()
trim
()
htmlspecialchars
()
Laravel Validation Rules
Every controller MUST use Form Request validation.
Example:
public
 
function
 rules()
:
 
array
{
    
return
 [
        
'first_name'
 => 
'required|string|max:255'
,
        
'email'
 => 
'required|email:rfc,dns'
,
        
'phone'
 => 
'nullable|string|max:20'
,
    ]
;
}
Dangerous File Upload Protection
Allowed:
PDF
JPG
PNG
DOCX
Blocked:
PHP
EXE
JS
SH
BAT
Required:
MIME type validation
File size limits
Virus scanning
Randomized filenames
Storage outside public directory
9. API Security Rules
API Authentication
Use:
Laravel Sanctum
Expiring tokens
Device-based token tracking
API Rate Limiting
MANDATORY.
Global API Rate Limit
60
 requests
/
minute
Authentication Routes
5
 requests
/
minute
Password Reset Routes
3
 requests
/
minute
Search API
20
 requests
/
minute
Example Rate Limiter
RateLimiter::
for
(
'api'
,
 
function
 (Request 
$request
) {
    
return
 Limit::perMinute(
60
)->by(
$request
->user()
?
->id 
?:
 
$request
->ip())
;
})
;
API Response Rules
NEVER expose:
SQL errors
Stack traces
File paths
Internal IDs
Debug data
Framework versions
10. Database Security Rules
Mandatory Protections
Use Migrations Only
Cursor AI MUST NEVER:
Alter database manually
Use unsafe raw SQL
Use UUIDs
Recommended:
$table
->uuid(
'uuid'
)->unique()
;
Avoid exposing sequential IDs.
Database Indexing
Create indexes for:
Email
Company Name
Invoice Number
Phone Number
Status
Created Date
Transactions
Use transactions for:
Invoice generation
Payment updates
Customer deletion
Bulk imports
Example:
DB
::transaction(
function
 () {
})
;
11. Authentication Security
Google reCAPTCHA Security
Google reCAPTCHA MUST be implemented on:
Login page
Password reset page
Registration page
Sensitive forms
Use:
Google reCAPTCHA v3 OR Enterprise
Local Development Environment Rules
During local development:
reCAPTCHA MUST NOT block development workflows
Localhost environment MUST bypass verification safely
Use environment-based conditional validation
Example:
RECAPTCHA_ENABLED=true
RECAPTCHA_BYPASS_LOCAL=true
Example logic:
if
(app()->environment(
'local'
)) {
    
return
 
true
;
}
Cursor AI MUST ensure:
Production environment NEVER bypasses reCAPTCHA
Local bypass works ONLY in local environment
Staging and production MUST enforce verification strictly
Password Rules
Password Rules
Minimum:
12 characters
Uppercase
Lowercase
Number
Symbol
Account Protection
Required:
Login throttling
Account lockout after failed attempts
Email verification
2FA support
Password breach detection
Session Protection
Use:
SESSION_SECURE_COOKIE=true
SESSION_HTTP_ONLY=true
SESSION_SAME_SITE=lax
12. Authorization Rules
Policy Based Authorization
Every resource MUST use Policies.
Example:
public
 
function
 update(User 
$user
,
 Invoice 
$invoice
)
{
    
return
 
$user
->id 
===
 
$invoice
->created_by
;
}
Role Based Access
Roles must be separated.
Finance users MUST NOT:
Access system settings
Manage admins
Staff users MUST NOT:
Delete invoices
Access audit logs
12.1 User Activity Monitoring & Audit Center
Super Admin Monitoring Requirements
Super Admin MUST have a dedicated activity monitoring dashboard.
The system MUST track:
User logins
Failed login attempts
IP addresses
Browser/device details
Route access history
Customer modifications
Invoice changes
Report generation
Payment activities
Permission changes
Module access history
Export/download activities
Suspicious activities
Activity Dashboard Features
Super Admin MUST be able to:
Filter activities by user
Filter by date range
Filter by module
View user session history
Force logout active sessions
Disable suspicious accounts
Export audit reports
Monitor real-time activity logs
Dynamic Restriction System
Super Admin MUST be able to restrict sections dynamically.
Examples:
Invoice Area
Reports Area
Payments Area
Customer Management
User Management
Audit Logs
Settings
Restrictions MUST be manageable without code changes.
The system MUST use:
Role-based restrictions
Permission-based restrictions
Middleware-based restrictions
Dynamic menu visibility
13. Logging & Audit Trails
Mandatory Audit Logs
Log:
Login attempts
Failed logins
Customer edits
Invoice changes
Payment status changes
Role changes
Password resets
API abuse attempts
Secure Logging
DO NOT log:
Passwords
Access tokens
Credit card data
Sensitive personal data
14. Backup & Disaster Recovery
Backup Rules
Daily:
Database backup
Weekly:
Full server backup
Monthly:
Encrypted offsite backup
Backup Security
Backups MUST:
Be encrypted
Be access restricted
Never be public
Be stored separately
15. Infrastructure Security
Server Hardening
Mandatory:
Disable root SSH login
SSH key authentication only
Fail2Ban
UFW Firewall
Automatic security updates
Disable unused services
Separate DB server if scaling
Firewall Rules
Allow only:
80
443
SSH restricted IP
Block all unnecessary ports.
Cloudflare Protection
Enable:
WAF
Bot protection
DDoS protection
Rate limiting
Country blocking if needed
16. Secure Coding Standards
MUST FOLLOW
Use:
Dependency Injection
SOLID Principles
Strict typing
Repository pattern
Service layer
Avoid:
Fat controllers
Business logic in controllers
Raw queries
Hardcoded secrets
Duplicate logic
17. Environment Security
.env Protection
Never expose:
APP_KEY
DB_PASSWORD
SMTP passwords
API keys
Cloud credentials
Production Configuration
APP_DEBUG=false
APP_ENV=production
LOG_LEVEL=warning
18. Queue & Job Security
Queue Requirements
Sensitive jobs MUST:
Validate payloads
Retry safely
Log failures
Use timeout limits
Example:
public
 
$timeout
 
=
 
120
;
19. File Storage Security
Storage Rules
Use:
storage
/
app
/
private
Never:
Store sensitive files publicly
Allow direct URL access
Use signed temporary URLs where required.
19.1 Payment Gateway Architecture
Payment Gateway Integration Requirements
The CRM MUST support scalable IPG (Internet Payment Gateway) integrations.
The system architecture MUST support:
Sri Lankan local payment gateways
International payment gateways
Multiple payment gateway switching
Dynamic gateway activation
Future gateway integrations
Supported Sri Lankan Gateway Examples
The architecture SHOULD support:
HNB IPG
Commercial Bank IPG
Sampath Vishwa
Nations Trust Bank IPG
PayHere
WEBXPAY
Genie Business
Supported International Gateways
The architecture SHOULD support:
Stripe
PayPal
2Checkout
Authorize.net
Wise Payments
Razorpay
Payment Features
The CRM MUST support:
Invoice payment links
Online invoice settlement
Partial payments
Multi-currency support
Payment status synchronization
Webhook verification
Transaction logs
Refund management
Secure callback validation
Payment Security Rules
Cursor AI MUST:
Validate all callbacks/webhooks
Verify payment signatures
Prevent duplicate transactions
Log all gateway responses
Encrypt transaction references
Never store raw card details
Follow PCI-DSS best practices
Sensitive payment operations MUST use:
Signed requests
Encrypted payloads
Transaction verification middleware
API throttling
20. Monitoring & Detection
Monitoring Stack
Recommended:
Laravel Telescope (staging only)
Sentry
Uptime Kuma
Grafana
Prometheus
Alerting
Alerts for:
Failed login spikes
High API usage
Database failures
Queue failures
Storage failures
Unauthorized access attempts
21. Recommended Packages
Security Packages
Recommended:
spatie/laravel-permission
laravel/sanctum
spatie/laravel-activitylog
spatie/laravel-backup
mews/purifier
pragmarx/google2fa
22. Performance Optimization
Required Optimizations
Use:
Redis caching
Query optimization
Eager loading
Pagination
Queue processing
Route caching
Config caching
Avoid:
N+1 queries
Unindexed searches
Heavy synchronous tasks
23. CI/CD Security
Deployment Rules
Deployment pipeline MUST:
Run tests
Run static analysis
Run security scans
Prevent deployment on failures
Branch Strategy
Use:
main
staging
development
Protected branches required.
24. Mandatory Testing
Required Tests
Unit Tests
Services
Repositories
Helpers
Feature Tests
Authentication
Authorization
Invoice flows
Search flows
Security Tests
SQL injection
XSS
CSRF
Rate limit abuse
Permission bypass
25. CRM Future Scalability
System should support future modules:
WhatsApp integration
Email automation
SMS gateway
Payment gateways
Client portal
Mobile app API
AI chatbot integration
ERP integration
Multi company support
26. Final Cursor AI Instructions
Cursor AI MUST:
Generate production-grade code only
Follow PSR standards
Follow Laravel conventions strictly
Prefer secure defaults
Validate everything
Sanitize everything
Log critical events
Protect every endpoint
Use middleware correctly
Avoid shortcuts
Never compromise security for speed
Cursor AI MUST NEVER:
Disable authentication
Remove middleware
Skip validation
Expose debug data
Use insecure packages
Store plain passwords
Trust client-side validation alone
Ignore authorization policies
27. Recommended Development Workflow
Create database schema
Create models
Create migrations
Create form requests
Create policies
Create services
Create repositories
Create controllers
Apply middleware
Write tests
Run security review
Deploy to staging
Perform penetration testing
Deploy production
28. Final Recommendation
This CRM should be developed with a “Security First Architecture”.
The system should prioritize:
Data integrity
Customer privacy
Attack prevention
Scalability
Auditability
Maintainability
All AI generated code from Cursor AI MUST be reviewed manually before deployment.
No AI-generated code should go directly into production without:
Human review
Security validation
Testing
Performance checks
END OF DOCUMENT
