burp-licensing-sdk
v1.0.0
Published
TypeScript SDK for licensing manager - provides license validation, info retrieval, and purchase capabilities
Downloads
4
Maintainers
Readme
Licensing SDK for TypeScript/JavaScript
A comprehensive TypeScript SDK for integrating with the Licensing Manager system. Provides secure license validation, information retrieval, and purchase capabilities with mathematical validation and offline caching.
Installation
npm install @yourbrand/licensing-sdkQuick Start
import { LicenseClient, LicenseConfig } from '@yourbrand/licensing-sdk';
// Configure the client
const config: LicenseConfig = {
serverUrl: 'https://your-license-server.com',
appId: 'your-app-id',
apiKey: 'your-api-key', // Optional
enableOfflineCache: true,
cacheDuration: 3600000 // 1 hour
};
// Create client instance
const licenseClient = new LicenseClient(config);Core Functions
1. checkLicense() - Validate License (App Startup)
Use this function when your application starts to verify if the license is valid.
import { ClientInfo } from '@yourbrand/licensing-sdk';
const clientInfo: ClientInfo = {
appVersion: '1.0.0',
platform: 'web', // or 'mobile', 'desktop'
deviceId: 'unique-device-identifier'
};
try {
const result = await licenseClient.checkLicense('ABCD-EFGH-IJKL-1234', clientInfo);
if (result.valid) {
console.log('License is valid!');
console.log('Status:', result.status);
console.log('Features:', result.features);
console.log('Expires:', result.expiresAt);
// Start your application
startApplication(result.features);
} else {
console.log('License invalid:', result.message);
// Show license error or purchase screen
showLicenseError(result);
}
} catch (error) {
console.error('License check failed:', error);
// Handle offline validation or show error
}2. getLicense() / getLicenseInfo() - Get License Details
Retrieve detailed information about a license.
try {
const licenseInfo = await licenseClient.getLicense('ABCD-EFGH-IJKL-1234');
console.log('License Key:', licenseInfo.licenseKey);
console.log('Type:', licenseInfo.type); // lifetime, monthly, yearly, subscription
console.log('Status:', licenseInfo.status);
console.log('Max Users:', licenseInfo.maxUsers);
console.log('Max Devices:', licenseInfo.maxDevices);
console.log('Validation Count:', licenseInfo.validationCount);
// Both functions are identical
const sameInfo = await licenseClient.getLicenseInfo('ABCD-EFGH-IJKL-1234');
} catch (error) {
console.error('Failed to get license info:', error);
}3. createLicense() - Purchase New License
Create a new license through payment processing (Stripe or custom payment system).
import { PaymentInfo } from '@yourbrand/licensing-sdk';
// Stripe Payment
const stripePaymentInfo: PaymentInfo = {
method: 'stripe',
stripePaymentMethodId: 'pm_1234567890',
stripeCustomerId: 'cus_1234567890',
licenseType: 'monthly',
customerEmail: '[email protected]',
metadata: {
productId: 'premium-license',
campaignId: 'summer-sale'
}
};
// Custom Payment System
const customPaymentInfo: PaymentInfo = {
method: 'custom',
customPaymentData: {
transactionId: 'txn_1234567890',
paymentProvider: 'paypal',
amount: 99.99,
currency: 'USD'
},
licenseType: 'lifetime',
customerEmail: '[email protected]'
};
try {
const result = await licenseClient.createLicense(stripePaymentInfo);
if (result.success) {
console.log('License purchased successfully!');
console.log('License Key:', result.licenseKey);
console.log('Transaction ID:', result.transactionId);
// Store the license key securely
storeLicenseKey(result.licenseKey!);
// Start using the new license
const validation = await licenseClient.checkLicense(result.licenseKey!);
} else {
console.log('Purchase failed:', result.error);
// Handle payment failure
}
} catch (error) {
console.error('Purchase error:', error);
}Configuration Management
Secure Configuration File
import { ConfigManager, SecureConfig } from '@yourbrand/licensing-sdk';
const configManager = new ConfigManager();
// Create default configuration
const config = configManager.createDefaultConfig(
'https://your-license-server.com',
'your-app-id'
);
// Save configuration (optionally encrypted)
const encryptionKey = 'your-secret-encryption-key';
const configString = configManager.saveConfig(config, encryptionKey);
// Save to file or storage
localStorage.setItem('license_config', configString);
// Load configuration later
const loadedConfig = configManager.loadConfig(configString, encryptionKey);
const licenseClient = new LicenseClient(loadedConfig);Environment-specific Configuration
// Development configuration
const devConfig: LicenseConfig = {
serverUrl: 'http://localhost:8080',
appId: 'myapp-dev',
enableOfflineCache: true,
timeout: 10000 // Longer timeout for development
};
// Production configuration
const prodConfig: LicenseConfig = {
serverUrl: 'https://api.yourcompany.com',
appId: 'myapp-prod',
apiKey: process.env.LICENSE_API_KEY,
enableSigning: true,
signingKey: process.env.LICENSE_SIGNING_KEY,
enableOfflineCache: true,
cacheDuration: 1800000 // 30 minutes
};
const config = process.env.NODE_ENV === 'production' ? prodConfig : devConfig;
const licenseClient = new LicenseClient(config);Offline Validation
The SDK supports offline license validation using mathematical validation:
import { LicenseValidator } from '@yourbrand/licensing-sdk';
// Mathematical validation works offline
const isValidFormat = LicenseValidator.validateKeyFormat('ABCD-EFGH-IJKL-1234');
if (isValidFormat) {
console.log('License key format is mathematically valid');
// Try online validation
try {
const result = await licenseClient.checkLicense('ABCD-EFGH-IJKL-1234');
// Use online result
} catch (error) {
// Fallback to cached result if server is unreachable
console.log('Using cached validation result due to connectivity issues');
}
}Error Handling
try {
const result = await licenseClient.checkLicense(licenseKey);
switch (result.status) {
case 'active':
// License is valid and active
break;
case 'expired':
// License has expired
showRenewalDialog();
break;
case 'revoked':
// License has been revoked
showContactSupport();
break;
case 'suspended':
// License is temporarily suspended
showSuspensionNotice();
break;
case 'invalid_format':
// License key format is invalid
showInvalidLicenseError();
break;
}
} catch (error) {
if (error.message.includes('ECONNREFUSED')) {
// Server unreachable - try cached validation
console.log('Server unreachable, using offline validation');
} else {
console.error('Validation error:', error);
}
}Cache Management
// Clear all cached data
licenseClient.clearCache();
// Set custom cache duration (in milliseconds)
licenseClient.setCacheDuration(7200000); // 2 hours
// Check cache statistics
const cacheManager = new CacheManager(true, 3600000);
const stats = cacheManager.getStats();
console.log('Cache stats:', stats);Integration Examples
React Application
import React, { useState, useEffect } from 'react';
import { LicenseClient, LicenseConfig, ValidationResult } from '@yourbrand/licensing-sdk';
const App: React.FC = () => {
const [licenseValid, setLicenseValid] = useState<boolean | null>(null);
const [licenseInfo, setLicenseInfo] = useState<ValidationResult | null>(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
const validateLicense = async () => {
const config: LicenseConfig = {
serverUrl: process.env.REACT_APP_LICENSE_SERVER!,
appId: process.env.REACT_APP_ID!,
apiKey: process.env.REACT_APP_LICENSE_API_KEY
};
const client = new LicenseClient(config);
const licenseKey = localStorage.getItem('license_key');
if (!licenseKey) {
setLicenseValid(false);
setLoading(false);
return;
}
try {
const result = await client.checkLicense(licenseKey, {
appVersion: '1.0.0',
platform: 'web',
deviceId: 'browser-' + Date.now()
});
setLicenseValid(result.valid);
setLicenseInfo(result);
} catch (error) {
console.error('License validation failed:', error);
setLicenseValid(false);
} finally {
setLoading(false);
}
};
validateLicense();
}, []);
if (loading) {
return <div>Validating license...</div>;
}
if (!licenseValid) {
return <LicensePurchaseComponent />;
}
return (
<div>
<h1>Application</h1>
<p>License Status: {licenseInfo?.status}</p>
{/* Your application content */}
</div>
);
};Node.js Server
import { LicenseClient } from '@yourbrand/licensing-sdk';
class LicenseService {
private client: LicenseClient;
constructor() {
this.client = new LicenseClient({
serverUrl: process.env.LICENSE_SERVER_URL!,
appId: process.env.APP_ID!,
apiKey: process.env.LICENSE_API_KEY!,
enableSigning: true,
signingKey: process.env.LICENSE_SIGNING_KEY!
});
}
async validateUserLicense(userId: string, licenseKey: string): Promise<boolean> {
try {
const result = await this.client.checkLicense(licenseKey, {
appVersion: process.env.APP_VERSION || '1.0.0',
platform: 'server',
deviceId: `server-${userId}`
});
return result.valid && result.status === 'active';
} catch (error) {
console.error(`License validation failed for user ${userId}:`, error);
return false;
}
}
async purchaseLicense(userEmail: string, licenseType: string): Promise<string | null> {
try {
const result = await this.client.createLicense({
method: 'stripe',
licenseType: licenseType as any,
customerEmail: userEmail,
stripePaymentMethodId: 'pm_card_visa' // This would come from Stripe
});
return result.success ? result.licenseKey! : null;
} catch (error) {
console.error('License purchase failed:', error);
return null;
}
}
}
export default LicenseService;API Reference
LicenseClient
Constructor
new LicenseClient(config: LicenseConfig)
Methods
checkLicense(licenseKey: string, clientInfo?: ClientInfo): Promise<ValidationResult>getLicense(licenseKey: string): Promise<LicenseInfo>getLicenseInfo(licenseKey: string): Promise<LicenseInfo>createLicense(paymentInfo: PaymentInfo): Promise<PurchaseResult>updateHeartbeat(licenseKey: string, clientInfo?: ClientInfo): Promise<void>clearCache(): voidsetCacheDuration(duration: number): void
LicenseValidator
Static Methods
validateKeyFormat(licenseKey: string): boolean
Security Features
- Mathematical Validation: License keys use a modified Luhn algorithm for offline validation
- Request Signing: Optional HMAC signing for secure communication
- Encrypted Configuration: Configuration files can be encrypted
- Integrity Verification: Configuration integrity is verified with hashes
- Secure Caching: Cached data includes expiration and integrity checks
License Types
lifetime: Never expires, one-time paymentmonthly: Monthly subscriptionyearly: Annual subscriptionsubscription: Custom subscription period
Error Codes
invalid_format: License key format is invalidnot_found: License key not found in databaseexpired: License has expiredrevoked: License has been revokedsuspended: License is temporarily suspendedserver_error: Server communication error
Support
For support and documentation, visit: https://docs.yourcompany.com/licensing-sdk
