sanitizePath function
Removes dangerous characters from path that could cause security issues.
Strips null bytes, path traversal sequences, and control characters.
Implementation
String sanitizePath(String path) {
var p = path;
// Remove null bytes.
p = p.replaceAll('\x00', '');
// Remove control characters (0x01-0x1F, 0x7F) except tab/newline.
p = p.replaceAll(RegExp(r'[\x01-\x08\x0B\x0C\x0E-\x1F\x7F]'), '');
// Collapse path traversal.
while (p.contains('..')) {
p = p.replaceAll('..', '');
}
// Remove leading/trailing whitespace from each segment.
p = p.split('/').map((s) => s.trim()).where((s) => s.isNotEmpty).join('/');
// Preserve leading slash.
if (path.startsWith('/') && !p.startsWith('/')) {
p = '/$p';
}
return p;
}