Files
myeasycms-v2/packages/shared/src/utils.ts
Giancarlo Buomprisco 9681e1f90b Chore: force Zod v3, replace deprecated Supabase vars in local dev, updated Dev Tool (#425)
* - Replaced Supabase local environment variables
- Updates packages
- Force Zod v3 if peer deps require Zod v4
- Updated Dev Tool

* Use correct field for pnpm overrides

* Fix inaccuracies in the Agents files; fix type casting in `useForm`

* Updated lock file

* Be more specific when intercepting POST request in flaky e2e test
2025-12-13 12:20:15 +08:00

64 lines
1.7 KiB
TypeScript

/**
* Check if the code is running in a browser environment.
*/
export function isBrowser() {
return typeof window !== 'undefined';
}
/**
* @name formatCurrency
* @description Format the currency based on the currency code
*/
export function formatCurrency(params: {
currencyCode: string;
locale: string;
value: string | number;
}) {
const [lang, region] = params.locale.split('-');
return new Intl.NumberFormat(region ?? lang, {
style: 'currency',
currency: params.currencyCode,
}).format(Number(params.value));
}
/**
* @name isSafeRedirectPath
* @description Checks if a path is safe for redirects (prevents open redirect attacks).
* Safe paths must:
* - Start with a single `/`
* - NOT start with `//` (protocol-relative URLs)
* - NOT contain `://` (absolute URLs)
* - NOT contain backslash (URL normalization attacks)
*/
export function isSafeRedirectPath(path: string): boolean {
if (!path || typeof path !== 'string') return false;
// Must start with exactly one forward slash (relative path)
if (!path.startsWith('/') || path.startsWith('//')) return false;
// Must not contain protocol indicators
if (path.includes('://')) return false;
// Must not contain backslashes (can be normalized to forward slashes)
if (path.includes('\\')) return false;
return true;
}
/**
* @name getSafeRedirectPath
* @description Returns the path if safe, otherwise returns the fallback.
* Use this to validate user-supplied redirect URLs to prevent open redirect attacks.
*/
export function getSafeRedirectPath(
path: string | null | undefined,
fallback: string,
): string {
if (path && isSafeRedirectPath(path)) {
return path;
}
return fallback;
}