UNPKG

@appwarden/middleware

Version:

Instantly shut off access your app deployed on Cloudflare or Vercel

109 lines (104 loc) 2.85 kB
import { LOCKDOWN_TEST_EXPIRY_MS } from "./chunk-JWUAFJ2E.js"; // src/utils/errors.ts var errorsMap = { mode: '`CSP_MODE` must be one of "disabled", "report-only", or "enforced"', directives: { ["DirectivesRequired" /* DirectivesRequired */]: '`CSP_DIRECTIVES` must be provided when `CSP_MODE` is "report-only" or "enforced"', ["DirectivesBadParse" /* DirectivesBadParse */]: "Failed to parse `CSP_DIRECTIVES`. Is it a valid JSON string?" }, appwardenApiToken: "Please provide a valid `appwardenApiToken`. Learn more at https://appwarden.com/docs/guides/api-token-management." }; var getErrors = (error) => { const matches = []; const errors = [...Object.entries(error.flatten().fieldErrors)]; for (const issue of error.issues) { errors.push( ...Object.entries( "returnTypeError" in issue ? issue.returnTypeError.flatten().fieldErrors : {} ) ); } for (const [field, maybeSchemaErrorKey] of errors) { let match = errorsMap[field]; if (match) { if (match instanceof Object) { if (maybeSchemaErrorKey) { match = match[maybeSchemaErrorKey[0]]; } } matches.push(match); } } return matches; }; // src/utils/memory-cache.ts var MemoryCache = class { cache = /* @__PURE__ */ new Map(); maxSize; constructor(options) { this.maxSize = options.maxSize; } get(key) { let item; if (this.cache.has(key)) { item = this.cache.get(key); this.cache.delete(key); if (item !== void 0) { this.cache.set(key, item); } } return item; } put(key, value) { if (this.cache.has(key)) { this.cache.delete(key); } else if (this.cache.size >= this.maxSize) { const firstKey = this.cache.keys().next().value; if (firstKey !== void 0) { this.cache.delete(firstKey); } } this.cache.set(key, value); } getValues() { return this.cache; } // the default value will be expired here static isExpired = (lockValue) => { if (!lockValue) { return true; } return Date.now() > lockValue.lastCheck + 3e4; }; static isTestExpired = (lockValue) => { if (!lockValue) { return true; } return Date.now() > lockValue.isLockedTest + LOCKDOWN_TEST_EXPIRY_MS; }; }; // src/schemas/helpers.ts import { z } from "zod"; var BoolOrStringSchema = z.union([z.string(), z.boolean()]).optional(); var BooleanSchema = BoolOrStringSchema.transform((val) => { if (val === "true" || val === true) { return true; } else if (val === "false" || val === false) { return false; } throw new Error("Invalid value"); }); var LockValue = z.object({ isLocked: z.number(), isLockedTest: z.number(), lastCheck: z.number(), code: z.string() }); export { getErrors, MemoryCache, BooleanSchema, LockValue };