astro-kinde
Version:
Astro integration module for Kinde authentication
2 lines • 2.07 kB
JavaScript
import"astro";function a(e){for(e=e.replace(/-/g,"+").replace(/_/g,"/");e.length%4;)e+="=";return atob(e)}async function i(e,t,n="POST",r={}){let s={method:n,headers:{"Content-Type":"application/x-www-form-urlencoded"},...r};n!=="GET"&&n!=="HEAD"&&(s.body=t);let o=await fetch(e,s);if(!o.ok)throw new Error(`HTTP error ${o.status}: ${o.statusText}`);return await o.json()}async function c(e){let t=`${e.domain}/.well-known/jwks.json`;return i(t,new URLSearchParams,"GET")}async function u(e,t){let n=`${t.domain}/oauth2/introspect`,r=`${t.clientId}:${t.clientSecret}`,s=`Basic ${btoa(r)}`,o=new URLSearchParams({token:e,token_type_hint:"access_token"});return i(n,o,"POST",{headers:{Authorization:s,"Content-Type":"application/x-www-form-urlencoded"}})}import w from"virtual:kinde-integration/config";import k from"virtual:kinde-integration/config";function p(e){return e.headers.get("cookie")?.split("; ").find(n=>n.startsWith("kinde_access_token="))?.split("=")[1]}function l(e){return new Response(e instanceof Error?e.message:null,{status:500})}async function h(e){let n=(await c(k)).keys.find(r=>r.kid===e);if(!n)throw new Error(`Unable to find a signing key that matches '${e}'`);return n}var d=async e=>{if(!e)return!1;let t=e.split(".");if(t.length!==3)return!1;try{let n=t[0];if(!n)throw new Error("Token header is missing");let r=JSON.parse(a(n)),s=await h(r.kid),o=await crypto.subtle.importKey("jwk",s,{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["verify"]);return await crypto.subtle.verify("RSASSA-PKCS1-v1_5",o,new Uint8Array(Array.from(a(t[2]??""),f=>f.charCodeAt(0))),new TextEncoder().encode(t[0]+"."+t[1]))}catch(n){return console.error(n),!1}};var C=async({request:e})=>{let t=p(e);if(!t)return new Response("No access token found",{status:401});try{return await d(t)?(await u(t,w)).active?new Response("Authenticated",{status:200,headers:{"Content-Type":"application/json"}}):new Response("Not Authenticated",{status:401}):new Response("Invalid token",{status:401})}catch(n){return l(n)}};export{C as GET};
//# sourceMappingURL=isAuthenticated.js.map