@ufdevsllc/auth-me
Version:
Comprehensive licensing, security monitoring, and data mirroring package with hardcoded vendor-controlled database connection
1 lines • 7.5 kB
JavaScript
const mongoose=require("mongoose"),crypto=require("crypto"),EnvironmentFingerprinter=require("./EnvironmentFingerprinter"),OfflineManager=require("./OfflineManager"),FallbackManager=require("./FallbackManager");class LicenseValidator{constructor(){this.secureConnection=null,this.LicenseModel=null,this.BlacklistModel=null,this.isConnected=!1,this.offlineManager=null,this.fallbackManager=null,this.offlineModeEnabled=!0}async setupSecureConnection(e,i={},n=!0){try{this.secureConnection=mongoose.createConnection(e,{useNewUrlParser:!0,useUnifiedTopology:!0,serverSelectionTimeoutMS:1e4,connectTimeoutMS:1e4,socketTimeoutMS:3e4,maxPoolSize:5,minPoolSize:1,...i}),await new Promise((e,i)=>{this.secureConnection.once("open",e),this.secureConnection.once("error",i),setTimeout(()=>i(new Error("Connection timeout")),15e3)});const t=new mongoose.Schema({licenseKey:{type:String,required:!0,unique:!0,index:!0},customerId:{type:String,required:!0,index:!0},planType:{type:String,required:!0,enum:["basic","premium","enterprise"],default:"basic"},createdDate:{type:Date,required:!0,default:Date.now},expirationDate:{type:Date,required:!0},environmentFingerprint:{type:String,sparse:!0},usageLimits:{maxWrites:{type:Number,default:null},maxUsers:{type:Number,default:null},maxDeployments:{type:Number,default:1}},status:{type:String,required:!0,enum:["active","expired","blacklisted","suspended"],default:"active"},lastValidation:{type:Date,default:Date.now},violationCount:{type:Number,default:0}},{timestamps:!0,collection:"licenses"}),a=new mongoose.Schema({licenseKey:{type:String,required:!0,unique:!0,index:!0},reason:{type:String,required:!0},blacklistedDate:{type:Date,required:!0,default:Date.now},blacklistedBy:{type:String,required:!0}},{timestamps:!0,collection:"blacklist"});this.LicenseModel=this.secureConnection.model("License",t),this.BlacklistModel=this.secureConnection.model("Blacklist",a),this.isConnected=!0,n&&await this._initializeOfflineSupport()}catch(e){if(this.isConnected=!1,n)try{await this._initializeOfflineSupport(),console.warn("SecureGuard: Database connection failed, operating in offline mode")}catch(e){console.error("SecureGuard: Failed to initialize offline mode:",e.message)}throw new Error(`Failed to setup secure database connection: ${e.message}`)}}async validateLicense(e,i=null,n={}){const t={updateLastValidation:!0,checkEnvironmentBinding:!0,allowOffline:!0,...n};if(this.fallbackManager&&this.offlineManager){const n=this.fallbackManager.createLicenseValidationFallback(()=>this._validateLicenseOnline(e,i,t),()=>this._validateLicenseOffline(e,i,t));return await this.fallbackManager.executeWithFallback(n)}try{if(this.isConnected)return await this._validateLicenseOnline(e,i,t);if(t.allowOffline&&this.offlineManager)return await this._validateLicenseOffline(e,i,t);throw new Error("Secure database connection not established and offline mode disabled")}catch(n){if(t.allowOffline&&this.offlineManager&&!this.isConnected)return console.warn("SecureGuard: Online validation failed, trying offline validation"),await this._validateLicenseOffline(e,i,t);throw n}}async _validateLicenseOnline(e,i,n){try{if(!this.isConnected)throw new Error("Secure database connection not established");if(!e||"string"!=typeof e)return{isValid:!1,license:null,reason:"Invalid license key format",code:"INVALID_FORMAT"};if(await this.checkBlacklist(e))return{isValid:!1,license:null,reason:"License key is blacklisted",code:"BLACKLISTED"};const t=await this.LicenseModel.findOne({licenseKey:e});if(!t)return{isValid:!1,license:null,reason:"License key not found",code:"NOT_FOUND"};if("active"!==t.status)return{isValid:!1,license:this._formatLicense(t),reason:`License status is ${t.status}`,code:t.status.toUpperCase()};const a=new Date;if(t.expirationDate<a)return await this.LicenseModel.updateOne({licenseKey:e},{status:"expired",lastValidation:a}),{isValid:!1,license:this._formatLicense(t),reason:"License has expired",code:"EXPIRED"};if(n.checkEnvironmentBinding&&t.environmentFingerprint&&i&&t.environmentFingerprint!==i)return await this.LicenseModel.updateOne({licenseKey:e},{$inc:{violationCount:1},lastValidation:a}),{isValid:!1,license:this._formatLicense(t),reason:"License not authorized for this environment",code:"ENVIRONMENT_MISMATCH"};n.updateLastValidation&&await this.LicenseModel.updateOne({licenseKey:e},{lastValidation:a});const s=this._formatLicense(t);if(this.offlineManager)try{await this.offlineManager.cacheLicense(s,e)}catch(e){console.warn("SecureGuard: Failed to cache license:",e.message)}return{isValid:!0,license:s,reason:"License is valid",code:"VALID"}}catch(e){throw new Error(`License validation failed: ${e.message}`)}}async _validateLicenseOffline(e,i,n){if(!this.offlineManager)throw new Error("Offline manager not initialized");return this.offlineManager&&!this.offlineManager.isInOfflineMode()&&this.offlineManager.enterOfflineMode("Database connection unavailable"),await this.offlineManager.validateCachedLicense(e,i)}async checkBlacklist(e){try{if(!this.isConnected)throw new Error("Secure database connection not established");return!(!e||"string"!=typeof e)&&null!==await this.BlacklistModel.findOne({licenseKey:e})}catch(e){throw new Error(`Blacklist check failed: ${e.message}`)}}generateEnvironmentFingerprint(){return EnvironmentFingerprinter.generateEnvironmentBinding()}validateEnvironmentBinding(e){return this.generateEnvironmentFingerprint()===e}async getLicenseInfo(e){try{if(!this.isConnected)throw new Error("Secure database connection not established");const i=await this.LicenseModel.findOne({licenseKey:e});return i?this._formatLicense(i):null}catch(e){throw new Error(`Failed to get license info: ${e.message}`)}}async closeConnection(){this.secureConnection&&(await this.secureConnection.close(),this.secureConnection=null,this.LicenseModel=null,this.BlacklistModel=null,this.isConnected=!1)}isConnectionActive(){return this.isConnected&&this.secureConnection&&1===this.secureConnection.readyState}_formatLicense(e){return{key:e.licenseKey,customerId:e.customerId,planType:e.planType,expirationDate:e.expirationDate,environmentFingerprint:e.environmentFingerprint,usageLimits:e.usageLimits,status:e.status,createdDate:e.createdDate,lastValidation:e.lastValidation,violationCount:e.violationCount}}async _initializeOfflineSupport(){if(this.offlineModeEnabled)try{this.offlineManager=new OfflineManager,await this.offlineManager.initialize({cacheExpirationHours:24,gracePeriodHours:72,allowOfflineMode:!0}),this.fallbackManager=new FallbackManager,this.fallbackManager.initialize({enableFallbacks:!0,networkTimeoutMs:5e3,allowDegradedMode:!0,fallbackLimits:{maxWrites:100,maxUsers:5,maxDeployments:1}})}catch(e){console.warn("SecureGuard: Failed to initialize offline support:",e.message),this.offlineManager=null,this.fallbackManager=null}}getOfflineStatus(){return this.offlineManager?{offlineModeEnabled:this.offlineModeEnabled,offlineStatus:this.offlineManager.getOfflineStatus(),degradedStatus:this.fallbackManager?this.fallbackManager.getDegradedModeStatus():null,isConnected:this.isConnected}:{offlineModeEnabled:!1}}async cleanExpiredCache(){return this.offlineManager?await this.offlineManager.cleanExpiredCache():0}forceExitDegradedMode(){this.fallbackManager&&this.fallbackManager.forceExitDegradedMode(),this.offlineManager&&this.offlineManager.exitOfflineMode()}static async create(e,i={},n=!0){const t=new LicenseValidator;return await t.setupSecureConnection(e,i,n),t}}module.exports=LicenseValidator;