@n8n_io/license-sdk 2.17.0 → 2.19.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/LicenseManager.d.mts +12 -12
- package/dist/LicenseManager.d.ts +12 -12
- package/dist/LicenseManager.js +3 -3
- package/dist/LicenseManager.js.map +1 -1
- package/dist/LicenseManager.mjs +3 -3
- package/dist/LicenseManager.mjs.map +1 -1
- package/dist/_tsup-dts-rollup.d.mts +227 -213
- package/dist/_tsup-dts-rollup.d.ts +227 -213
- package/dist/httpRequest.d.mts +2 -2
- package/dist/httpRequest.d.ts +2 -2
- package/dist/httpRequest.js +1 -1
- package/dist/httpRequest.js.map +1 -1
- package/dist/httpRequest.mjs +1 -1
- package/dist/httpRequest.mjs.map +1 -1
- package/package.json +4 -4
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
export { AUTORENEWAL_INTERVAL } from './_tsup-dts-rollup';
|
|
2
|
-
export { TLicenseManagerConfig } from './_tsup-dts-rollup';
|
|
3
|
-
export { TLicenseBlock } from './_tsup-dts-rollup';
|
|
4
|
-
export { TLicenseContainer } from './_tsup-dts-rollup';
|
|
5
|
-
export { TFeatures } from './_tsup-dts-rollup';
|
|
6
|
-
export { TUsageMetric } from './_tsup-dts-rollup';
|
|
7
|
-
export { TPassthroughData } from './_tsup-dts-rollup';
|
|
8
|
-
export { TMetadata } from './_tsup-dts-rollup';
|
|
9
|
-
export { TEntitlement } from './_tsup-dts-rollup';
|
|
10
|
-
export { TLicenseCertObj } from './_tsup-dts-rollup';
|
|
11
|
-
export { TLogger } from './_tsup-dts-rollup';
|
|
12
|
-
export { LicenseManager } from './_tsup-dts-rollup';
|
|
1
|
+
export { AUTORENEWAL_INTERVAL } from './_tsup-dts-rollup.mjs';
|
|
2
|
+
export { TLicenseManagerConfig } from './_tsup-dts-rollup.mjs';
|
|
3
|
+
export { TLicenseBlock } from './_tsup-dts-rollup.mjs';
|
|
4
|
+
export { TLicenseContainer } from './_tsup-dts-rollup.mjs';
|
|
5
|
+
export { TFeatures } from './_tsup-dts-rollup.mjs';
|
|
6
|
+
export { TUsageMetric } from './_tsup-dts-rollup.mjs';
|
|
7
|
+
export { TPassthroughData } from './_tsup-dts-rollup.mjs';
|
|
8
|
+
export { TMetadata } from './_tsup-dts-rollup.mjs';
|
|
9
|
+
export { TEntitlement } from './_tsup-dts-rollup.mjs';
|
|
10
|
+
export { TLicenseCertObj } from './_tsup-dts-rollup.mjs';
|
|
11
|
+
export { TLogger } from './_tsup-dts-rollup.mjs';
|
|
12
|
+
export { LicenseManager } from './_tsup-dts-rollup.mjs';
|
package/dist/LicenseManager.d.ts
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
export { AUTORENEWAL_INTERVAL } from './_tsup-dts-rollup';
|
|
2
|
-
export { TLicenseManagerConfig } from './_tsup-dts-rollup';
|
|
3
|
-
export { TLicenseBlock } from './_tsup-dts-rollup';
|
|
4
|
-
export { TLicenseContainer } from './_tsup-dts-rollup';
|
|
5
|
-
export { TFeatures } from './_tsup-dts-rollup';
|
|
6
|
-
export { TUsageMetric } from './_tsup-dts-rollup';
|
|
7
|
-
export { TPassthroughData } from './_tsup-dts-rollup';
|
|
8
|
-
export { TMetadata } from './_tsup-dts-rollup';
|
|
9
|
-
export { TEntitlement } from './_tsup-dts-rollup';
|
|
10
|
-
export { TLicenseCertObj } from './_tsup-dts-rollup';
|
|
11
|
-
export { TLogger } from './_tsup-dts-rollup';
|
|
12
|
-
export { LicenseManager } from './_tsup-dts-rollup';
|
|
1
|
+
export { AUTORENEWAL_INTERVAL } from './_tsup-dts-rollup.js';
|
|
2
|
+
export { TLicenseManagerConfig } from './_tsup-dts-rollup.js';
|
|
3
|
+
export { TLicenseBlock } from './_tsup-dts-rollup.js';
|
|
4
|
+
export { TLicenseContainer } from './_tsup-dts-rollup.js';
|
|
5
|
+
export { TFeatures } from './_tsup-dts-rollup.js';
|
|
6
|
+
export { TUsageMetric } from './_tsup-dts-rollup.js';
|
|
7
|
+
export { TPassthroughData } from './_tsup-dts-rollup.js';
|
|
8
|
+
export { TMetadata } from './_tsup-dts-rollup.js';
|
|
9
|
+
export { TEntitlement } from './_tsup-dts-rollup.js';
|
|
10
|
+
export { TLicenseCertObj } from './_tsup-dts-rollup.js';
|
|
11
|
+
export { TLogger } from './_tsup-dts-rollup.js';
|
|
12
|
+
export { LicenseManager } from './_tsup-dts-rollup.js';
|
package/dist/LicenseManager.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var D=Object.create;var u=Object.defineProperty;var A=Object.getOwnPropertyDescriptor;var
|
|
1
|
+
"use strict";var D=Object.create;var u=Object.defineProperty;var A=Object.getOwnPropertyDescriptor;var S=Object.getOwnPropertyNames;var L=Object.getPrototypeOf,x=Object.prototype.hasOwnProperty;var O=(r,e)=>{for(var t in e)u(r,t,{get:e[t],enumerable:!0})},C=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of S(e))!x.call(r,n)&&n!==t&&u(r,n,{get:()=>e[n],enumerable:!(i=A(e,n))||i.enumerable});return r};var v=(r,e,t)=>(t=r!=null?D(L(r)):{},C(e||!r||!r.__esModule?u(t,"default",{value:r,enumerable:!0}):t,r)),N=r=>C(u({},"__esModule",{value:!0}),r);var z={};O(z,{AUTORENEWAL_INTERVAL:()=>h,LicenseManager:()=>p});module.exports=N(z);var f=v(require("crypto-js")),b=require("node-machine-id"),R=v(require("node-rsa")),F=require("assert"),m=require("crypto");var c=require("undici"),I=require("url");var T="2.19.0";function g(r){let e=process.env[r];return e?new c.ProxyAgent(e):null}var y=g("http_proxy_license_server")||g("http_proxy"),E=g("https_proxy_license_server")||g("https_proxy"),M={...y?{"http:":y}:{},...E?{"https:":E}:{}},P=(process.env.no_proxy??"").split(",").map(r=>r.trim()),k=(0,c.getGlobalDispatcher)();(0,c.setGlobalDispatcher)(new class extends c.Dispatcher{dispatch(r,e){if(r.origin){let{host:t,protocol:i}=typeof r.origin=="string"?new I.URL(r.origin):r.origin;if(!P.some(n=>n.startsWith(".")?t.endsWith(n):t===n)){let n=M[i];n&&n.dispatch(r,e)}}return k.dispatch(r,e)}});async function d(r,e,t={}){try{let i=await(0,c.fetch)(r,{method:"post",body:JSON.stringify(e),headers:{"Content-Type":"application/json","User-Agent":`License-SDK/${T} (Node.js ${process.version}; ${process.platform}) ${t.productIdentifier}`},signal:AbortSignal.timeout(t.timeoutInMs??3e4)}),n=await i.json();return{status:i.status,data:n}}catch(i){throw new Error("Connection Error",{cause:i})}}var h=15*60*1e3;var p=class{constructor(e){this.isShuttingDown=!1;this.config=e,this.config.logger?this.logger=this.config.logger:this.logger={error(){console.log("ERROR:",...arguments)},warn(){console.log("WARN:",...arguments)},info(){console.log("INFO:",...arguments)},debug(){console.log("DEBUG:",...arguments)}},this.x509IssuerCert=new m.X509Certificate(`-----BEGIN CERTIFICATE-----
|
|
2
2
|
MIIFDDCCAvQCCQCWGBewlWbp0DANBgkqhkiG9w0BAQsFADBIMQswCQYDVQQGEwJE
|
|
3
3
|
RTEPMA0GA1UECAwGQmVybGluMQ8wDQYDVQQHDAZCZXJsaW4xFzAVBgNVBAMMDmxp
|
|
4
4
|
Y2Vuc2UubjhuLmlvMB4XDTIyMDYyNDA0MDkzM1oXDTQ5MTEwOTA0MDkzM1owSDEL
|
|
@@ -26,7 +26,7 @@ uMNs3MjEmfbaBV1K0GKG5UToF9UmUxxVmTcRUZrAQX+yBkRezDTpOQuRnB58BDQP
|
|
|
26
26
|
A62lcgZlikzJw3lHue33qAudyUrUmjfHGll7GFQNeLO42jPMeM4NJiNIrBZ7j0uD
|
|
27
27
|
4slHdDi/44PHcKchvde/5k7ZJMi6OC1Vu+bOnKvzhnWQIOkHFQ55m13oslV2ozZT
|
|
28
28
|
/oqhn/8/LeV0ooZuYnBeRkRTveniUeho2OFe5xZvWSSfuBrbHt9+zBg+5MWPUTIJ
|
|
29
|
-
-----END CERTIFICATE-----`),this.config.autoRenewEnabled=this.config.autoRenewEnabled??!0,this.config.renewOnInit=this.config.renewOnInit??!1,this.config.offlineMode=this.config.offlineMode??!1,this.config.autoRenewOffset=this.config.autoRenewOffset??60*60*72,this.config.server=this.config.server??"https://license.n8n.io/v1"}get isInitialized(){return!!this.initializationPromise}log(e,t){this.logger[t](`[license SDK] ${e}`)}async initialize(){return this.initializationPromise?this.initializationPromise:(this.initializationPromise=this._doInitialization(),await this.initializationPromise)}async _doInitialization(){(0,
|
|
29
|
+
-----END CERTIFICATE-----`),this.config.autoRenewEnabled=this.config.autoRenewEnabled??!0,this.config.renewOnInit=this.config.renewOnInit??!1,this.config.offlineMode=this.config.offlineMode??!1,this.config.autoRenewOffset=this.config.autoRenewOffset??60*60*72,this.config.detachFloatingOnShutdown=this.config.detachFloatingOnShutdown??!0,this.config.server=this.config.server??"https://license.n8n.io/v1"}get isInitialized(){return!!this.initializationPromise}log(e,t){this.logger[t](`[license SDK] ${e}`)}async initialize(){return this.initializationPromise?this.initializationPromise:(this.initializationPromise=this._doInitialization(),await this.initializationPromise)}async _doInitialization(){(0,F.ok)(!this.initializationPromise,"Initialization already in progress"),this.deviceFingerprint=await this.computeDeviceFingerprint(),this.log(`initializing for deviceFingerprint ${this.deviceFingerprint}`,"debug"),await this.initCert(),this.clearRepeatingTimer(this.upcomingEntitlementChangesCheckTimer),this.upcomingEntitlementChangesCheckTimer=this.setupRepeatingTimer(()=>this.setTimerForNextEntitlementChange(),h),this.config.renewOnInit&&this.config.autoRenewEnabled&&this.hasCert()&&(this.licenseCert.detachedEntitlementsCount>0||this.isOlderThan(this.licenseCert.issuedAt,24*60*60*1e3))?await this.renewalCron({force:!0}):this.log("Skipping renewal on init because cert was issued less than 24 hours ago or not initialized","debug"),this.config.autoRenewEnabled&&(this.clearRepeatingTimer(this.renewalTimer),this.renewalTimer=this.setupRepeatingTimer(()=>this.renewalCron({force:!1}),h))}setupSingleTimer(e,t){return setTimeout(e,t)}clearSingleTimer(e){e&&clearTimeout(e)}setupRepeatingTimer(e,t){return setInterval(e,t)}clearRepeatingTimer(e){e&&clearInterval(e)}isOlderThan(e,t){return Date.now()-e.getTime()>t}async reload(){await this.reset(),await this.initialize()}async reset(){this.initializationPromise&&await this.initializationPromise,this.clearRepeatingTimer(this.renewalTimer),this.renewalTimer=void 0,this.clearRepeatingTimer(this.upcomingEntitlementChangesCheckTimer),this.upcomingEntitlementChangesCheckTimer=void 0,this.clearSingleTimer(this.entitlementChangeTimer),this.entitlementChangeTimer=void 0,this.licenseCert=void 0,this.deviceFingerprint=void 0,this.initializationPromise=void 0}async computeDeviceFingerprint(){return this.config.deviceFingerprint&&typeof this.config.deviceFingerprint=="function"?await this.config.deviceFingerprint():await(0,b.machineId)()}async activate(e){if(!this.isInitialized)throw new Error("activation failed because SDK was not yet initialized");if(this.isShuttingDown)throw new Error("activation failed because SDK is shutting down");if(this.config.offlineMode)throw new Error("activation failed because SDK is in offline mode");let t={reservationId:e,tenantId:this.config.tenantId,productIdentifier:this.config.productIdentifier,deviceFingerprint:this.deviceFingerprint};this.hasCert()&&(t.consumerId=this.licenseCert.consumerId,t.renewalToken=this.licenseCert.renewalToken);let i;try{i=await d(`${this.config.server}/activate`,t,{timeoutInMs:1e4,productIdentifier:this.config.productIdentifier})}catch(n){throw this.log("license activation failed: "+n.message,"warn"),new Error(n.message)}if(i.status==200){if(!i.data.hasOwnProperty("licenseKey")||!i.data.hasOwnProperty("x509"))throw this.log("unexpected server response","warn"),new Error("unexpected server response");let n=this.stringifyCertContainer({licenseKey:i.data.licenseKey,x509:i.data.x509});await this.config.saveCertStr(n),await this.initCert(),this.log("license successfully activated","info"),(i.data.detachedEntitlementsCount??!1)&&this.log(`skipped importing ${i.data.detachedEntitlementsCount} floating entitlements which are currently in use elsewhere`,"info")}else{let n=`license activation failed: ${i.data.message??"unknown reason"}`,s=new Error(n);throw i.data.errorId&&(s.errorId=i.data.errorId),this.log(n,"warn"),s}}async renew(){return this._renew({cause:"request"})}async _renew({detachFloatingEntitlements:e=!1,cause:t="unknown"}={}){if(!this.hasCert())throw new Error("renewal failed because current cert is not initialized");if(this.licenseCert.isEphemeral)return;if(this.isTerminated())throw new Error("renewal failed because current cert was terminated");if(this.config.offlineMode)throw new Error("renewal failed because SDK is in offline mode");if(this.config.tenantId!==this.licenseCert.tenantId)throw new Error("renewal failed because tenant ID does not match");if(t!=="request"&&this.licenseCert.deviceLock&&this.deviceFingerprint!==this.licenseCert.deviceFingerprint)throw new Error("renewal failed because device fingerprint does not match");let[i,n]=await Promise.all([this.config.collectUsageMetrics?this.config.collectUsageMetrics():[],this.config.collectPassthroughData?this.config.collectPassthroughData():{}]),s;try{s=await d(`${this.config.server}/renew`,{consumerId:this.licenseCert.consumerId,tenantId:this.config.tenantId,deviceFingerprint:this.deviceFingerprint,productIdentifier:this.config.productIdentifier,renewalToken:this.licenseCert.renewalToken,detachFloatingEntitlements:e,cause:t,usageMetrics:i,passthroughData:n},{timeoutInMs:1e4,productIdentifier:this.config.productIdentifier})}catch(o){throw this.log("license renewal failed: "+o.message,"warn"),new Error(o.message)}let a=s.data;if(s.status==200){if(!a.hasOwnProperty("licenseKey")||!a.hasOwnProperty("x509"))throw this.log("license renewal failed: unexpected server response","warn"),new Error("unexpected server response");let o=this.stringifyCertContainer({licenseKey:a.licenseKey,x509:a.x509});await this.config.saveCertStr(o),this.log("license successfully renewed","debug"),(a.detachedEntitlementsCount??!1)&&(e?this.log(`${a.detachedEntitlementsCount} floating entitlements were returned to the pool`,"info"):this.log(`skipped importing ${a.detachedEntitlementsCount} floating entitlements which are currently in use elsewhere`,"info")),await this.initCert()}else{let o=`license renewal failed: ${a.message??"unknown reason"}`;this.log(o,"warn");let l=new Error(o);throw a.errorId&&(l.errorId=a.errorId,["NOT_FOUND","CONSUMER_TERMINATED"].includes(a.errorId)&&(this.log("license was terminated by the server. Deleting local cert.","warn"),await this.config.saveCertStr(""),await this.initCert())),l}}hasCert(){return!!this.licenseCert}isTerminated(){if(!this.hasCert())throw new Error("Cert is not initialized");let e=new Date;return this.licenseCert.terminatesAt<e}getExpiryDate(){if(!this.hasCert())throw new Error("Cert is not initialized");return this.licenseCert.expiresAt}getTerminationDate(){if(!this.hasCert())throw new Error("Cert is not initialized");return this.licenseCert.terminatesAt}isValid(e=!0){let t=s=>{e&&this.log(s,"error")};if(!this.hasCert())return t("cert is invalid because it is undefined"),!1;let i=this.licenseCert,n=new Date;return i.expiresAt<n?(t("cert is invalid because it has expired"),!1):i.terminatesAt<n?(t("cert is invalid because it was terminated"),!1):i.createdAt.getTime()-3e5>n.getTime()?(t("cert is invalid because system clock is out of sync"),!1):i.deviceLock&&this.deviceFingerprint!==i.deviceFingerprint?(t("cert is invalid because device fingerprint does not match"),!1):this.config.tenantId!==i.tenantId?(t("cert is invalid because tenant ID does not match"),!1):!0}hasFeatureEnabled(e,t=!0){return!!this.getFeatureValue(e,t)}hasFeatureDefined(e,t=!0){return this.getFeatureValue(e,t)!==void 0}hasQuotaLeft(e,t){let i=this.getFeatureValue(e);if(i===void 0)return!1;if(typeof i!="number")throw new Error(`${e} cannot be used as quota as it is not numeric`);return i===-1?!0:Math.ceil(t)<Math.ceil(i)}getFeatureValue(e,t=!0){if(!this.hasCert()||t&&!this.isValid())return;let i=this.getFeatures();if(i.hasOwnProperty(e))return i[e]}updateCurrentFeatures(){if(!this.hasCert())return;let e=new Date;(this.licenseCert.expiresAt<e||this.licenseCert.terminatesAt<e)&&(this.currentFeatures={}),this.currentFeatures=this.licenseCert.entitlements.filter(t=>t.validFrom<=e&&t.validTo>e).sort((t,i)=>t.validFrom.getTime()-i.validFrom.getTime()).reduce((t,i)=>({...t,...i.features,...i.featureOverrides}),{})}getFeatures(){return this.hasCert()?this.currentFeatures??{}:{}}getCurrentEntitlements(){if(!this.hasCert())return[];let e=new Date;return this.licenseCert.entitlements.filter(t=>t.validFrom<=e&&t.validTo>e)}getManagementJwt(){return this.licenseCert?this.licenseCert.managementJwt:""}async getCertStr(){return this.config.loadCertStr()}getConsumerId(){return this.licenseCert?.consumerId}isRenewalDue(){if(!this.licenseCert||this.licenseCert.isEphemeral)return!1;let e=Date.now(),t=1e3*60*15,i=1e3*60*20,n=this.licenseCert.expiresAt.getTime(),s=this.licenseCert.issuedAt.getTime(),a=this.licenseCert.terminatesAt.getTime(),o=e>n-this.config.autoRenewOffset*1e3&&e<a,l=this.getCurrentEntitlements().find(w=>e>=w.validTo.getTime()-t&&e<=w.validTo.getTime())!==void 0&&s<e-i;return o||l}formatDuration(e){let t=Math.floor(e/3600),i=Math.floor(e%3600/60),n=e%60;return`${t}h ${i}m ${n}s`}toString(){return`## CONSUMER CONFIG ##
|
|
30
30
|
tenantId: ${this.config.tenantId??"<n/a>"}
|
|
31
31
|
productIdentifier: ${this.config.productIdentifier??"<n/a>"}
|
|
32
32
|
deviceFingerprint: ${this.deviceFingerprint??"<n/a>"}
|
|
@@ -55,5 +55,5 @@ validFrom: ${e.validFrom}
|
|
|
55
55
|
validTo: ${e.validTo}
|
|
56
56
|
features: ${JSON.stringify(e.features)}
|
|
57
57
|
featureOverrides: ${JSON.stringify(e.featureOverrides)}
|
|
58
|
-
`).join("")}triggerOnFeatureChangeCallback(){this.config.onFeatureChange&&this.config.onFeatureChange(this.currentFeatures??{})}setTimerForNextEntitlementChange(){if(!this.hasCert())return;let e=Date.now(),t=new Set;t.add(this.licenseCert.expiresAt.getTime()-e),t.add(this.licenseCert.terminatesAt.getTime()-e);let i=[...this.licenseCert.entitlements.reduce((s,a)=>(s.add(a.validFrom.getTime()-e),s.add(a.validTo.getTime()-e),s),t)].filter(s=>s>=0&&s<=h).sort((s,a)=>s-a);if(i.length===0)return;let n=i[0];this.clearSingleTimer(this.entitlementChangeTimer),this.entitlementChangeTimer=this.setupSingleTimer(()=>{this.updateCurrentFeatures(),this.triggerOnFeatureChangeCallback(),this.setTimerForNextEntitlementChange()},n+1e3)}async renewalCron({force:e}){if(e||this.isRenewalDue()){this.log("attempting license renewal","debug");try{await this._renew({cause:e?"startup":"auto"})}catch{}}}async initCert(){if(!this.isShuttingDown)try{let e=await this.getCertStr();if(!e){this.licenseCert=void 0;return}if(e.length<50)throw new Error("cert string is undefined or too short");let{x509:t,licenseKey:i}=this.parseLicenseCertContainerStr(e);if(this.x509Cert=new
|
|
58
|
+
`).join("")}triggerOnFeatureChangeCallback(){this.config.onFeatureChange&&this.config.onFeatureChange(this.currentFeatures??{})}setTimerForNextEntitlementChange(){if(!this.hasCert())return;let e=Date.now(),t=new Set;t.add(this.licenseCert.expiresAt.getTime()-e),t.add(this.licenseCert.terminatesAt.getTime()-e);let i=[...this.licenseCert.entitlements.reduce((s,a)=>(s.add(a.validFrom.getTime()-e),s.add(a.validTo.getTime()-e),s),t)].filter(s=>s>=0&&s<=h).sort((s,a)=>s-a);if(i.length===0)return;let n=i[0];this.clearSingleTimer(this.entitlementChangeTimer),this.entitlementChangeTimer=this.setupSingleTimer(()=>{this.updateCurrentFeatures(),this.triggerOnFeatureChangeCallback(),this.setTimerForNextEntitlementChange()},n+1e3)}async renewalCron({force:e}){if(e||this.isRenewalDue()){this.log("attempting license renewal","debug");try{await this._renew({cause:e?"startup":"auto"})}catch{}}}async initCert(){if(!this.isShuttingDown)try{let e=await this.getCertStr();if(!e){this.licenseCert=void 0;return}if(e.length<50)throw new Error("cert string is undefined or too short");let{x509:t,licenseKey:i}=this.parseLicenseCertContainerStr(e);if(this.x509Cert=new m.X509Certificate(t),!this.x509Cert.checkIssued(this.getIssuerCert()))throw new Error("cert was not issued by an approved issuer");let s=this.x509Cert.publicKey.export({format:"pem",type:"pkcs1"});this.key=new R.default(s),this.licenseCert=this.parseLicenseKeyStr(i),this.updateCurrentFeatures(),this.setTimerForNextEntitlementChange()}catch(e){this.log(`cert could not be initialized. ${e instanceof Error?e.message:""}`,"error")}}stringifyCertContainer(e){let t=JSON.stringify(e);return Buffer.from(t).toString("base64")}parseLicenseCertContainerStr(e){let t=Buffer.from(e,"base64").toString("ascii"),i=JSON.parse(t);if(!i.hasOwnProperty("licenseKey")||!i.hasOwnProperty("x509"))throw new Error("license cert container could not be parsed");return i}parseLicenseKeyStr(e){let t=this.validateLicenseKey(e),i={...t};return i.createdAt=new Date(t.createdAt),i.issuedAt=new Date(t.issuedAt),i.expiresAt=new Date(t.expiresAt),i.terminatesAt=new Date(t.terminatesAt),i.detachedEntitlementsCount=t.detachedEntitlementsCount??0,i.entitlements=i.entitlements.map(n=>(n.validFrom=new Date(n.validFrom),n.validTo=new Date(n.validTo),n)),i}validateLicenseKey(e){e=e.replace(/(\r\n|\n|\r)/gm,"");let t=e.match(/^-----BEGIN LICENSE KEY-----(?<encryptedSymmetricKey>.+\|\|)(?<encryptedData>.+)\|\|(?<signature>.+)-----END LICENSE KEY-----$/);if(!t)throw new Error("license key could not be parsed");let i=t.groups.encryptedSymmetricKey,n=t.groups.encryptedData,s=t.groups.signature,a,o;try{a=this.key.decryptPublic(i,"utf8")}catch{throw new Error("Invalid data: Could not extract symmetric key")}try{o=f.default.AES.decrypt(n,a).toString(f.default.enc.Utf8)}catch{throw new Error("Invalid Data: Could not decrypt data with key found")}if(this.key.verify(Buffer.from(o),s,"utf8","base64"))return JSON.parse(o);throw new Error("License Key signature invalid")}getIssuerCert(){return this.x509IssuerCert}async clear(){try{await this.detachFloatingEntitlements()}catch(e){this.log(`failed to detach floating entitlements (${e}). Continuing with clearing license certificate`,"warn")}finally{await this.config.saveCertStr(""),await this.initCert()}}async shutdown(){this.isShuttingDown=!0,this.clearRepeatingTimer(this.renewalTimer),this.clearRepeatingTimer(this.upcomingEntitlementChangesCheckTimer),this.clearSingleTimer(this.entitlementChangeTimer),this.config.detachFloatingOnShutdown&&await this.detachFloatingEntitlements()}async detachFloatingEntitlements(){if(!this.hasCert())return;this.licenseCert.entitlements.some(t=>t.isFloatable??!1)&&await this._renew({detachFloatingEntitlements:!0,cause:"shutdown"})}enableAutoRenewals(){this.config.autoRenewEnabled!==!0&&(this.config.autoRenewEnabled=!0,this.log("License autorenewals enabled","info"),this.clearRepeatingTimer(this.renewalTimer),this.renewalTimer=this.setupRepeatingTimer(()=>this.renewalCron({force:!1}),h))}disableAutoRenewals(){this.config.autoRenewEnabled!==!1&&(this.config.autoRenewEnabled=!1,this.log("License autorenewals disabled","info"),this.clearRepeatingTimer(this.renewalTimer),this.renewalTimer=void 0)}};0&&(module.exports={AUTORENEWAL_INTERVAL,LicenseManager});
|
|
59
59
|
//# sourceMappingURL=LicenseManager.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/LicenseManager.ts","../src/httpRequest.ts"],"sourcesContent":["import CryptoJS from 'crypto-js'\nimport { machineId } from 'node-machine-id'\nimport NodeRSA from 'node-rsa'\nimport { ok } from 'node:assert'\nimport { X509Certificate } from 'node:crypto'\nimport { postRequest } from './httpRequest'\n\n/** How often (ms) to renew the license periodically. */\nexport const AUTORENEWAL_INTERVAL = 15 * 60 * 1000 // 15 minutes\n\nexport type TLicenseManagerConfig = {\n server?: string\n tenantId: number\n productIdentifier: string\n\n /**\n * Whether to renew the license periodically.\n *\n * @default true\n */\n autoRenewEnabled?: boolean\n offlineMode?: boolean\n renewOnInit?: boolean\n autoRenewOffset?: number\n loadCertStr: () => Promise<TLicenseBlock>\n saveCertStr: (cert: TLicenseBlock) => Promise<void>\n collectUsageMetrics?: () => Promise<Array<TUsageMetric>>\n collectPassthroughData?: () => Promise<TPassthroughData>\n deviceFingerprint?: () => string | Promise<string>\n onFeatureChange?: (features: TFeatures) => any\n logger?: TLogger\n}\n\nexport type TLicenseBlock = string\n\nexport type TLicenseContainer = {\n licenseKey: string\n x509: string\n}\n\nexport type TFeatures = { [key: string]: boolean | number | string }\n\nexport type TUsageMetric = { name: string; value: number }\n\nexport type TPassthroughData = Record<string, unknown>\n\nexport type TMetadata = {\n [key: string]: boolean | number | string | Array<any> | {}\n}\n\nexport type TEntitlement = {\n id: string\n productId: string\n productMetadata: TMetadata\n features: TFeatures\n featureOverrides: TFeatures\n validFrom: Date\n validTo: Date\n isFloatable: boolean\n}\n\nexport type TLicenseCertObj = {\n consumerId: string\n consumerRef?: string\n version: number\n tenantId: number\n renewalToken: string\n deviceLock: boolean\n deviceFingerprint: string\n createdAt: Date\n issuedAt: Date\n expiresAt: Date\n terminatesAt: Date\n entitlements: TEntitlement[]\n /**\n * Indicates the number of floating entitlements that are not attached to the consumer\n * because they are in use elsewhere at the time of renewal.\n */\n detachedEntitlementsCount: number\n managementJwt: string\n /**\n * Specifies whether the license is ephemeral and therefore does not have corresponding entries in the license server DB.\n */\n isEphemeral: boolean\n}\n\nexport type TLogger = {\n error: Function\n warn: Function\n info: Function\n debug: Function\n}\n\ntype SingleTimer = NodeJS.Timeout\ntype RepeatingTimer = NodeJS.Timeout\n\nconst enum LogLevel {\n ERROR = 'error',\n WARN = 'warn',\n INFO = 'info',\n DEBUG = 'debug',\n}\n\nexport class LicenseManager {\n public config: TLicenseManagerConfig\n\n private initializationPromise?: Promise<void>\n private key?: NodeRSA\n private logger: TLogger\n protected licenseCert?: TLicenseCertObj\n private x509Cert?: X509Certificate\n private x509IssuerCert: X509Certificate\n private deviceFingerprint?: string\n private renewalTimer?: RepeatingTimer\n private upcomingEntitlementChangesCheckTimer?: RepeatingTimer\n private entitlementChangeTimer?: SingleTimer\n private currentFeatures?: TFeatures\n private isShuttingDown = false\n\n get isInitialized() {\n return !!this.initializationPromise\n }\n\n constructor(config: TLicenseManagerConfig) {\n this.config = config\n\n if (this.config.logger) {\n this.logger = this.config.logger\n } else {\n this.logger = {\n error() {\n console.log('ERROR:', ...arguments)\n },\n warn() {\n console.log('WARN:', ...arguments)\n },\n info() {\n console.log('INFO:', ...arguments)\n },\n debug() {\n console.log('DEBUG:', ...arguments)\n },\n }\n }\n\n this.x509IssuerCert = new X509Certificate(\n '-----BEGIN CERTIFICATE-----\\n' +\n 'MIIFDDCCAvQCCQCWGBewlWbp0DANBgkqhkiG9w0BAQsFADBIMQswCQYDVQQGEwJE\\n' +\n 'RTEPMA0GA1UECAwGQmVybGluMQ8wDQYDVQQHDAZCZXJsaW4xFzAV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h6C92cJqy6iehS8c77r1prj62gr6Acdy5QGh8\\n' +\n 'ax30ANDbPtkezVIIBk+0JjLkMxr3mwqCRsPgMshPcxhZwEafmZrWPPGRVsOfukB3\\n' +\n 'Gp10cIv1YmZ7AFY4i/izj5184+A+GjxrJBULQG1JfX4c7KW06Kaps85AaX/Tp0fl\\n' +\n '/hZ6oUe48aSSTuAW38hWZ5jCpBqfFyQ15ablJZt0fB8NkXEdFUcUEt/OHJfqF5fP\\n' +\n 'Nt5PWC1AuBxzSbzjwabOy/M4r8m5CzCeXSIjqbcsAq52myMoxvNrjKRtucQ7CjqK\\n' +\n 'LR6WdhMf+NLvyTI+evXMoXpDzlevkCpz17uDiDt9XrmvLSf3Ff8mdTRwzVmOmHfc\\n' +\n 'Ruz5v7WBR4cpBR/sC+WxOw9heLMHgYhPyRUM4voo55EcJGusXr/iavblBAnI0GUw\\n' +\n 'uMNs3MjEmfbaBV1K0GKG5UToF9UmUxxVmTcRUZrAQX+yBkRezDTpOQuRnB58BDQP\\n' +\n 'A62lcgZlikzJw3lHue33qAudyUrUmjfHGll7GFQNeLO42jPMeM4NJiNIrBZ7j0uD\\n' +\n '4slHdDi/44PHcKchvde/5k7ZJMi6OC1Vu+bOnKvzhnWQIOkHFQ55m13oslV2ozZT\\n' +\n '/oqhn/8/LeV0ooZuYnBeRkRTveniUeho2OFe5xZvWSSfuBrbHt9+zBg+5MWPUTIJ\\n' +\n '-----END CERTIFICATE-----'\n )\n\n //set defaults for not set config properties:\n this.config.autoRenewEnabled = this.config.autoRenewEnabled ?? true\n this.config.renewOnInit = this.config.renewOnInit ?? false\n this.config.offlineMode = this.config.offlineMode ?? false\n this.config.autoRenewOffset = this.config.autoRenewOffset ?? 60 * 60 * 72 // default: 72 hours\n this.config.server = this.config.server ?? 'https://license.n8n.io/v1'\n }\n\n log(msg: string, logLevel: LogLevel) {\n this.logger[logLevel](`[license SDK] ${msg}`)\n }\n\n async initialize() {\n if (this.initializationPromise) {\n return this.initializationPromise\n }\n\n this.initializationPromise = this._doInitialization()\n\n return await this.initializationPromise\n }\n\n /** Initializes the license manager */\n private async _doInitialization() {\n ok(!this.initializationPromise, 'Initialization already in progress')\n\n this.deviceFingerprint = await this.computeDeviceFingerprint()\n this.log(\n `initializing for deviceFingerprint ${this.deviceFingerprint}`,\n LogLevel.DEBUG\n )\n\n await this.initCert() // doesn't throw!\n\n // Clear and set up periodic timer for entitlement changes\n this.clearRepeatingTimer(this.upcomingEntitlementChangesCheckTimer)\n this.upcomingEntitlementChangesCheckTimer = this.setupRepeatingTimer(\n () => this.setTimerForNextEntitlementChange(),\n AUTORENEWAL_INTERVAL\n )\n\n // Perform initial renewal if conditions are met\n // If local cert has detachedEntitlementsCount marker, a force renewal makes sense as floating entitlements might get attached\n // Otherwise do the renewal only if the cert is older than 24 hours\n if (\n this.config.renewOnInit &&\n this.config.autoRenewEnabled &&\n this.hasCert() &&\n (this.licenseCert.detachedEntitlementsCount > 0 ||\n this.isOlderThan(this.licenseCert.issuedAt, 24 * 60 * 60 * 1000)) // 24 hours\n ) {\n await this.renewalCron({ force: true })\n } else {\n this.log(\n 'Skipping renewal on init because cert was issued less than 24 hours ago or not initialized',\n LogLevel.DEBUG\n )\n }\n\n // Set up periodic renewal if enabled\n if (this.config.autoRenewEnabled) {\n this.clearRepeatingTimer(this.renewalTimer)\n this.renewalTimer = this.setupRepeatingTimer(\n () => this.renewalCron({ force: false }),\n AUTORENEWAL_INTERVAL\n )\n }\n }\n\n private setupSingleTimer(\n callback: () => void,\n interval: number\n ): SingleTimer {\n return setTimeout(callback, interval)\n }\n\n clearSingleTimer(timer: SingleTimer | undefined) {\n if (timer) {\n clearTimeout(timer)\n }\n }\n\n setupRepeatingTimer(callback: () => void, interval: number): RepeatingTimer {\n return setInterval(callback, interval)\n }\n\n clearRepeatingTimer(timer: RepeatingTimer | undefined) {\n if (timer) {\n clearInterval(timer)\n }\n }\n\n private isOlderThan(date: Date, durationInMs: number) {\n return Date.now() - date.getTime() > durationInMs\n }\n\n async reload() {\n await this.reset()\n await this.initialize()\n }\n\n async reset() {\n // Make sure initialization is not ongoing before resetting\n if (this.initializationPromise) {\n await this.initializationPromise\n }\n this.clearRepeatingTimer(this.renewalTimer)\n this.renewalTimer = undefined\n this.clearRepeatingTimer(this.upcomingEntitlementChangesCheckTimer)\n this.upcomingEntitlementChangesCheckTimer = undefined\n this.clearSingleTimer(this.entitlementChangeTimer)\n this.entitlementChangeTimer = undefined\n\n this.licenseCert = undefined\n this.deviceFingerprint = undefined\n this.initializationPromise = undefined\n }\n\n async computeDeviceFingerprint() {\n if (\n this.config.deviceFingerprint &&\n typeof this.config.deviceFingerprint === 'function'\n ) {\n return await this.config.deviceFingerprint()\n }\n return await machineId()\n }\n\n async activate(reservationId: string) {\n if (!this.isInitialized) {\n throw new Error('activation failed because SDK was not yet initialized')\n }\n\n if (this.isShuttingDown) {\n throw new Error('activation failed because SDK is shutting down')\n }\n\n if (this.config.offlineMode) {\n throw new Error('activation failed because SDK is in offline mode')\n }\n\n const postData: {\n reservationId: string\n tenantId: number\n productIdentifier: string\n deviceFingerprint: string\n consumerId?: string\n renewalToken?: string\n } = {\n reservationId,\n tenantId: this.config.tenantId,\n productIdentifier: this.config.productIdentifier,\n deviceFingerprint: this.deviceFingerprint!,\n }\n\n if (this.hasCert()) {\n postData.consumerId = this.licenseCert.consumerId\n postData.renewalToken = this.licenseCert.renewalToken\n }\n\n type ResponseDataFormat = {\n licenseKey?: string\n x509?: string\n detachedEntitlementsCount?: number\n message?: string\n errorId?: string\n }\n\n type PostRequestResponse = Awaited<\n ReturnType<typeof postRequest<ResponseDataFormat>>\n >\n\n let response: PostRequestResponse\n\n try {\n response = await postRequest<{\n licenseKey?: string\n x509?: string\n message?: string\n errorId?: string\n }>(`${this.config.server!}/activate`, postData, { timeoutInMs: 10000 })\n } catch (error) {\n this.log(\n 'license activation failed: ' + (error as Error).message,\n LogLevel.WARN\n )\n throw new Error((error as Error).message)\n }\n\n if (response.status == 200) {\n if (\n !response.data.hasOwnProperty('licenseKey') ||\n !response.data.hasOwnProperty('x509')\n ) {\n this.log('unexpected server response', LogLevel.WARN)\n throw new Error('unexpected server response')\n }\n const containerStr = this.stringifyCertContainer({\n licenseKey: response.data.licenseKey,\n x509: response.data.x509,\n } as TLicenseContainer)\n await this.config.saveCertStr(containerStr)\n await this.initCert()\n this.log('license successfully activated', LogLevel.INFO)\n if (response.data.detachedEntitlementsCount ?? 0 > 0) {\n this.log(\n `skipped importing ${response.data.detachedEntitlementsCount} floating entitlements which are currently in use elsewhere`,\n LogLevel.INFO\n )\n }\n } else {\n const errorMsg = `license activation failed: ${\n response.data.message ?? 'unknown reason'\n }`\n const e = new Error(errorMsg) as Error & { errorId?: string }\n\n if (response.data.errorId) {\n e.errorId = response.data.errorId\n }\n\n this.log(errorMsg, LogLevel.WARN)\n throw e\n }\n }\n\n async renew() {\n return this._renew({ cause: 'request' })\n }\n\n async _renew({\n detachFloatingEntitlements = false,\n cause = 'unknown',\n }: {\n detachFloatingEntitlements?: Boolean\n cause?: 'startup' | 'shutdown' | 'request' | 'auto' | 'unknown'\n } = {}) {\n if (!this.hasCert()) {\n throw new Error('renewal failed because current cert is not initialized')\n }\n\n if (this.licenseCert.isEphemeral) {\n return\n }\n\n if (this.isTerminated()) {\n throw new Error('renewal failed because current cert was terminated')\n }\n\n if (this.config.offlineMode) {\n throw new Error('renewal failed because SDK is in offline mode')\n }\n\n if (this.config.tenantId !== this.licenseCert.tenantId) {\n throw new Error('renewal failed because tenant ID does not match')\n }\n\n // error out if device fingerprint does not match but allow renewal on explicit request\n // as the consumer might have been changed to more permissive settings on the server\n if (\n cause !== 'request' &&\n this.licenseCert.deviceLock &&\n this.deviceFingerprint !== this.licenseCert.deviceFingerprint\n ) {\n throw new Error(\n 'renewal failed because device fingerprint does not match'\n )\n }\n\n const [usageMetrics, passthroughData] = await Promise.all([\n this.config.collectUsageMetrics ? this.config.collectUsageMetrics() : [],\n this.config.collectPassthroughData\n ? this.config.collectPassthroughData()\n : {},\n ])\n\n type ResponseDataFormat = {\n licenseKey?: string\n x509?: string\n detachedEntitlementsCount?: number\n message?: string\n errorId?: string\n }\n\n type PostRequestResponse = Awaited<\n ReturnType<typeof postRequest<ResponseDataFormat>>\n >\n\n let response: PostRequestResponse\n\n try {\n response = await postRequest<ResponseDataFormat>(\n `${this.config.server!}/renew`,\n {\n consumerId: this.licenseCert.consumerId,\n tenantId: this.config.tenantId,\n deviceFingerprint: this.deviceFingerprint,\n productIdentifier: this.config.productIdentifier,\n renewalToken: this.licenseCert.renewalToken,\n detachFloatingEntitlements,\n cause,\n usageMetrics,\n passthroughData,\n },\n { timeoutInMs: 10000 }\n )\n } catch (error) {\n this.log(\n 'license renewal failed: ' + (error as Error).message,\n LogLevel.WARN\n )\n throw new Error((error as Error).message)\n }\n\n const responseData = response.data\n\n if (response.status == 200) {\n if (\n !responseData.hasOwnProperty('licenseKey') ||\n !responseData.hasOwnProperty('x509')\n ) {\n this.log(\n 'license renewal failed: unexpected server response',\n LogLevel.WARN\n )\n throw new Error('unexpected server response')\n }\n const containerStr = this.stringifyCertContainer({\n licenseKey: responseData.licenseKey,\n x509: responseData.x509,\n } as TLicenseContainer)\n await this.config.saveCertStr(containerStr)\n this.log('license successfully renewed', LogLevel.DEBUG)\n if (responseData.detachedEntitlementsCount ?? 0 > 0) {\n this.log(\n `skipped importing ${responseData.detachedEntitlementsCount} floating entitlements which are currently in use elsewhere`,\n LogLevel.INFO\n )\n }\n await this.initCert()\n } else {\n const errorMsg = `license renewal failed: ${\n responseData.message ?? 'unknown reason'\n }`\n\n this.log(errorMsg, LogLevel.WARN)\n\n const e = new Error(errorMsg) as Error & { errorId?: string }\n\n if (responseData.errorId) {\n e.errorId = responseData.errorId\n\n if (\n ['NOT_FOUND', 'CONSUMER_TERMINATED'].includes(responseData.errorId)\n ) {\n this.log(\n 'license was terminated by the server. Deleting local cert.',\n LogLevel.WARN\n )\n await this.config.saveCertStr('')\n await this.initCert()\n }\n }\n\n throw e\n }\n }\n\n private hasCert(): this is { licenseCert: TLicenseCertObj } {\n return !!this.licenseCert\n }\n\n isTerminated(): boolean {\n if (!this.hasCert()) {\n throw new Error('Cert is not initialized')\n }\n\n const now = new Date()\n\n return this.licenseCert.terminatesAt < now\n }\n\n getExpiryDate(): Date {\n if (!this.hasCert()) {\n throw new Error('Cert is not initialized')\n }\n\n return this.licenseCert.expiresAt\n }\n\n getTerminationDate(): Date {\n if (!this.hasCert()) {\n throw new Error('Cert is not initialized')\n }\n\n return this.licenseCert.terminatesAt\n }\n\n isValid(useLogger = true): boolean {\n const error = (msg: string) => {\n if (useLogger) {\n this.log(msg, LogLevel.ERROR)\n }\n }\n\n if (!this.hasCert()) {\n error('cert is invalid because it is undefined')\n return false\n }\n\n const cert = this.licenseCert as TLicenseCertObj\n const now = new Date()\n\n if (cert.expiresAt < now) {\n error('cert is invalid because it has expired')\n return false\n }\n\n if (cert.terminatesAt < now) {\n error('cert is invalid because it was terminated')\n return false\n }\n\n //allow clocks to be out of sync by no more than 300,000 ms / = 5 minutes\n if (cert.createdAt.getTime() - 300000 > now.getTime()) {\n error('cert is invalid because system clock is out of sync')\n return false\n }\n\n if (cert.deviceLock && this.deviceFingerprint !== cert.deviceFingerprint) {\n error('cert is invalid because device fingerprint does not match')\n return false\n }\n\n if (this.config.tenantId !== cert.tenantId) {\n error('cert is invalid because tenant ID does not match')\n return false\n }\n\n return true\n }\n\n hasFeatureEnabled(\n feature: string,\n requireValidCert: boolean = true\n ): boolean {\n return this.getFeatureValue(feature, requireValidCert) ? true : false\n }\n\n hasFeatureDefined(\n feature: string,\n requireValidCert: boolean = true\n ): boolean {\n return this.getFeatureValue(feature, requireValidCert) !== undefined\n ? true\n : false\n }\n\n hasQuotaLeft(quotaFeatureName: string, currentConsumption: number): boolean {\n const quota = this.getFeatureValue(quotaFeatureName)\n\n if (quota === undefined) {\n return false\n }\n\n if (typeof quota !== 'number') {\n throw new Error(\n `${quotaFeatureName} cannot be used as quota as it is not numeric`\n )\n }\n\n // -1 means unlimited quota!\n if (quota === -1) {\n return true\n }\n\n return Math.ceil(currentConsumption) < Math.ceil(quota)\n }\n\n getFeatureValue(\n feature: string,\n requireValidCert: boolean = true\n ): undefined | boolean | number | string {\n if (!this.hasCert()) {\n return undefined\n }\n\n if (requireValidCert && !this.isValid()) {\n return undefined\n }\n\n const currentFeatures = this.getFeatures()\n\n if (!currentFeatures.hasOwnProperty(feature)) {\n return undefined\n }\n\n return currentFeatures[feature]\n }\n\n private updateCurrentFeatures() {\n if (!this.hasCert()) {\n return\n }\n\n const now = new Date()\n\n if (\n this.licenseCert.expiresAt < now ||\n this.licenseCert.terminatesAt < now\n ) {\n this.currentFeatures = {} as TFeatures\n }\n\n this.currentFeatures = this.licenseCert.entitlements\n .filter(\n (entitlement) =>\n entitlement.validFrom <= now && entitlement.validTo > now\n )\n .sort(\n (entitlement1, entitlement2) =>\n entitlement1.validFrom.getTime() - entitlement2.validFrom.getTime()\n )\n .reduce((currentFeatures, entitlement) => {\n return {\n ...currentFeatures,\n ...entitlement.features,\n ...entitlement.featureOverrides,\n }\n }, {} as TFeatures)\n }\n\n getFeatures() {\n if (!this.hasCert()) {\n return {}\n }\n\n return this.currentFeatures ?? {}\n }\n\n getCurrentEntitlements() {\n if (!this.hasCert()) {\n return []\n }\n\n const now = new Date()\n\n return this.licenseCert.entitlements.filter(\n (entitlement) => entitlement.validFrom <= now && entitlement.validTo > now\n )\n }\n\n getManagementJwt() {\n if (!this.licenseCert) {\n return ''\n }\n\n return this.licenseCert.managementJwt\n }\n\n async getCertStr(): Promise<TLicenseBlock> {\n return this.config.loadCertStr()\n }\n\n getConsumerId() {\n return this.licenseCert?.consumerId\n }\n\n isRenewalDue(): boolean {\n if (!this.licenseCert || this.licenseCert.isEphemeral) {\n return false\n }\n\n const now = Date.now()\n const mins15inMs = 1000 * 60 * 15\n const mins20inMs = 1000 * 60 * 20\n const expiry = this.licenseCert.expiresAt.getTime()\n const issuedAt = this.licenseCert.issuedAt.getTime()\n const termination = this.licenseCert.terminatesAt.getTime()\n\n //consumerRenewalDue is TRUE when current time is close enough to consumer expiry and not after consumer termination\n const consumerRenewalDue =\n now > expiry - this.config.autoRenewOffset! * 1000 && now < termination\n\n //entitlementRenewalDue is TRUE when one currently valid entitlement will expire in the next 15 minutes\n //and the Cert was issued more than 20 minutes ago\n const entitlementRenewalDue =\n this.getCurrentEntitlements().find(\n (entitlement) =>\n now >= entitlement.validTo.getTime() - mins15inMs &&\n now <= entitlement.validTo.getTime()\n ) !== undefined && issuedAt < now - mins20inMs\n\n return consumerRenewalDue || entitlementRenewalDue\n }\n\n private formatDuration(seconds: number): string {\n const hours = Math.floor(seconds / 3600)\n const minutes = Math.floor((seconds % 3600) / 60)\n const remainingSeconds = seconds % 60\n\n return `${hours}h ${minutes}m ${remainingSeconds}s`\n }\n\n toString() {\n return (\n `## CONSUMER CONFIG ##\\n` +\n `tenantId: ${this.config.tenantId ?? '<n/a>'}\\n` +\n `productIdentifier: ${this.config.productIdentifier ?? '<n/a>'}\\n` +\n `deviceFingerprint: ${this.deviceFingerprint ?? '<n/a>'}\\n` +\n `autoRenewalEnabled: ${\n this.config.autoRenewEnabled ? 'true' : 'false (!)'\n }\\n` +\n `autoRenewalOffset: ${\n this.config.autoRenewOffset\n } (= ${this.formatDuration(this.config.autoRenewOffset ?? 0)})\\n` +\n '--\\n' +\n `## LICENSE CERT ##\\n` +\n `version: ${this.licenseCert?.version ?? '<n/a>'}\\n` +\n `tenantId: ${this.licenseCert?.tenantId ?? '<n/a>'} ${\n this.licenseCert?.tenantId !== this.config.tenantId ? '(!)' : ''\n }\\n` +\n `consumerId: ${this.licenseCert?.consumerId ?? '<n/a>'}\\n` +\n `deviceFingerprint: ${this.licenseCert?.deviceFingerprint ?? '<n/a>'} ${\n this.licenseCert?.deviceFingerprint !== this.deviceFingerprint\n ? '(!)'\n : ''\n }\\n` +\n `createdAt: ${this.licenseCert?.createdAt ?? '<n/a>'}\\n` +\n `issuedAt: ${this.licenseCert?.issuedAt ?? '<n/a>'}\\n` +\n `expiresAt: ${this.licenseCert?.expiresAt ?? '<n/a>'}\\n` +\n `terminatesAt: ${this.licenseCert?.terminatesAt ?? '<n/a>'}\\n` +\n `isEphemeral: ${this.licenseCert?.isEphemeral ?? '<n/a>'}\\n` +\n `isValid: ${this.isValid(false)}\\n` +\n `isRenewalDue: ${this.isRenewalDue()}\\n` +\n `detachedEntitlementsCount: ${\n this.licenseCert?.detachedEntitlementsCount ?? '<n/a>'\n }\\n` +\n `entitlements: ${this.licenseCert?.entitlements.length ?? 0}\\n` +\n this.licenseCert?.entitlements\n .map((entitlement, index) => {\n return (\n '--\\n' +\n `## ENTITLEMENT ${index + 1} ##\\n` +\n `id: ${entitlement.id}\\n` +\n `productId: ${entitlement.productId}\\n` +\n `validFrom: ${entitlement.validFrom}\\n` +\n `validTo: ${entitlement.validTo}\\n` +\n `features: ${JSON.stringify(entitlement.features)}\\n` +\n `featureOverrides: ${JSON.stringify(\n entitlement.featureOverrides\n )}\\n`\n )\n })\n .join('')\n )\n }\n\n private triggerOnFeatureChangeCallback() {\n if (this.config.onFeatureChange) {\n this.config.onFeatureChange(this.currentFeatures ?? {})\n }\n }\n\n private setTimerForNextEntitlementChange() {\n if (!this.hasCert()) {\n return\n }\n\n const now = Date.now()\n const offsets = new Set<number>()\n\n offsets.add(this.licenseCert.expiresAt.getTime() - now)\n offsets.add(this.licenseCert.terminatesAt.getTime() - now)\n\n const upcomingEventOffsets = [\n ...this.licenseCert.entitlements.reduce((offsets, entitlement) => {\n offsets.add(entitlement.validFrom.getTime() - now)\n offsets.add(entitlement.validTo.getTime() - now)\n return offsets\n }, offsets),\n ]\n .filter((offset) => offset >= 0 && offset <= AUTORENEWAL_INTERVAL) // keep if offset is within the next 15 minutes\n .sort((a, b) => a - b)\n\n //console.dir(upcomingEventOffsets.map((offset) => offset / 1000 / 60))\n\n if (upcomingEventOffsets.length === 0) {\n return\n }\n\n const timeTillNextEventInMs = upcomingEventOffsets[0]\n\n this.clearSingleTimer(this.entitlementChangeTimer)\n this.entitlementChangeTimer = this.setupSingleTimer(() => {\n this.updateCurrentFeatures()\n this.triggerOnFeatureChangeCallback()\n this.setTimerForNextEntitlementChange()\n }, timeTillNextEventInMs + 1000)\n }\n\n private async renewalCron({ force }: { force: boolean }) {\n if (force || this.isRenewalDue()) {\n this.log('attempting license renewal', LogLevel.DEBUG)\n try {\n await this._renew({ cause: force ? 'startup' : 'auto' })\n } catch (e) {}\n }\n }\n\n private async initCert() {\n if (this.isShuttingDown) {\n return\n }\n\n try {\n const containerStr = await this.getCertStr()\n if (!containerStr) {\n this.licenseCert = undefined\n return\n }\n if (containerStr.length < 50) {\n throw new Error('cert string is undefined or too short')\n }\n const { x509, licenseKey } =\n this.parseLicenseCertContainerStr(containerStr)\n this.x509Cert = new X509Certificate(x509)\n const hasApprovedIssuer = this.x509Cert.checkIssued(this.getIssuerCert())\n if (!hasApprovedIssuer) {\n throw new Error('cert was not issued by an approved issuer')\n }\n const publicKey = this.x509Cert.publicKey.export({\n format: 'pem',\n type: 'pkcs1',\n })\n this.key = new NodeRSA(publicKey)\n this.licenseCert = this.parseLicenseKeyStr(licenseKey)\n this.updateCurrentFeatures()\n this.setTimerForNextEntitlementChange()\n } catch (e) {\n this.log(\n `cert could not be initialized. ${e instanceof Error ? e.message : ''}`,\n LogLevel.ERROR\n )\n }\n }\n\n private stringifyCertContainer(container: TLicenseContainer): string {\n const containerStr = JSON.stringify(container)\n return Buffer.from(containerStr).toString('base64')\n }\n\n private parseLicenseCertContainerStr(\n stringifiedContainer: string\n ): TLicenseContainer {\n const containerStr = Buffer.from(stringifiedContainer, 'base64').toString(\n 'ascii'\n )\n const container = JSON.parse(containerStr)\n if (\n !container.hasOwnProperty('licenseKey') ||\n !container.hasOwnProperty('x509')\n ) {\n throw new Error('license cert container could not be parsed')\n }\n\n return container as TLicenseContainer\n }\n\n private parseLicenseKeyStr(certStr: string): TLicenseCertObj {\n const certPayload = this.validateLicenseKey(certStr)\n\n const cert = { ...certPayload } as TLicenseCertObj\n\n // turn timestamp strings into Date objects\n cert.createdAt = new Date(certPayload.createdAt)\n cert.issuedAt = new Date(certPayload.issuedAt)\n cert.expiresAt = new Date(certPayload.expiresAt)\n cert.terminatesAt = new Date(certPayload.terminatesAt)\n\n // make sure detachedEntitlementsCount is a number (certs issues before this field was introduced will have it missing)\n cert.detachedEntitlementsCount = certPayload.detachedEntitlementsCount ?? 0\n\n cert.entitlements = cert.entitlements.map((entitlement) => {\n entitlement.validFrom = new Date(entitlement.validFrom)\n entitlement.validTo = new Date(entitlement.validTo)\n return entitlement\n })\n\n return cert\n }\n\n private validateLicenseKey(licenseKey: string) {\n //remove all line breaks\n licenseKey = licenseKey.replace(/(\\r\\n|\\n|\\r)/gm, '')\n\n //extract parts\n const match = licenseKey.match(\n /^-----BEGIN LICENSE KEY-----(?<encryptedSymmetricKey>.+\\|\\|)(?<encryptedData>.+)\\|\\|(?<signature>.+)-----END LICENSE KEY-----$/\n )\n\n if (!match) {\n throw new Error('license key could not be parsed')\n }\n\n const encryptedSymmetricKey = match.groups!.encryptedSymmetricKey\n const payload = match.groups!.encryptedData\n const signature = match.groups!.signature\n\n let symmetricKey, decryptedData\n\n //decrypt the random symmetric key\n try {\n symmetricKey = this.key!.decryptPublic(encryptedSymmetricKey, 'utf8')\n } catch (e) {\n throw new Error('Invalid data: Could not extract symmetric key')\n }\n\n //decrypt the payload\n try {\n decryptedData = CryptoJS.AES.decrypt(payload, symmetricKey).toString(\n CryptoJS.enc.Utf8\n )\n } catch (e) {\n throw new Error('Invalid Data: Could not decrypt data with key found')\n }\n\n //verify the signature.\n if (\n this.key!.verify(Buffer.from(decryptedData), signature, 'utf8', 'base64')\n ) {\n //return the decrypted data.\n return JSON.parse(decryptedData)\n } else {\n throw new Error('License Key signature invalid')\n }\n }\n\n public getIssuerCert() {\n return this.x509IssuerCert\n }\n\n public async shutdown() {\n this.isShuttingDown = true\n\n this.clearRepeatingTimer(this.renewalTimer)\n this.clearRepeatingTimer(this.upcomingEntitlementChangesCheckTimer)\n this.clearSingleTimer(this.entitlementChangeTimer)\n\n if (!this.hasCert()) {\n return\n }\n\n const hasFloatableEntitlements = this.licenseCert.entitlements.some(\n (entitlement) => entitlement.isFloatable ?? false\n )\n\n if (hasFloatableEntitlements) {\n await this._renew({ detachFloatingEntitlements: true, cause: 'shutdown' })\n }\n }\n\n /** Enable renewing the license periodically. */\n public enableAutoRenewals() {\n if (this.config.autoRenewEnabled === true) return\n\n this.config.autoRenewEnabled = true\n this.log('License autorenewals enabled', LogLevel.INFO)\n\n this.clearRepeatingTimer(this.renewalTimer)\n this.renewalTimer = this.setupRepeatingTimer(\n () => this.renewalCron({ force: false }),\n AUTORENEWAL_INTERVAL\n )\n }\n\n /** Disable renewing the license periodically. */\n public disableAutoRenewals() {\n if (this.config.autoRenewEnabled === false) return\n\n this.config.autoRenewEnabled = false\n this.log('License autorenewals disabled', LogLevel.INFO)\n\n this.clearRepeatingTimer(this.renewalTimer)\n this.renewalTimer = undefined\n }\n}\n","import {\n fetch,\n getGlobalDispatcher,\n setGlobalDispatcher,\n Dispatcher,\n ProxyAgent,\n} from 'undici'\n\nimport { URL } from 'node:url'\n\nfunction getProxyAgent(variableName: string) {\n const proxyURI = process.env[variableName]\n return proxyURI ? new ProxyAgent(proxyURI) : null\n}\n\nconst httpProxy =\n getProxyAgent('http_proxy_license_server') || getProxyAgent('http_proxy')\nconst httpsProxy =\n getProxyAgent('https_proxy_license_server') || getProxyAgent('https_proxy')\n\nconst proxyAgents = {\n ...(httpProxy ? { 'http:': httpProxy } : {}),\n ...(httpsProxy ? { 'https:': httpsProxy } : {}),\n}\n\nconst noProxyRules = (process.env['no_proxy'] ?? '')\n .split(',')\n .map((rule) => rule.trim())\n\nconst defaultDispatcher = getGlobalDispatcher()\n\nsetGlobalDispatcher(\n new (class extends Dispatcher {\n dispatch(options: any, handler: any) {\n if (options.origin) {\n const { host, protocol } =\n typeof options.origin === 'string'\n ? new URL(options.origin)\n : options.origin\n if (\n !noProxyRules.some((rule) =>\n rule.startsWith('.') ? host.endsWith(rule) : host === rule\n )\n ) {\n const proxyAgent = proxyAgents[protocol as 'http:' | 'https:']\n if (proxyAgent) {\n proxyAgent.dispatch(options, handler)\n }\n }\n }\n return defaultDispatcher.dispatch(options, handler)\n }\n })()\n)\n\nexport async function postRequest<T>(\n url: string,\n data: {},\n options: {\n timeoutInMs?: number\n } = {}\n) {\n const controller = new AbortController()\n\n const timeout = setTimeout(() => {\n controller.abort()\n }, options.timeoutInMs ?? 30000)\n\n try {\n const response = await fetch(url, {\n method: 'post',\n body: JSON.stringify(data),\n headers: { 'Content-Type': 'application/json' },\n signal: controller.signal,\n })\n\n const responseJson = await response.json()\n\n return {\n status: response.status,\n data: responseJson as T,\n }\n } catch (err) {\n throw new Error('Connection Error', { cause: err })\n } finally {\n clearTimeout(timeout)\n }\n}\n\nexport default {\n postRequest,\n}\n"],"mappings":"0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,0BAAAE,EAAA,mBAAAC,IAAA,eAAAC,EAAAJ,GAAA,IAAAK,EAAqB,wBACrBC,EAA0B,2BAC1BC,EAAoB,uBACpBC,EAAmB,kBACnBC,EAAgC,kBCJhC,IAAAC,EAMO,kBAEPC,EAAoB,eAEpB,SAASC,EAAcC,EAAsB,CAC3C,IAAMC,EAAW,QAAQ,IAAID,CAAY,EACzC,OAAOC,EAAW,IAAI,aAAWA,CAAQ,EAAI,IAC/C,CAEA,IAAMC,EACJH,EAAc,2BAA2B,GAAKA,EAAc,YAAY,EACpEI,EACJJ,EAAc,4BAA4B,GAAKA,EAAc,aAAa,EAEtEK,EAAc,CAClB,GAAIF,EAAY,CAAE,QAASA,CAAU,EAAI,CAAC,EAC1C,GAAIC,EAAa,CAAE,SAAUA,CAAW,EAAI,CAAC,CAC/C,EAEME,GAAgB,QAAQ,IAAI,UAAe,IAC9C,MAAM,GAAG,EACT,IAAKC,GAASA,EAAK,KAAK,CAAC,EA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AAgC,MAAa,EAEtD,KAAK,oBAAoB,KAAK,YAAY,EAC1C,KAAK,aAAe,KAAK,oBACvB,IAAM,KAAK,YAAY,CAAE,MAAO,EAAM,CAAC,EACvC5B,CACF,EACF,CAGO,qBAAsB,CACvB,KAAK,OAAO,mBAAqB,KAErC,KAAK,OAAO,iBAAmB,GAC/B,KAAK,IAAI,gCAAiC,MAAa,EAEvD,KAAK,oBAAoB,KAAK,YAAY,EAC1C,KAAK,aAAe,OACtB,CACF","names":["LicenseManager_exports","__export","AUTORENEWAL_INTERVAL","LicenseManager","__toCommonJS","import_crypto_js","import_node_machine_id","import_node_rsa","import_node_assert","import_node_crypto","import_undici","import_node_url","getProxyAgent","variableName","proxyURI","httpProxy","httpsProxy","proxyAgents","noProxyRules","rule","defaultDispatcher","options","handler","host","protocol","proxyAgent","postRequest","url","data","controller","timeout","response","responseJson","err","AUTORENEWAL_INTERVAL","LicenseManager","config","msg","logLevel","AUTORENEWAL_INTERVAL","callback","interval","timer","date","durationInMs","reservationId","postData","response","postRequest","error","containerStr","errorMsg","e","detachFloatingEntitlements","cause","usageMetrics","passthroughData","responseData","now","useLogger","cert","feature","requireValidCert","quotaFeatureName","currentConsumption","quota","currentFeatures","entitlement","entitlement1","entitlement2","mins15inMs","mins20inMs","expiry","issuedAt","termination","consumerRenewalDue","entitlementRenewalDue","seconds","hours","minutes","remainingSeconds","index","offsets","upcomingEventOffsets","offset","a","b","timeTillNextEventInMs","force","x509","licenseKey","publicKey","NodeRSA","container","stringifiedContainer","certStr","certPayload","match","encryptedSymmetricKey","payload","signature","symmetricKey","decryptedData","CryptoJS"]}
|
|
1
|
+
{"version":3,"sources":["../src/LicenseManager.ts","../src/httpRequest.ts","../src/version.ts"],"sourcesContent":["import CryptoJS from 'crypto-js'\nimport { machineId } from 'node-machine-id'\nimport NodeRSA from 'node-rsa'\nimport { ok } from 'node:assert'\nimport { X509Certificate } from 'node:crypto'\nimport { postRequest } from './httpRequest'\n\n/** How often to consider periodic license renewal (in ms) */\nexport const AUTORENEWAL_INTERVAL = 15 * 60 * 1000 // 15 minutes\n\nexport type TLicenseManagerConfig = {\n server?: string\n tenantId: number\n productIdentifier: string\n\n /**\n * Whether to renew the license periodically.\n *\n * @default true\n */\n autoRenewEnabled?: boolean\n /**\n * Whether to return any floatable entitlements to the pool on SDK shutdown.\n *\n * @default true\n */\n detachFloatingOnShutdown?: boolean\n offlineMode?: boolean\n renewOnInit?: boolean\n autoRenewOffset?: number\n loadCertStr: () => Promise<TLicenseBlock>\n saveCertStr: (cert: TLicenseBlock) => Promise<void>\n collectUsageMetrics?: () => Promise<Array<TUsageMetric>>\n collectPassthroughData?: () => Promise<TPassthroughData>\n deviceFingerprint?: () => string | Promise<string>\n onFeatureChange?: (features: TFeatures) => any\n logger?: TLogger\n}\n\nexport type TLicenseBlock = string\n\nexport type TLicenseContainer = {\n licenseKey: string\n x509: string\n}\n\nexport type TFeatures = { [key: string]: boolean | number | string }\n\nexport type TUsageMetric = { name: string; value: number }\n\nexport type TPassthroughData = Record<string, unknown>\n\nexport type TMetadata = {\n [key: string]: boolean | number | string | Array<any> | {}\n}\n\nexport type TEntitlement = {\n id: string\n productId: string\n productMetadata: TMetadata\n features: TFeatures\n featureOverrides: TFeatures\n validFrom: Date\n validTo: Date\n isFloatable: boolean\n}\n\nexport type TLicenseCertObj = {\n consumerId: string\n consumerRef?: string\n version: number\n tenantId: number\n renewalToken: string\n deviceLock: boolean\n deviceFingerprint: string\n createdAt: Date\n issuedAt: Date\n expiresAt: Date\n terminatesAt: Date\n entitlements: TEntitlement[]\n /**\n * Indicates the number of floating entitlements that are not attached to the consumer\n * because they are in use elsewhere at the time of renewal.\n */\n detachedEntitlementsCount: number\n managementJwt: string\n /**\n * Specifies whether the license is ephemeral and therefore does not have corresponding entries in the license server DB.\n */\n isEphemeral: boolean\n}\n\nexport type TLogger = {\n error: Function\n warn: Function\n info: Function\n debug: Function\n}\n\ntype SingleTimer = NodeJS.Timeout\ntype RepeatingTimer = NodeJS.Timeout\n\nconst enum LogLevel {\n ERROR = 'error',\n WARN = 'warn',\n INFO = 'info',\n DEBUG = 'debug',\n}\n\nexport class LicenseManager {\n public config: TLicenseManagerConfig\n\n private initializationPromise?: Promise<void>\n private key?: NodeRSA\n private logger: TLogger\n protected licenseCert?: TLicenseCertObj\n private x509Cert?: X509Certificate\n private x509IssuerCert: X509Certificate\n private deviceFingerprint?: string\n private renewalTimer?: RepeatingTimer\n private upcomingEntitlementChangesCheckTimer?: RepeatingTimer\n private entitlementChangeTimer?: SingleTimer\n private currentFeatures?: TFeatures\n private isShuttingDown = false\n\n get isInitialized() {\n return !!this.initializationPromise\n }\n\n constructor(config: TLicenseManagerConfig) {\n this.config = config\n\n if (this.config.logger) {\n this.logger = this.config.logger\n } else {\n this.logger = {\n error() {\n console.log('ERROR:', ...arguments)\n },\n warn() {\n console.log('WARN:', ...arguments)\n },\n info() {\n console.log('INFO:', ...arguments)\n },\n debug() {\n console.log('DEBUG:', ...arguments)\n },\n }\n }\n\n this.x509IssuerCert = new X509Certificate(\n '-----BEGIN CERTIFICATE-----\\n' +\n 'MIIFDDCCAvQCCQCWGBewlWbp0DANBgkqhkiG9w0BAQsFADBIMQswCQYDVQQGEwJE\\n' +\n 'RTEPMA0GA1UECAwGQmVybGluMQ8wDQYDVQQHDAZCZXJsaW4xFzAVBgNVBAMMDmxp\\n' +\n 'Y2Vuc2UubjhuLmlvMB4XDTIyMDYyNDA0MDkzM1oXDTQ5MTEwOTA0MDkzM1owSDEL\\n' +\n 'MAkGA1UEBhMCREUxDzANBgNVBAgMBkJlcmxpbjEPMA0GA1UEBwwGQmVybGluMRcw\\n' +\n 'FQYDVQQDDA5saWNlbnNlLm44bi5pbzCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCC\\n' +\n 'AgoCggIBANK6Uj5CSyPaa2rf/bwH/AqzzINeWg4n94pECv4p8tsjy0+ZscodNn7Q\\n' +\n 'IvYW/6IUpax8fZvHCSqu0L7fsgLkw0+HDLls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evXMoXpDzlevkCpz17uDiDt9XrmvLSf3Ff8mdTRwzVmOmHfc\\n' +\n 'Ruz5v7WBR4cpBR/sC+WxOw9heLMHgYhPyRUM4voo55EcJGusXr/iavblBAnI0GUw\\n' +\n 'uMNs3MjEmfbaBV1K0GKG5UToF9UmUxxVmTcRUZrAQX+yBkRezDTpOQuRnB58BDQP\\n' +\n 'A62lcgZlikzJw3lHue33qAudyUrUmjfHGll7GFQNeLO42jPMeM4NJiNIrBZ7j0uD\\n' +\n '4slHdDi/44PHcKchvde/5k7ZJMi6OC1Vu+bOnKvzhnWQIOkHFQ55m13oslV2ozZT\\n' +\n '/oqhn/8/LeV0ooZuYnBeRkRTveniUeho2OFe5xZvWSSfuBrbHt9+zBg+5MWPUTIJ\\n' +\n '-----END CERTIFICATE-----'\n )\n\n //set defaults for not set config properties:\n this.config.autoRenewEnabled = this.config.autoRenewEnabled ?? true\n this.config.renewOnInit = this.config.renewOnInit ?? false\n this.config.offlineMode = this.config.offlineMode ?? false\n this.config.autoRenewOffset = this.config.autoRenewOffset ?? 60 * 60 * 72 // default: 72 hours\n this.config.detachFloatingOnShutdown =\n this.config.detachFloatingOnShutdown ?? true\n this.config.server = this.config.server ?? 'https://license.n8n.io/v1'\n }\n\n log(msg: string, logLevel: LogLevel) {\n this.logger[logLevel](`[license SDK] ${msg}`)\n }\n\n async initialize() {\n if (this.initializationPromise) {\n return this.initializationPromise\n }\n\n this.initializationPromise = this._doInitialization()\n\n return await this.initializationPromise\n }\n\n /** Initializes the license manager */\n private async _doInitialization() {\n ok(!this.initializationPromise, 'Initialization already in progress')\n\n this.deviceFingerprint = await this.computeDeviceFingerprint()\n this.log(\n `initializing for deviceFingerprint ${this.deviceFingerprint}`,\n LogLevel.DEBUG\n )\n\n await this.initCert() // doesn't throw!\n\n // Clear and set up periodic timer for entitlement changes\n this.clearRepeatingTimer(this.upcomingEntitlementChangesCheckTimer)\n this.upcomingEntitlementChangesCheckTimer = this.setupRepeatingTimer(\n () => this.setTimerForNextEntitlementChange(),\n AUTORENEWAL_INTERVAL\n )\n\n // Perform initial renewal if conditions are met\n // If local cert has detachedEntitlementsCount marker, a force renewal makes sense as floating entitlements might get attached\n // Otherwise do the renewal only if the cert is older than 24 hours\n if (\n this.config.renewOnInit &&\n this.config.autoRenewEnabled &&\n this.hasCert() &&\n (this.licenseCert.detachedEntitlementsCount > 0 ||\n this.isOlderThan(this.licenseCert.issuedAt, 24 * 60 * 60 * 1000)) // 24 hours\n ) {\n await this.renewalCron({ force: true })\n } else {\n this.log(\n 'Skipping renewal on init because cert was issued less than 24 hours ago or not initialized',\n LogLevel.DEBUG\n )\n }\n\n // Set up periodic renewal if enabled\n if (this.config.autoRenewEnabled) {\n this.clearRepeatingTimer(this.renewalTimer)\n this.renewalTimer = this.setupRepeatingTimer(\n () => this.renewalCron({ force: false }),\n AUTORENEWAL_INTERVAL\n )\n }\n }\n\n private setupSingleTimer(\n callback: () => void,\n interval: number\n ): SingleTimer {\n return setTimeout(callback, interval)\n }\n\n clearSingleTimer(timer: SingleTimer | undefined) {\n if (timer) {\n clearTimeout(timer)\n }\n }\n\n setupRepeatingTimer(callback: () => void, interval: number): RepeatingTimer {\n return setInterval(callback, interval)\n }\n\n clearRepeatingTimer(timer: RepeatingTimer | undefined) {\n if (timer) {\n clearInterval(timer)\n }\n }\n\n private isOlderThan(date: Date, durationInMs: number) {\n return Date.now() - date.getTime() > durationInMs\n }\n\n async reload() {\n await this.reset()\n await this.initialize()\n }\n\n async reset() {\n // Make sure initialization is not ongoing before resetting\n if (this.initializationPromise) {\n await this.initializationPromise\n }\n this.clearRepeatingTimer(this.renewalTimer)\n this.renewalTimer = undefined\n this.clearRepeatingTimer(this.upcomingEntitlementChangesCheckTimer)\n this.upcomingEntitlementChangesCheckTimer = undefined\n this.clearSingleTimer(this.entitlementChangeTimer)\n this.entitlementChangeTimer = undefined\n\n this.licenseCert = undefined\n this.deviceFingerprint = undefined\n this.initializationPromise = undefined\n }\n\n async computeDeviceFingerprint() {\n if (\n this.config.deviceFingerprint &&\n typeof this.config.deviceFingerprint === 'function'\n ) {\n return await this.config.deviceFingerprint()\n }\n return await machineId()\n }\n\n async activate(reservationId: string) {\n if (!this.isInitialized) {\n throw new Error('activation failed because SDK was not yet initialized')\n }\n\n if (this.isShuttingDown) {\n throw new Error('activation failed because SDK is shutting down')\n }\n\n if (this.config.offlineMode) {\n throw new Error('activation failed because SDK is in offline mode')\n }\n\n const postData: {\n reservationId: string\n tenantId: number\n productIdentifier: string\n deviceFingerprint: string\n consumerId?: string\n renewalToken?: string\n } = {\n reservationId,\n tenantId: this.config.tenantId,\n productIdentifier: this.config.productIdentifier,\n deviceFingerprint: this.deviceFingerprint!,\n }\n\n if (this.hasCert()) {\n postData.consumerId = this.licenseCert.consumerId\n postData.renewalToken = this.licenseCert.renewalToken\n }\n\n type ResponseDataFormat = {\n licenseKey?: string\n x509?: string\n detachedEntitlementsCount?: number\n message?: string\n errorId?: string\n }\n\n type PostRequestResponse = Awaited<\n ReturnType<typeof postRequest<ResponseDataFormat>>\n >\n\n let response: PostRequestResponse\n\n try {\n response = await postRequest<{\n licenseKey?: string\n x509?: string\n message?: string\n errorId?: string\n }>(`${this.config.server!}/activate`, postData, {\n timeoutInMs: 10000,\n productIdentifier: this.config.productIdentifier,\n })\n } catch (error) {\n this.log(\n 'license activation failed: ' + (error as Error).message,\n LogLevel.WARN\n )\n throw new Error((error as Error).message)\n }\n\n if (response.status == 200) {\n if (\n !response.data.hasOwnProperty('licenseKey') ||\n !response.data.hasOwnProperty('x509')\n ) {\n this.log('unexpected server response', LogLevel.WARN)\n throw new Error('unexpected server response')\n }\n const containerStr = this.stringifyCertContainer({\n licenseKey: response.data.licenseKey,\n x509: response.data.x509,\n } as TLicenseContainer)\n await this.config.saveCertStr(containerStr)\n await this.initCert()\n this.log('license successfully activated', LogLevel.INFO)\n if (response.data.detachedEntitlementsCount ?? 0 > 0) {\n this.log(\n `skipped importing ${response.data.detachedEntitlementsCount} floating entitlements which are currently in use elsewhere`,\n LogLevel.INFO\n )\n }\n } else {\n const errorMsg = `license activation failed: ${\n response.data.message ?? 'unknown reason'\n }`\n const e = new Error(errorMsg) as Error & { errorId?: string }\n\n if (response.data.errorId) {\n e.errorId = response.data.errorId\n }\n\n this.log(errorMsg, LogLevel.WARN)\n throw e\n }\n }\n\n async renew() {\n return this._renew({ cause: 'request' })\n }\n\n async _renew({\n detachFloatingEntitlements = false,\n cause = 'unknown',\n }: {\n detachFloatingEntitlements?: Boolean\n cause?: 'startup' | 'shutdown' | 'request' | 'auto' | 'unknown'\n } = {}) {\n if (!this.hasCert()) {\n throw new Error('renewal failed because current cert is not initialized')\n }\n\n if (this.licenseCert.isEphemeral) {\n return\n }\n\n if (this.isTerminated()) {\n throw new Error('renewal failed because current cert was terminated')\n }\n\n if (this.config.offlineMode) {\n throw new Error('renewal failed because SDK is in offline mode')\n }\n\n if (this.config.tenantId !== this.licenseCert.tenantId) {\n throw new Error('renewal failed because tenant ID does not match')\n }\n\n // error out if device fingerprint does not match but allow renewal on explicit request\n // as the consumer might have been changed to more permissive settings on the server\n if (\n cause !== 'request' &&\n this.licenseCert.deviceLock &&\n this.deviceFingerprint !== this.licenseCert.deviceFingerprint\n ) {\n throw new Error(\n 'renewal failed because device fingerprint does not match'\n )\n }\n\n const [usageMetrics, passthroughData] = await Promise.all([\n this.config.collectUsageMetrics ? this.config.collectUsageMetrics() : [],\n this.config.collectPassthroughData\n ? this.config.collectPassthroughData()\n : {},\n ])\n\n type ResponseDataFormat = {\n licenseKey?: string\n x509?: string\n detachedEntitlementsCount?: number\n message?: string\n errorId?: string\n }\n\n type PostRequestResponse = Awaited<\n ReturnType<typeof postRequest<ResponseDataFormat>>\n >\n\n let response: PostRequestResponse\n\n try {\n response = await postRequest<ResponseDataFormat>(\n `${this.config.server!}/renew`,\n {\n consumerId: this.licenseCert.consumerId,\n tenantId: this.config.tenantId,\n deviceFingerprint: this.deviceFingerprint,\n productIdentifier: this.config.productIdentifier,\n renewalToken: this.licenseCert.renewalToken,\n detachFloatingEntitlements,\n cause,\n usageMetrics,\n passthroughData,\n },\n { timeoutInMs: 10000, productIdentifier: this.config.productIdentifier }\n )\n } catch (error) {\n this.log(\n 'license renewal failed: ' + (error as Error).message,\n LogLevel.WARN\n )\n throw new Error((error as Error).message)\n }\n\n const responseData = response.data\n\n if (response.status == 200) {\n if (\n !responseData.hasOwnProperty('licenseKey') ||\n !responseData.hasOwnProperty('x509')\n ) {\n this.log(\n 'license renewal failed: unexpected server response',\n LogLevel.WARN\n )\n throw new Error('unexpected server response')\n }\n const containerStr = this.stringifyCertContainer({\n licenseKey: responseData.licenseKey,\n x509: responseData.x509,\n } as TLicenseContainer)\n await this.config.saveCertStr(containerStr)\n\n this.log('license successfully renewed', LogLevel.DEBUG)\n\n if (responseData.detachedEntitlementsCount ?? 0 > 0) {\n if (detachFloatingEntitlements) {\n this.log(\n `${responseData.detachedEntitlementsCount} floating entitlements were returned to the pool`,\n LogLevel.INFO\n )\n } else {\n this.log(\n `skipped importing ${responseData.detachedEntitlementsCount} floating entitlements which are currently in use elsewhere`,\n LogLevel.INFO\n )\n }\n }\n\n await this.initCert()\n } else {\n const errorMsg = `license renewal failed: ${\n responseData.message ?? 'unknown reason'\n }`\n\n this.log(errorMsg, LogLevel.WARN)\n\n const e = new Error(errorMsg) as Error & { errorId?: string }\n\n if (responseData.errorId) {\n e.errorId = responseData.errorId\n\n if (\n ['NOT_FOUND', 'CONSUMER_TERMINATED'].includes(responseData.errorId)\n ) {\n this.log(\n 'license was terminated by the server. Deleting local cert.',\n LogLevel.WARN\n )\n await this.config.saveCertStr('')\n await this.initCert()\n }\n }\n\n throw e\n }\n }\n\n private hasCert(): this is { licenseCert: TLicenseCertObj } {\n return !!this.licenseCert\n }\n\n isTerminated(): boolean {\n if (!this.hasCert()) {\n throw new Error('Cert is not initialized')\n }\n\n const now = new Date()\n\n return this.licenseCert.terminatesAt < now\n }\n\n getExpiryDate(): Date {\n if (!this.hasCert()) {\n throw new Error('Cert is not initialized')\n }\n\n return this.licenseCert.expiresAt\n }\n\n getTerminationDate(): Date {\n if (!this.hasCert()) {\n throw new Error('Cert is not initialized')\n }\n\n return this.licenseCert.terminatesAt\n }\n\n isValid(useLogger = true): boolean {\n const error = (msg: string) => {\n if (useLogger) {\n this.log(msg, LogLevel.ERROR)\n }\n }\n\n if (!this.hasCert()) {\n error('cert is invalid because it is undefined')\n return false\n }\n\n const cert = this.licenseCert as TLicenseCertObj\n const now = new Date()\n\n if (cert.expiresAt < now) {\n error('cert is invalid because it has expired')\n return false\n }\n\n if (cert.terminatesAt < now) {\n error('cert is invalid because it was terminated')\n return false\n }\n\n //allow clocks to be out of sync by no more than 300,000 ms / = 5 minutes\n if (cert.createdAt.getTime() - 300000 > now.getTime()) {\n error('cert is invalid because system clock is out of sync')\n return false\n }\n\n if (cert.deviceLock && this.deviceFingerprint !== cert.deviceFingerprint) {\n error('cert is invalid because device fingerprint does not match')\n return false\n }\n\n if (this.config.tenantId !== cert.tenantId) {\n error('cert is invalid because tenant ID does not match')\n return false\n }\n\n return true\n }\n\n hasFeatureEnabled(\n feature: string,\n requireValidCert: boolean = true\n ): boolean {\n return this.getFeatureValue(feature, requireValidCert) ? true : false\n }\n\n hasFeatureDefined(\n feature: string,\n requireValidCert: boolean = true\n ): boolean {\n return this.getFeatureValue(feature, requireValidCert) !== undefined\n ? true\n : false\n }\n\n hasQuotaLeft(quotaFeatureName: string, currentConsumption: number): boolean {\n const quota = this.getFeatureValue(quotaFeatureName)\n\n if (quota === undefined) {\n return false\n }\n\n if (typeof quota !== 'number') {\n throw new Error(\n `${quotaFeatureName} cannot be used as quota as it is not numeric`\n )\n }\n\n // -1 means unlimited quota!\n if (quota === -1) {\n return true\n }\n\n return Math.ceil(currentConsumption) < Math.ceil(quota)\n }\n\n getFeatureValue(\n feature: string,\n requireValidCert: boolean = true\n ): undefined | boolean | number | string {\n if (!this.hasCert()) {\n return undefined\n }\n\n if (requireValidCert && !this.isValid()) {\n return undefined\n }\n\n const currentFeatures = this.getFeatures()\n\n if (!currentFeatures.hasOwnProperty(feature)) {\n return undefined\n }\n\n return currentFeatures[feature]\n }\n\n private updateCurrentFeatures() {\n if (!this.hasCert()) {\n return\n }\n\n const now = new Date()\n\n if (\n this.licenseCert.expiresAt < now ||\n this.licenseCert.terminatesAt < now\n ) {\n this.currentFeatures = {} as TFeatures\n }\n\n this.currentFeatures = this.licenseCert.entitlements\n .filter(\n (entitlement) =>\n entitlement.validFrom <= now && entitlement.validTo > now\n )\n .sort(\n (entitlement1, entitlement2) =>\n entitlement1.validFrom.getTime() - entitlement2.validFrom.getTime()\n )\n .reduce((currentFeatures, entitlement) => {\n return {\n ...currentFeatures,\n ...entitlement.features,\n ...entitlement.featureOverrides,\n }\n }, {} as TFeatures)\n }\n\n getFeatures() {\n if (!this.hasCert()) {\n return {}\n }\n\n return this.currentFeatures ?? {}\n }\n\n getCurrentEntitlements() {\n if (!this.hasCert()) {\n return []\n }\n\n const now = new Date()\n\n return this.licenseCert.entitlements.filter(\n (entitlement) => entitlement.validFrom <= now && entitlement.validTo > now\n )\n }\n\n getManagementJwt() {\n if (!this.licenseCert) {\n return ''\n }\n\n return this.licenseCert.managementJwt\n }\n\n async getCertStr(): Promise<TLicenseBlock> {\n return this.config.loadCertStr()\n }\n\n getConsumerId() {\n return this.licenseCert?.consumerId\n }\n\n isRenewalDue(): boolean {\n if (!this.licenseCert || this.licenseCert.isEphemeral) {\n return false\n }\n\n const now = Date.now()\n const mins15inMs = 1000 * 60 * 15\n const mins20inMs = 1000 * 60 * 20\n const expiry = this.licenseCert.expiresAt.getTime()\n const issuedAt = this.licenseCert.issuedAt.getTime()\n const termination = this.licenseCert.terminatesAt.getTime()\n\n //consumerRenewalDue is TRUE when current time is close enough to consumer expiry and not after consumer termination\n const consumerRenewalDue =\n now > expiry - this.config.autoRenewOffset! * 1000 && now < termination\n\n //entitlementRenewalDue is TRUE when one currently valid entitlement will expire in the next 15 minutes\n //and the Cert was issued more than 20 minutes ago\n const entitlementRenewalDue =\n this.getCurrentEntitlements().find(\n (entitlement) =>\n now >= entitlement.validTo.getTime() - mins15inMs &&\n now <= entitlement.validTo.getTime()\n ) !== undefined && issuedAt < now - mins20inMs\n\n return consumerRenewalDue || entitlementRenewalDue\n }\n\n private formatDuration(seconds: number): string {\n const hours = Math.floor(seconds / 3600)\n const minutes = Math.floor((seconds % 3600) / 60)\n const remainingSeconds = seconds % 60\n\n return `${hours}h ${minutes}m ${remainingSeconds}s`\n }\n\n toString() {\n return (\n `## CONSUMER CONFIG ##\\n` +\n `tenantId: ${this.config.tenantId ?? '<n/a>'}\\n` +\n `productIdentifier: ${this.config.productIdentifier ?? '<n/a>'}\\n` +\n `deviceFingerprint: ${this.deviceFingerprint ?? '<n/a>'}\\n` +\n `autoRenewalEnabled: ${\n this.config.autoRenewEnabled ? 'true' : 'false (!)'\n }\\n` +\n `autoRenewalOffset: ${\n this.config.autoRenewOffset\n } (= ${this.formatDuration(this.config.autoRenewOffset ?? 0)})\\n` +\n '--\\n' +\n `## LICENSE CERT ##\\n` +\n `version: ${this.licenseCert?.version ?? '<n/a>'}\\n` +\n `tenantId: ${this.licenseCert?.tenantId ?? '<n/a>'} ${\n this.licenseCert?.tenantId !== this.config.tenantId ? '(!)' : ''\n }\\n` +\n `consumerId: ${this.licenseCert?.consumerId ?? '<n/a>'}\\n` +\n `deviceFingerprint: ${this.licenseCert?.deviceFingerprint ?? '<n/a>'} ${\n this.licenseCert?.deviceFingerprint !== this.deviceFingerprint\n ? '(!)'\n : ''\n }\\n` +\n `createdAt: ${this.licenseCert?.createdAt ?? '<n/a>'}\\n` +\n `issuedAt: ${this.licenseCert?.issuedAt ?? '<n/a>'}\\n` +\n `expiresAt: ${this.licenseCert?.expiresAt ?? '<n/a>'}\\n` +\n `terminatesAt: ${this.licenseCert?.terminatesAt ?? '<n/a>'}\\n` +\n `isEphemeral: ${this.licenseCert?.isEphemeral ?? '<n/a>'}\\n` +\n `isValid: ${this.isValid(false)}\\n` +\n `isRenewalDue: ${this.isRenewalDue()}\\n` +\n `detachedEntitlementsCount: ${\n this.licenseCert?.detachedEntitlementsCount ?? '<n/a>'\n }\\n` +\n `entitlements: ${this.licenseCert?.entitlements.length ?? 0}\\n` +\n this.licenseCert?.entitlements\n .map((entitlement, index) => {\n return (\n '--\\n' +\n `## ENTITLEMENT ${index + 1} ##\\n` +\n `id: ${entitlement.id}\\n` +\n `productId: ${entitlement.productId}\\n` +\n `validFrom: ${entitlement.validFrom}\\n` +\n `validTo: ${entitlement.validTo}\\n` +\n `features: ${JSON.stringify(entitlement.features)}\\n` +\n `featureOverrides: ${JSON.stringify(\n entitlement.featureOverrides\n )}\\n`\n )\n })\n .join('')\n )\n }\n\n private triggerOnFeatureChangeCallback() {\n if (this.config.onFeatureChange) {\n this.config.onFeatureChange(this.currentFeatures ?? {})\n }\n }\n\n private setTimerForNextEntitlementChange() {\n if (!this.hasCert()) {\n return\n }\n\n const now = Date.now()\n const offsets = new Set<number>()\n\n offsets.add(this.licenseCert.expiresAt.getTime() - now)\n offsets.add(this.licenseCert.terminatesAt.getTime() - now)\n\n const upcomingEventOffsets = [\n ...this.licenseCert.entitlements.reduce((offsets, entitlement) => {\n offsets.add(entitlement.validFrom.getTime() - now)\n offsets.add(entitlement.validTo.getTime() - now)\n return offsets\n }, offsets),\n ]\n .filter((offset) => offset >= 0 && offset <= AUTORENEWAL_INTERVAL) // keep if offset is within the next 15 minutes\n .sort((a, b) => a - b)\n\n //console.dir(upcomingEventOffsets.map((offset) => offset / 1000 / 60))\n\n if (upcomingEventOffsets.length === 0) {\n return\n }\n\n const timeTillNextEventInMs = upcomingEventOffsets[0]\n\n this.clearSingleTimer(this.entitlementChangeTimer)\n this.entitlementChangeTimer = this.setupSingleTimer(() => {\n this.updateCurrentFeatures()\n this.triggerOnFeatureChangeCallback()\n this.setTimerForNextEntitlementChange()\n }, timeTillNextEventInMs + 1000)\n }\n\n private async renewalCron({ force }: { force: boolean }) {\n if (force || this.isRenewalDue()) {\n this.log('attempting license renewal', LogLevel.DEBUG)\n try {\n await this._renew({ cause: force ? 'startup' : 'auto' })\n } catch (e) {}\n }\n }\n\n private async initCert() {\n if (this.isShuttingDown) {\n return\n }\n\n try {\n const containerStr = await this.getCertStr()\n if (!containerStr) {\n this.licenseCert = undefined\n return\n }\n if (containerStr.length < 50) {\n throw new Error('cert string is undefined or too short')\n }\n const { x509, licenseKey } =\n this.parseLicenseCertContainerStr(containerStr)\n this.x509Cert = new X509Certificate(x509)\n const hasApprovedIssuer = this.x509Cert.checkIssued(this.getIssuerCert())\n if (!hasApprovedIssuer) {\n throw new Error('cert was not issued by an approved issuer')\n }\n const publicKey = this.x509Cert.publicKey.export({\n format: 'pem',\n type: 'pkcs1',\n })\n this.key = new NodeRSA(publicKey)\n this.licenseCert = this.parseLicenseKeyStr(licenseKey)\n this.updateCurrentFeatures()\n this.setTimerForNextEntitlementChange()\n } catch (e) {\n this.log(\n `cert could not be initialized. ${e instanceof Error ? e.message : ''}`,\n LogLevel.ERROR\n )\n }\n }\n\n private stringifyCertContainer(container: TLicenseContainer): string {\n const containerStr = JSON.stringify(container)\n return Buffer.from(containerStr).toString('base64')\n }\n\n private parseLicenseCertContainerStr(\n stringifiedContainer: string\n ): TLicenseContainer {\n const containerStr = Buffer.from(stringifiedContainer, 'base64').toString(\n 'ascii'\n )\n const container = JSON.parse(containerStr)\n if (\n !container.hasOwnProperty('licenseKey') ||\n !container.hasOwnProperty('x509')\n ) {\n throw new Error('license cert container could not be parsed')\n }\n\n return container as TLicenseContainer\n }\n\n private parseLicenseKeyStr(certStr: string): TLicenseCertObj {\n const certPayload = this.validateLicenseKey(certStr)\n\n const cert = { ...certPayload } as TLicenseCertObj\n\n // turn timestamp strings into Date objects\n cert.createdAt = new Date(certPayload.createdAt)\n cert.issuedAt = new Date(certPayload.issuedAt)\n cert.expiresAt = new Date(certPayload.expiresAt)\n cert.terminatesAt = new Date(certPayload.terminatesAt)\n\n // make sure detachedEntitlementsCount is a number (certs issues before this field was introduced will have it missing)\n cert.detachedEntitlementsCount = certPayload.detachedEntitlementsCount ?? 0\n\n cert.entitlements = cert.entitlements.map((entitlement) => {\n entitlement.validFrom = new Date(entitlement.validFrom)\n entitlement.validTo = new Date(entitlement.validTo)\n return entitlement\n })\n\n return cert\n }\n\n private validateLicenseKey(licenseKey: string) {\n //remove all line breaks\n licenseKey = licenseKey.replace(/(\\r\\n|\\n|\\r)/gm, '')\n\n //extract parts\n const match = licenseKey.match(\n /^-----BEGIN LICENSE KEY-----(?<encryptedSymmetricKey>.+\\|\\|)(?<encryptedData>.+)\\|\\|(?<signature>.+)-----END LICENSE KEY-----$/\n )\n\n if (!match) {\n throw new Error('license key could not be parsed')\n }\n\n const encryptedSymmetricKey = match.groups!.encryptedSymmetricKey\n const payload = match.groups!.encryptedData\n const signature = match.groups!.signature\n\n let symmetricKey, decryptedData\n\n //decrypt the random symmetric key\n try {\n symmetricKey = this.key!.decryptPublic(encryptedSymmetricKey, 'utf8')\n } catch (e) {\n throw new Error('Invalid data: Could not extract symmetric key')\n }\n\n //decrypt the payload\n try {\n decryptedData = CryptoJS.AES.decrypt(payload, symmetricKey).toString(\n CryptoJS.enc.Utf8\n )\n } catch (e) {\n throw new Error('Invalid Data: Could not decrypt data with key found')\n }\n\n //verify the signature.\n if (\n this.key!.verify(Buffer.from(decryptedData), signature, 'utf8', 'base64')\n ) {\n //return the decrypted data.\n return JSON.parse(decryptedData)\n } else {\n throw new Error('License Key signature invalid')\n }\n }\n\n public getIssuerCert() {\n return this.x509IssuerCert\n }\n\n /**\n * Detaches any floating entitlements and clears the local license cert.\n */\n public async clear() {\n try {\n await this.detachFloatingEntitlements()\n } catch (err) {\n this.log(\n `failed to detach floating entitlements (${err}). Continuing with clearing license certificate`,\n LogLevel.WARN\n )\n } finally {\n await this.config.saveCertStr('')\n await this.initCert()\n }\n }\n\n public async shutdown() {\n this.isShuttingDown = true\n\n this.clearRepeatingTimer(this.renewalTimer)\n this.clearRepeatingTimer(this.upcomingEntitlementChangesCheckTimer)\n this.clearSingleTimer(this.entitlementChangeTimer)\n\n if (this.config.detachFloatingOnShutdown) {\n await this.detachFloatingEntitlements()\n }\n }\n\n private async detachFloatingEntitlements() {\n if (!this.hasCert()) {\n return\n }\n\n const hasFloatableEntitlements = this.licenseCert.entitlements.some(\n (entitlement) => entitlement.isFloatable ?? false\n )\n\n if (hasFloatableEntitlements) {\n await this._renew({\n detachFloatingEntitlements: true,\n cause: 'shutdown',\n })\n }\n }\n\n /** Enable renewing the license periodically. */\n public enableAutoRenewals() {\n if (this.config.autoRenewEnabled === true) return\n\n this.config.autoRenewEnabled = true\n this.log('License autorenewals enabled', LogLevel.INFO)\n\n this.clearRepeatingTimer(this.renewalTimer)\n this.renewalTimer = this.setupRepeatingTimer(\n () => this.renewalCron({ force: false }),\n AUTORENEWAL_INTERVAL\n )\n }\n\n /** Disable renewing the license periodically. */\n public disableAutoRenewals() {\n if (this.config.autoRenewEnabled === false) return\n\n this.config.autoRenewEnabled = false\n this.log('License autorenewals disabled', LogLevel.INFO)\n\n this.clearRepeatingTimer(this.renewalTimer)\n this.renewalTimer = undefined\n }\n}\n","import {\n fetch,\n getGlobalDispatcher,\n setGlobalDispatcher,\n Dispatcher,\n ProxyAgent,\n} from 'undici'\n\nimport { URL } from 'node:url'\nimport { SDK_VERSION } from './version'\n\nfunction getProxyAgent(variableName: string) {\n const proxyURI = process.env[variableName]\n return proxyURI ? new ProxyAgent(proxyURI) : null\n}\n\nconst httpProxy =\n getProxyAgent('http_proxy_license_server') || getProxyAgent('http_proxy')\nconst httpsProxy =\n getProxyAgent('https_proxy_license_server') || getProxyAgent('https_proxy')\n\nconst proxyAgents = {\n ...(httpProxy ? { 'http:': httpProxy } : {}),\n ...(httpsProxy ? { 'https:': httpsProxy } : {}),\n}\n\nconst noProxyRules = (process.env['no_proxy'] ?? '')\n .split(',')\n .map((rule) => rule.trim())\n\nconst defaultDispatcher = getGlobalDispatcher()\n\nsetGlobalDispatcher(\n new (class extends Dispatcher {\n dispatch(options: any, handler: any) {\n if (options.origin) {\n const { host, protocol } =\n typeof options.origin === 'string'\n ? new URL(options.origin)\n : options.origin\n if (\n !noProxyRules.some((rule) =>\n rule.startsWith('.') ? host.endsWith(rule) : host === rule\n )\n ) {\n const proxyAgent = proxyAgents[protocol as 'http:' | 'https:']\n if (proxyAgent) {\n proxyAgent.dispatch(options, handler)\n }\n }\n }\n return defaultDispatcher.dispatch(options, handler)\n }\n })()\n)\n\nexport async function postRequest<T>(\n url: string,\n data: {},\n options: {\n timeoutInMs?: number\n productIdentifier?: string\n } = {}\n) {\n try {\n const response = await fetch(url, {\n method: 'post',\n body: JSON.stringify(data),\n headers: {\n 'Content-Type': 'application/json',\n 'User-Agent': `License-SDK/${SDK_VERSION} (Node.js ${process.version}; ${process.platform}) ${options.productIdentifier}`,\n },\n signal: AbortSignal.timeout(options.timeoutInMs ?? 30_000),\n })\n\n const responseJson = await response.json()\n\n return {\n status: response.status,\n data: responseJson as T,\n }\n } catch (err) {\n throw new Error('Connection Error', { cause: err })\n }\n}\n\nexport default {\n postRequest,\n}\n","// '2.19.0' is replaced before publishing to npm at .github/workflows/publish_sdk.yml\nexport const SDK_VERSION = '2.19.0'\n"],"mappings":"0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,0BAAAE,EAAA,mBAAAC,IAAA,eAAAC,EAAAJ,GAAA,IAAAK,EAAqB,wBACrBC,EAA0B,2BAC1BC,EAAoB,uBACpBC,EAAmB,kBACnBC,EAAgC,kBCJhC,IAAAC,EAMO,kBAEPC,EAAoB,eCPb,IAAMC,EAAc,SDU3B,SAASC,EAAcC,EAAsB,CAC3C,IAAMC,EAAW,QAAQ,IAAID,CAAY,EACzC,OAAOC,EAAW,IAAI,aAAWA,CAAQ,EAAI,IAC/C,CAEA,IAAMC,EACJH,EAAc,2BAA2B,GAAKA,EAAc,YAAY,EACpEI,EACJJ,EAAc,4BAA4B,GAAKA,EAAc,aAAa,EAEtE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AASE,EAAK,CACZ,KAAK,IACH,2CAA2CA,CAAG,kDAC9C,MACF,CACF,QAAE,CACA,MAAM,KAAK,OAAO,YAAY,EAAE,EAChC,MAAM,KAAK,SAAS,CACtB,CACF,CAEA,MAAa,UAAW,CACtB,KAAK,eAAiB,GAEtB,KAAK,oBAAoB,KAAK,YAAY,EAC1C,KAAK,oBAAoB,KAAK,oCAAoC,EAClE,KAAK,iBAAiB,KAAK,sBAAsB,EAE7C,KAAK,OAAO,0BACd,MAAM,KAAK,2BAA2B,CAE1C,CAEA,MAAc,4BAA6B,CACzC,GAAI,CAAC,KAAK,QAAQ,EAChB,OAG+B,KAAK,YAAY,aAAa,KAC5DrC,GAAgBA,EAAY,aAAe,EAC9C,GAGE,MAAM,KAAK,OAAO,CAChB,2BAA4B,GAC5B,MAAO,UACT,CAAC,CAEL,CAGO,oBAAqB,CACtB,KAAK,OAAO,mBAAqB,KAErC,KAAK,OAAO,iBAAmB,GAC/B,KAAK,IAAI,+BAAgC,MAAa,EAEtD,KAAK,oBAAoB,KAAK,YAAY,EAC1C,KAAK,aAAe,KAAK,oBACvB,IAAM,KAAK,YAAY,CAAE,MAAO,EAAM,CAAC,EACvC5B,CACF,EACF,CAGO,qBAAsB,CACvB,KAAK,OAAO,mBAAqB,KAErC,KAAK,OAAO,iBAAmB,GAC/B,KAAK,IAAI,gCAAiC,MAAa,EAEvD,KAAK,oBAAoB,KAAK,YAAY,EAC1C,KAAK,aAAe,OACtB,CACF","names":["LicenseManager_exports","__export","AUTORENEWAL_INTERVAL","LicenseManager","__toCommonJS","import_crypto_js","import_node_machine_id","import_node_rsa","import_node_assert","import_node_crypto","import_undici","import_node_url","SDK_VERSION","getProxyAgent","variableName","proxyURI","httpProxy","httpsProxy","proxyAgents","noProxyRules","rule","defaultDispatcher","options","handler","host","protocol","proxyAgent","postRequest","url","data","response","SDK_VERSION","responseJson","err","AUTORENEWAL_INTERVAL","LicenseManager","config","msg","logLevel","AUTORENEWAL_INTERVAL","callback","interval","timer","date","durationInMs","reservationId","postData","response","postRequest","error","containerStr","errorMsg","e","detachFloatingEntitlements","cause","usageMetrics","passthroughData","responseData","now","useLogger","cert","feature","requireValidCert","quotaFeatureName","currentConsumption","quota","currentFeatures","entitlement","entitlement1","entitlement2","mins15inMs","mins20inMs","expiry","issuedAt","termination","consumerRenewalDue","entitlementRenewalDue","seconds","hours","minutes","remainingSeconds","index","offsets","upcomingEventOffsets","offset","a","b","timeTillNextEventInMs","force","x509","licenseKey","publicKey","NodeRSA","container","stringifiedContainer","certStr","certPayload","match","encryptedSymmetricKey","payload","signature","symmetricKey","decryptedData","CryptoJS","err"]}
|
package/dist/LicenseManager.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import
|
|
1
|
+
import p from"crypto-js";import{machineId as A}from"node-machine-id";import S from"node-rsa";import{ok as L}from"node:assert";import{X509Certificate as w}from"node:crypto";import{fetch as v,getGlobalDispatcher as T,setGlobalDispatcher as y,Dispatcher as E,ProxyAgent as I}from"undici";import{URL as b}from"node:url";var d="2.19.0";function l(a){let e=process.env[a];return e?new I(e):null}var f=l("http_proxy_license_server")||l("http_proxy"),m=l("https_proxy_license_server")||l("https_proxy"),R={...f?{"http:":f}:{},...m?{"https:":m}:{}},F=(process.env.no_proxy??"").split(",").map(a=>a.trim()),D=T();y(new class extends E{dispatch(a,e){if(a.origin){let{host:t,protocol:i}=typeof a.origin=="string"?new b(a.origin):a.origin;if(!F.some(n=>n.startsWith(".")?t.endsWith(n):t===n)){let n=R[i];n&&n.dispatch(a,e)}}return D.dispatch(a,e)}});async function u(a,e,t={}){try{let i=await v(a,{method:"post",body:JSON.stringify(e),headers:{"Content-Type":"application/json","User-Agent":`License-SDK/${d} (Node.js ${process.version}; ${process.platform}) ${t.productIdentifier}`},signal:AbortSignal.timeout(t.timeoutInMs??3e4)}),n=await i.json();return{status:i.status,data:n}}catch(i){throw new Error("Connection Error",{cause:i})}}var h=15*60*1e3;var C=class{constructor(e){this.isShuttingDown=!1;this.config=e,this.config.logger?this.logger=this.config.logger:this.logger={error(){console.log("ERROR:",...arguments)},warn(){console.log("WARN:",...arguments)},info(){console.log("INFO:",...arguments)},debug(){console.log("DEBUG:",...arguments)}},this.x509IssuerCert=new w(`-----BEGIN CERTIFICATE-----
|
|
2
2
|
MIIFDDCCAvQCCQCWGBewlWbp0DANBgkqhkiG9w0BAQsFADBIMQswCQYDVQQGEwJE
|
|
3
3
|
RTEPMA0GA1UECAwGQmVybGluMQ8wDQYDVQQHDAZCZXJsaW4xFzAVBgNVBAMMDmxp
|
|
4
4
|
Y2Vuc2UubjhuLmlvMB4XDTIyMDYyNDA0MDkzM1oXDTQ5MTEwOTA0MDkzM1owSDEL
|
|
@@ -26,7 +26,7 @@ uMNs3MjEmfbaBV1K0GKG5UToF9UmUxxVmTcRUZrAQX+yBkRezDTpOQuRnB58BDQP
|
|
|
26
26
|
A62lcgZlikzJw3lHue33qAudyUrUmjfHGll7GFQNeLO42jPMeM4NJiNIrBZ7j0uD
|
|
27
27
|
4slHdDi/44PHcKchvde/5k7ZJMi6OC1Vu+bOnKvzhnWQIOkHFQ55m13oslV2ozZT
|
|
28
28
|
/oqhn/8/LeV0ooZuYnBeRkRTveniUeho2OFe5xZvWSSfuBrbHt9+zBg+5MWPUTIJ
|
|
29
|
-
-----END CERTIFICATE-----`),this.config.autoRenewEnabled=this.config.autoRenewEnabled??!0,this.config.renewOnInit=this.config.renewOnInit??!1,this.config.offlineMode=this.config.offlineMode??!1,this.config.autoRenewOffset=this.config.autoRenewOffset??60*60*72,this.config.server=this.config.server??"https://license.n8n.io/v1"}get isInitialized(){return!!this.initializationPromise}log(e,t){this.logger[t](`[license SDK] ${e}`)}async initialize(){return this.initializationPromise?this.initializationPromise:(this.initializationPromise=this._doInitialization(),await this.initializationPromise)}async _doInitialization(){
|
|
29
|
+
-----END CERTIFICATE-----`),this.config.autoRenewEnabled=this.config.autoRenewEnabled??!0,this.config.renewOnInit=this.config.renewOnInit??!1,this.config.offlineMode=this.config.offlineMode??!1,this.config.autoRenewOffset=this.config.autoRenewOffset??60*60*72,this.config.detachFloatingOnShutdown=this.config.detachFloatingOnShutdown??!0,this.config.server=this.config.server??"https://license.n8n.io/v1"}get isInitialized(){return!!this.initializationPromise}log(e,t){this.logger[t](`[license SDK] ${e}`)}async initialize(){return this.initializationPromise?this.initializationPromise:(this.initializationPromise=this._doInitialization(),await this.initializationPromise)}async _doInitialization(){L(!this.initializationPromise,"Initialization already in progress"),this.deviceFingerprint=await this.computeDeviceFingerprint(),this.log(`initializing for deviceFingerprint ${this.deviceFingerprint}`,"debug"),await this.initCert(),this.clearRepeatingTimer(this.upcomingEntitlementChangesCheckTimer),this.upcomingEntitlementChangesCheckTimer=this.setupRepeatingTimer(()=>this.setTimerForNextEntitlementChange(),h),this.config.renewOnInit&&this.config.autoRenewEnabled&&this.hasCert()&&(this.licenseCert.detachedEntitlementsCount>0||this.isOlderThan(this.licenseCert.issuedAt,24*60*60*1e3))?await this.renewalCron({force:!0}):this.log("Skipping renewal on init because cert was issued less than 24 hours ago or not initialized","debug"),this.config.autoRenewEnabled&&(this.clearRepeatingTimer(this.renewalTimer),this.renewalTimer=this.setupRepeatingTimer(()=>this.renewalCron({force:!1}),h))}setupSingleTimer(e,t){return setTimeout(e,t)}clearSingleTimer(e){e&&clearTimeout(e)}setupRepeatingTimer(e,t){return setInterval(e,t)}clearRepeatingTimer(e){e&&clearInterval(e)}isOlderThan(e,t){return Date.now()-e.getTime()>t}async reload(){await this.reset(),await this.initialize()}async reset(){this.initializationPromise&&await this.initializationPromise,this.clearRepeatingTimer(this.renewalTimer),this.renewalTimer=void 0,this.clearRepeatingTimer(this.upcomingEntitlementChangesCheckTimer),this.upcomingEntitlementChangesCheckTimer=void 0,this.clearSingleTimer(this.entitlementChangeTimer),this.entitlementChangeTimer=void 0,this.licenseCert=void 0,this.deviceFingerprint=void 0,this.initializationPromise=void 0}async computeDeviceFingerprint(){return this.config.deviceFingerprint&&typeof this.config.deviceFingerprint=="function"?await this.config.deviceFingerprint():await A()}async activate(e){if(!this.isInitialized)throw new Error("activation failed because SDK was not yet initialized");if(this.isShuttingDown)throw new Error("activation failed because SDK is shutting down");if(this.config.offlineMode)throw new Error("activation failed because SDK is in offline mode");let t={reservationId:e,tenantId:this.config.tenantId,productIdentifier:this.config.productIdentifier,deviceFingerprint:this.deviceFingerprint};this.hasCert()&&(t.consumerId=this.licenseCert.consumerId,t.renewalToken=this.licenseCert.renewalToken);let i;try{i=await u(`${this.config.server}/activate`,t,{timeoutInMs:1e4,productIdentifier:this.config.productIdentifier})}catch(n){throw this.log("license activation failed: "+n.message,"warn"),new Error(n.message)}if(i.status==200){if(!i.data.hasOwnProperty("licenseKey")||!i.data.hasOwnProperty("x509"))throw this.log("unexpected server response","warn"),new Error("unexpected server response");let n=this.stringifyCertContainer({licenseKey:i.data.licenseKey,x509:i.data.x509});await this.config.saveCertStr(n),await this.initCert(),this.log("license successfully activated","info"),(i.data.detachedEntitlementsCount??!1)&&this.log(`skipped importing ${i.data.detachedEntitlementsCount} floating entitlements which are currently in use elsewhere`,"info")}else{let n=`license activation failed: ${i.data.message??"unknown reason"}`,r=new Error(n);throw i.data.errorId&&(r.errorId=i.data.errorId),this.log(n,"warn"),r}}async renew(){return this._renew({cause:"request"})}async _renew({detachFloatingEntitlements:e=!1,cause:t="unknown"}={}){if(!this.hasCert())throw new Error("renewal failed because current cert is not initialized");if(this.licenseCert.isEphemeral)return;if(this.isTerminated())throw new Error("renewal failed because current cert was terminated");if(this.config.offlineMode)throw new Error("renewal failed because SDK is in offline mode");if(this.config.tenantId!==this.licenseCert.tenantId)throw new Error("renewal failed because tenant ID does not match");if(t!=="request"&&this.licenseCert.deviceLock&&this.deviceFingerprint!==this.licenseCert.deviceFingerprint)throw new Error("renewal failed because device fingerprint does not match");let[i,n]=await Promise.all([this.config.collectUsageMetrics?this.config.collectUsageMetrics():[],this.config.collectPassthroughData?this.config.collectPassthroughData():{}]),r;try{r=await u(`${this.config.server}/renew`,{consumerId:this.licenseCert.consumerId,tenantId:this.config.tenantId,deviceFingerprint:this.deviceFingerprint,productIdentifier:this.config.productIdentifier,renewalToken:this.licenseCert.renewalToken,detachFloatingEntitlements:e,cause:t,usageMetrics:i,passthroughData:n},{timeoutInMs:1e4,productIdentifier:this.config.productIdentifier})}catch(o){throw this.log("license renewal failed: "+o.message,"warn"),new Error(o.message)}let s=r.data;if(r.status==200){if(!s.hasOwnProperty("licenseKey")||!s.hasOwnProperty("x509"))throw this.log("license renewal failed: unexpected server response","warn"),new Error("unexpected server response");let o=this.stringifyCertContainer({licenseKey:s.licenseKey,x509:s.x509});await this.config.saveCertStr(o),this.log("license successfully renewed","debug"),(s.detachedEntitlementsCount??!1)&&(e?this.log(`${s.detachedEntitlementsCount} floating entitlements were returned to the pool`,"info"):this.log(`skipped importing ${s.detachedEntitlementsCount} floating entitlements which are currently in use elsewhere`,"info")),await this.initCert()}else{let o=`license renewal failed: ${s.message??"unknown reason"}`;this.log(o,"warn");let c=new Error(o);throw s.errorId&&(c.errorId=s.errorId,["NOT_FOUND","CONSUMER_TERMINATED"].includes(s.errorId)&&(this.log("license was terminated by the server. Deleting local cert.","warn"),await this.config.saveCertStr(""),await this.initCert())),c}}hasCert(){return!!this.licenseCert}isTerminated(){if(!this.hasCert())throw new Error("Cert is not initialized");let e=new Date;return this.licenseCert.terminatesAt<e}getExpiryDate(){if(!this.hasCert())throw new Error("Cert is not initialized");return this.licenseCert.expiresAt}getTerminationDate(){if(!this.hasCert())throw new Error("Cert is not initialized");return this.licenseCert.terminatesAt}isValid(e=!0){let t=r=>{e&&this.log(r,"error")};if(!this.hasCert())return t("cert is invalid because it is undefined"),!1;let i=this.licenseCert,n=new Date;return i.expiresAt<n?(t("cert is invalid because it has expired"),!1):i.terminatesAt<n?(t("cert is invalid because it was terminated"),!1):i.createdAt.getTime()-3e5>n.getTime()?(t("cert is invalid because system clock is out of sync"),!1):i.deviceLock&&this.deviceFingerprint!==i.deviceFingerprint?(t("cert is invalid because device fingerprint does not match"),!1):this.config.tenantId!==i.tenantId?(t("cert is invalid because tenant ID does not match"),!1):!0}hasFeatureEnabled(e,t=!0){return!!this.getFeatureValue(e,t)}hasFeatureDefined(e,t=!0){return this.getFeatureValue(e,t)!==void 0}hasQuotaLeft(e,t){let i=this.getFeatureValue(e);if(i===void 0)return!1;if(typeof i!="number")throw new Error(`${e} cannot be used as quota as it is not numeric`);return i===-1?!0:Math.ceil(t)<Math.ceil(i)}getFeatureValue(e,t=!0){if(!this.hasCert()||t&&!this.isValid())return;let i=this.getFeatures();if(i.hasOwnProperty(e))return i[e]}updateCurrentFeatures(){if(!this.hasCert())return;let e=new Date;(this.licenseCert.expiresAt<e||this.licenseCert.terminatesAt<e)&&(this.currentFeatures={}),this.currentFeatures=this.licenseCert.entitlements.filter(t=>t.validFrom<=e&&t.validTo>e).sort((t,i)=>t.validFrom.getTime()-i.validFrom.getTime()).reduce((t,i)=>({...t,...i.features,...i.featureOverrides}),{})}getFeatures(){return this.hasCert()?this.currentFeatures??{}:{}}getCurrentEntitlements(){if(!this.hasCert())return[];let e=new Date;return this.licenseCert.entitlements.filter(t=>t.validFrom<=e&&t.validTo>e)}getManagementJwt(){return this.licenseCert?this.licenseCert.managementJwt:""}async getCertStr(){return this.config.loadCertStr()}getConsumerId(){return this.licenseCert?.consumerId}isRenewalDue(){if(!this.licenseCert||this.licenseCert.isEphemeral)return!1;let e=Date.now(),t=1e3*60*15,i=1e3*60*20,n=this.licenseCert.expiresAt.getTime(),r=this.licenseCert.issuedAt.getTime(),s=this.licenseCert.terminatesAt.getTime(),o=e>n-this.config.autoRenewOffset*1e3&&e<s,c=this.getCurrentEntitlements().find(g=>e>=g.validTo.getTime()-t&&e<=g.validTo.getTime())!==void 0&&r<e-i;return o||c}formatDuration(e){let t=Math.floor(e/3600),i=Math.floor(e%3600/60),n=e%60;return`${t}h ${i}m ${n}s`}toString(){return`## CONSUMER CONFIG ##
|
|
30
30
|
tenantId: ${this.config.tenantId??"<n/a>"}
|
|
31
31
|
productIdentifier: ${this.config.productIdentifier??"<n/a>"}
|
|
32
32
|
deviceFingerprint: ${this.deviceFingerprint??"<n/a>"}
|
|
@@ -55,5 +55,5 @@ validFrom: ${e.validFrom}
|
|
|
55
55
|
validTo: ${e.validTo}
|
|
56
56
|
features: ${JSON.stringify(e.features)}
|
|
57
57
|
featureOverrides: ${JSON.stringify(e.featureOverrides)}
|
|
58
|
-
`).join("")}triggerOnFeatureChangeCallback(){this.config.onFeatureChange&&this.config.onFeatureChange(this.currentFeatures??{})}setTimerForNextEntitlementChange(){if(!this.hasCert())return;let e=Date.now(),t=new Set;t.add(this.licenseCert.expiresAt.getTime()-e),t.add(this.licenseCert.terminatesAt.getTime()-e);let i=[...this.licenseCert.entitlements.reduce((r,s)=>(r.add(s.validFrom.getTime()-e),r.add(s.validTo.getTime()-e),r),t)].filter(r=>r>=0&&r<=h).sort((r,s)=>r-s);if(i.length===0)return;let n=i[0];this.clearSingleTimer(this.entitlementChangeTimer),this.entitlementChangeTimer=this.setupSingleTimer(()=>{this.updateCurrentFeatures(),this.triggerOnFeatureChangeCallback(),this.setTimerForNextEntitlementChange()},n+1e3)}async renewalCron({force:e}){if(e||this.isRenewalDue()){this.log("attempting license renewal","debug");try{await this._renew({cause:e?"startup":"auto"})}catch{}}}async initCert(){if(!this.isShuttingDown)try{let e=await this.getCertStr();if(!e){this.licenseCert=void 0;return}if(e.length<50)throw new Error("cert string is undefined or too short");let{x509:t,licenseKey:i}=this.parseLicenseCertContainerStr(e);if(this.x509Cert=new
|
|
58
|
+
`).join("")}triggerOnFeatureChangeCallback(){this.config.onFeatureChange&&this.config.onFeatureChange(this.currentFeatures??{})}setTimerForNextEntitlementChange(){if(!this.hasCert())return;let e=Date.now(),t=new Set;t.add(this.licenseCert.expiresAt.getTime()-e),t.add(this.licenseCert.terminatesAt.getTime()-e);let i=[...this.licenseCert.entitlements.reduce((r,s)=>(r.add(s.validFrom.getTime()-e),r.add(s.validTo.getTime()-e),r),t)].filter(r=>r>=0&&r<=h).sort((r,s)=>r-s);if(i.length===0)return;let n=i[0];this.clearSingleTimer(this.entitlementChangeTimer),this.entitlementChangeTimer=this.setupSingleTimer(()=>{this.updateCurrentFeatures(),this.triggerOnFeatureChangeCallback(),this.setTimerForNextEntitlementChange()},n+1e3)}async renewalCron({force:e}){if(e||this.isRenewalDue()){this.log("attempting license renewal","debug");try{await this._renew({cause:e?"startup":"auto"})}catch{}}}async initCert(){if(!this.isShuttingDown)try{let e=await this.getCertStr();if(!e){this.licenseCert=void 0;return}if(e.length<50)throw new Error("cert string is undefined or too short");let{x509:t,licenseKey:i}=this.parseLicenseCertContainerStr(e);if(this.x509Cert=new w(t),!this.x509Cert.checkIssued(this.getIssuerCert()))throw new Error("cert was not issued by an approved issuer");let r=this.x509Cert.publicKey.export({format:"pem",type:"pkcs1"});this.key=new S(r),this.licenseCert=this.parseLicenseKeyStr(i),this.updateCurrentFeatures(),this.setTimerForNextEntitlementChange()}catch(e){this.log(`cert could not be initialized. ${e instanceof Error?e.message:""}`,"error")}}stringifyCertContainer(e){let t=JSON.stringify(e);return Buffer.from(t).toString("base64")}parseLicenseCertContainerStr(e){let t=Buffer.from(e,"base64").toString("ascii"),i=JSON.parse(t);if(!i.hasOwnProperty("licenseKey")||!i.hasOwnProperty("x509"))throw new Error("license cert container could not be parsed");return i}parseLicenseKeyStr(e){let t=this.validateLicenseKey(e),i={...t};return i.createdAt=new Date(t.createdAt),i.issuedAt=new Date(t.issuedAt),i.expiresAt=new Date(t.expiresAt),i.terminatesAt=new Date(t.terminatesAt),i.detachedEntitlementsCount=t.detachedEntitlementsCount??0,i.entitlements=i.entitlements.map(n=>(n.validFrom=new Date(n.validFrom),n.validTo=new Date(n.validTo),n)),i}validateLicenseKey(e){e=e.replace(/(\r\n|\n|\r)/gm,"");let t=e.match(/^-----BEGIN LICENSE KEY-----(?<encryptedSymmetricKey>.+\|\|)(?<encryptedData>.+)\|\|(?<signature>.+)-----END LICENSE KEY-----$/);if(!t)throw new Error("license key could not be parsed");let i=t.groups.encryptedSymmetricKey,n=t.groups.encryptedData,r=t.groups.signature,s,o;try{s=this.key.decryptPublic(i,"utf8")}catch{throw new Error("Invalid data: Could not extract symmetric key")}try{o=p.AES.decrypt(n,s).toString(p.enc.Utf8)}catch{throw new Error("Invalid Data: Could not decrypt data with key found")}if(this.key.verify(Buffer.from(o),r,"utf8","base64"))return JSON.parse(o);throw new Error("License Key signature invalid")}getIssuerCert(){return this.x509IssuerCert}async clear(){try{await this.detachFloatingEntitlements()}catch(e){this.log(`failed to detach floating entitlements (${e}). Continuing with clearing license certificate`,"warn")}finally{await this.config.saveCertStr(""),await this.initCert()}}async shutdown(){this.isShuttingDown=!0,this.clearRepeatingTimer(this.renewalTimer),this.clearRepeatingTimer(this.upcomingEntitlementChangesCheckTimer),this.clearSingleTimer(this.entitlementChangeTimer),this.config.detachFloatingOnShutdown&&await this.detachFloatingEntitlements()}async detachFloatingEntitlements(){if(!this.hasCert())return;this.licenseCert.entitlements.some(t=>t.isFloatable??!1)&&await this._renew({detachFloatingEntitlements:!0,cause:"shutdown"})}enableAutoRenewals(){this.config.autoRenewEnabled!==!0&&(this.config.autoRenewEnabled=!0,this.log("License autorenewals enabled","info"),this.clearRepeatingTimer(this.renewalTimer),this.renewalTimer=this.setupRepeatingTimer(()=>this.renewalCron({force:!1}),h))}disableAutoRenewals(){this.config.autoRenewEnabled!==!1&&(this.config.autoRenewEnabled=!1,this.log("License autorenewals disabled","info"),this.clearRepeatingTimer(this.renewalTimer),this.renewalTimer=void 0)}};export{h as AUTORENEWAL_INTERVAL,C as LicenseManager};
|
|
59
59
|
//# sourceMappingURL=LicenseManager.mjs.map
|