cripta
Version:
A layer of encryption a little too judicious
1 lines • 13.9 kB
JavaScript
import V,{createHash,randomBytes}from'crypto';import {Envir,toInt,Timestamp,DataBag}from't0n';function p(r,t,e){let n=createHash(t);return typeof r=="string"?n.update(r,"utf8"):n.update(r),!e||e==="buffer"?n.digest():n.digest(e)}function H(r,t="hex"){return p(r,"md5",t)}function X(r,t="hex"){return p(r,"sha1",t)}function f(r,t="hex"){return p(r,"sha256",t)}function q(r,t="hex"){return p(r,"sha512",t)}var T=16,w=5,O=40;function $(r,t=""){if(!r||typeof r!="string"||typeof t!="string")return "";let e=r.length;t||(t=I(j(T%e||P(w,T)).toString("base64")));let n=t.length%2,s=n?t:"",i=n?"":t;return s+I(createHash("sha256").update(Buffer.from(t+r)).digest("base64").substring(0,O))+i}function W(r,t){if(!r||!t||typeof r!="string"||typeof t!="string")return false;let e=M(t);return e?$(r,e)===t:false}function M(r){if(!r||typeof r!="string")return "";let t=r.length%O;return t&&t%2?r.slice(0,t):r.slice(-t)}function j(r){return typeof randomBytes=="function"?randomBytes(r):F(r)}function F(r){let t=Buffer.alloc(r);for(let e=0;e<r;e++)t[e]=Math.floor(Math.random()*256)&255;return t}function P(r,t){return r=Math.ceil(r),Math.floor(Math.random()*(Math.floor(t)-r+1))+r}function I(r){return r.replace(/[=+]/g,t=>{switch(t){case "=":return "";case "+":return ".";default:return t}})}var h=class r{constructor(t){this.entropy=4;this.baseAlphabet="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_";this.setKey(t?.key||Envir.get("APP_KEY",Envir.get("KEY"))).setSeed(t?.seed).setEntropy(t?.entropy);}static#t={};setKey(t){return typeof t!="string"?this:(t=t?.trim(),t?t.indexOf("base64:")>-1?(this.key=f(Buffer.from(t.substring(7),"base64"),"buffer"),this):(this.key=f(t,"buffer"),this):this)}setSeed(t){if(!t)return this;let e=typeof t=="number"?Math.abs(t):toInt(t);return (!this.seed||this.seed!==e)&&(this.alphabet=this.sortSeed(this.baseAlphabet,e)),this.seed=e,this}setEntropy(t){return t==null?this:(this.entropy=typeof t=="number"?Math.abs(t):toInt(t),this)}getInt(t){let e=this[t];return typeof e=="number"?e:toInt(e)}sortSeed(t,e=null){if(!e)return t;let n=typeof e=="string"?this.hashStringToNumber(e):e,s=Array.isArray(t)?JSON.stringify(t):t,i=`${this.hashStringToNumber(s)}-${n}`;if(r.#t[i])return r.#t[i];let u=Array.isArray(t),l=u?[...t]:this.#r(t),U=this.createSeededRNG(n),S=l.map((d,C)=>({item:d,sortKey:U()})).sort((d,C)=>d.sortKey-C.sortKey).map(d=>d.item),A=u?S:S.join("");return r.#t[i]=A,A}#r(t){return t.split(/(?!^)(?=.)/u).filter(Boolean)}createSeededRNG(t){return function(){t|=0,t=t+1831565813|0;let e=Math.imul(t^t>>>15,1|t);return e=e+Math.imul(e^e>>>7,61|e)^e,((e^e>>>14)>>>0)/4294967296}}hashStringToNumber(t){let e=5381;for(let n=0;n<t.length;n++)e=e*33^t.charCodeAt(n);return e>>>0}};var v=["null","boolean","string","int","float","bigint","array","object","symbol","undefined"],a=Object.fromEntries(v.map((r,t)=>[r,t]));var g=class{constructor(t){this.separator="";this.config=new h;this.lastConfig=null;this.#t=["","===","==","="];t&&this.setConfig(t);}same(){return this.config.entropy=0,this.setConfig(this.config)}unique(){return this.config.entropy=4,this.setConfig(this.config)}setConfig(t){return this.config=t instanceof h?t:new h(t),this}onceConfig(t){return t instanceof h||(t=new h(t)),this.lastConfig=this.config,this.config=Object.assign(new h,t),this}onceKey(t){return this.lastConfig=Object.assign(new h,this.config),this.config.setKey(t),this}maybeRestoreConfig(){return this.lastConfig!==null&&(this.config=Object.assign(new h,this.lastConfig),this.lastConfig=null),this}validateConfig(){let t=this.config.key;if(!t||!t?.byteLength||!t.length)throw new Error("Secret key is required for use cripta.")}encode(t){this.validateConfig();let e=this.config.entropy,n=e?V.randomBytes(e):Buffer.alloc(0),s=Buffer.from(this.toText(t)),i=this.baseEncode(Buffer.concat([this.cipher(s,this.forgeKey(n)),n]));return this.maybeRestoreConfig(),i}decode(t){this.validateConfig();let e=this.baseDecode(t),n=this.config.entropy,s=n?e.subarray(-n):Buffer.alloc(0),i=n?e.subarray(0,-n):e,u=this.convert(this.cipher(i,this.forgeKey(s)).toString("utf8"));return this.maybeRestoreConfig(),u}convert(t){let e=t.indexOf(this.separator);if(e!==-1){let n=t.substring(0,e),s=parseInt(n,10),i=t.substring(e+1);switch(s){case a.null:return null;case a.boolean:return i==="true"||i==="1";case a.string:return i;case a.int:return parseInt(i,10);case a.float:return parseFloat(i);case a.bigint:return BigInt(i);case a.array:case a.object:try{return JSON.parse(i)}catch{return null}case a.symbol:return Symbol.for(i);case a.undefined:return}}try{return JSON.parse(t)}catch{return t}}toText(t){if(t===null)return `${a.null}${this.separator}`;if(t===void 0)return `${a.undefined}${this.separator}`;let e=typeof t;return e==="boolean"?`${a.boolean}${this.separator}${t?"1":"0"}`:e==="string"?`${a.string}${this.separator}${t}`:e==="number"?`${Number.isInteger(t)?a.int:a.float}${this.separator}${t}`:e==="bigint"?`${a.bigint}${this.separator}${t.toString()}`:e==="symbol"?`${a.symbol}${this.separator}${Symbol.keyFor(t)??t.toString()}`:Array.isArray(t)?`${a.array}${this.separator}${JSON.stringify(t)}`:e==="object"?`${a.object}${this.separator}${JSON.stringify(t)}`:""}cipher(t,e){let n=Buffer.allocUnsafe(t.length),s=e.length;for(let i=0;i<t.length;i++)n[i]=t[i]^e[i%s];return n}forgeKey(t){return f(Buffer.concat([this.config.key,t]),"buffer")}maybeUseAlphabet(t,e,n){return !t||typeof t!="string"||!e||!n||e===n?t:this.strtr(t,e,n)}strtr(t,e,n){let s="";for(let i=0;i<t.length;i++){let u=t[i],l=e.indexOf(u);s+=l!==-1&&l<n.length?n[l]:u;}return s}baseEncode(t){return this.maybeUseAlphabet(t.toString("base64").replace(/[=+/]/g,e=>{switch(e){case "=":return "";case "+":return "-";case "/":return "_";default:return e}}),this.config.baseAlphabet,this.config.alphabet)}#t;baseDecode(t){t=this.maybeUseAlphabet(t,this.config.alphabet,this.config.baseAlphabet);let e=t.length%4;return e&&(t+=this.#t[e]),Buffer.from(t.replace(/[-_]/g,n=>n==="-"?"+":"/"),"base64")}};var o=class r{static{this.AUDIENCE="aud";}static{this.EXPIRATION_TIME="exp";}static{this.ID="jti";}static{this.ISSUED_AT="iat";}static{this.ISSUER="iss";}static{this.NOT_BEFORE="nbf";}static{this.SUBJECT="sub";}static{this.NOW="now";}static{this.BROWSER="bwr";}static{this.IP="ip";}static{this.LOCATION="loc";}static{this.ALL=[r.AUDIENCE,r.EXPIRATION_TIME,r.ID,r.ISSUED_AT,r.ISSUER,r.NOT_BEFORE,r.SUBJECT,r.NOW,r.IP,r.BROWSER,r.LOCATION];}static{this.RFC7519=[r.AUDIENCE,r.EXPIRATION_TIME,r.ID,r.ISSUED_AT,r.ISSUER,r.NOT_BEFORE,r.SUBJECT];}static{this.DATE_CLAIMS=[r.ISSUED_AT,r.NOT_BEFORE,r.EXPIRATION_TIME];}static{this.CUSTOM=[r.IP,r.BROWSER,r.LOCATION];}};var c=class{constructor(){this.claims=new DataBag;this.header=new DataBag;this.headerString="";this.body=Symbol("UNDEFINED");this.bodyString="";this.signature="";this.#t=false;this.#r=new h({entropy:0});this.#n=0;this.#e=new g;this.#s=".";}#t;#r;#n;#e;#s;secret(t){this.#e.config.setKey(t),this.#r.setKey(t);}parseHeader(t=""){if(t)try{let e=this.#e.decode(t);typeof e=="object"&&(this.header.replace(e),this.headerString=t);}catch{}return this}encodedHeader(){return this.#i(),this.headerString=this.#e.encode(this.#t?this.header.all():this.#u(this.header.all()))}parseBody(t=""){if(t&&this.header.has("e"))try{let e=this.#e.onceKey(this.header.get("e")).decode(t);this.body=e,this.bodyString=t;}catch{}return this}encodedBody(){return this.bodyString=this.#e.onceKey(this.#a()).encode(this.body)}setSignature(t){return this.signature=t,this}sign(){return this.#h(this.headerString+this.bodyString,this.secret+this.#a())}signed(){return this.signature?this.signature===this.sign():false}isValid(){return this.body!==Symbol("UNDEFINED")&&this.signed()?this.validateClaims():false}isInvalid(){return !this.isValid()}hasValue(t,e=null){return this.header.has(t)?e===null?true:this.header.get(t)===e:this.body&&typeof this.body=="object"&&Object.keys(this.body).length>0&&t in this.body?e===null?true:this.body[t]===e:false}validateClaims(){let t=this.claims.get(o.NOW,Math.floor(Date.now()/1e3));return !(this.isExpired(t)||!this.notBefore(t)||!this.issuedBefore(t)||!this.validate(o.AUDIENCE)||!this.validate(o.ISSUER)||!this.validate(o.ID)||!this.validate(o.SUBJECT)||!this.validateCustomClaims())}isExpired(t=null){let e=o.EXPIRATION_TIME;return this.header.has(e)?Timestamp.timestamp(t)-this.#n>=this.header.get(e):false}#o(t,e=null){return this.header.has(t)?Timestamp.timestamp(e)+this.#n>=this.header.get(t):true}notBefore(t=null){return this.#o(o.NOT_BEFORE,t)}issuedBefore(t=null){return this.#o(o.ISSUED_AT,t)}validate(t,e=null){e=e||this.claims.get(t,null);let n=this.getTokenValue(t);return n=Array.isArray(n)?n:[n],Array.isArray(e)?e.every(s=>n.includes(s)):n.includes(e)}getTokenValue(t){return this.header.has(t)?this.header.get(t):this.body&&typeof this.body=="object"&&Object.keys(this.body).length>0&&t in this.body?this.body[t]:null}validateCustomClaims(){let t=["e",...o.ALL],e={};this.header.toArray().forEach(([i,u])=>{t.includes(i)||(e[i]=u);});let n={};this.claims.toArray().forEach(([i,u])=>{!t.includes(i)&&!(i in e)&&(n[i]=u);});let s={...e,...n};for(let i in s)if(!this.validate(i,s[i]))return false;return true}same(t=""){this.#t=true,this.header.set("e",this.#h(t||this.#e.config.key?.toString("hex")).substring(0,6)),this.#e.config.entropy=0;}unique(){this.#t=false,this.#i(),this.#e.config.entropy=4;}leeway(t=null){this.#n=typeof t=="number"?Math.abs(t):0;}#a(){return this.header.get("e")||this.#i()}#i(){if(this.#t&&this.header.has("e"))return this.header.get("e");let t=V.randomBytes(3).toString("hex");return this.header.set("e",t),t}#h(t,e=null){return e&&this.#r.setKey(e),this.#e.onceConfig(this.#r).encode(f(String(t),"binary").toString().substring(0,16))}getParts(t){if(!t)return false;let e=t.split(this.#s);return e.length===3?e:false}toString(){return [this.headerString||this.encodedHeader(),this.bodyString||this.encodedBody(),this.sign()].join(this.#s)}#u(t){let e=Object.keys(t),n={};for(let s=e.length-1;s>0;s--){let i=Math.floor(Math.random()*(s+1));[e[s],e[i]]=[e[i],e[s]];}return e.forEach(s=>{n[s]=t[s];}),n}};var y=class{constructor(){this.token=new c;}same(){return this.token.same(),this}unique(){return this.token.unique(),this}body(t){return this.token.body=t,this}payload(t){return this.body(t)}content(t){return this.body(t)}secret(t){return this.token.secret(t),this}phrase(t){return this.secret(t)}passphrase(t){return this.secret(t)}expiresAt(t){return this.token.header.set(o.EXPIRATION_TIME,Timestamp.timestamp(t)),this}expiration(t){return this.expiresAt(t)}exp(t){return this.expiresAt(t)}canOnlyBeUsedAfter(t){return this.token.header.set(o.NOT_BEFORE,Timestamp.timestamp(t)),this}notBefore(t){return this.canOnlyBeUsedAfter(t)}nbf(t){return this.canOnlyBeUsedAfter(t)}issuedAt(t){return this.token.header.set(o.ISSUED_AT,Timestamp.timestamp(t)),this}issuedBefore(t){return this.issuedAt(t)}iat(t){return this.issuedAt(t)}identifiedBy(t){return this.token.header.set(o.ID,t),this}jti(t){return this.identifiedBy(t)}relatedTo(t){return this.token.header.set(o.SUBJECT,t),this}sub(t){return this.relatedTo(t)}permittedFor(...t){return this.token.header.set(o.AUDIENCE,[...this.token.header.get(o.AUDIENCE,[]),...t.flat().filter(e=>typeof e!="object"&&e!==null)]),this}audience(...t){return this.permittedFor(...t)}aud(...t){return this.permittedFor(...t)}issuedBy(t){return this.token.header.set(o.ISSUER,t),this}iss(t){return this.issuedBy(t)}withClaim(t,e){return this.token.header.set(t,e),this}with(t,e){return this.withClaim(t,e)}get(){return this.token.headerString="",this.token.bodyString="",this.token.toString()}toString(){return this.get()}};var b=class{constructor(t){this.token=new c;this.tokenString="";this.parsed=false;this.tokenString=String(t);}same(){return this.token.same(),this}unique(){return this.token.unique(),this}leeway(t){return this.token.leeway(t),this}secret(t){return this.token.secret(t),this}phrase(t){return this.secret(t)}passphrase(t){return this.secret(t)}validAt(t){return this.token.claims.set(o.NOW,Timestamp.timestamp(t)),this}expiresAt(t){return this.validAt(t)}expiration(t){return this.validAt(t)}exp(t){return this.validAt(t)}canOnlyBeUsedAfter(t){return this.validAt(t)}notBefore(t){return this.validAt(t)}nbf(t){return this.validAt(t)}issuedAt(t){return this.validAt(t)}issuedBefore(t){return this.validAt(t)}iat(t){return this.validAt(t)}identifiedBy(t){return this.token.claims.set(o.ID,t),this}jti(t){return this.identifiedBy(t)}relatedTo(t){return this.token.claims.set(o.SUBJECT,t),this}sub(t){return this.relatedTo(t)}permittedFor(...t){return this.token.claims.set(o.AUDIENCE,[...this.token.claims.get(o.AUDIENCE,[]),...t.flat().filter(e=>typeof e!="object"&&e!==null)]),this}audience(...t){return this.permittedFor(...t)}aud(...t){return this.permittedFor(...t)}issuedBy(t){return this.token.claims.set(o.ISSUER,t),this}iss(t){return this.issuedBy(t)}withClaim(t,e){return this.token.claims.set(t,e),this}with(t,e){return this.withClaim(t,e)}parseToken(){if(this.parsed||!this.tokenString||typeof this.tokenString!="string")return;let t=this.token.getParts(this.tokenString);if(t===false||t.length!==3)return;let[e,n,s]=t;this.token.parseHeader(e).parseBody(n).setSignature(s),this.parsed=true;}isValid(){return this.parseToken(),this.token.isValid()}isInvalid(){return !this.isValid()}hasValue(t,e=null){return this.parseToken(),this.token.hasValue(t,e)}has(t,e=null){return this.hasValue(t,e)}get(){return this.parseToken(),this.token.body}toString(){return this.tokenString}};var B=class{static create(){return new y}static parse(t){return new b(t)}};var Ot=r=>new g(r);export{o as Claim,h as Config,g as Cripta,O as HASH_LEN,v as INDEX_TYPE,T as SALT_MAX_LEN,w as SALT_MIN_LEN,a as TYPE,B as Token,W as compare,Ot as cripta,M as getSalt,$ as hash,H as md5,X as sha1,f as sha256,q as sha512};