UNPKG

authrix

Version:

Lightweight, flexible authentication library for Node.js and TypeScript.

1 lines 10.6 kB
import {d,a as a$3,b,c as c$1}from'./chunk-KPKS7MLL.mjs';import {a as a$2}from'./chunk-BHP666OX.mjs';import {f,c as c$2,d as d$1}from'./chunk-5VQXQYKM.mjs';import {b as b$1}from'./chunk-GACMQPPZ.mjs';import {a as a$1}from'./chunk-3SAEGOMQ.mjs';var c=class{static{this.cache={};}static{this.detectionComplete=false;}static{this.environmentInfo={isNextJsAvailable:false,context:"unknown",hasAppRouterSupport:false,hasPagesRouterSupport:false,hasMiddlewareSupport:false,detectionComplete:false,runtimeInfo:{hasRequire:false,hasProcess:false,hasGlobalThis:false,hasNextData:false}};}static{this.overridePatch=null;}static async loadModules(){if(this.detectionComplete)return this.cache;this.environmentInfo.runtimeInfo={hasRequire:typeof a$1<"u",hasProcess:typeof process<"u",hasGlobalThis:typeof globalThis<"u",hasNextData:typeof globalThis.c<"u",nextRuntime:typeof process<"u"?process.env?.NEXT_RUNTIME:void 0};let o=async n=>{try{return await import(n)}catch{return null}},e=await o("next/server");e&&(this.cache.NextRequest=e.NextRequest,this.cache.NextResponse=e.NextResponse,this.environmentInfo.hasMiddlewareSupport=true,this.environmentInfo.isNextJsAvailable=true);let t=await o("next/headers");return t&&(this.cache.cookies=t.cookies,this.cache.headers=t.headers,this.environmentInfo.hasAppRouterSupport=true,this.environmentInfo.isNextJsAvailable=true),this.cache.cookies?this.environmentInfo.context="app-router":this.cache.NextRequest&&this.cache.NextResponse?this.environmentInfo.context="middleware":(this.environmentInfo.context="pages-router",this.environmentInfo.hasPagesRouterSupport=true),this.detectionComplete=true,this.environmentInfo.detectionComplete=true,this.overridePatch&&(this.environmentInfo={...this.environmentInfo,...this.overridePatch}),this.cache}static getEnvironmentInfo(){return {...this.environmentInfo}}static reset(){return this.cache={},this.detectionComplete=false,this.loadModules(),this.getEnvironmentInfo()}static setOverride(o){this.overridePatch={...this.overridePatch||{},...o},this.environmentInfo={...this.environmentInfo,...o};}};var a=class{static getCookieName(){try{return b$1?.cookieName||"auth_token"}catch{return "auth_token"}}static normalizeMaxAge(o){return typeof o!="number"?o:o>1e6?Math.floor(o/1e3):o}static createCookieString(o,e,t={}){let n=this.normalizeOptions(t);typeof n.maxAge=="number"&&(n.maxAge=this.normalizeMaxAge(n.maxAge));let r=[`${o}=${e}`];return n.httpOnly&&r.push("HttpOnly"),n.path&&r.push(`Path=${n.path}`),n.maxAge!==void 0&&r.push(`Max-Age=${n.maxAge}`),n.expires&&r.push(`Expires=${n.expires.toUTCString()}`),n.sameSite&&r.push(`SameSite=${n.sameSite}`),n.secure&&r.push("Secure"),r.join("; ")}static createLogoutCookie(o){return this.createCookieString(o,"",{expires:new Date(0),path:"/",httpOnly:true})}static normalizeOptions(o={}){let e=process.env.NODE_ENV==="production",t={...o};return t.httpOnly!==false&&(t.httpOnly=true),t.path||(t.path="/"),t.sameSite||(t.sameSite="lax"),t.sameSite==="none"&&(t.secure=true),typeof t.secure>"u"&&(t.secure=e),t}},l=class{static isValidStructure(o){if(!o||typeof o!="string")return false;let e=o.split(".");return e.length===3&&e.every(t=>t.length>0)}static extractPayload(o){try{if(!this.isValidStructure(o))return null;let e=o.split(".")[1],n=(e+"=".repeat((4-e.length%4)%4)).replace(/-/g,"+").replace(/_/g,"/"),r;return typeof atob=="function"?r=atob(n):r=Buffer.from(n,"base64").toString("utf8"),JSON.parse(r)}catch{return null}}static isExpired(o){let e=this.extractPayload(o);return e?.exp?Math.floor(Date.now()/1e3)>=e.exp:true}};async function A(s,o={}){let e=o.cookieName||a.getCookieName(),t=s.cookies?.get(e)?.value||null;if(!t)return {isAuthenticated:false,user:null,reason:"No token provided"};if(!l.isValidStructure(t))return {isAuthenticated:false,user:null,reason:"Invalid token structure"};try{a$2(t);}catch{return {isAuthenticated:false,user:null,reason:"Invalid or expired token"}}let n=l.extractPayload(t),r=n?{id:n.id,email:n.email,createdAt:n.createdAt?new Date(n.createdAt):void 0}:null;return {isAuthenticated:!!r,user:r,reason:r?"Token valid":"Invalid token payload"}}async function M(s,o={}){let e=await A(s,o);if(!e.isAuthenticated)return e;try{let t=o.cookieName||a.getCookieName(),n=s.cookies?.get(t)?.value;if(!n)return e;let r=new AbortController,i=setTimeout(()=>r.abort(),o.timeout||5e3),C=o.validationEndpoint||"/api/auth/validate",S=s.nextUrl?.origin||s.url?.split("/").slice(0,3).join("/"),y=await fetch(`${S}${C}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},signal:r.signal});return clearTimeout(i),y.ok?{isAuthenticated:!0,user:(await y.json()).user,reason:"Token validated via API"}:e}catch{return e}}function H(s){return async(o,e)=>{try{let t=o&&o.cookies?o.cookies[a.getCookieName()]:null,n=await d(t);return n?(o.user=n,s(o,e)):e.status(401).json({success:!1,error:{message:"Authentication required"}})}catch{return e.status(500).json({success:false,error:{message:"Authentication failed"}})}}}function q(){return async function(o){if(o.method!=="POST")return Response.json({error:"Method not allowed"},{status:405});try{let{email:e,password:t}=await o.json();if(!e||!t)return Response.json({error:"Email and password are required"},{status:400});let n=await a$3(e,t),r=Response.json({success:!0,user:n.user,message:"Account created successfully"}),i=a.createCookieString(a.getCookieName(),n.token,{...n.cookieOptions});return r.headers.set("Set-Cookie",i),r}catch(e){let t=e instanceof Error?e.message:"Signup failed",n=e instanceof f?409:400;return Response.json({error:t},{status:n})}}}function U(){return async function(o){if(o.method!=="POST")return Response.json({error:"Method not allowed"},{status:405});try{let{email:e,password:t}=await o.json();if(!e||!t)return Response.json({error:"Email and password are required"},{status:400});let n=await b(e,t),r=Response.json({success:!0,user:n.user,message:"Signed in successfully"}),i=a.createCookieString(a.getCookieName(),n.token,{...n.cookieOptions});return r.headers.set("Set-Cookie",i),r}catch(e){let t=e instanceof Error?e.message:"Signin failed",n=e instanceof c$2?401:e instanceof d$1?403:400;return Response.json({error:t},{status:n})}}}function D(){return async function(o){if(o.method!=="POST")return Response.json({error:"Method not allowed"},{status:405});try{let e=c$1(),t=Response.json({success:!0,message:e.message}),n=a.createLogoutCookie(a.getCookieName());return t.headers.set("Set-Cookie",n),t}catch{return Response.json({error:"Logout failed"},{status:500})}}}function _(){return async function(o){if(o.method!=="GET")return Response.json({error:"Method not allowed"},{status:405});try{let e=o.headers.get("cookie"),n=N(e||"")[a.getCookieName()],r=await d(n);return r?Response.json({success:!0,user:r}):Response.json({error:"Not authenticated"},{status:401})}catch{return Response.json({error:"Failed to get current user"},{status:500})}}}function $(){return async function(o){try{let e=o.headers.get("Authorization");if(!e?.startsWith("Bearer "))return Response.json({success:!1,error:"Authorization header required"},{status:401});let t=e.slice(7),n=await d(t);return n?Response.json({success:!0,user:n}):Response.json({success:!1,error:"Invalid token"},{status:401})}catch{return Response.json({success:false,error:"Token validation failed"},{status:500})}}}function z(){return async function(o,e){if(o.method!=="POST")return e.status(405).json({error:"Method not allowed"});try{let{email:t,password:n}=o.body;if(!t||!n)return e.status(400).json({error:"Email and password are required"});let r=await a$3(t,n),i=a.createCookieString(a.getCookieName(),r.token,{...r.cookieOptions});return e.setHeader("Set-Cookie",i),e.json({success:!0,user:r.user,message:"Account created successfully"})}catch(t){let n=t instanceof Error?t.message:"Signup failed",r=t instanceof f?409:400;return e.status(r).json({error:n})}}}function L(){return async function(o,e){if(o.method!=="POST")return e.status(405).json({error:"Method not allowed"});try{let{email:t,password:n}=o.body;if(!t||!n)return e.status(400).json({error:"Email and password are required"});let r=await b(t,n),i=a.createCookieString(a.getCookieName(),r.token,{...r.cookieOptions});return e.setHeader("Set-Cookie",i),e.json({success:!0,user:r.user,message:"Signed in successfully"})}catch(t){let n=t instanceof Error?t.message:"Signin failed",r=t instanceof c$2?401:t instanceof d$1?403:400;return e.status(r).json({error:n})}}}function J(){return async function(o,e){if(o.method!=="POST")return e.status(405).json({error:"Method not allowed"});try{let t=c$1(),n=a.createLogoutCookie(a.getCookieName());return e.setHeader("Set-Cookie",n),e.json({success:!0,message:t.message})}catch{return e.status(500).json({error:"Logout failed"})}}}function V(){return async function(o,e){if(o.method!=="GET")return e.status(405).json({error:"Method not allowed"});try{let t=o.cookies[a.getCookieName()],n=await d(t);return n?e.json({success:!0,user:n}):e.status(401).json({error:"Not authenticated"})}catch{return e.status(500).json({error:"Failed to get current user"})}}}function F(){return async function(o,e){if(o.method!=="POST")return e.status(405).json({error:"Method not allowed"});try{let t=o.headers.authorization;if(!t?.startsWith("Bearer "))return e.status(401).json({success:!1,error:"Authorization header required"});let n=t.slice(7),r=await d(n);return r?e.json({success:!0,user:r}):e.status(401).json({success:!1,error:"Invalid token"})}catch{return e.status(500).json({success:false,error:"Token validation failed"})}}}function N(s){let o={};return s&&s.split(";").forEach(e=>{let[t,...n]=e.trim().split("=");t&&n.length>0&&(o[t]=n.join("="));}),o}function G(){return c.loadModules(),c.getEnvironmentInfo()}function B(){return c.reset()}function Q(){c.reset();}function X(s=true){c.setOverride({isNextJsAvailable:s});}async function K(){return await c.loadModules(),c.getEnvironmentInfo()}function W(s,o){return a.createCookieString(a.getCookieName(),s,{httpOnly:true,path:"/",maxAge:604800,sameSite:"lax",secure:process.env.NODE_ENV==="production",...o})}function Y(){return a.createLogoutCookie(a.getCookieName())}function Z(s,o,e){let t=Response.json(s,{status:e?.status||200,headers:e?.headers});if(o){let n=a.createCookieString(a.getCookieName(),o,{httpOnly:true,path:"/",maxAge:604800,sameSite:"lax",secure:process.env.NODE_ENV==="production",...e?.cookieOptions});t.headers.set("Set-Cookie",n);}return t}export{A as a,M as b,H as c,q as d,U as e,D as f,_ as g,$ as h,z as i,L as j,J as k,V as l,F as m,G as n,B as o,Q as p,X as q,K as r,W as s,Y as t,Z as u};