UNPKG

@shlomiatar/nano-jwt

Version:

A tiny, minimalistic HS256/HS512 jwt verifier using WebCryptoAPIs (for browser/bun/cloudflare)

2 lines (1 loc) 833 B
var[g,y]=[new TextDecoder,new TextEncoder],f=(r)=>new Uint8Array(atob(r.replace(/-/g,"+").replace(/_/g,"/")).split("").map((n)=>n.charCodeAt(0))),u=(r)=>JSON.parse(g.decode(f(r))),b=(r,n="HS256",t)=>{let a,p=`SHA-${n.substring(2)}`,d=t?typeof t==="function"?t:(o)=>Object.keys(t??{}).every((e)=>o[e]===t[e]):()=>!0;return{verify:async(o)=>{try{a=a??await crypto.subtle.importKey("raw",y.encode(r),{name:"HMAC",hash:p},!1,["verify"]);let[e,s,i,...T]=o.split(".");if(!e||!s||!i||T.length)return[!1,{error:"invalid_format"}];if(u(e).alg!=n)return[!1,{error:"unsupported_algorithm"}];if(!await crypto.subtle.verify("HMAC",a,f(i),y.encode(`${e}.${s}`)))return[!1,{error:"bad_signature"}];let c=u(s),l=d(c);if(l!==!0)return[!1,{error:l||"invalid_payload"}];return[!0,c]}catch{return[!1,{error:"verification_failed"}]}}}};export{b as jwt};