mirror of
https://github.com/Sevichecc/Urara-Blog.git
synced 2025-05-04 18:39:29 +08:00
1 line
No EOL
2.4 KiB
Text
1 line
No EOL
2.4 KiB
Text
import*as e from"worktop/base64";import*as r from"worktop/buffer";import*as t from"worktop/crypto";var a=new Error("Invalid token"),i=new Error("Expired token");function n(t){return e.base64url(r.toBinary(r.asUTF8(JSON.stringify(t))))}function o(t){return e.base64url(r.toBinary(t))}function s(e){return JSON.parse(r.toUTF8(r.asBinary(e)))}function p(r){let t=r.split(".");if(3!==t.length)throw a;try{let r=e.decode(t[1]);var i=s(e.decode(t[0])),n=s(r)}catch{throw a}return{header:i,payload:n,signature:t[2]}}function y(e,r,t){return r.iat=r.iat||Date.now()/1e3|0,null==r.exp&&null!=t&&(r.exp=r.iat+t),e+"."+n(r)}function u(e,r){let t=p(r),n=t.payload;if(!r.startsWith(e+"."))throw a;if(null!=n.exp&&n.exp<Date.now()/1e3)throw i;return t}function l(e,r,t){let{kid:a,typ:i,header:o,...s}=t,p={...o,alg:e+r,typ:i||"JWT"};return null!=a&&(p.kid=a),{header:n(p),config:s}}function d(e,r){let i,{key:n,expires:s,...p}=r,{header:d,config:c}=l("HS",e,p);return i={async sign(r){let a=y(d,{...c,...r},s);return a+"."+o(await t.HMAC(`SHA-${e}`,n,a))},async verify(e){let r=u(d,e);if(await i.sign(r.payload)!==e)throw a;return r.payload}}}function c(i,n){let{privkey:s,pubkey:p,expires:d,...c}=n,{header:f,config:S}=l("RS",i,c),w="RSASSA-PKCS1-v1_5",h={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${i}`};return{async sign(e){let a=await crypto.subtle.importKey("pkcs8",r.asPEM(s),h,!1,["sign"]),i=y(f,{...S,...e},d);return i+"."+o(await t.sign(w,a,i))},async verify(i){let[n,o,s]=i.split("."),y=u(f,i),l=n+"."+o,d=r.asBinary(e.decode(s)),c=await crypto.subtle.importKey("spki",r.asPEM(p),h,!1,["verify"]);if(await t.verify(w,c,l,d))return y.payload;throw a}}}function f(i,n){let{privkey:s,pubkey:p,expires:d,...c}=n,{header:f,config:S}=l("ES",i,c),w={name:"ECDSA",namedCurve:`P-${i}`},h={name:"ECDSA",hash:`SHA-${i}`};return{async sign(e){let a=await crypto.subtle.importKey("pkcs8",r.asPEM(s),w,!1,["sign"]),i=y(f,{...S,...e},d);return i+"."+o(await t.sign(h,a,i))},async verify(i){let[n,o,s]=i.split("."),y=u(f,i),l=n+"."+o,d=r.asBinary(e.decode(s)),c=await crypto.subtle.importKey("spki",r.asPEM(p),w,!1,["verify"]);if(await t.verify(h,c,l,d))return y.payload;throw a}}}var S=d.bind(0,"256"),w=d.bind(0,"384"),h=d.bind(0,"512"),b=c.bind(0,"256"),g=c.bind(0,"384"),k=c.bind(0,"512"),v=f.bind(0,"256"),E=f.bind(0,"384"),m=f.bind(0,"512");export{v as ES256,E as ES384,m as ES512,i as EXPIRED,S as HS256,w as HS384,h as HS512,a as INVALID,b as RS256,g as RS384,k as RS512,p as decode}; |