UNPKG

authrix

Version:

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

17 lines (14 loc) 17.2 kB
'use strict';var chunkPTWJCNT6_cjs=require('./chunk-PTWJCNT6.cjs');require('./chunk-RUOJ57HW.cjs'),require('./chunk-O5GBK76P.cjs');var chunkIRGTWVM7_cjs=require('./chunk-IRGTWVM7.cjs'),chunkD6WM53FN_cjs=require('./chunk-D6WM53FN.cjs');var y,N,A,w,p;function h(){try{let e=typeof chunkD6WM53FN_cjs.a<"u"?chunkD6WM53FN_cjs.a:null;if(!e)throw new Error("require is not available");return e("next/headers")}catch(e){throw new Error(`Next.js App Router functions require 'next/headers' to be available. Make sure you're using Next.js 13+ with App Router and this function is called within a Server Component or API Route. Original error: ${e instanceof Error?e.message:"Unknown error"}`)}}var u=false,c="unknown",d=false;function b(){try{return chunkIRGTWVM7_cjs.a?.cookieName||"auth_token"}catch{return "auth_token"}}function S(){if(!d)try{let e,t,r;if(typeof chunkD6WM53FN_cjs.a<"u"){try{chunkD6WM53FN_cjs.a.resolve("next"),u=!0;}catch{}if(u){try{e=chunkD6WM53FN_cjs.a("next/server"),y=e.NextRequest,N=e.NextResponse;}catch{}try{t=chunkD6WM53FN_cjs.a("next"),A=t.NextApiRequest,w=t.NextApiResponse;}catch{}try{r=chunkD6WM53FN_cjs.a("next/headers"),p=r.cookies;}catch{p=null;}}}u||(typeof globalThis<"u"&&(globalThis.n||globalThis.s||globalThis.next)&&(u=!0),typeof process<"u"&&process.env?.NEXT_RUNTIME&&(u=!0),typeof process<"u"&&process.env?.NEXT_PUBLIC_VERCEL_URL&&(u=!0)),u&&(p&&typeof p=="function"?c="app-router":A&&w?c="pages-router":y&&N?c="middleware":typeof process<"u"&&(process.env.NEXT_RUNTIME==="edge"?c="middleware":process.env.NEXT_RUNTIME==="nodejs"&&(c="app-router"))),d=!0;}catch{u=false,c="unknown",d=true;}}function $(){d||S();}S();function P(){return $(),{isNextJsAvailable:u,context:c,hasAppRouterSupport:!!p,hasPagesRouterSupport:!!(A&&w),hasMiddlewareSupport:!!(y&&N),detectionComplete:d,runtimeInfo:{hasRequire:typeof chunkD6WM53FN_cjs.a<"u",hasGlobalThis:typeof globalThis<"u",hasProcess:typeof process<"u",nextRuntime:typeof process<"u"?process.env?.NEXT_RUNTIME:void 0,hasNextData:typeof globalThis<"u"?!!globalThis.n:false}}}async function q(e,t){try{let r=await chunkPTWJCNT6_cjs.a(e,t);try{return chunkD6WM53FN_cjs.a("next/headers").cookies().set(chunkIRGTWVM7_cjs.a.cookieName,r.token,r.cookieOptions),r.user}catch{throw new Error("Next.js App Router functions require 'next/headers' to be available. This function must be called from a Server Component, Server Action, or Route Handler in Next.js App Router. If you're in an API route or Pages Router, use signupNextPages instead. If you want to handle cookies manually, use signupCore and handle the cookie setting yourself.")}}catch(r){throw r instanceof Error&&r.message.includes("next/headers")?r:new Error(`Signup failed: ${r instanceof Error?r.message:String(r)}`)}}async function U(e,t){try{let r=await chunkPTWJCNT6_cjs.c(e,t);try{return chunkD6WM53FN_cjs.a("next/headers").cookies().set(chunkIRGTWVM7_cjs.a.cookieName,r.token,r.cookieOptions),r.user}catch{throw new Error("Next.js App Router functions require 'next/headers' to be available. This function must be called from a Server Component, Server Action, or Route Handler in Next.js App Router. If you're in an API route or Pages Router, use signinNextPages instead. If you want to handle cookies manually, use signinCore and handle the cookie setting yourself.")}}catch(r){throw r instanceof Error&&r.message.includes("next/headers")?r:new Error(`Signin failed: ${r instanceof Error?r.message:String(r)}`)}}function O(){try{let e=chunkPTWJCNT6_cjs.e();try{return h().cookies().set(chunkIRGTWVM7_cjs.a.cookieName,"",e.cookieOptions),{message:e.message}}catch{throw new Error("Next.js App Router functions require 'next/headers' to be available. This function must be called from a Server Component, Server Action, or Route Handler in Next.js App Router. If you're in an API route or Pages Router, use logoutNextPages instead. If you want to handle cookies manually, use logoutCore and handle the cookie clearing yourself.")}}catch(e){throw e instanceof Error&&e.message.includes("next/headers")?e:new Error(`Logout failed: ${e instanceof Error?e.message:String(e)}`)}}async function M(){try{try{let r=h().cookies().get(chunkIRGTWVM7_cjs.a.cookieName)?.value||null;return chunkPTWJCNT6_cjs.h(r)}catch{throw new Error("Next.js App Router functions require 'next/headers' to be available. This function must be called from a Server Component, Server Action, or Route Handler in Next.js App Router. If you're in an API route or Pages Router, use getCurrentUserNextPages instead. If you want to handle token extraction manually, use getCurrentUserFromToken with manual token extraction.")}}catch(e){throw e instanceof Error&&e.message.includes("next/headers")?e:new Error(`Get current user failed: ${e instanceof Error?e.message:String(e)}`)}}async function F(){try{try{let r=h().cookies().get(chunkIRGTWVM7_cjs.a.cookieName)?.value||null;return chunkPTWJCNT6_cjs.j(r)}catch{return !1}}catch{return false}}async function J(e,t,r){try{let o=await chunkPTWJCNT6_cjs.a(e,t);if(!r||typeof r.setHeader!="function")throw new Error("signupNextPages requires a valid Next.js API response object. Make sure you are calling this function from within a Next.js API route handler. If you want to handle cookies manually, use signupCore instead.");return r.setHeader("Set-Cookie",`${chunkIRGTWVM7_cjs.a.cookieName}=${o.token}; HttpOnly; Path=/; Max-Age=${o.cookieOptions.maxAge}; SameSite=Lax${o.cookieOptions.secure?"; Secure":""}`),o.user}catch(o){throw new Error(`Signup failed: ${o instanceof Error?o.message:String(o)}`)}}async function L(e,t,r){try{let o=await chunkPTWJCNT6_cjs.c(e,t);if(!r||typeof r.setHeader!="function")throw new Error("signinNextPages requires a valid Next.js API response object. Make sure you are calling this function from within a Next.js API route handler. If you want to handle cookies manually, use signinCore instead.");return r.setHeader("Set-Cookie",`${chunkIRGTWVM7_cjs.a.cookieName}=${o.token}; HttpOnly; Path=/; Max-Age=${o.cookieOptions.maxAge}; SameSite=Lax${o.cookieOptions.secure?"; Secure":""}`),o.user}catch(o){throw new Error(`Signin failed: ${o instanceof Error?o.message:String(o)}`)}}function _(e){try{let t=chunkPTWJCNT6_cjs.e();if(!e||typeof e.setHeader!="function")throw new Error("logoutNextPages requires a valid Next.js API response object. Make sure you are calling this function from within a Next.js API route handler. If you want to handle cookies manually, use logoutCore instead.");return e.setHeader("Set-Cookie",`${chunkIRGTWVM7_cjs.a.cookieName}=; HttpOnly; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT; SameSite=Lax${t.cookieOptions.secure?"; Secure":""}`),{message:t.message}}catch(t){throw new Error(`Logout failed: ${t instanceof Error?t.message:String(t)}`)}}async function R(e){try{if(!e||!e.cookies)throw new Error("getCurrentUserNextPages requires a valid Next.js API request object with cookies. Make sure you are calling this function from within a Next.js API route handler. If you want to handle token extraction manually, use getCurrentUserFromToken instead.");let t=e.cookies[chunkIRGTWVM7_cjs.a.cookieName]||null;return chunkPTWJCNT6_cjs.h(t)}catch(t){throw new Error(`Get current user failed: ${t instanceof Error?t.message:String(t)}`)}}async function D(e){try{if(!e||!e.cookies)return !1;let t=e.cookies[chunkIRGTWVM7_cjs.a.cookieName]||null;return chunkPTWJCNT6_cjs.j(t)}catch{return false}}function C(e){if(!e||typeof e!="string")return false;let t=e.split(".");return t.length!==3?false:t.every(r=>r.length>0)}function v(e){try{let t=e.split(".");if(t.length!==3)return null;let r=t[1],o=r+"=".repeat((4-r.length%4)%4),s=atob(o.replace(/-/g,"+").replace(/_/g,"/"));return JSON.parse(s)}catch{return null}}function V(e){let t=v(e);if(!t||!t.exp)return true;let r=Math.floor(Date.now()/1e3);return t.exp<r}async function G(e,t={}){let r=t.cookieName||b(),o=e.cookies.get(r)?.value||null;if(!o)return {isAuthenticated:false,user:null,reason:"No token provided"};if(!C(o))return {isAuthenticated:false,user:null,reason:"Invalid token structure"};if(V(o))return {isAuthenticated:false,user:null,reason:"Token expired"};let s=v(o),a=s?{id:s.id,email:s.email,createdAt:s.createdAt?new Date(s.createdAt):void 0}:null;return {isAuthenticated:!!a,user:a,reason:a?"Token appears valid":"Invalid token payload"}}async function z(e,t={}){let r=t.cookieName||b(),o=e.cookies.get(r)?.value||null;if(!o)return {isAuthenticated:false,user:null,reason:"No token provided"};if(!C(o))return {isAuthenticated:false,user:null,reason:"Invalid token structure"};try{let s=t.validationEndpoint||"/api/auth/validate",a=e.nextUrl.origin,f=new AbortController,T=setTimeout(()=>{f.abort();},t.timeout||5e3),E=await fetch(`${a}${s}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`},signal:f.signal});return clearTimeout(T),E.ok?{isAuthenticated:!0,user:(await E.json()).user,reason:"Token validated via API"}:{isAuthenticated:!1,user:null,reason:"Token validation failed"}}catch{let a=v(o),f=a?{id:a.id,email:a.email,createdAt:a.createdAt?new Date(a.createdAt):void 0}:null;return {isAuthenticated:!!f,user:f,reason:"Fallback validation (API unavailable)"}}}function X(e){return async(t,r)=>{try{let o=await R(t);return o?(t.user=o,e(t,r)):r.status(401).json({success:!1,error:{message:"Authentication required"}})}catch{return r.status(500).json({success:false,error:{message:"Authentication failed"}})}}}async function B(e,t,r){try{let o=await chunkPTWJCNT6_cjs.a(e,t);if(r&&typeof r.setHeader=="function")return r.setHeader("Set-Cookie",`${chunkIRGTWVM7_cjs.a.cookieName}=${o.token}; HttpOnly; Path=/; Max-Age=${o.cookieOptions.maxAge}; SameSite=Lax${o.cookieOptions.secure?"; Secure":""}`),o.user;try{return h().cookies().set(chunkIRGTWVM7_cjs.a.cookieName,o.token,o.cookieOptions),o.user}catch{throw new Error(`Unable to set authentication cookie. This function requires either: 1. A Next.js API response object (Pages Router): signupNextFlexible(email, password, res) 2. Next.js App Router context (Server Component/Action/Route Handler) Alternative: Use signupCore() and handle cookie setting manually: const result = await signupCore(email, password); // Then set result.token as a cookie manually`)}}catch(o){throw new Error(`Signup failed: ${o instanceof Error?o.message:String(o)}`)}}async function W(e,t,r){try{let o=await chunkPTWJCNT6_cjs.c(e,t);if(r&&typeof r.setHeader=="function")return r.setHeader("Set-Cookie",`${chunkIRGTWVM7_cjs.a.cookieName}=${o.token}; HttpOnly; Path=/; Max-Age=${o.cookieOptions.maxAge}; SameSite=Lax${o.cookieOptions.secure?"; Secure":""}`),o.user;try{return h().cookies().set(chunkIRGTWVM7_cjs.a.cookieName,o.token,o.cookieOptions),o.user}catch{throw new Error(`Unable to set authentication cookie. This function requires either: 1. A Next.js API response object (Pages Router): signinNextFlexible(email, password, res) 2. Next.js App Router context (Server Component/Action/Route Handler) Alternative: Use signinCore() and handle cookie setting manually: const result = await signinCore(email, password); // Then set result.token as a cookie manually`)}}catch(o){throw new Error(`Signin failed: ${o instanceof Error?o.message:String(o)}`)}}async function Y(e){try{if(e&&e.cookies){let t=e.cookies[chunkIRGTWVM7_cjs.a.cookieName]||null;return chunkPTWJCNT6_cjs.h(t)}try{let o=h().cookies().get(chunkIRGTWVM7_cjs.a.cookieName)?.value||null;return chunkPTWJCNT6_cjs.h(o)}catch{throw new Error(`Unable to read authentication cookie. This function requires either: 1. A Next.js API request object (Pages Router): getCurrentUserNextFlexible(req) 2. Next.js App Router context (Server Component/Action/Route Handler) Alternative: Extract the token manually and use getCurrentUserFromToken(token)`)}}catch(t){throw new Error(`Get current user failed: ${t instanceof Error?t.message:String(t)}`)}}function K(e,t){return e.headers.set("x-user-id",t.id),e.headers.set("x-user-email",t.email),e}function Q(){return async function(t){try{let r=t.headers.get("Authorization");if(!r||!r.startsWith("Bearer "))return Response.json({success:!1,error:"Authorization header required"},{status:401});let o=r.slice(7),s=await chunkPTWJCNT6_cjs.h(o);return s?Response.json({success:!0,user:{id:s.id,email:s.email,createdAt:s.createdAt}}):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(t,r){if(t.method!=="POST")return r.status(405).json({error:"Method not allowed"});try{let o=t.headers.authorization;if(!o||!o.startsWith("Bearer "))return r.status(401).json({success:!1,error:"Authorization header required"});let s=o.slice(7),a=await chunkPTWJCNT6_cjs.h(s);return a?r.json({success:!0,user:{id:a.id,email:a.email,createdAt:a.createdAt}}):r.status(401).json({success:!1,error:"Invalid token"})}catch{return r.status(500).json({success:false,error:"Token validation failed"})}}}function ee(){return d=false,u=false,c="unknown",y=N=A=w=p=void 0,S(),P()}function te(e,t){u=e,t&&(c=t),d=true;}async function re(e,t){let r=await chunkPTWJCNT6_cjs.a(e,t);try{return chunkD6WM53FN_cjs.a("next/headers").cookies().set(chunkIRGTWVM7_cjs.a.cookieName,r.token,r.cookieOptions),r.user}catch{throw new Error("Failed to set authentication cookie. Make sure you're calling this from a Next.js App Router context (Server Component, Server Action, or Route Handler). For Pages Router, use signupNextPages(email, password, res) instead. For manual cookie handling, use signupCore(email, password) and handle the cookie yourself.")}}async function oe(e,t){let r=await chunkPTWJCNT6_cjs.c(e,t);try{return chunkD6WM53FN_cjs.a("next/headers").cookies().set(chunkIRGTWVM7_cjs.a.cookieName,r.token,r.cookieOptions),r.user}catch{throw new Error("Failed to set authentication cookie. Make sure you're calling this from a Next.js App Router context (Server Component, Server Action, or Route Handler). For Pages Router, use signinNextPages(email, password, res) instead. For manual cookie handling, use signinCore(email, password) and handle the cookie yourself.")}}function ne(){let e=chunkPTWJCNT6_cjs.e();try{let{cookies:t}=chunkD6WM53FN_cjs.a("next/headers");return t().set(chunkIRGTWVM7_cjs.a.cookieName,"",e.cookieOptions),{message:e.message}}catch{throw new Error("Failed to clear authentication cookie. Make sure you're calling this from a Next.js App Router context (Server Component, Server Action, or Route Handler). For Pages Router, use logoutNextPages(res) instead. For manual cookie handling, use logoutCore() and handle the cookie yourself.")}}async function se(){try{let{cookies:e}=chunkD6WM53FN_cjs.a("next/headers"),r=e().get(chunkIRGTWVM7_cjs.a.cookieName)?.value||null;return chunkPTWJCNT6_cjs.h(r)}catch{throw new Error("Failed to read authentication cookie. Make sure you're calling this from a Next.js App Router context (Server Component, Server Action, or Route Handler). For Pages Router, use getCurrentUserNextPages(req) instead. For manual token handling, extract the token yourself and use getCurrentUserFromToken(token).")}}async function ae(){try{let{cookies:e}=chunkD6WM53FN_cjs.a("next/headers"),r=e().get(chunkIRGTWVM7_cjs.a.cookieName)?.value||null;return chunkPTWJCNT6_cjs.j(r)}catch{return false}}function ie(e,t){let r={secure:t?.secure??process.env.NODE_ENV==="production",maxAge:t?.maxAge??6048e5,sameSite:t?.sameSite??"lax",path:t?.path??"/"};return `${chunkIRGTWVM7_cjs.a.cookieName}=${e}; HttpOnly; Path=${r.path}; Max-Age=${r.maxAge}; SameSite=${r.sameSite}${r.secure?"; Secure":""}`}function ue(e){let t={secure:e?.secure??process.env.NODE_ENV==="production",sameSite:e?.sameSite??"lax",path:e?.path??"/"};return `${chunkIRGTWVM7_cjs.a.cookieName}=; HttpOnly; Path=${t.path}; Expires=Thu, 01 Jan 1970 00:00:00 GMT; SameSite=${t.sameSite}${t.secure?"; Secure":""}`}Object.defineProperty(exports,"authConfig",{enumerable:true,get:function(){return chunkIRGTWVM7_cjs.a}});Object.defineProperty(exports,"getAuthrixStatus",{enumerable:true,get:function(){return chunkIRGTWVM7_cjs.d}});Object.defineProperty(exports,"initAuth",{enumerable:true,get:function(){return chunkIRGTWVM7_cjs.b}});Object.defineProperty(exports,"isAuthrixInitialized",{enumerable:true,get:function(){return chunkIRGTWVM7_cjs.c}});exports.checkAuthMiddleware=G;exports.checkAuthMiddlewareSecure=z;exports.createAuthCookieString=ie;exports.createAuthenticatedResponse=K;exports.createLogoutCookieString=ue;exports.createTokenValidationHandler=Q;exports.createTokenValidationHandlerPages=Z;exports.forceNextJsAvailability=te;exports.getCurrentUserNext=se;exports.getCurrentUserNextApp=M;exports.getCurrentUserNextFlexible=Y;exports.getCurrentUserNextPages=R;exports.getNextJsEnvironmentInfo=P;exports.isAuthenticatedNext=ae;exports.isAuthenticatedNextApp=F;exports.isAuthenticatedNextPages=D;exports.logoutNext=ne;exports.logoutNextApp=O;exports.logoutNextPages=_;exports.redetectNextJsEnvironment=ee;exports.signinNext=oe;exports.signinNextApp=U;exports.signinNextFlexible=W;exports.signinNextPages=L;exports.signupNext=re;exports.signupNextApp=q;exports.signupNextFlexible=B;exports.signupNextPages=J;exports.withAuth=X;