blade
Version:
React at the edge.
54 lines (52 loc) • 2.07 kB
JavaScript
import { EmptyFieldsError, InvalidPermissionsError } from "blade/errors";
import { verifyJWT } from "blade/server/utils";
//#region ../blade-auth/dist/utils-CUmNvaMX.js
/**
* Check given object for empty values. Throws an error if the object contains
* empty values.
*
* @param to Object to check for empty values.
* @param allowed Optional array of keys to exclude. Used in cases where `null`
* is allowed as a value.
*/
const avoidEmptyFields = (to, allowed) => {
const emptyFields = Object.keys(to || {}).filter((key) => !(allowed || []).includes(key) && typeof to?.[key] !== "boolean" && !to?.[key]);
if (emptyFields.length > 0) throw new EmptyFieldsError({ fields: emptyFields });
};
const AUTH_SECRET = import.meta.env?.BLADE_AUTH_SECRET || (import.meta.env?.BLADE_ENV === "development" ? "default-secret-1234" : "");
if (!AUTH_SECRET && typeof import.meta.env !== "undefined") throw new Error("Please add a `BLADE_AUTH_SECRET` environment variable.");
/**
* Retrieve the account that authored the incoming query.
*
* @param cookies - The list of cookies provided to the trigger.
*
* @returns The ID of the account that authored the incoming query.
*/
const getSessionCookie = async (cookies) => {
const token = cookies.session;
let sessionId = null;
let accountId = null;
if (token) try {
const tokenPayload = await verifyJWT(token, AUTH_SECRET);
sessionId = tokenPayload?.sub || null;
accountId = tokenPayload?.aud || null;
} catch (err) {
console.warn(`Failed to decode token: \`${err.message}\``);
}
if (!(sessionId && accountId)) throw new InvalidPermissionsError({ message: "No session provided for authentication." });
return {
sessionId,
accountId
};
};
/**
* Generate pseudo-random unique identifiers.
*
* @returns A unique identifier.
*/
const generateUniqueId = () => {
return crypto.getRandomValues(new Uint32Array(1))[0].toString();
};
const EMAIL_VERIFICATION_COOLDOWN = 2e4;
//#endregion
export { getSessionCookie as a, generateUniqueId as i, EMAIL_VERIFICATION_COOLDOWN as n, avoidEmptyFields as r, AUTH_SECRET as t };