authrix
Version:
Lightweight, flexible authentication library for Node.js and TypeScript.
1 lines • 4.21 kB
JavaScript
import {i}from'./chunk-7D6A3JGP.mjs';import'./chunk-KPKS7MLL.mjs';import'./chunk-BHP666OX.mjs';import'./chunk-A4X5QZSX.mjs';import'./chunk-YS4LLLFP.mjs';import'./chunk-5VQXQYKM.mjs';import'./chunk-5NOQNI5F.mjs';import {b as b$1}from'./chunk-GACMQPPZ.mjs';import'./chunk-3SAEGOMQ.mjs';var f=class{static fromCookie(e){return t=>t.cookies?.[e]?t.cookies[e]:t.headers?.cookie&&this.parseCookies(t.headers.cookie)[e]||null}static fromHeader(e="authorization",t="Bearer "){return n=>{let s=n.headers?.[e.toLowerCase()];if(!s)return null;let a=Array.isArray(s)?s[0]:s;return typeof a!="string"?null:t&&a.startsWith(t)?a.slice(t.length):a}}static fromQuery(e="token"){return t=>t.query?.[e]||null}static fromBody(e="token"){return t=>t.body?.[e]||null}static chain(...e){return async t=>{for(let n of e){let s=await n(t);if(s)return s}return null}}static parseCookies(e){let t={};return e.split(/;\s*/).forEach(n=>{let[s,...a]=n.split("=");s&&(t[s]=a.join("="));}),t}},v=class{static express(e,t,n){e.status&&e.json?e.status(t).json(n):e.writeHead&&e.end&&(e.writeHead(t,{"Content-Type":"application/json"}),e.end(JSON.stringify(n)));}static fastify(e,t,n){e.code&&e.send?e.code(t).send(n):this.express(e,t,n);}static koa(e,t,n){e.response?(e.response.status=t,e.response.body=n):e.status!==void 0&&e.body!==void 0&&(e.status=t,e.body=n);}static auto(e,t,n){if(e.status&&e.json)this.express(e,t,n);else if(e.code&&e.send)this.fastify(e,t,n);else if(e.response||e.status!==void 0&&e.body!==void 0)this.koa(e,t,n);else if(e.writeHead&&e.end)e.writeHead(t,{"Content-Type":"application/json"}),e.end(JSON.stringify(n));else throw new Error("Unsupported response object")}},b=class{constructor(e=6e4){this.cache=new Map;this.timeout=e;}get(e){let t=this.cache.get(e);return t?Date.now()-t.timestamp>this.timeout?(this.cache.delete(e),null):t.result:null}set(e,t){this.cache.set(e,{result:t,timestamp:Date.now()}),this.cache.size>1e3&&this.cleanup();}cleanup(){let e=Date.now();for(let[t,n]of this.cache.entries())e-n.timestamp>this.timeout&&this.cache.delete(t);}clear(){this.cache.clear();}},w=class{static matches(e,t){return t.some(n=>typeof n=="string"?new RegExp("^"+n.replace(/\*/g,".*").replace(/\?/g,".")+"$").test(e):n.test(e))}};function y(r={}){let{required:e=true,tokenExtractor:t=f.chain(f.fromCookie(r.cookieName||b$1.cookieName),f.fromHeader("authorization","Bearer ")),errorHandler:n=j,successHandler:s,enableCache:a=true,cacheTimeout:d=6e4,allowedPaths:m=[],excludedPaths:E=[],roles:H=[],permissions:x=[],onUnauthorized:P,onForbidden:p}=r,R=a?new b(d):null;return async function(i$1,u,c){try{let g=i$1.path||i$1.url||i$1.originalUrl||"";if(E.length>0&&w.matches(g,E)||m.length>0&&!w.matches(g,m))return c?.();let l=await t(i$1),o;if(R&&l){let h=R.get(l);h?o=h:(o=await i(l),R.set(l,o));}else o=await i(l);if(C(i$1,o,l),e&&!o.isValid)return P?await P(i$1,u):n(new Error(o.error||"Authentication required"),i$1,u,c);if(o.isValid&&H.length>0){let h=o.user?.metadata?.roles||[];if(!H.some(k=>h.includes(k)))return p?await p(i$1,u):n(new Error("Insufficient permissions"),i$1,u,c)}if(o.isValid&&x.length>0){let h=o.user?.metadata?.permissions||[];if(!x.every(k=>h.includes(k)))return p?await p(i$1,u):n(new Error("Insufficient permissions"),i$1,u,c)}if(s)return await s(o,i$1,u,c);c?.();}catch(g){return n(g,i$1,u,c)}}}function C(r,e,t){r.auth=e,r.user=e.user,r.isAuthenticated=e.isValid,r.token=t,r.hasRole=n=>r.user?.metadata?.roles?.includes(n)||false,r.hasPermission=n=>r.user?.metadata?.permissions?.includes(n)||false,r.hasAnyRole=n=>n.some(s=>r.hasRole(s)),r.hasAllPermissions=n=>n.every(s=>r.hasPermission(s));}function j(r,e,t,n){let s=r.status||401,a=r.message||"Authentication required";try{v.auto(t,s,{success:!1,error:{message:a}});}catch{if(n)n(r);else throw r}}var B={express(r){return y(r)},fastify(r){let e=y(r);return async(t,n)=>{await e(t,n,()=>{});}},koa(r){let e=y(r);return async(t,n)=>{await e(t.request,t,n);}},hapi(r){let e=y(r);return {method:async(t,n)=>new Promise((s,a)=>{e(t,{status:d=>({json:m=>n.response(m).code(d)})},d=>{d?a(d):s(n.continue);});})}}};B.express({required:true});var O=B.express({required:false});export{y as createAuthMiddleware,O as optionalAuthMiddleware};