Skip to main content

System Architecture

KeyBox is a distributed license management system built on a three-tier architecture:
1

API Layer

Express.js REST API handling license operations, validation, and activation
2

Cache Layer

Redis-based caching system for high-performance license validation
3

Database Layer

MongoDB storing persistent license data and relationships

API Request Flow

When a client validates a license, KeyBox follows this request flow:

Validation Endpoint

The validation controller implements a two-tier lookup strategy:
~/workspace/source/apps/server/src/controllers/redisLicense.controller.ts
export const validateLicense = async (req: Request, res: Response) => {
  const { key } = req.body;
  const currentMachineId = machineIdSync(true);
  
  // 1. Try Redis first
  const cached = await getCachedLicense(key);
  if (cached) {
    console.log("REDIS HIT for license:", key);
    // Validate and return cached data
  }
  
  // 2. MongoDB fallback
  console.log("MONGO HIT for license:", key);
  const license = await License.findOne({ key });
  // Validate and cache result
}
Redis cache hits serve validation requests in sub-millisecond time, significantly reducing database load.

Validation Process

KeyBox performs comprehensive validation checks in this order:
Verifies the license key exists in the database.
{
  "valid": false,
  "status": "invalid",
  "message": "Key does not exist"
}
Checks if the license is bound to the correct machine (if activated).
if (license.machineId && license.machineId !== currentMachineId) {
  return res.json({
    valid: false,
    status: "machine_mismatch",
    message: "License is not valid for this machine"
  });
}
Checks the current license status:
  • PENDING: License created but not yet activated
  • ACTIVE: License is valid and active
  • EXPIRED: License has passed expiration date
  • REVOKED: License manually revoked by developer
For active licenses, validates the current date against expiresAt.
if (now > license.expiresAt) {
  license.status = Status.EXPIRED;
  await license.save();
  await invalidateCachedLicense(key);
}

Caching Strategy

KeyBox uses Redis for intelligent license caching:

Cache Configuration

~/workspace/source/apps/server/src/cache/license.cache.ts
const TTL_SECONDS = 604800; // 1 week

export interface CachedLicense {
  status: Status;
  message?: string;
  expiresAt?: number;
  duration?: string;
  machineId?: string;
}

Cache Operations

1

Write-Through Caching

When MongoDB is queried, results are immediately cached to Redis with a 7-day TTL
2

Cache Invalidation

Cache is invalidated when license state changes (activation, revocation, expiration)
await invalidateCachedLicense(key);
3

Graceful Degradation

If Redis is unavailable, the system falls back to MongoDB without errors
catch (error) {
  console.error("Redis error:", error);
  return null; // Continue without cache
}
Cache entries include machineId to prevent unauthorized license transfers between machines.

License Creation Flow

When a new license is created:
~/workspace/source/apps/server/src/controllers/license.controller.ts
export const createLicense = async (req: AuthRequest, res: Response) => {
  const { duration, clientId, projectId, services } = req.body;
  
  const issuedAt = new Date();
  const expiresAt = new Date();
  expiresAt.setMonth(issuedAt.getMonth() + duration);
  
  const key = generateKey(projectId);
  
  const license = await License.create({
    key,
    duration,
    issuedAt,
    expiresAt,
    status: Status.PENDING, // Starts as PENDING
    services: services || ["Hosting"],
    user: req.userId,
    client: clientId,
    project: projectId,
  });
}
New licenses start with PENDING status and transition to ACTIVE only upon first activation.

Automated License Expiration

KeyBox includes a cron job for automatic license expiration:
~/workspace/source/apps/server/src/api/cron/expired-licenses.ts
export default async function handler(req: VercelRequest, res: VercelResponse) {
  const now = new Date();
  
  // Find licenses that should expire
  const expiredLicenses = await License.find({
    expiresAt: { $lt: now },
    status: Status.ACTIVE,
  }).select("key");
  
  // Update database
  await License.updateMany(
    { key: { $in: expiredLicenses.map((l) => l.key) } },
    { $set: { status: Status.EXPIRED } }
  );
  
  // Invalidate Redis cache
  for (const license of expiredLicenses) {
    await invalidateCachedLicense(license.key);
  }
}
The cron job runs on Vercel’s infrastructure and is protected by the x-vercel-cron header to prevent unauthorized execution.

Performance Characteristics

OperationWith RedisWithout Redis
License Validation< 1ms50-100ms
Cache Hit Rate~95%0%
Database Load5% of requests100% of requests
For production deployments, Redis caching is strongly recommended to handle high-volume validation requests.

Security Considerations

  • All API endpoints require authentication via JWT middleware
  • Machine IDs are hashed using SHA-256 for privacy
  • License keys are unique and indexed for fast lookups
  • Rate limiting prevents brute-force validation attempts
  • Cron endpoints are protected by Vercel’s authentication headers

Next Steps

License Lifecycle

Learn about license states and transitions

Machine Binding

Understand device-level license enforcement

Build docs developers (and LLMs) love