From a5ed6f8cf013ccc6570cf701c04c4752bdb05586 Mon Sep 17 00:00:00 2001 From: ANIRUDDHA ADAK Date: Thu, 10 Sep 2026 09:20:40 +0530 Subject: [PATCH] fix(electron-utils): trim and normalize URLs in safeExternalUrl (#274) Co-authored-by: Aniruddha Adak --- packages/electron-utils/src/safe-external-url.ts | 12 ++++++++---- .../electron-utils/tests/safe-external-url.test.ts | 9 +++++++++ 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/packages/electron-utils/src/safe-external-url.ts b/packages/electron-utils/src/safe-external-url.ts index d54496b..94061d9 100644 --- a/packages/electron-utils/src/safe-external-url.ts +++ b/packages/electron-utils/src/safe-external-url.ts @@ -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 } diff --git a/packages/electron-utils/tests/safe-external-url.test.ts b/packages/electron-utils/tests/safe-external-url.test.ts index e67eb03..80d9f69 100644 --- a/packages/electron-utils/tests/safe-external-url.test.ts +++ b/packages/electron-utils/tests/safe-external-url.test.ts @@ -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() + }) })