import"../../node-crypto-polyfill.js";import{utf8ToUint8Array as u,encodeBase64URL as w,arrayBufferToBase64URL as m,decodeBase64URL as d}from"./encode.js";import{decodeJwtSignature as g}from"./decode-jwt-signature.js";import{AlgorithmTypes as s,JwtAlgorithmNotImplemented as H,JwtTokenInvalid as S,JwtTokenNotBefore as b,JwtTokenExpired as E,JwtTokenSignatureMismatched as K,CryptoKeyFormat as h,CryptoKeyUsage as l}from"./types.js";const p=t=>{switch(t.toUpperCase()){case"HS256":return{name:"HMAC",hash:{name:"SHA-256"}};case"HS384":return{name:"HMAC",hash:{name:"SHA-384"}};case"HS512":return{name:"HMAC",hash:{name:"SHA-512"}};case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"ES256":return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw new H(t)}},A=async(t,e,n=s.HS256)=>{if(!crypto.subtle||!crypto.subtle.importKey)throw new Error("`crypto.subtle.importKey` is undefined. JWT auth middleware requires it.");e.startsWith("-----BEGIN PRIVATE KEY-----")&&(e=e.replace("-----BEGIN PRIVATE KEY-----","").replace("-----END PRIVATE KEY-----","").split(/\\n|\n/).join("").trim(),e=atob(e));const r=n===s.RS256||n===s.ES256,a=await crypto.subtle.importKey(r?h.PKCS8:h.RAW,r?T(e):u(e),p(n),!1,[l.Sign]);return await crypto.subtle.sign(p(n),a,u(t))};function T(t){const e=new ArrayBuffer(t.length),n=new Uint8Array(e);for(let r=0,a=t.length;r<a;r++)n[r]=t.charCodeAt(r);return e}const U=async(t,e,n=s.HS256,r)=>{const a=await w(JSON.stringify(t)),i=`${await w(JSON.stringify({alg:n,typ:"JWT",kid:r}))}.${a}`,c=await m(await A(i,e,n));return`${i}.${c}`},v=async(t,e,n=s.HS256,r=!1)=>{const a=t.split(".");if(a.length!==3)throw new S(t);const{payload:o}=C(t),i=Math.floor(Date.now()/1e3);if(typeof o.nbf=="number"&&o.nbf>i)throw new b(t);if(!r&&typeof o.exp=="number"&&o.exp<=i)throw new E(t);const c=a.slice(0,2).join("."),f=a[2];let y=!1;if(typeof e!="string"?y=await R(c,f,e,n):y=await m(await A(c,e,n))===f,!y)throw new K(t);return!0},C=t=>{try{const[e,n]=t.split("."),r=JSON.parse(d(e)),a=JSON.parse(d(n));return{header:r,payload:a}}catch{throw new S(t)}},R=async(t,e,n,r)=>{const a=await crypto.subtle.importKey("jwk",n,p(r),!1,[l.Verify]);return await crypto.subtle.verify(p(r),a,g(e),u(t))};export{C as decode,U as sign,v as verify};
