gendesign/tradein-mvp/frontend/src/lib/safeUrl.ts
lekss361 3665a61e48
All checks were successful
Deploy Trade-In / changes (push) Successful in 5s
Deploy Trade-In / build-backend (push) Has been skipped
Deploy Trade-In / build-frontend (push) Successful in 1m24s
Deploy Trade-In / deploy (push) Successful in 32s
fix(tradein-frontend): safeUrl validator, apiFetch dedup, ListingsCard a11y, error boundary (#512)
2026-05-24 11:47:38 +00:00

23 lines
789 B
TypeScript

/**
* Validate an external URL string. Returns the URL only if it parses and uses
* an http/https scheme — otherwise null.
*
* Defends against:
* - javascript: URLs (XSS via href clicks)
* - data: URLs (data exfiltration, weird content)
* - file:, ftp:, custom-scheme abuse
* - malformed strings (null reference protection)
*
* Closes finding #3 from 2026-05-24 trade-in audit. Backend supplies
* lot.source_url verbatim from scraped sites — must not trust the string.
*/
export function safeUrl(raw: string | null | undefined): string | null {
if (!raw || typeof raw !== "string") return null;
try {
const u = new URL(raw);
if (u.protocol !== "http:" && u.protocol !== "https:") return null;
return u.toString();
} catch {
return null;
}
}