Bairdy
Bairdy9mo ago

Deno - Sanitize Filters

Does Deno have anything similar to https://www.php.net/manual/en/filter.filters.sanitize.php for HTTP HTML POST forms? Example:
function filterSanitizeString(input: string): string {
// Remove control characters
let sanitized = input.replace(/[\x00-\x1F\x7F-\x9F]/g, "");

// Remove potential SQL injection code
sanitized = sanitized.replace(/('|--|;)/g, "");

// Remove potential script injection
sanitized = sanitized.replace(/(<script>|<\/script>)/gi, "");

// Escape special HTML characters to prevent basic HTML injection
sanitized = sanitized.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;');

return sanitized;
}
function filterSanitizeString(input: string): string {
// Remove control characters
let sanitized = input.replace(/[\x00-\x1F\x7F-\x9F]/g, "");

// Remove potential SQL injection code
sanitized = sanitized.replace(/('|--|;)/g, "");

// Remove potential script injection
sanitized = sanitized.replace(/(<script>|<\/script>)/gi, "");

// Escape special HTML characters to prevent basic HTML injection
sanitized = sanitized.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;');

return sanitized;
}
2 Replies
Deno AI Helper
Deno AI Helper9mo ago
The documentation does not provide a specific function or module for sanitizing HTML form inputs like PHP's filter.filters.sanitize. However, it does provide an example of a simple HTML sanitization function to prevent XSS vulnerabilities in the context of server-side rendering. Here's the example from the documentation:
function sanitizeHtml(text) {
return text
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&#039;");
}
function sanitizeHtml(text) {
return text
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&#039;");
}
This function replaces special HTML characters with their corresponding HTML entities to prevent basic HTML injection. However, it does not cover SQL injection prevention or script tag removal as in your provided example. For more advanced sanitization needs, you might need to use or create a more comprehensive function or use a third-party library, but please note that this advice is not explicitly supported by the documentation.
Leokuma
Leokuma9mo ago
AFAIK there's only HTML escaping: https://deno.land/std@0.203.0/html/mod.ts?s=escape