# Product Requirements Document
# Central License & Entitlement Management Platform

**Product:** ApnarBusiness License Server  
**Primary Domain:** `license.apnarbusiness.com`  
**Parent Platform:** `apnarbusiness.com`  
**Document Version:** 1.0  
**Status:** Proposed  
**Document Type:** Product + Technical Requirements

---

## 1. Product Overview

ApnarBusiness is a digital platform that sells:

- Digital courses
- Software products
- Downloadable software
- SaaS products
- Future digital products

The platform requires a centralized system for managing software licenses, activations, entitlements, subscriptions, domains, and license lifecycle events.

The proposed product is a standalone centralized License & Entitlement Management Service hosted at:

`license.apnarbusiness.com`

The License Server will be responsible for license authorization and entitlement management, while the main ApnarBusiness platform remains responsible for customers, products, pricing, orders, payments, and subscriptions.

---

# 2. Core Architectural Principle

The system will follow a strict separation of responsibility.

### ApnarBusiness Main Platform

Responsible for:

- Customers
- Products
- Pricing
- Plans
- Orders
- Payments
- Subscriptions
- Invoices
- Refunds
- Customer account management

### License Server

Responsible for:

- License creation
- License lifecycle
- License keys
- Product licensing
- Entitlements
- Activations
- Domain binding
- Installation tracking
- License validation
- License expiration
- Grace periods
- Revocation
- Suspension
- License events
- Activation events
- Auditability

### SaaS Application

Responsible for:

- Actual application access
- User authentication
- Application authorization
- Application-specific business rules

The License Server must not become the payment system.

---

# 3. Goals

The system must:

1. Provide centralized license management.
2. Support multiple software products.
3. Support downloadable software.
4. Support SaaS products.
5. Support monthly subscriptions.
6. Support quarterly subscriptions.
7. Support yearly subscriptions.
8. Support lifetime licenses.
9. Support trial licenses.
10. Support domain activation.
11. Support activation limits.
12. Support license expiration.
13. Support grace periods.
14. Support suspension.
15. Support revocation.
16. Support license renewal.
17. Support feature entitlements.
18. Provide secure API-based validation.
19. Provide activation history.
20. Provide complete audit history.
21. Support future products without redesigning the system.
22. Prevent duplicate webhook processing.
23. Provide resilience when the license server is temporarily unavailable.
24. Provide security and abuse detection.

---

# 4. Non-Goals

The License Server will not:

- Process customer payments.
- Store credit card information.
- Replace the main marketplace.
- Replace the main subscription management system.
- Become the primary customer database.
- Handle normal SaaS user authentication.
- Store application business data.

---

# 5. Product Types

The system must support:

### Downloadable

Software installed on the customer's infrastructure.

Example:

`customer.com`

### SaaS

Software hosted by ApnarBusiness.

Example:

`erp.apnarbusiness.com`

### Hybrid

Products that support both deployment models.

---

# 6. License Types

Supported types:

### Subscription

Recurring billing.

Supported intervals:

- Monthly
- Quarterly
- Yearly

### Lifetime

No expiration date.

### Trial

Temporary license.

### Temporary

Custom-duration license.

---

# 7. License Lifecycle

Normal lifecycle:

```text
PENDING
   ↓
ACTIVE
   ↓
GRACE
   ↓
EXPIRED
```

Alternative states:

```text
ACTIVE
   ↓
SUSPENDED
```

or:

```text
ACTIVE
   ↓
REVOKED
```

or:

```text
ACTIVE
   ↓
CANCELLED
```

Reinstatement may be allowed for suspended licenses.

Revocation should normally be treated as a high-severity action.

---

# 8. License Activation

For downloadable software:

```text
Customer installs software
        ↓
Enters license key
        ↓
Application sends activation request
        ↓
License Server validates
        ↓
Product matches?
License active?
Activation available?
Domain valid?
        ↓
Activation created
        ↓
Signed authorization returned
```

The activation must store:

- License
- Product
- Domain
- Installation ID
- Environment
- IP
- Software version
- Activation time
- Last seen time

---

# 9. Domain Binding

The system must support domain-based activation.

Example:

```text
License
   ↓
customer.com
```

An activation on:

```text
another.com
```

must be rejected when the license has reached its activation/domain policy.

Domain normalization must be implemented so that:

```text
https://www.example.com/
example.com
WWW.EXAMPLE.COM
```

can be normalized consistently.

---

# 10. Environment Support

The system must distinguish:

- Production
- Staging
- Development
- Local

Plans may have different activation policies.

Example:

```text
Production: 1
Staging: 1
Development: unlimited
```

---

# 11. Entitlement System

Licensing must not depend only on active/inactive status.

Each license can contain entitlements such as:

```text
users.max = 20
storage.max_gb = 100
api.access = true
premium.reports = true
premium.analytics = true
```

Entitlements must be stored as a snapshot on the license.

This prevents future plan changes from unexpectedly modifying historical licenses.

---

# 12. Product Versioning

The system must support software versions.

Each product may have:

```text
1.0.0
1.1.0
2.0.0
2.4.1
```

Versions may be:

- Active
- Deprecated
- Blocked

The License Server may later enforce minimum license versions or software versions.

---

# 13. Main Platform Integration

The main platform communicates with the License Server through authenticated internal APIs and/or signed webhooks.

Example:

```text
Customer purchases software
        ↓
Payment successful
        ↓
Order marked PAID
        ↓
Subscription created
        ↓
License Server receives event
        ↓
License created/activated
```

---

# 14. Renewal Workflow

```text
Customer renews subscription
        ↓
Payment successful
        ↓
Main platform updates subscription
        ↓
Main platform sends renewal event
        ↓
License Server updates expires_at
        ↓
License remains ACTIVE
```

---

# 15. Payment Failure Workflow

Payment failure must not immediately destroy the license.

Recommended:

```text
ACTIVE
   ↓
Payment failed
   ↓
GRACE
   ↓
Grace period ends
   ↓
EXPIRED / SUSPENDED
```

Grace duration should be configurable.

---

# 16. Refund Workflow

When a refund occurs:

```text
Refund created
      ↓
Main Platform event
      ↓
License Server
      ↓
License suspended/revoked according to policy
```

The exact behavior should be configurable by product/plan.

---

# 17. Activation Limit

Every license may have:

```text
max_activations
```

Example:

```text
max_activations = 1
```

When one active activation exists:

```text
Second activation → ACTIVATION_LIMIT_REACHED
```

Admin may manually deactivate an old installation.

---

# 18. Deactivation

Customer may deactivate an installation.

Example:

```text
Old Server
   ↓
Deactivate
   ↓
Activation becomes inactive
   ↓
New Server
   ↓
Activate
```

---

# 19. Heartbeat

Downloadable applications should periodically send heartbeat requests.

Recommended:

- Daily for normal products
- Configurable by product
- Never require a network request on every application request

Heartbeat updates:

```text
last_seen_at
software_version
domain
installation status
```

---

# 20. Graceful Offline Operation

The downloadable application should not immediately stop working because of a temporary License Server outage.

The system should support:

- Cached validation
- Signed license token
- Offline authorization window
- Grace period

Example:

```text
License Server unavailable
        ↓
Local signed token still valid
        ↓
Application continues
```

This prevents infrastructure outages from unnecessarily breaking customer applications.

---

# 21. License Key Security

License keys must:

- Be generated using cryptographically secure randomness.
- Never be sequential.
- Never be stored as plaintext in the database.
- Be stored as hashes where possible.
- Have only the last few characters available for display.
- Be rate-limited during validation.
- Be revocable.

Example:

```text
AB-CMS-7F92-K2MX
```

Database:

```text
license_key_hash
license_key_last4
```

---

# 22. API Security

Internal APIs must use:

- API credentials
- Request signatures
- Timestamp validation
- Replay protection
- Idempotency keys
- HTTPS
- Rate limiting
- Request IDs

Public APIs must use:

- HTTPS
- Rate limiting
- Product identification
- License validation
- Installation identity
- Domain validation
- Abuse detection

---

# 23. Idempotency

Operations that create or modify licenses must support:

```http
Idempotency-Key
```

Example:

```text
Main Platform
      ↓
Create License
      ↓
Network timeout
      ↓
Retry
```

The retry must not create a second license.

---

# 24. Webhook Reliability

Webhook processing must support:

- Signature verification
- Duplicate detection
- Retry
- Exponential backoff
- Failed event storage
- Manual replay
- Event IDs

States:

```text
PENDING
PROCESSING
PROCESSED
FAILED
IGNORED
```

---

# 25. API Versioning

All APIs must be versioned.

Example:

```text
/api/v1/...
```

Future breaking changes:

```text
/api/v2/...
```

Existing downloadable software must continue to work with the supported API version.

---

# 26. Admin Dashboard

Admin dashboard should provide:

### Dashboard

- Total products
- Active licenses
- Expired licenses
- Suspended licenses
- Revoked licenses
- Total activations
- Recent activations
- Recent validation failures
- License growth
- Product-wise statistics

### Product Management

- Create product
- Edit product
- Manage versions
- Manage plans
- Manage entitlements

### License Management

- Search license
- View license
- Suspend
- Revoke
- Reinstate
- Renew
- Change entitlements
- View activations
- View events

### Activation Management

- Search domain
- View installation
- Deactivate
- Block
- Unblock

### Security

- Validation failures
- Suspicious domains
- Repeated activation attempts
- Rate-limit events

---

# 27. Audit Requirements

Every administrative state-changing operation must create an audit log.

Example:

```text
Admin:
123

Action:
license.revoked

License:
98231

Reason:
Fraud

IP:
...

Timestamp:
...
```

Audit records should not be silently editable.

---

# 28. Observability

System must provide:

- Structured logs
- Request IDs
- Error tracking
- API latency metrics
- Validation metrics
- Activation metrics
- Webhook processing metrics
- Failed webhook alerts
- Database monitoring

---

# 29. Reliability

Target:

### Availability

At least:

`99.9%`

for public validation APIs.

The architecture should allow:

- Multiple application instances
- Load balancing
- Redis
- Queue workers
- Database backups
- Health checks

---

# 30. Performance

License validation should normally complete within:

`< 300 ms`

under normal load.

Heavy operations such as:

- Reports
- Analytics
- Webhook processing
- Audit processing

must not block validation requests.

---

# 31. Caching

Redis may be used for:

- License validation cache
- Rate limiting
- API credentials
- Short-lived activation locks
- Idempotency
- Distributed locks

However, cached data must never allow a revoked license to remain authorized beyond the defined security policy.

---

# 32. Concurrency

Activation requires transactional protection.

Example:

```text
max_activations = 1

Request A → activation
Request B → activation
```

Both requests must not successfully create activations simultaneously.

Use:

- Database transaction
- Row locking
- Unique constraints
- Atomic counters where appropriate

---

# 33. Database Integrity

Foreign keys should be used where appropriate.

Critical unique constraints:

```text
products.code
products.slug

plans(product_id, code)

entitlements(product_id, code)

plan_entitlements(plan_id, entitlement_id)

license_entitlements(license_id, entitlement_id)

licenses.license_key_hash

webhook_events.external_event_id

idempotency_keys.key

api_keys.key_hash
```

---

# 34. Data Retention

Validation logs may become extremely large.

Recommended:

```text
Validation logs:
90–180 days online

Audit logs:
Long-term retention

License events:
Long-term retention

Activation events:
Long-term retention

Webhook events:
Long-term retention or archival
```

Retention must be configurable.

---

# 35. Backup

Database:

- Daily full backup
- Frequent incremental/binlog backup where supported
- Off-site backup
- Backup encryption
- Restore testing

A backup that has never been restored should not be considered verified.

---

# 36. Disaster Recovery

Target:

```text
RPO: ≤ 15 minutes
RTO: ≤ 1 hour
```

The exact targets may be adjusted according to business scale.

---

# 37. SaaS Integration

For SaaS products, the License Server provides entitlement information.

Example:

```text
SaaS
  ↓
Check license/entitlement
  ↓
users.max = 20
  ↓
Application enforces user limit
```

The License Server does not replace the SaaS application's authorization layer.

---

# 38. Downloadable Software Integration

Downloadable software uses:

```text
Activate
Validate
Heartbeat
Deactivate
```

Recommended local architecture:

```text
Application
    ↓
Local License Service
    ↓
Signed license/token
    ↓
Application authorization
```

The application should not call the License Server on every page request.

---

# 39. Product SDK

Eventually provide official client SDKs.

Potentially:

```text
Laravel/PHP SDK
Node.js SDK
JavaScript SDK
WordPress/PHP SDK
```

Laravel example:

```php
License::activate($licenseKey);
License::validate();
License::has('api.access');
License::get('users.max');
```

The SDK should hide:

- API calls
- Authentication
- Token handling
- Retry
- Caching
- Offline validation
- Error handling

---

# 40. Recommended Service Architecture

Initial architecture:

```text
                    Internet
                       │
                       ▼
                Load Balancer
                       │
             ┌─────────┴─────────┐
             │                   │
             ▼                   ▼
       License API 1       License API 2
             │                   │
             └─────────┬─────────┘
                       │
                  Redis Cache
                       │
                  Queue System
                       │
                 MySQL Database
```

For the first production version, a modular Laravel monolith is preferable to prematurely creating microservices.

---

# 41. Recommended Laravel Architecture

Suggested modules:

```text
app/
├── Domain/
│   ├── License/
│   ├── Activation/
│   ├── Product/
│   ├── Plan/
│   ├── Entitlement/
│   ├── Webhook/
│   ├── Api/
│   └── Audit/
│
├── Application/
│   ├── License/
│   ├── Activation/
│   └── Webhook/
│
├── Infrastructure/
│   ├── Persistence/
│   ├── Cache/
│   ├── Queue/
│   └── Security/
│
└── Http/
    ├── Controllers/
    ├── Requests/
    ├── Resources/
    └── Middleware/
```

Do not make the entire application controller-driven business logic.

Business rules should live in domain/application services.

---

# 42. Core Services

Recommended services:

```text
LicenseService
LicenseActivationService
LicenseValidationService
LicenseRenewalService
LicenseSuspensionService
LicenseRevocationService

EntitlementService

ProductService
PlanService

ActivationService

WebhookService
WebhookProcessingService

DomainValidationService

LicenseTokenService

AuditService
```

---

# 43. Important Business Rules

### Rule 1

A license cannot be activated if:

```text
status != active
```

unless the specific grace policy allows it.

### Rule 2

Expired licenses cannot create new production activations.

### Rule 3

Revoked licenses cannot be reactivated automatically.

### Rule 4

Activation count cannot exceed the license's allowed limit.

### Rule 5

Product mismatch must reject validation.

### Rule 6

Invalid domain must reject activation where domain binding is required.

### Rule 7

A duplicate webhook must never create duplicate licenses.

### Rule 8

A duplicate activation request must not create duplicate installations.

### Rule 9

License keys must never be logged in plaintext.

### Rule 10

Payment state must come from the main platform.

---

# 44. License State Machine

```text
                    ┌─────────────┐
                    │   PENDING   │
                    └──────┬──────┘
                           │
                           ▼
                    ┌─────────────┐
              ┌────▶│    ACTIVE   │◀───────┐
              │     └──────┬──────┘        │
              │            │               │
              │            ▼               │
              │     ┌─────────────┐        │
              │     │    GRACE    │        │
              │     └──────┬──────┘        │
              │            │               │
              │            ▼               │
              │     ┌─────────────┐        │
              │     │   EXPIRED   │        │
              │     └─────────────┘        │
              │                            │
              │     ┌─────────────┐        │
              └─────│  SUSPENDED  │────────┘
                    └─────────────┘

ACTIVE ────────────▶ REVOKED
ACTIVE ────────────▶ CANCELLED
```

---

# 45. Security Threat Model

The system must consider:

### Brute-force license validation

Mitigation:

- Rate limiting
- Key hashing
- Monitoring
- Temporary IP blocking

### License key leakage

Mitigation:

- Key rotation
- Revocation
- Activation limits
- Domain binding

### Replay attacks

Mitigation:

- Timestamp
- Nonce/request ID
- Signature
- Short-lived tokens

### API credential leakage

Mitigation:

- Hashed secrets
- Key rotation
- Expiration
- Revocation
- IP restrictions for internal clients

### Fake License Server responses

For downloadable software, signed server responses should be used.

The software should verify the signature using a public key embedded in the client.

---

# 46. Signed License Response

Instead of trusting only:

```json
{
    "valid": true
}
```

the server may return a signed payload:

```json
{
    "license_id": "01J...",
    "product": "coaching-management",
    "status": "active",
    "expires_at": "2027-08-10",
    "entitlements": {
        "users.max": 20
    }
}
```

The payload is signed using the License Server's private key.

Customer application contains the corresponding public key.

This provides stronger protection against forged responses.

---

# 47. Multi-Product Future

The platform must be designed so that:

```text
ApnarBusiness
   │
   ├── CRM
   ├── ERP
   ├── POS
   ├── Coaching
   ├── HRM
   ├── School Management
   └── Future Products
```

all use the same License Server.

---

# 48. Future Multi-Tenant Licensing

Future versions may support:

```text
Customer
   ├── License A
   ├── License B
   └── License C
```

and:

```text
Organization
   ├── Users
   ├── Products
   └── Licenses
```

This should not require a fundamental redesign.

---

# 49. Reporting

Admin reporting should include:

- Active licenses
- Expired licenses
- Revenue-independent license statistics
- Product-wise licenses
- Plan-wise licenses
- Activation counts
- Domain counts
- Validation failures
- Revocations
- Suspensions
- Renewals
- Trial conversions

Revenue itself remains the responsibility of the main platform.

---

# 50. MVP Scope

The first production release should include:

### Database

- products
- product_versions
- plans
- entitlements
- plan_entitlements
- licenses
- license_entitlements
- activations
- activation_events
- license_events
- api_clients
- api_keys
- webhook_events
- idempotency_keys
- validation_logs
- audit_logs

### APIs

- Create license
- Get license
- Renew
- Suspend
- Reinstate
- Revoke
- Activate
- Validate
- Deactivate
- Heartbeat
- Entitlements
- Main-platform webhook

### Admin

- Dashboard
- Product management
- Plan management
- Entitlement management
- License management
- Activation management
- Events
- Audit logs

---

# 51. Phase 2

After MVP:

- Offline signed tokens
- License SDK
- Automated abuse detection
- Advanced analytics
- Domain blacklist
- Version restrictions
- License transfer
- Activation self-service
- Customer license portal
- Email notifications
- Webhook outbound events

---

# 52. Phase 3

Future:

- Multi-organization licensing
- Enterprise licenses
- Floating licenses
- Device licensing
- IP restrictions
- Region restrictions
- Advanced fraud detection
- License leasing
- White-label licensing
- External vendor licensing

---

# 53. Success Criteria

The system will be considered successful when:

1. A paid software order can automatically generate a license.
2. The license can be activated by downloadable software.
3. Invalid licenses are rejected.
4. Expired licenses are rejected according to policy.
5. Renewals automatically extend licenses.
6. Payment failures trigger configured grace/suspension behavior.
7. Domain activation works correctly.
8. Activation limits are enforced atomically.
9. Duplicate webhooks do not create duplicate licenses.
10. License events are fully auditable.
11. Multiple products can share the same licensing infrastructure.
12. Temporary License Server outages do not unnecessarily break customer applications.
13. License keys cannot be trivially extracted from the database.
14. API access is authenticated and rate-limited.
15. The architecture can support future SaaS and downloadable products without redesign.

---

# 54. Final Architectural Decision

The final system should follow this principle:

```text
                    APNAR BUSINESS
                    ───────────────

          Commerce / Billing / Customer
                       │
                       │
                       ▼
              LICENSE SERVER
          ───────────────────────
          Authorization
          Entitlements
          Activations
          Domains
          Expiration
          Revocation
          Validation
                       │
             ┌─────────┴─────────┐
             ▼                   ▼
       Downloadable            SaaS
        Software              Products
```

The License Server is therefore not simply a "license key checker".

It is a centralized:

**License + Entitlement + Activation + Authorization Infrastructure**

for the entire ApnarBusiness product ecosystem.