Skip to content

Architecture Overview

VetheonGames edited this page Sep 20, 2025 · 1 revision

Architecture Overview

Comprehensive overview of Source-License's system architecture, components, and design patterns.

🏛️ System Architecture

Source-License follows a modular Ruby/Sinatra architecture designed for scalability, maintainability, and security.

High-Level Architecture

┌─────────────────────────────────────────────────────────────────┐
│                        External Services                        │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐           │
│  │   Stripe    │  │   PayPal    │  │    SMTP     │           │
│  │   Payment   │  │   Payment   │  │   Email     │           │
│  └─────────────┘  └─────────────┘  └─────────────┘           │
└─────────────────────────────────────────────────────────────────┘
                                 │
┌─────────────────────────────────────────────────────────────────┐
│                      Application Layer                          │
│                                                                 │
│  ┌─────────────────┐  ┌─────────────────┐  ┌─────────────────┐ │
│  │   Public Web    │  │  Admin Panel    │  │   REST API      │ │
│  │   Interface     │  │   Interface     │  │   Endpoints     │ │
│  │                 │  │                 │  │                 │ │
│  │ • Homepage      │  │ • Dashboard     │  │ • License Ops   │ │
│  │ • Product List  │  │ • License Mgmt  │  │ • Authentication│ │
│  │ • Shopping Cart │  │ • User Mgmt     │  │ • Webhooks      │ │
│  │ • Checkout      │  │ • Payment Mgmt  │  │ • Settings API  │ │
│  └─────────────────┘  └─────────────────┘  └─────────────────┘ │
└─────────────────────────────────────────────────────────────────┘
                                 │
┌─────────────────────────────────────────────────────────────────┐
│                    Controller Layer                             │
│                                                                 │
│  ┌─────────────────────────────────────────────────────────────┐ │
│  │               Modular Controllers                           │ │
│  │                                                             │ │
│  │  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐         │ │
│  │  │   Public    │  │    Admin    │  │     API     │         │ │
│  │  │ Controller  │  │ Controller  │  │ Controller  │         │ │
│  │  └─────────────┘  └─────────────┘  └─────────────┘         │ │
│  │                                                             │ │
│  │  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐         │ │
│  │  │ User Auth   │  │  Products   │  │  Licenses   │         │ │
│  │  │ Controller  │  │ Controller  │  │ Controller  │         │ │
│  │  └─────────────┘  └─────────────┘  └─────────────┘         │ │
│  └─────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────┘
                                 │
┌─────────────────────────────────────────────────────────────────┐
│                     Business Logic Layer                        │
│                                                                 │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐             │
│  │   License   │  │   Payment   │  │    User     │             │
│  │  Generator  │  │  Processor  │  │    Auth     │             │
│  └─────────────┘  └─────────────┘  └─────────────┘             │
│                                                                 │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐             │
│  │  Security   │  │   Logger    │  │  Settings   │             │
│  │ Middleware  │  │   System    │  │  Manager    │             │
│  └─────────────┘  └─────────────┘  └─────────────┘             │
└─────────────────────────────────────────────────────────────────┘
                                 │
┌─────────────────────────────────────────────────────────────────┐
│                       Data Layer                                │
│                                                                 │
│  ┌─────────────────────────────────────────────────────────────┐ │
│  │                    Sequel ORM                               │ │
│  │                                                             │ │
│  │  ┌─────────┐  ┌─────────┐  ┌─────────┐  ┌─────────┐        │ │
│  │  │  User   │  │ Product │  │ License │  │  Order  │        │ │
│  │  │  Model  │  │  Model  │  │  Model  │  │  Model  │        │ │
│  │  └─────────┘  └─────────┘  └─────────┘  └─────────┘        │ │
│  │                                                             │ │
│  │  ┌─────────┐  ┌─────────┐  ┌─────────┐  ┌─────────┐        │ │
│  │  │  Admin  │  │  Tax    │  │ Billing │  │Activation│        │ │
│  │  │  Model  │  │  Model  │  │  Model  │  │  Model  │        │ │
│  │  └─────────┘  └─────────┘  └─────────┘  └─────────┘        │ │
│  └─────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────┘
                                 │
┌─────────────────────────────────────────────────────────────────┐
│                      Database Layer                             │
│                                                                 │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐             │
│  │    MySQL    │  │ PostgreSQL  │  │   SQLite    │             │
│  │  Production │  │ Production  │  │ Development │             │
│  └─────────────┘  └─────────────┘  └─────────────┘             │
└─────────────────────────────────────────────────────────────────┘

📂 Directory Structure

Source-License/
├── app.rb                      # Main application entry point
├── config.ru                  # Rack configuration for deployment
├── launch.rb                  # Cross-platform launcher script
├── Gemfile                    # Ruby dependencies
├── .env.example               # Environment configuration template
│
├── lib/                       # Core application logic
│   ├── models.rb              # Database models (Sequel ORM)
│   ├── license_generator.rb   # License creation and management
│   ├── payment_processor.rb   # Stripe/PayPal integration
│   ├── database.rb            # Database configuration and migrations
│   ├── auth.rb                # Authentication helpers
│   ├── enhanced_auth.rb       # Advanced authentication features
│   ├── user_auth.rb           # User-specific authentication
│   ├── security.rb            # Security middleware and utilities
│   ├── logger.rb              # Logging configuration
│   ├── helpers.rb             # Template helpers and utilities
│   ├── customization.rb       # Theme and branding management
│   ├── settings_manager.rb    # Configuration management
│   ├── migrations.rb          # Database migration system
│   │
│   ├── controllers/           # Modular controller architecture
│   │   ├── application.rb     # Main application controller
│   │   ├── base_controller.rb # Base controller with common functionality
│   │   ├── public_controller.rb    # Public website routes
│   │   ├── admin_controller.rb     # Admin interface routes
│   │   ├── user_auth_controller.rb # User authentication routes
│   │   ├── api_controller.rb       # REST API endpoints
│   │   ├── admin_namespace.rb      # Admin namespace configuration
│   │   └── admin/                  # Admin sub-controllers
│   │       ├── products_controller.rb   # Product management
│   │       ├── licenses_controller.rb   # License management
│   │       ├── taxes_controller.rb      # Tax configuration
│   │       └── features_controller.rb   # Feature management
│   │
│   ├── settings/              # Configuration management system
│   │   ├── settings_store.rb          # Settings storage layer
│   │   ├── settings_schema.rb         # Configuration schema
│   │   ├── settings_validator.rb      # Settings validation
│   │   ├── settings_exporter.rb       # Export functionality
│   │   ├── settings_env_mapper.rb     # Environment mapping
│   │   └── settings_configuration_tester.rb # Configuration testing
│   │
│   └── logging/               # Comprehensive logging system
│       ├── error_tracking.rb         # Error tracking and reporting
│       ├── security_logger.rb        # Security event logging
│       └── specialized_loggers.rb    # Specialized logging components
│
├── views/                     # ERB template files
│   ├── layouts/               # Layout templates
│   │   ├── main_layout.erb    # Public website layout
│   │   └── admin_layout.erb   # Admin interface layout
│   │
│   ├── partials/              # Reusable components
│   │   ├── _navigation.erb    # Navigation menu
│   │   └── _footer.erb        # Footer component
│   │
│   ├── admin/                 # Admin interface templates
│   │   ├── dashboard.erb      # Admin dashboard
│   │   ├── products.erb       # Product management
│   │   ├── licenses.erb       # License management
│   │   ├── customers.erb      # Customer management
│   │   ├── orders.erb         # Order management
│   │   ├── settings.erb       # System settings
│   │   └── [various admin views]
│   │
│   ├── users/                 # User account templates
│   │   ├── dashboard.erb      # User dashboard
│   │   ├── profile.erb        # User profile
│   │   ├── licenses.erb       # User license management
│   │   └── [user-related views]
│   │
│   ├── licenses/              # License management templates
│   │   ├── lookup.erb         # License lookup interface
│   │   └── validate.erb       # License validation interface
│   │
│   └── errors/                # Error page templates
│       ├── 404.erb            # Not found page
│       └── 500.erb            # Server error page
│
├── test/                      # Comprehensive test suite
│   ├── app_test.rb            # Application integration tests
│   ├── models_test.rb         # Database model tests
│   ├── auth_test.rb           # Authentication tests
│   ├── security_test.rb       # Security tests
│   ├── customization_test.rb  # Customization tests
│   ├── helpers_test.rb        # Helper function tests
│   ├── test_helper.rb         # Test configuration
│   ├── factories.rb           # Test data factories
│   └── html_reports/          # Test coverage reports
│
├── downloads/                 # Product download files (auto-created)
├── logs/                      # Application logs (auto-created)
├── installer-logs/            # Installation logs (auto-created)
└── deployment-logs/           # Deployment logs (auto-created)

🔧 Core Components

1. Application Entry Point (app.rb)

The main application file that:

  • Loads all required dependencies
  • Sets up database connection
  • Configures Sinatra settings
  • Loads modular controllers
  • Configures middleware stack
#!/usr/bin/env ruby
# frozen_string_literal: true

require 'sinatra/base'
require 'sinatra/json'
require 'sinatra/cookies'
# ... other dependencies

# Load application modules
require_relative 'lib/database'
Database.setup

require_relative 'lib/models'
require_relative 'lib/helpers'
# ... other modules

require_relative 'lib/controllers/application'

2. Modular Controller Architecture

Source-License uses a modular controller pattern for better organization:

Base Controller (lib/controllers/base_controller.rb)

  • Common functionality shared across all controllers
  • Authentication helpers
  • Error handling
  • Response formatting

Specialized Controllers

  • PublicController: Handles public website routes (homepage, products, cart)
  • AdminController: Manages admin interface routes and authentication
  • ApiController: Provides REST API endpoints with JWT authentication
  • UserAuthController: Handles user registration, login, password reset

Admin Sub-Controllers

  • ProductsController: Product management (CRUD operations)
  • LicensesController: License management and generation
  • TaxesController: Tax configuration and management
  • FeaturesController: Feature flag management

3. Database Layer

Sequel ORM Integration

Source-License uses Sequel ORM for database operations:

# Database configuration
DB = Sequel.connect(
  adapter: ENV['DATABASE_ADAPTER'],
  host: ENV['DATABASE_HOST'],
  database: ENV['DATABASE_NAME'],
  user: ENV['DATABASE_USER'],
  password: ENV['DATABASE_PASSWORD']
)

Migration System

Automated database migrations handle schema changes:

# lib/migrations.rb
class DatabaseMigrator
  def self.run_migrations
    # Check and apply pending migrations
    # Create tables, add indexes, modify schemas
  end
end

4. Security Architecture

Multi-Layer Security

  1. Application Security: CSRF protection, secure headers, input validation
  2. Authentication: BCrypt password hashing, JWT tokens, session management
  3. Authorization: Role-based access control, admin permissions
  4. API Security: Rate limiting, token validation, secure endpoints

Security Middleware

class SecurityMiddleware
  def initialize(app)
    @app = app
  end

  def call(env)
    # Apply security headers
    # Rate limiting
    # CSRF protection
    # Input sanitization
  end
end

5. Business Logic Components

License Generator (lib/license_generator.rb)

  • Cryptographically secure license key generation
  • Multiple license formats (XXXX-XXXX, UUID, custom)
  • Activation limit enforcement
  • Expiration date management

Payment Processor (lib/payment_processor.rb)

  • Stripe and PayPal integration
  • Webhook handling for payment confirmations
  • Subscription management
  • Refund processing

Settings Manager (lib/settings_manager.rb)

  • Centralized configuration management
  • Environment-based settings
  • Dynamic configuration updates
  • Settings validation and schema enforcement

🔄 Request Flow

Public Website Request Flow

1. User Request → Nginx/Apache (Production) → Sinatra Application
2. Security Middleware → Rate Limiting → CSRF Protection
3. Router → PublicController
4. Controller Logic → Database Models → Business Logic
5. Template Rendering → Response → User

Admin Interface Request Flow

1. Admin Request → Security Middleware
2. Admin Authentication Check → Session Validation
3. Router → AdminController
4. Permission Check → Controller Logic
5. Database Operations → Template Rendering
6. Admin Response → Dashboard/Management Interface

API Request Flow

1. API Request → Security Middleware
2. JWT Token Validation → Rate Limiting
3. Router → ApiController
4. Business Logic → Database Operations
5. JSON Response → Client Application

🗄️ Database Schema

Core Tables

Users Table

CREATE TABLE users (
  id INT PRIMARY KEY AUTO_INCREMENT,
  email VARCHAR(255) UNIQUE NOT NULL,
  password_hash VARCHAR(255) NOT NULL,
  name VARCHAR(255),
  status ENUM('active', 'inactive', 'suspended') DEFAULT 'active',
  email_verified BOOLEAN DEFAULT FALSE,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

Products Table

CREATE TABLE products (
  id INT PRIMARY KEY AUTO_INCREMENT,
  name VARCHAR(255) NOT NULL,
  description TEXT,
  price DECIMAL(10,2) NOT NULL,
  license_type ENUM('one_time', 'subscription') NOT NULL,
  max_activations INT DEFAULT 1,
  license_duration_days INT,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

Licenses Table

CREATE TABLE licenses (
  id INT PRIMARY KEY AUTO_INCREMENT,
  license_key VARCHAR(255) UNIQUE NOT NULL,
  product_id INT NOT NULL,
  customer_email VARCHAR(255) NOT NULL,
  status ENUM('active', 'suspended', 'revoked', 'expired') DEFAULT 'active',
  activation_count INT DEFAULT 0,
  max_activations INT NOT NULL,
  expires_at TIMESTAMP,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  FOREIGN KEY (product_id) REFERENCES products(id)
);

Orders Table

CREATE TABLE orders (
  id INT PRIMARY KEY AUTO_INCREMENT,
  email VARCHAR(255) NOT NULL,
  amount DECIMAL(10,2) NOT NULL,
  status ENUM('pending', 'completed', 'failed', 'refunded') DEFAULT 'pending',
  payment_method ENUM('stripe', 'paypal', 'free', 'manual') NOT NULL,
  payment_details JSON,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

Relationship Mapping

Users (1) ←→ (N) Licenses
Products (1) ←→ (N) Licenses
Products (1) ←→ (N) OrderItems
Orders (1) ←→ (N) OrderItems
Orders (1) ←→ (N) Licenses
Licenses (1) ←→ (N) LicenseActivations
Licenses (1) ←→ (1) Subscription

🔌 Integration Architecture

Payment Gateway Integration

Stripe Integration

class StripePaymentProcessor
  def process_payment(amount, payment_method, metadata = {})
    # Create payment intent
    # Handle 3D Secure authentication
    # Process confirmation
    # Handle webhooks
  end
end

PayPal Integration

class PayPalPaymentProcessor
  def create_order(amount, items)
    # Create PayPal order
    # Generate approval URL
    # Handle capture confirmation
  end
end

Email Integration

class EmailService
  def send_license_email(license, customer_email)
    # Configure SMTP settings
    # Generate license email template
    # Send with attachments
    # Log delivery status
  end
end

🛡️ Security Features

Authentication & Authorization

  • BCrypt Password Hashing: Secure password storage
  • JWT Token Authentication: Stateless API authentication
  • Session Management: Secure cookie-based sessions
  • Role-Based Access Control: Admin permission system

Application Security

  • CSRF Protection: Cross-site request forgery prevention
  • XSS Protection: Input sanitization and output encoding
  • SQL Injection Prevention: Sequel ORM parameterized queries
  • Rate Limiting: API and form submission rate limiting

Data Protection

  • Encrypted Storage: Sensitive data encryption at rest
  • Secure Transmission: HTTPS enforcement in production
  • Audit Logging: Comprehensive security event logging
  • Data Validation: Input validation and sanitization

📊 Performance Considerations

Database Optimization

  • Connection Pooling: Efficient database connection management
  • Query Optimization: Optimized Sequel queries with proper indexes
  • Migration Management: Automated schema versioning

Caching Strategy

  • Application-Level Caching: Configurable caching for settings and templates
  • Database Query Caching: Sequel query result caching
  • Static Asset Optimization: Efficient serving of CSS/JS/images

Scalability Design

  • Modular Architecture: Easy horizontal scaling
  • Stateless Design: Session-independent request handling
  • Load Balancer Ready: Nginx/Apache proxy configuration support

🔧 Configuration Management

Environment-Based Configuration

# Development
APP_ENV=development
DATABASE_ADAPTER=sqlite

# Production
APP_ENV=production
DATABASE_ADAPTER=mysql
FORCE_SSL=true

Settings System

class SettingsManager
  def self.get(key)
    # Retrieve setting with environment override
    # Cache frequently accessed settings
    # Validate setting values
  end
end

This architecture provides a solid foundation for enterprise-grade software licensing with:

  • Modularity: Easy to extend and maintain
  • Security: Multiple layers of protection
  • Scalability: Designed for growth
  • Flexibility: Configurable for various use cases
  • Reliability: Comprehensive error handling and logging

Clone this wiki locally