@ouim/simple-logto
Version:
A simpler way to use @logto/react with prebuilt UI components and hooks for fast authentication setup
2 lines (1 loc) • 4.4 kB
JavaScript
;Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const w=require("jose"),g=new Map,y=5*60*1e3;function i(e,t="guest_logto_authtoken"){if(typeof(e==null?void 0:e.get)=="function"){const r=e.get(t);return(r==null?void 0:r.value)||l()}else if(e&&typeof e=="object")return e[t]||l();return l()}function d(e,t="logto_authtoken"){if(typeof(e==null?void 0:e.get)=="function"){const r=e.get(t);return(r==null?void 0:r.value)||null}else if(e&&typeof e=="object")return e[t]||null;return null}function h(e){const t=typeof e.get=="function"?e.get("authorization"):e.authorization;return typeof t=="string"&&t.startsWith("Bearer ")?t.slice(7):null}function I(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");const r=t.length%4;return r&&(t+="=".repeat(4-r)),typeof atob<"u"?atob(t):Buffer.from(t,"base64").toString()}async function p(e){const r=`${e.replace(/\/+$/,"")}/oidc/jwks`,o=Date.now(),n=g.get(r);if(n&&n.expires>o)return n.keys;try{const s=await fetch(r);if(!s.ok)throw new Error(`Failed to fetch JWKS: ${s.status} ${s.statusText}`);const a=(await s.json()).keys||[];return g.set(r,{keys:a,expires:o+y}),a}catch(s){throw new Error(`Failed to fetch JWKS from ${r}: ${s instanceof Error?s.message:"Unknown error"}`)}}function v(e,t,r){if(!e||e.length===0)throw new Error("No keys found in JWKS");if(t){const n=e.find(s=>s.kid===t);if(n)return n;throw new Error(`Key with kid "${t}" not found in JWKS`)}if(r){const n=e.find(s=>s.alg===r);if(n)return n}const o=e.find(n=>n.kty==="RSA"&&(n.use==="sig"||!n.use));return o||e[0]}function A(e,t){const{logtoUrl:r,audience:o,requiredScope:n}=t,s=new URL("oidc",r).toString();if(e.iss!==s)throw new Error(`Invalid issuer. Expected: ${s}, Got: ${e.iss}`);if(o&&e.aud!==o)throw new Error(`Invalid audience. Expected: ${o}, Got: ${e.aud}`);const u=Math.floor(Date.now()/1e3);if(e.exp&&e.exp<u)throw new Error("Token has expired");if(e.nbf&&e.nbf>u)throw new Error("Token is not yet valid");if(n&&(!e.scope||!e.scope.includes(n)))throw new Error(`Missing required scope: ${n}`)}async function c(e,t){const{logtoUrl:r}=t;try{const[o]=e.split(".");if(!o)throw new Error("Invalid JWT format");const n=I(o),s=JSON.parse(n),u=await p(r),a=v(u,s.kid,s.alg),x=await w.importJWK(a),{payload:f}=await w.jwtVerify(e,x);return A(f,t),{userId:f.sub,isAuthenticated:!0,payload:f,isGuest:!1}}catch(o){throw new Error(`Token verification failed: ${o instanceof Error?o.message:"Unknown error"}`)}}const l=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){const t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)});function k(e){return async(t,r,o)=>{try{let n=d(t.cookies,e.cookieName);if(n||(n=h(t.headers)),!n){if(e.allowGuest){const u=i(t.cookies);return t.auth={userId:null,isAuthenticated:!1,payload:null,isGuest:!0,guestId:u||void 0},o()}return r.status(401).json({error:"Authentication required",message:"No token found in cookies or Authorization header"})}const s=await c(n,e);return t.auth=s,o()}catch(n){if(e.allowGuest){const s=i(t.cookies);return t.auth={userId:null,isAuthenticated:!1,payload:null,isGuest:!0,guestId:s||void 0},o()}return r.status(401).json({error:"Authentication failed",message:n instanceof Error?n.message:"Unknown error"})}}}async function E(e,t){try{let r=d(e.cookies,t.cookieName);return r||(r=h(e.headers)),r?{success:!0,auth:await c(r,t)}:t.allowGuest?{success:!1,error:"No authentication token found",auth:{userId:null,isAuthenticated:!1,payload:null,isGuest:!0,guestId:i(e.cookies)||void 0}}:{success:!1,error:"No token found in cookies or Authorization header"}}catch(r){if(t.allowGuest){const n={userId:null,isAuthenticated:!1,payload:null,isGuest:!0,guestId:i(e.cookies)||void 0};return{success:!1,error:r instanceof Error?r.message:"Unknown error",auth:n}}return{success:!1,error:r instanceof Error?r.message:"Unknown error"}}}async function m(e,t){let r;if(typeof e=="string")r=e;else{const o=d(e.cookies,t.cookieName)||h(e.headers);if(!o){if(t.allowGuest)return{userId:null,isAuthenticated:!1,payload:null,isGuest:!0,guestId:i(e.cookies)||void 0};throw new Error("No token found in request")}r=o}try{return await c(r,t)}catch(o){if(t.allowGuest&&typeof e=="object")return{userId:null,isAuthenticated:!1,payload:null,isGuest:!0,guestId:i(e.cookies)||void 0};throw o}}exports.createExpressAuthMiddleware=k;exports.verifyAuth=m;exports.verifyLogtoToken=c;exports.verifyNextAuth=E;