UNPKG

cookie-to-guard

Version:

Library for protecting cookies from tampering

1 lines 2.81 kB
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e=e||self,e.CookieGuard=t())}(this,function(){"use strict";function e(e,t){let n=0;for(let r=0;r<e.length;r++){const o=e.charCodeAt(r);n=(n<<5)-n+o,n|=0}return n.toString(36)+t}return class{constructor(t){if(!t||!t.cookieName)throw new Error("CookieGuard: cookieName is required");this.config={cookieName:t.cookieName,signatureName:`${t.cookieName}_sig`,redirectUrl:t.redirectUrl||null,onDetect:t.onDetect||null,autoReset:t.autoReset!==!1,domain:t.domain||null,secure:t.secure||!1,sameSite:t.sameSite||"Lax",secret:t.secret||this._generateSecret()},this.initialized=!1,this._initialize()}_generateSecret(){return"cg_"+Math.random().toString(36).substring(2,15)+Math.random().toString(36).substring(2,15)}_getCookie(e){const t=document.cookie.split(";");for(let n of t){if(n=n.trim(),n.startsWith(e+"="))return decodeURIComponent(n.substring(e.length+1))}return null}_setCookie(e,t,n=365){const r=new Date;r.setTime(r.getTime()+864e5*n),document.cookie=e+"="+encodeURIComponent(t)+";expires="+r.toUTCString()+";path=/;"}_deleteCookie(e){document.cookie=e+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;"}_createSignature(e){return e.split("").reverse().join("")+this.config.secret}_verifySignature(e,t){return this._createSignature(e)===t}_verifyCookie(){const t=this._getCookie(this.config.cookieName),n=this._getCookie(this.config.signatureName);t&&n?this._verifySignature(t,n)||this._handleCookieTampering():t&&!n&&this._setCookie(this.config.signatureName,this._createSignature(t))}_handleCookieTampering(){this.config.onDetect&&"function"==typeof this.config.onDetect&&this.config.onDetect(),this.config.autoReset&&(this._deleteCookie(this.config.cookieName),this._deleteCookie(this.config.signatureName),this.config.redirectUrl&&(window.location.href=this.config.redirectUrl)}_initialize(){if(!this.initialized){this._verifyCookie();"undefined"!=typeof window&&(this.__originalFetch=window.fetch,window.fetch=async(...e)=>(this._verifyCookie(),this.__originalFetch.apply(this,e))),this.initialized=!0}}setSecureCookie(t,n=365){const r=e(t,this.config.secret),o={days:n,path:"/"};let i=`${this.config.cookieName}=${encodeURIComponent(t)}; expires=${new Date(Date.now()+864e5*n).toUTCString()}; path=${o.path}; SameSite=${this.config.sameSite}; `;this.config.domain&&(i+=`domain=${this.config.domain}; `),this.config.secure&&(i+="Secure; "),document.cookie=i,document.cookie=`${this.config.signatureName}=${encodeURIComponent(r)}; `+i.split("; ").slice(1).join("; ")}getSecureCookie(){return this._verifyCookie(),this._getCookie(this.config.cookieName)}deleteSecureCookie(){this._deleteCookie(this.config.cookieName),this._deleteCookie(this.config.signatureName)}}});