Nocron Backend
Nocron Backend Project Summary - Automation API
🎯 Product
Nocron Backend is a robust and scalable RESTful API for task automation and workflow scheduling. It’s the central engine of the Nocron platform, designed to eliminate the complexity of traditional cron jobs while providing enterprise-level features.
Key features:
- Task scheduling based on cron and events
- Multiple trigger types (Schedule, Webhook, Email, API)
- Real-time execution with live monitoring via WebSockets
- Template system for common use cases
- JWT authentication with refresh tokens and automatic rotation
- Role-based access control (User, Admin, SuperAdmin)
- API Key management with granular permissions
- Advanced analytics with engagement and performance metrics
- Multi-channel notification system (Email, Push, In-App, SMS, Webhook)
- Stripe integration for subscriptions and payments
- Notion API integration for workspace synchronization
- Complete audit trail with tracking of all actions
- Automated security alerts with pattern detection
🛠️ Technology Stack
Backend Framework
- NestJS 11.0.1 - Progressive Node.js framework
- Node.js 18.17.0+ - JavaScript runtime
- TypeScript 5.7.3 - Typed superset of JavaScript
Database
- PostgreSQL 15+ - Relational database (Neon Cloud)
- Prisma ORM 6.15.0 - Modern ORM with type-safety
Authentication and Security
- Passport.js - Authentication middleware
- JWT (jsonwebtoken v9.0.2) - Access and refresh tokens
- Argon2 (v0.44.0) - Password hashing (recommended)
- Bcrypt (v6.0.0) - Alternative password hashing
Validation and Transformation
- class-validator (v0.14.2) - DTO validation
- class-transformer (v0.5.1) - Object transformation
External Integrations
- @notionhq/client v5.1.0 - Notion API integration
- Stripe v18.5.0 - Payment processing
- Nodemailer v7.0.6 - Email sending
- Socket.io v4.8.1 - WebSockets for real-time
Scheduling and Tasks
- node-cron v3.0.3 - Cron-style task scheduler
- @nestjs/schedule v4.1.2 - NestJS scheduling module
Documentation
- @nestjs/swagger v7.4.2 - OpenAPI/Swagger documentation
- swagger-ui-express v5.0.1 - Interactive Swagger UI
Testing
- Jest v30.0.0 - Testing framework
- ts-jest v29.2.5 - Jest preset for TypeScript
- Supertest v7.0.0 - HTTP API testing
Development Tools
- ESLint v9.18.0 - Code linter
- Prettier v3.4.2 - Code formatter
- Husky v9.1.7 - Git hooks
- ts-node v10.9.2 - TypeScript execution in Node.js
- tsx v4.19.2 - Fast TypeScript executor
🏗️ Architecture
Folder Structure
nocron/backend/
├── src/ # Source code
│ ├── auth/ # Authentication and authorization
│ ├── users/ # User management
│ ├── tasks/ # Core task system
│ ├── api/v1/ # REST API version 1
│ ├── admin/ # Admin panel
│ ├── analytics/ # Analytics engine
│ ├── billing/ # Stripe and subscriptions
│ ├── dashboard/ # Real-time metrics
│ ├── email/ # Email service
│ ├── notifications/ # Notification system
│ ├── reports/ # Reports and analytics
│ ├── notion/ # Notion integration
│ ├── health/ # Health checks
│ ├── monitoring/ # System monitoring
│ ├── auditLog/ # Audit logs
│ ├── sessions/ # Session management
│ ├── webhooks/ # Webhook handling
│ ├── queue/ # Task queue
│ ├── retry/ # Retry system
│ ├── scheduler/ # Task scheduler
│ ├── alerts/ # Security alerts
│ ├── realtime/ # WebSockets
│ ├── common/ # Guards, interceptors, pipes
│ ├── config/ # Configuration
│ ├── prisma/ # Prisma service
│ ├── utils/ # Utilities
│ ├── app.module.ts # Root module
│ ├── app-minimal.module.ts # Minimal module
│ ├── main.ts # Main bootstrap
│ └── main-minimal.ts # Minimal bootstrap
│
├── prisma/ # Prisma ORM
│ ├── schema.prisma # Database schema
│ └── seed.ts # Initial data
│
├── test/ # E2E tests
│ ├── jest-e2e.json # Jest E2E configuration
│ └── jest-smoke.json # Smoke tests configuration
│
├── docs/ # Documentation
│ ├── README.md
│ ├── ARCHITECTURE.md
│ ├── DECISIONS.md
│ ├── ROADMAP.md
│ └── nocron_backend_roadmap.md
│
├── .github/ # GitHub configuration
│ ├── workflows/ # CI/CD workflows
│ └── ISSUE_TEMPLATE/ # Issue templates
│
├── sdk/ # Client SDKs
│ └── javascript/ # JavaScript/TypeScript SDK
│
├── issues/ # Audit tracking
│ ├── GITHUB-ISSUES-CREATED-SUMMARY.md
│ ├── GITHUB-PROJECT-MANAGEMENT.md
│ ├── SPRINT-PLANNING.md
│ └── PROJECT-WORKFLOW-GUIDE.md
│
├── package.json # Dependencies and scripts
├── tsconfig.json # TypeScript configuration
├── nest-cli.json # Nest CLI configuration
├── .env # Environment variables
├── .env.test # Testing variables
├── .gitignore # Git ignore
├── .prettierrc # Prettier configuration
├── eslint.config.mjs # ESLint configuration
├── README.md # Main documentation
├── CLAUDE-BACKEND-STATE.md # Project state
└── CONTRIBUTING.md # Contribution guide
🔧 Modules and Services
Auth Module (src/auth/)
Key files:
auth.service.ts- Authentication logic (register, login, refresh, logout)auth.controller.ts- Authentication endpointsroles.service.ts- Role and permission managementadmin-roles.controller.ts- Administrative role endpointsstrategies/jwt.strategy.ts- Passport JWT strategydto/register.dto.ts,login.dto.ts,change-password.dto.ts- Validation DTOs
Functionality:
- User registration with Argon2/Bcrypt hashing
- Login with JWT access + refresh tokens
- Refresh token with automatic rotation
- Role system (User, Admin, SuperAdmin)
- Authentication and authorization guards
- Token version for global token invalidation
Users Module (src/users/)
Functionality:
- Complete user CRUD
- Profile management
- Password change
- Notion token management
- Relationships with tasks and subscriptions
Tasks Module (src/tasks/)
Functionality:
- Task creation and management
- Support for multiple action types:
- HTTP_REQUEST
- EMAIL_SEND
- DATABASE_QUERY
- API_CALL
- CUSTOM_SCRIPT
- NOTION_SYNC
- Scheduling with cron expressions
- Immediate task execution
- Execution logs
- States: ACTIVE, PAUSED, STOPPED, FAILED
API v1 Module (src/api/v1/)
Public endpoints:
/api/v1/tasks- Task CRUD with API Key authentication/api/v1/analytics- Metrics and analytics- Swagger documentation at
/api/docs
Billing Module (src/billing/)
Functionality:
- Complete Stripe integration
- Subscription management (BASIC, PRO, ENTERPRISE)
- Webhook handling for Stripe events
- Payment and invoice tracking
- Usage limits per plan
- Subscription cancellation and renewal
Notifications Module (src/notifications/)
Functionality:
- Multi-channel system (Email, Push, In-App, SMS, Webhook)
- Notification templates with variables
- User preferences per type and channel
- Tracking of sending, delivery, reading and clicks
- Notification queue
- Retry logic for failures
Email Module (src/email/)
Functionality:
- Nodemailer integration (Gmail SMTP configured)
- Templates with Handlebars
- Dynamic variables
- Opens and clicks tracking
- Rate limiting
- Sending logs
Analytics Module (src/analytics/)
Functionality:
- User event tracking
- Engagement metrics
- Cohort analysis
- Funnel analytics
- Retention metrics
- Custom events
Dashboard Module (src/dashboard/)
Functionality:
- Real-time metrics
- Active tasks overview
- Execution statistics
- Performance charts
- Recent alerts and notifications
Reports Module (src/reports/)
Functionality:
- Executive reports
- Customizable reports
- Multi-format export
- Report scheduling
- Execution history
- Advanced analytics
Admin Module (src/admin/)
Functionality:
- User management
- Administrative analytics
- Subscription control
- Audit log review
- Security alert management
- System configuration
Notion Module (src/notion/)
Functionality:
- Notion API integration (@notionhq/client)
- Workspace synchronization
- OAuth flow
- Access to databases and pages
- Notion webhooks
Health Module (src/health/)
Endpoints:
/health- Basic health check- Database connectivity check
- External services status
Monitoring Module (src/monitoring/)
Functionality:
- System metrics
- Performance monitoring
- Error tracking
- Uptime monitoring
AuditLog Module (src/auditLog/)
Functionality:
- Automatic logging of all requests
- Global interceptor
- Unique TransactionId per request
- Complete request/response capture
- Security metadata (IP, User-Agent)
- Classification by action type
- Critical action flags
Sessions Module (src/sessions/)
Functionality:
- Refresh token management
- Active session tracking
- Session revocation
- Expired session cleanup
- Device information
Webhooks Module (src/webhooks/)
Functionality:
- Stripe webhook handling
- Retry logic with exponential backoff
- Signature verification
- Idempotency
- Event logging
Queue Module (src/queue/)
Functionality:
- Asynchronous task queue
- Background processing
- Priority queues
- Retry logic
- Dead letter queue
Retry Module (src/retry/)
Functionality:
- Configurable retry system
- Exponential backoff
- Max attempts
- Error handling
Scheduler Module (src/scheduler/)
Functionality:
- Task scheduling with node-cron
- Cron expression evaluation
- Timezone support
- Next execution calculation
Alerts Module (src/alerts/)
Files:
security-alerts.service.ts- Suspicious pattern detectionalert-email.service.ts- Email alert sendingalert-webhook.service.ts- Webhook alert sendingalert-coordinator.service.ts- Alert coordinationalerts.controller.ts- Alert management endpoints
Functionality:
- Automatic detection of:
- Multiple failed login attempts
- Access from unusual IPs
- Burst of admin accesses
- Suspicious user agents
- Severity levels (LOW, MEDIUM, HIGH, CRITICAL)
- Multi-channel notifications
- Alert acknowledgement and resolution
- False positive marking
Realtime Module (src/realtime/)
Functionality:
- WebSockets with Socket.io
- Real-time notifications
- Running task updates
- Dashboard live updates
Common Module (src/common/)
Components:
- Guards: JwtAuthGuard, RolesGuard, ApiKeyGuard
- Interceptors: AuditLogInterceptor, TransformInterceptor
- Pipes: Custom ValidationPipe
- Decorators: @Roles(), @Public(), @ApiKey()
- Filters: HttpExceptionFilter
Config Module (src/config/)
Configuration:
- Database configuration
- JWT configuration
- Email configuration
- Stripe configuration
- Environment validation
🔐 Security
Implemented Protections
- Password Hashing - Argon2 (recommended) + Bcrypt
- Input Validation - class-validator on all DTOs
- SQL Injection Protection - Prisma ORM with parameterized queries
- XSS Protection - Input sanitization
- CORS - Configured for allowed domains
- Rate Limiting - Per endpoint and per API Key
- Audit Logging - All actions logged
- Security Alerts - Automatic suspicious pattern detection
📡 API Endpoints
Authentication
POST /auth/register - User registration
POST /auth/login - JWT login
POST /auth/refresh - Refresh token
POST /auth/logout - Logout and session revocation
POST /auth/change-password - Password change
Users
GET /users - List users (Admin)
GET /users/:id - Get user
PATCH /users/:id - Update user
DELETE /users/:id - Delete user
Tasks (API v1)
GET /api/v1/tasks - List user tasks
POST /api/v1/tasks - Create new task
GET /api/v1/tasks/:id - Get task details
PUT /api/v1/tasks/:id - Update task
DELETE /api/v1/tasks/:id - Delete task
POST /api/v1/tasks/:id/execute - Execute task immediately
GET /api/v1/tasks/:id/logs - Get execution logs
Dashboard
GET /dashboard/overview - General overview
GET /dashboard/metrics - Real-time metrics
GET /dashboard/recent-tasks - Recent tasks
Analytics
GET /analytics/dashboard - Analytics dashboard
GET /analytics/summary - Metrics summary
GET /analytics/cohorts - Cohort analysis
GET /analytics/engagement - Engagement metrics
Reports
GET /reports/executive-summary - Executive report
GET /reports/custom - Custom reports
POST /reports/custom - Create custom report
GET /reports/:id/execute - Execute report
Admin
GET /admin/users - User management
GET /admin/analytics - Administrative analytics
GET /admin/audit-logs - Audit logs
GET /admin/security-alerts - Security alerts
POST /admin/roles/:userId - Assign role to user
DELETE /admin/roles/:userId/:role - Remove role from user
Billing
GET /billing/subscription - Get current subscription
POST /billing/subscription - Create subscription
PUT /billing/subscription - Update subscription
DELETE /billing/subscription - Cancel subscription
POST /webhooks/stripe - Stripe webhook
Notifications
GET /notifications - List notifications
GET /notifications/:id - Get notification
PATCH /notifications/:id/read - Mark as read
GET /notifications/preferences - Get preferences
PUT /notifications/preferences - Update preferences
Health & Status
GET /health - Health check
GET /api/status - API status
Documentation
GET /api/docs - Swagger UI
GET /api-json - OpenAPI spec JSON
Test Types
- Unit Tests -
*.spec.tsin each module - E2E Tests -
test/*.e2e-spec.tsagainst real DB - Smoke Tests -
test/jest-smoke.jsonfor quick validation
Testing Against Real DB
The project uses a PostgreSQL database on Neon for E2E tests, not mocks. This ensures tests reflect real behavior.
📊 Audit and Quality Assurance
Tracking System
- Repository: https://github.com/Datanarch/backend_nocron
- Issues created: 15 (5 Critical + 5 Major + 5 Minor)
- Milestones: 3 with defined dates
- Labels: Organized by priority and category
Critical Issues Identified
- #1 - Password hashing inconsistency (auth vs users)
- #2 - Circular dependencies between users and auth
- #3 - Type safety issues with ‘as any’ casts
- #4 - Missing queue management for notifications
- #5 - Command injection vulnerability in PDF generation
Major Issues
- #6 - Implement duplicateTask endpoint
- #7 - Replace mock implementations in reports
- #8 - Real tracking of task duration
- #9 - Missing DB fields (tags, status)
- #10 - Rate limiting for email service
Complete Audit (2025-09-27)
- Modules audited: 12
- Issues identified: 35 (8 critical, 7 major, 20 minor)
- Production readiness: 75%
- Overall score: ✅ Excellent architecture, manageable issues
🔗 Links and Resources
Development
- Local API: http://localhost:3001
- Swagger UI: http://localhost:3001/api/docs
- API Status: http://localhost:3001/api/status
- Health Check: http://localhost:3001/health
- Prisma Studio:
npx prisma studio(port 5555)
GitHub
- Repository: https://github.com/Datanarch/backend_nocron
- Issues: https://github.com/Datanarch/backend_nocron/issues
- Milestones: https://github.com/Datanarch/backend_nocron/milestones
Database
- Provider: Neon PostgreSQL (cloud)
External Documentation
- NestJS: https://docs.nestjs.com
- Prisma: https://www.prisma.io/docs
- Stripe: https://stripe.com/docs/api
- Notion API: https://developers.notion.com
📄 License
MIT License - See LICENSE file for details
📞 Support
- Email: support@nocron.com
- Documentation: https://docs.nocron.com
- Community: https://community.nocron.com
- Status Page: https://status.nocron.com
Current status: ✅ Complete and functional backend with 15 identified issues pending for production
Last updated: 2025-10-17 Document version: 1.0
Built with ❤️ by the NoCron Team