authrix
Version:
Lightweight, flexible authentication library for Node.js and TypeScript.
17 lines (14 loc) • 15.7 kB
JavaScript
import {a as a$1,c as c$1,e,h as h$1,j}from'./chunk-TQPPJTEW.mjs';import'./chunk-ML66D24Y.mjs';import'./chunk-2W6WDMNG.mjs';import {a as a$2}from'./chunk-ZNCUQ2DE.mjs';export{a as authConfig,d as getAuthrixStatus,b as initAuth,c as isAuthrixInitialized}from'./chunk-ZNCUQ2DE.mjs';import {a}from'./chunk-3SAEGOMQ.mjs';var y,N,A,w,p;function h(){try{let e=typeof a<"u"?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 a$2?.cookieName||"auth_token"}catch{return "auth_token"}}function S(){if(!d)try{let e,t,r;if(typeof a<"u"){try{a.resolve("next"),u=!0;}catch{}if(u){try{e=a("next/server"),y=e.NextRequest,N=e.NextResponse;}catch{}try{t=a("next"),A=t.NextApiRequest,w=t.NextApiResponse;}catch{}try{r=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 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 a$1(e,t);try{return a("next/headers").cookies().set(a$2.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 c$1(e,t);try{return a("next/headers").cookies().set(a$2.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$1=e();try{return h().cookies().set(a$2.cookieName,"",e$1.cookieOptions),{message:e$1.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(a$2.cookieName)?.value||null;return h$1(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(a$2.cookieName)?.value||null;return j(r)}catch{return !1}}catch{return false}}async function J(e,t,r){try{let o=await a$1(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",`${a$2.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 c$1(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",`${a$2.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$1){try{let t=e();if(!e$1||typeof e$1.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$1.setHeader("Set-Cookie",`${a$2.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[a$2.cookieName]||null;return h$1(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[a$2.cookieName]||null;return 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 a$1(e,t);if(r&&typeof r.setHeader=="function")return r.setHeader("Set-Cookie",`${a$2.cookieName}=${o.token}; HttpOnly; Path=/; Max-Age=${o.cookieOptions.maxAge}; SameSite=Lax${o.cookieOptions.secure?"; Secure":""}`),o.user;try{return h().cookies().set(a$2.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 c$1(e,t);if(r&&typeof r.setHeader=="function")return r.setHeader("Set-Cookie",`${a$2.cookieName}=${o.token}; HttpOnly; Path=/; Max-Age=${o.cookieOptions.maxAge}; SameSite=Lax${o.cookieOptions.secure?"; Secure":""}`),o.user;try{return h().cookies().set(a$2.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[a$2.cookieName]||null;return h$1(t)}try{let o=h().cookies().get(a$2.cookieName)?.value||null;return h$1(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 h$1(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 h$1(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 a$1(e,t);try{return a("next/headers").cookies().set(a$2.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 c$1(e,t);try{return a("next/headers").cookies().set(a$2.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$1=e();try{let{cookies:t}=a("next/headers");return t().set(a$2.cookieName,"",e$1.cookieOptions),{message:e$1.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}=a("next/headers"),r=e().get(a$2.cookieName)?.value||null;return h$1(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}=a("next/headers"),r=e().get(a$2.cookieName)?.value||null;return 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 `${a$2.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 `${a$2.cookieName}=; HttpOnly; Path=${t.path}; Expires=Thu, 01 Jan 1970 00:00:00 GMT; SameSite=${t.sameSite}${t.secure?"; Secure":""}`}export{G as checkAuthMiddleware,z as checkAuthMiddlewareSecure,ie as createAuthCookieString,K as createAuthenticatedResponse,ue as createLogoutCookieString,Q as createTokenValidationHandler,Z as createTokenValidationHandlerPages,te as forceNextJsAvailability,se as getCurrentUserNext,M as getCurrentUserNextApp,Y as getCurrentUserNextFlexible,R as getCurrentUserNextPages,P as getNextJsEnvironmentInfo,ae as isAuthenticatedNext,F as isAuthenticatedNextApp,D as isAuthenticatedNextPages,ne as logoutNext,O as logoutNextApp,_ as logoutNextPages,ee as redetectNextJsEnvironment,oe as signinNext,U as signinNextApp,W as signinNextFlexible,L as signinNextPages,re as signupNext,q as signupNextApp,B as signupNextFlexible,J as signupNextPages,X as withAuth};