azion
Version:
Azion Packages for Edge Computing.
254 lines (253 loc) • 7.29 kB
JavaScript
class H extends Error {
constructor(t) {
super(`${t} is not an implemented algorithm`), this.name = "JwtAlgorithmNotImplemented";
}
}
class f extends Error {
constructor(t) {
super(`invalid JWT token: ${t}`), this.name = "JwtTokenInvalid";
}
}
class P extends Error {
constructor(t) {
super(`token (${t}) is being used before it's valid`), this.name = "JwtTokenNotBefore";
}
}
class J extends Error {
constructor(t) {
super(`token (${t}) expired`), this.name = "JwtTokenExpired";
}
}
class x extends Error {
constructor(t, r) {
super(`Incorrect "iat" claim must be a older than "${t}" (iat: "${r}")`), this.name = "JwtTokenIssuedAt";
}
}
class g extends Error {
constructor(t) {
super(`jwt header is invalid: ${JSON.stringify(t)}`), this.name = "JwtHeaderInvalid";
}
}
class K extends Error {
constructor(t) {
super(`token(${t}) signature mismatched`), this.name = "JwtTokenSignatureMismatched";
}
}
var i = /* @__PURE__ */ ((e) => (e.Encrypt = "encrypt", e.Decrypt = "decrypt", e.Sign = "sign", e.Verify = "verify", e.DeriveKey = "deriveKey", e.DeriveBits = "deriveBits", e.WrapKey = "wrapKey", e.UnwrapKey = "unwrapKey", e))(i || {}), h = /* @__PURE__ */ ((e) => (e.HS256 = "HS256", e.HS384 = "HS384", e.HS512 = "HS512", e.RS256 = "RS256", e.RS384 = "RS384", e.RS512 = "RS512", e.PS256 = "PS256", e.PS384 = "PS384", e.PS512 = "PS512", e.ES256 = "ES256", e.ES384 = "ES384", e.ES512 = "ES512", e.EdDSA = "EdDSA", e))(h || {});
const m = (e) => E(e.replace(/_|-/g, (t) => ({ _: "/", "-": "+" })[t] ?? t)), y = (e) => R(e).replace(/\/|\+/g, (t) => ({ "/": "_", "+": "-" })[t] ?? t), R = (e) => {
let t = "";
const r = new Uint8Array(e);
for (let n = 0, a = r.length; n < a; n++)
t += String.fromCharCode(r[n]);
return btoa(t);
}, E = (e) => {
const t = atob(e), r = new Uint8Array(new ArrayBuffer(t.length)), n = t.length / 2;
for (let a = 0, s = t.length - 1; a <= n; a++, s--)
r[a] = t.charCodeAt(a), r[s] = t.charCodeAt(s);
return r;
}, u = new TextEncoder(), C = new TextDecoder();
async function I(e, t, r) {
const n = b(t), a = await D(e, n);
return await crypto.subtle.sign(n, a, r);
}
async function $(e, t, r, n) {
const a = b(t), s = await B(e, a);
return await crypto.subtle.verify(a, s, r, n);
}
function d(e) {
return E(
e.split(`
`).filter((t) => !t.includes("BEGIN") && !t.includes("END")).join("").replace(/\s/g, "")
);
}
async function D(e, t) {
if (!crypto.subtle || !crypto.subtle.importKey)
throw new Error("`crypto.subtle.importKey` is undefined. JWT auth middleware requires it.");
if (v(e)) {
if (e.type !== "private")
throw new Error(`unexpected non private key: CryptoKey.type is ${e.type}`);
return e;
}
const r = [i.Sign];
return typeof e == "object" ? await crypto.subtle.importKey("jwk", e, t, !1, r) : e.includes("PRIVATE") ? await crypto.subtle.importKey("pkcs8", d(e), t, !1, r) : await crypto.subtle.importKey("raw", u.encode(e), t, !1, r);
}
async function B(e, t) {
if (!crypto.subtle || !crypto.subtle.importKey)
throw new Error("`crypto.subtle.importKey` is undefined. JWT auth middleware requires it.");
if (v(e)) {
if (e.type === "public" || e.type === "secret")
return e;
e = await l(e);
}
if (typeof e == "string" && e.includes("PRIVATE")) {
const n = await crypto.subtle.importKey("pkcs8", d(e), t, !0, [i.Sign]);
e = await l(n);
}
const r = [i.Verify];
return typeof e == "object" ? await crypto.subtle.importKey("jwk", e, t, !1, r) : e.includes("PUBLIC") ? await crypto.subtle.importKey("spki", d(e), t, !1, r) : await crypto.subtle.importKey("raw", u.encode(e), t, !1, r);
}
async function l(e) {
if (e.type !== "private")
throw new Error(`unexpected key type: ${e.type}`);
if (!e.extractable)
throw new Error("unexpected private key is unextractable");
const t = await crypto.subtle.exportKey("jwk", e), { kty: r } = t, { alg: n, e: a, n: s } = t, { crv: o, x: c, y: S } = t;
return { kty: r, alg: n, e: a, n: s, crv: o, x: c, y: S, key_ops: [i.Verify] };
}
function b(e) {
switch (e) {
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 "RS384":
return {
name: "RSASSA-PKCS1-v1_5",
hash: {
name: "SHA-384"
}
};
case "RS512":
return {
name: "RSASSA-PKCS1-v1_5",
hash: {
name: "SHA-512"
}
};
case "PS256":
return {
name: "RSA-PSS",
hash: {
name: "SHA-256"
},
saltLength: 32
// 256 >> 3
};
case "PS384":
return {
name: "RSA-PSS",
hash: {
name: "SHA-384"
},
saltLength: 48
// 384 >> 3
};
case "PS512":
return {
name: "RSA-PSS",
hash: {
name: "SHA-512"
},
saltLength: 64
// 512 >> 3,
};
case "ES256":
return {
name: "ECDSA",
hash: {
name: "SHA-256"
},
namedCurve: "P-256"
};
case "ES384":
return {
name: "ECDSA",
hash: {
name: "SHA-384"
},
namedCurve: "P-384"
};
case "ES512":
return {
name: "ECDSA",
hash: {
name: "SHA-512"
},
namedCurve: "P-521"
};
case "EdDSA":
return {
name: "Ed25519",
namedCurve: "Ed25519"
};
default:
throw new H(e);
}
}
function v(e) {
return e instanceof CryptoKey;
}
const p = (e) => (
// eslint-disable-next-line
// @ts-ignore
y(u.encode(JSON.stringify(e))).replace(/=/g, "")
), j = (e) => y(e).replace(/=/g, ""), w = (e) => JSON.parse(C.decode(m(e)));
function T(e) {
if (typeof e == "object" && e !== null) {
const t = e;
return "alg" in t && Object.values(h).includes(t.alg) && (!("typ" in t) || t.typ === "JWT");
}
return !1;
}
const N = async (e, t, r = "HS256") => {
const n = p(e), s = `${p({ alg: r, typ: "JWT" })}.${n}`, o = await I(t, r, u.encode(s)), c = j(o);
return `${s}.${c}`;
}, W = async (e, t, r = "HS256") => {
const n = e.split(".");
if (n.length !== 3)
throw new f(e);
const { header: a, payload: s } = A(e);
if (!T(a))
throw new g(a);
const o = Math.floor(Date.now() / 1e3);
if (s.nbf && s.nbf > o)
throw new P(e);
if (s.exp && s.exp <= o)
throw new J(e);
if (s.iat && o < s.iat)
throw new x(o, s.iat);
const c = e.substring(0, e.lastIndexOf("."));
if (!await $(t, r, m(n[2]), u.encode(c)))
throw new K(e);
return s;
}, A = (e) => {
try {
const [t, r] = e.split("."), n = w(t), a = w(r);
return {
header: n,
payload: a
};
} catch {
throw new f(e);
}
}, _ = { decode: A, sign: N, verify: W };
export {
A as decode,
_ as default,
N as sign,
W as verify
};