fix(electron-utils): trim and normalize URLs in safeExternalUrl (#274)
Co-authored-by: Aniruddha Adak <aniruddhaadak80@users.noreply.github.com>
This commit is contained in:
co-authored by
Aniruddha Adak
parent
12026fd21a
commit
a5ed6f8cf0
@@ -12,17 +12,21 @@ export interface SafeExternalUrlOptions {
|
||||
const DEFAULT_PROTOCOLS: readonly string[] = ['http:', 'https:']
|
||||
|
||||
/**
|
||||
* Returns the URL string when it parses and its protocol is on the allowlist,
|
||||
* otherwise null. Callers must not fall back to opening the raw input.
|
||||
* Returns the trimmed URL string when it parses and its protocol is on the
|
||||
* allowlist, otherwise null. Callers must not fall back to opening the raw
|
||||
* input. Trims because the WHATWG parser silently strips surrounding
|
||||
* whitespace, so validating the raw input but returning it verbatim would
|
||||
* hand `shell.openExternal` a URL that fails there.
|
||||
*/
|
||||
export function safeExternalUrl(url: unknown, options?: SafeExternalUrlOptions): string | null {
|
||||
if (typeof url !== 'string') return null
|
||||
const text = url.trim()
|
||||
let parsed: URL
|
||||
try {
|
||||
parsed = new URL(url)
|
||||
parsed = new URL(text)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
const allowed = options?.allowedProtocols ?? DEFAULT_PROTOCOLS
|
||||
return allowed.includes(parsed.protocol) ? url : null
|
||||
return allowed.includes(parsed.protocol) ? text : null
|
||||
}
|
||||
|
||||
@@ -35,4 +35,13 @@ describe('safeExternalUrl', () => {
|
||||
expect(safeExternalUrl('mailto:a@b.com', opts)).toBe('mailto:a@b.com')
|
||||
expect(safeExternalUrl('http://example.com', opts)).toBeNull()
|
||||
})
|
||||
|
||||
it('trims surrounding whitespace instead of returning it verbatim', () => {
|
||||
// The WHATWG parser strips surrounding whitespace while parsing, so the
|
||||
// untrimmed input validates but would fail in shell.openExternal.
|
||||
expect(safeExternalUrl(' https://example.com/a?b=c ')).toBe('https://example.com/a?b=c')
|
||||
expect(safeExternalUrl('\nhttp://example.com\n')).toBe('http://example.com')
|
||||
expect(safeExternalUrl(' ')).toBeNull()
|
||||
expect(safeExternalUrl(' file:///etc/passwd ')).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user