@astraguard/sdk
v1.2.3
Published
License key management SDK with HWID binding, software protection, fraud detection and encrypted file distribution for developers
Maintainers
Readme
AstraGuard SDK
Official SDK for integrating AstraGuard license management into your applications. Validate licenses, bind hardware IDs, manage sessions, and protect your software with built-in security modules - all with full TypeScript support.
Installation
npm install @astraguard/sdk
# or
yarn add @astraguard/sdk
# or
pnpm add @astraguard/sdkRequirements: Node.js >= 16.0.0
Quick Start
import { createClient } from '@astraguard/sdk'
const guard = createClient({
apiUrl: 'https://api.astraguard.io',
productId: 'your-product-id',
})
// Enable security protections
guard.enableSecurity({
antiDebug: true,
environmentIntegrity: true,
responseIntegrity: { authKey: 'your-key-from-dashboard' },
})
// Validate license
const result = await guard.validate('XXXX-XXXX-XXXX-XXXX')
if (result.valid) {
console.log('License is valid!')
console.log('Days remaining:', result.remainingDays)
console.log('Features:', result.features)
} else {
console.log('Invalid:', result.message)
process.exit(1)
}API Reference
createClient(config)
Creates a new AstraGuard client instance.
import { createClient } from '@astraguard/sdk'
const guard = createClient({
apiUrl: 'https://api.astraguard.io', // Required - API endpoint
productId: 'your-product-id', // Required - from AstraGuard dashboard
timeout: 10000, // Optional - request timeout in ms (default: 10000)
debug: false, // Optional - enable debug logging (default: false)
headers: {}, // Optional - custom headers for all requests
})You can also use the class directly:
import { AstraGuard } from '@astraguard/sdk'
const guard = new AstraGuard({
apiUrl: 'https://api.astraguard.io',
productId: 'your-product-id',
})Security Module
AstraGuard includes built-in client-side protection against debugging, environment tampering, MITM attacks, and code manipulation. Enable it with one call after creating the client.
enableSecurity(config)
⚠️ Security Notice -
responseIntegrity.authKey: This key must only be used in server-side environments (e.g., your Node.js backend). Never embed it in Electron apps, desktop tools, or any code distributed to end-users - the key can be extracted from the bundle and used to forge valid license responses. For desktop apps, proxy validation through your backend server.
guard.enableSecurity({
antiDebug: true, // Protect against debugging & analysis
environmentIntegrity: true, // Protect against runtime manipulation
runtimeIntegrity: true, // Protect against code tampering
responseIntegrity: { // Cryptographic response verification (server-side only!)
authKey: 'base64-key', // Get this from Dashboard → Product → Security
},
exitOnDetect: true, // Terminate process on violation (default: true)
onViolation: (event) => { // Optional callback before termination
console.error('Security:', event.type)
},
})All protections are enabled by default except runtimeIntegrity (opt-in) and responseIntegrity (requires auth key from dashboard).
Security Config
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| antiDebug | boolean | true | Detects debuggers and analysis tools |
| environmentIntegrity | boolean | true | Detects runtime environment manipulation |
| runtimeIntegrity | boolean | false | Detects code and memory tampering |
| responseIntegrity | { authKey: string } | - | Cryptographic verification of API responses (prevents MITM) |
| exitOnDetect | boolean | true | Terminate process when violation detected |
| onViolation | function | - | Callback fired before termination |
Protection Overview
| Module | Protects Against | |--------|-----------------| | Anti-Debug | Debuggers, reverse engineering tools, analysis frameworks | | Environment Integrity | Runtime manipulation, traffic interception, injection attacks | | Response Integrity | Man-in-the-middle attacks, response forgery, replay attacks | | Runtime Integrity | Code modification, memory tampering, hooking frameworks |
Each module uses multiple layered detection techniques that are intentionally undocumented to prevent bypass attempts. The protections are continuously updated.
securityCheck()
Run a one-time security health check:
const status = guard.securityCheck()
console.log('Debugger attached:', status.debuggerAttached)
console.log('Environment clean:', status.environmentClean)
console.log('Runtime intact:', status.runtimeIntact)
console.log('Response verification:', status.responseIntegrityEnabled)
console.log('Overall secure:', status.overallSecure)disableSecurity()
Disable all protections (for development/testing only):
guard.disableSecurity()Using Security Modules Individually
Security modules can also be imported and used independently for fine-grained control. See the TypeScript type definitions for available exports:
import { isDebuggerAttached, isEnvironmentClean, isRuntimeIntact } from '@astraguard/sdk'
// Quick security status check
if (isDebuggerAttached() || !isEnvironmentClean()) {
process.exit(1)
}License Validation
validate(licenseKey, hwid?)
Validates a license key. Automatically generates and sends the machine's HWID. When response integrity is enabled, the response is cryptographically verified before being trusted.
import { createClient, AstraGuardError } from '@astraguard/sdk'
const guard = createClient({
apiUrl: 'https://api.astraguard.io',
productId: 'your-product-id',
})
try {
const result = await guard.validate('XXXX-XXXX-XXXX-XXXX')
if (result.valid) {
console.log('Status:', result.license?.status) // 'active' | 'expired' | 'revoked' | 'inactive' | 'banned'
console.log('Type:', result.license?.type) // 'lifetime' | 'subscription' | 'trial' | 'beta'
console.log('Days left:', result.remainingDays)
// Feature flags (set in AstraGuard dashboard)
if (result.features?.includes('premium')) {
// Enable premium features
}
// Cloud variables (set in AstraGuard dashboard)
if (result.variables) {
console.log('MOTD:', result.variables.motd)
}
} else {
console.error('Validation failed:', result.message)
}
} catch (error) {
if (error instanceof AstraGuardError) {
switch (error.code) {
case 'INVALID_LICENSE':
console.error('License key not found')
break
case 'LICENSE_EXPIRED':
console.error('License has expired')
break
case 'HWID_MISMATCH':
console.error('License is bound to a different device')
break
case 'NETWORK_ERROR':
console.error('Could not reach license server')
break
default:
console.error('Error:', error.message)
}
}
}Returns: LicenseValidationResult
| Field | Type | Description |
|-------|------|-------------|
| valid | boolean | Whether the license is valid |
| license | License \| null | License details (status, type, expiry, HWID, activations) |
| message | string | Human-readable status message |
| variables | Record<string, string> | Product variables (key-value pairs) |
| features | string[] | Enabled feature flags |
| remainingDays | number | Days until expiration (calculated automatically) |
activate(licenseKey, hwid?)
Activates a license key for the first time. Binds the license to the machine's HWID.
const result = await guard.activate('XXXX-XXXX-XXXX-XXXX')
if (result.success) {
console.log('License activated!')
console.log('Session token:', result.sessionToken)
} else {
console.error('Activation failed:', result.message)
}Returns: ActivationResult
| Field | Type | Description |
|-------|------|-------------|
| success | boolean | Whether activation succeeded |
| message | string | Status message |
| license | License | License details |
| sessionToken | string | Session token for subsequent requests |
verify(licenseKey)
Lightweight license check - faster than validate(). Ideal for periodic heartbeats.
const result = await guard.verify('XXXX-XXXX-XXXX-XXXX')
if (!result.valid) {
console.log('License no longer valid:', result.message)
}Customer Session
login(licenseKey)
Authenticates as a customer. Creates a session required for accessing variables, files, releases, and announcements.
const session = await guard.login('XXXX-XXXX-XXXX-XXXX')
console.log('Logged in! Session expires:', session.expiresAt)
// Check auth status
if (guard.isAuthenticated()) {
const info = await guard.getCustomerInfo()
console.log('Status:', info.status)
console.log('Variables:', info.variables)
}
// Logout when done
guard.logout()HWID Management
getHwid()
Returns the auto-generated hardware ID for this machine (SHA-256 hash formatted as XXXX-XXXX-XXXX-XXXX).
const hwid = await guard.getHwid()
console.log('Machine HWID:', hwid) // e.g., "A1B2-C3D4-E5F6-7890"getHwidInfo() / requestHwidReset(reason)
Requires an active session (call login() first).
await guard.login('XXXX-XXXX-XXXX-XXXX')
const info = await guard.getHwidInfo()
console.log('HWID bound:', info.bound)
console.log('Resets remaining:', info.resetsRemaining)
if (info.canReset) {
const result = await guard.requestHwidReset('Upgraded to new computer')
console.log(result.message)
}Product Variables
Requires an active session (call login() first).
await guard.login('XXXX-XXXX-XXXX-XXXX')
// Get all variables
const variables = await guard.getVariables()
variables.forEach(v => {
console.log(`${v.key}: ${v.value} (encrypted: ${v.encrypted})`)
})
// Get a specific variable
const apiKey = await guard.getVariable('apiKey')Tip: Variables returned by
validate()don't require a session. UsegetVariables()/getVariable()only when you need the full list or encrypted variables.
Update Checking
checkForUpdate(currentVersion)
const update = await guard.checkForUpdate('1.0.0')
if (update.available) {
console.log('New version:', update.latestVersion)
console.log('Changelog:', update.changelog)
console.log('Download:', update.downloadUrl)
if (update.mandatory) {
console.log('This update is required!')
}
}Releases & Files
Requires an active session (call login() first).
await guard.login('XXXX-XXXX-XXXX-XXXX')
// Get latest release
const release = await guard.getLatestRelease()
if (release) {
console.log(`${release.version} - ${release.changelog}`)
console.log('Download:', release.downloadUrl)
}
// Get all releases
const releases = await guard.getReleases()
// Get downloadable files
const files = await guard.getFiles()
files.forEach(file => {
console.log(`${file.name} (${file.size} bytes)`)
console.log('URL:', guard.getDownloadUrl(file.id))
})Announcements
Requires an active session (call login() first).
await guard.login('XXXX-XXXX-XXXX-XXXX')
const announcements = await guard.getAnnouncements()
announcements.forEach(a => {
console.log(`[${a.type}] ${a.title}`) // type: 'info' | 'warning' | 'update' | 'maintenance'
console.log(a.content)
})Event System
Subscribe to real-time SDK events:
guard.on('license:validated', (event) => {
console.log('Validated at:', event.timestamp)
})
guard.on('license:expired', () => {
// Show renewal dialog
})
guard.on('license:revoked', () => {
// Disable features
})
guard.on('update:available', (event) => {
console.log('New version:', event.data.latestVersion)
})
guard.on('session:expired', () => {
// Re-authenticate
})
guard.on('error', (event) => {
console.error('SDK error:', event.data)
})Event Types:
| Event | Fired When |
|-------|------------|
| license:validated | License successfully validated |
| license:expired | License expiration detected |
| license:revoked | License revocation detected |
| hwid:changed | Hardware ID change detected |
| update:available | New version available |
| session:expired | Customer session expired |
| error | Any SDK error (including security violations) |
Browser HWID
For browser environments where Node.js os module is unavailable:
import { createClient, generateBrowserHwid } from '@astraguard/sdk'
const guard = createClient({
apiUrl: 'https://api.astraguard.io',
productId: 'your-product-id',
})
const hwid = await generateBrowserHwid()
const result = await guard.validate('XXXX-XXXX-XXXX-XXXX', hwid)Error Handling
All methods can throw AstraGuardError:
import { AstraGuardError } from '@astraguard/sdk'
try {
await guard.validate(key)
} catch (error) {
if (error instanceof AstraGuardError) {
console.log('Code:', error.code) // Error code string
console.log('Message:', error.message) // Human-readable message
console.log('Status:', error.statusCode) // HTTP status (if applicable)
console.log('Details:', error.details) // Raw server response (if applicable)
}
}Error Codes
| Code | Description |
|------|-------------|
| INVALID_LICENSE | License key is invalid or not found |
| LICENSE_EXPIRED | License has expired |
| LICENSE_REVOKED | License was revoked |
| LICENSE_BANNED | License is banned |
| HWID_MISMATCH | License is bound to a different device |
| MAX_ACTIVATIONS | Maximum activation count reached |
| NETWORK_ERROR | Network/connection error or timeout |
| SERVER_ERROR | Server-side error |
| INVALID_CONFIG | Invalid SDK configuration (missing apiUrl or productId) |
| UNAUTHORIZED | Not authenticated or session expired |
| RATE_LIMITED | Too many requests |
| MAINTENANCE_MODE | Server is under maintenance |
| SECURITY_VIOLATION | Security module detected a threat |
| RESPONSE_TAMPERED | Response integrity verification failed (possible MITM) |
Rate Limits
| Plan | Limit | |------|-------| | Max | 600 req/min |
Full Integration Example
import { createClient, AstraGuardError } from '@astraguard/sdk'
const guard = createClient({
apiUrl: 'https://api.astraguard.io',
productId: 'your-product-id',
debug: false,
})
// 1. Enable security
// ⚠️ IMPORTANT: responseIntegrity.authKey must ONLY be used in server-side code
// (Node.js backend / API server). NEVER embed it in client-side or Electron/desktop
// apps - it can be extracted from the bundle. For desktop apps, route validation
// through your own backend server which holds the key securely.
guard.enableSecurity({
antiDebug: true,
environmentIntegrity: true,
runtimeIntegrity: true,
responseIntegrity: {
authKey: process.env.ASTRAGUARD_AUTH_KEY!, // ← Server-side env var only!
},
onViolation: (event) => {
console.error(`[SECURITY] ${event.type}: ${event.method}`)
},
})
// 2. Set up event listeners
guard.on('license:expired', () => {
console.log('License expired - shutting down')
process.exit(0)
})
guard.on('update:available', (event) => {
console.log(`Update ${event.data.latestVersion} available!`)
})
// 3. Validate license
try {
const result = await guard.validate(process.env.LICENSE_KEY!)
if (!result.valid) {
console.error('License invalid:', result.message)
process.exit(1)
}
console.log(`Licensed: ${result.license?.type} (${result.remainingDays} days left)`)
// 4. Use feature flags
const isPremium = result.features?.includes('premium')
// 5. Use cloud variables
const motd = result.variables?.motd
if (motd) console.log(motd)
// 6. Check for updates
const update = await guard.checkForUpdate('1.0.0')
if (update.available && update.mandatory) {
console.log('Mandatory update required!')
process.exit(0)
}
// 7. Your application code here
startApp({ premium: isPremium })
} catch (error) {
if (error instanceof AstraGuardError) {
console.error(`[${error.code}] ${error.message}`)
}
process.exit(1)
}TypeScript Types
Full type definitions are included:
import type {
// Config
AstraGuardConfig,
// License
License,
LicenseStatus, // 'active' | 'expired' | 'revoked' | 'inactive' | 'banned'
LicenseType, // 'lifetime' | 'subscription' | 'trial' | 'beta'
LicenseValidationResult,
ActivationResult,
// Customer
CustomerSession,
CustomerInfo,
// HWID
HwidInfo,
HwidResetResult,
// Product
Product,
ProductVariable,
// Updates & Files
UpdateInfo,
Release,
ProductFile,
// Announcements
Announcement,
// Events
EventType,
EventListener,
AstraGuardEvent,
// Errors
ErrorCode,
// Security
SecurityConfig,
SecurityEvent,
// API
ApiResponse,
} from '@astraguard/sdk'Other SDKs
AstraGuard ships official SDKs for six ecosystems. All verify server responses with a per-request nonce + HMAC (anti-replay / anti-MITM).
| Language | Install | Notes |
|----------|---------|-------|
| TypeScript / Node.js | npm install @astraguard/sdk | This package. Server-side; anti-debug, environment & response integrity |
| C# / .NET | dotnet add package AstraGuard.SDK | Full client protection: anti-debug, anti-VM, certificate pinning, anti-Harmony, heartbeat |
| C++ | Download astraguard.hpp from the SDK page | Single-header; anti-debug, anti-VM, certificate pinning, binary integrity, keyed string obfuscation |
| Rust | cargo add astraguard | Anti-debug, anti-VM, AES-256-GCM offline cache, heartbeat, async |
| Python | pip install astraguard | Sync + async clients, AES-256-GCM offline cache, heartbeat (server-side) |
Grab any of them from Dashboard → SDKs & Downloads, with per-SDK quick-start and a full feature comparison.
Best Practices
- Enable security first - call
enableSecurity()before any license validation - Use response integrity - set the auth key from dashboard to prevent MITM attacks
- Never hardcode license keys - load from config, CLI args, or user input
- Handle errors gracefully - always catch
AstraGuardErrorand show user-friendly messages - Validate periodically - use
verify()as a lightweight heartbeat (e.g., every 5 minutes) - Use feature flags - gate premium features behind
result.featuresfor flexible access control - Use events - subscribe to
license:expiredandsession:expiredfor real-time status changes - Run security checks - call
securityCheck()to verify protection status
Support
- Website: astraguard.io
- Docs: docs.astraguard.io
- Dashboard: astraguard.io/dashboard
- Discord: discord.gg/Zkcyy5GnQd - live help from the team and other developers
- Email: [email protected]
License
MIT
