aegis-auth
Version:
A credentials-based auth solution for Next.js (and other Node projects) with IP rate-limiting, account lockouts, and sessions in DB.
50 lines • 2.07 kB
JavaScript
// function from: https://github.com/better-auth/utils
import { subtle } from "uncrypto";
import { base64, base64Url } from "./base64";
import { hex } from "./hex";
export const createHMAC = (algorithm = "SHA-256", encoding = "none") => {
const hmac = {
importKey: async (key, keyUsage) => {
return subtle.importKey("raw", typeof key === "string" ? new TextEncoder().encode(key) : key, { name: "HMAC", hash: { name: algorithm } }, false, [keyUsage]);
},
sign: async (hmacKey, data) => {
let actualKey;
if (typeof hmacKey === "string") {
actualKey = await hmac.importKey(hmacKey, "sign");
}
else {
actualKey = hmacKey;
}
const signature = await subtle.sign("HMAC", actualKey, typeof data === "string" ? new TextEncoder().encode(data) : data);
if (encoding === "hex") {
return hex.encode(signature);
}
if (encoding === "base64" ||
encoding === "base64url" ||
encoding === "base64urlnopad") {
return base64Url.encode(signature, {
padding: encoding !== "base64urlnopad",
});
}
return signature;
},
verify: async (hmacKey, data, signature) => {
let key = hmacKey;
let sig = signature;
if (typeof key === "string") {
key = await hmac.importKey(key, "verify");
}
if (encoding === "hex") {
sig = hex.decode(sig);
}
if (encoding === "base64" ||
encoding === "base64url" ||
encoding === "base64urlnopad") {
sig = base64.decode(sig);
}
return subtle.verify("HMAC", key, typeof sig === "string" ? new TextEncoder().encode(sig) : sig, typeof data === "string" ? new TextEncoder().encode(data) : data);
},
};
return hmac;
};
//# sourceMappingURL=hmac.js.map