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.
85 lines • 2.83 kB
JavaScript
// function from: https://github.com/better-auth/utils
function getAlphabet(urlSafe) {
return urlSafe
? "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"
: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
}
function base64Encode(data, alphabet, padding) {
let result = "";
let buffer = 0;
let shift = 0;
for (const byte of data) {
buffer = (buffer << 8) | byte;
shift += 8;
while (shift >= 6) {
shift -= 6;
result += alphabet[(buffer >> shift) & 0x3f];
}
}
if (shift > 0) {
result += alphabet[(buffer << (6 - shift)) & 0x3f];
}
if (padding) {
const padCount = (4 - (result.length % 4)) % 4;
result += "=".repeat(padCount);
}
return result;
}
function base64Decode(data, alphabet) {
const decodeMap = new Map();
for (let i = 0; i < alphabet.length; i++) {
const char = alphabet[i];
if (char)
decodeMap.set(char, i);
}
const result = [];
let buffer = 0;
let bitsCollected = 0;
for (const char of data) {
if (char === "=")
break;
const value = decodeMap.get(char);
if (value === undefined) {
throw new Error(`Invalid Base64 character: ${char}`);
}
buffer = (buffer << 6) | value;
bitsCollected += 6;
if (bitsCollected >= 8) {
bitsCollected -= 8;
result.push((buffer >> bitsCollected) & 0xff);
}
}
return Uint8Array.from(result);
}
export const base64 = {
encode(data, options = {}) {
var _a;
const alphabet = getAlphabet(false);
const buffer = typeof data === "string"
? new TextEncoder().encode(data)
: new Uint8Array(data);
return base64Encode(buffer, alphabet, (_a = options.padding) !== null && _a !== void 0 ? _a : true);
},
decode(data) {
const decodedData = typeof data !== "string" ? new TextDecoder().decode(data) : data;
const urlSafe = decodedData.includes("-") || decodedData.includes("_");
const alphabet = getAlphabet(urlSafe);
return base64Decode(decodedData, alphabet);
},
};
export const base64Url = {
encode(data, options = {}) {
var _a;
const alphabet = getAlphabet(true);
const buffer = typeof data === "string"
? new TextEncoder().encode(data)
: new Uint8Array(data);
return base64Encode(buffer, alphabet, (_a = options.padding) !== null && _a !== void 0 ? _a : true);
},
decode(data) {
const urlSafe = data.includes("-") || data.includes("_");
const alphabet = getAlphabet(urlSafe);
return base64Decode(data, alphabet);
},
};
//# sourceMappingURL=base64.js.map