z-secure-service
Version:
A rate-limiting and API protection middleware that helps developers add security features to their APIs effortlessly.
55 lines (54 loc) • 1.84 kB
JavaScript
export function validateApiKey(apiKey) {
if (!apiKey) {
throw new Error("API key is missing.");
}
}
export function validateIdentificationKey(identificationKey) {
if (!identificationKey) {
throw new Error("Identification key is missing.");
}
}
export function validateRateLimiting(rule) {
console.log(rule);
if (!rule)
return;
const { algorithm } = rule;
if (!algorithm) {
throw new Error("Rate limiting algorithm is missing.");
}
if (algorithm === "TokenBucketRule") {
const { refillRate, refillIntervalMs, capacity } = rule.rule;
if (!refillRate || !refillIntervalMs || !capacity) {
throw new Error("TokenBucketRule requires refillRate, interval, and capacity.");
}
}
else if (algorithm === "FixedWindowRule") {
const { windowMs, limit } = rule.rule;
if (!windowMs || !limit) {
throw new Error("FixedWindowRule requires windowMs and limit.");
}
}
else if (algorithm === "LeakyBucketRule") {
const { leakRate, capacity, timeout } = rule.rule;
if (!leakRate || !capacity || !timeout) {
throw new Error("LeakyBucketRule requires leakRate, capacity, and timeout.");
}
}
else if (algorithm === "SlidingWindowRule") {
const { windowMs, limit } = rule.rule;
if (!windowMs || !limit) {
throw new Error("SlidingWindowRule requires windowMs and limit.");
}
}
else {
throw new Error(`Unsupported rate limiting algorithm: ${algorithm}`);
}
}
export function validateShield(rule) {
if (!rule)
return;
const { blocktime, limit, threshold, } = rule;
if (!blocktime || !limit || !threshold) {
throw new Error("Shield requires windowMs, limit, and threshold.");
}
}