Repository navigation
feat: warn before visiting external links #1536
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,179 @@ | ||
| import { useEffect, useRef, useState } from 'react'; | ||
| import { Button } from '@/components/ui/button'; | ||
| import { Checkbox } from '@/components/ui/checkbox'; | ||
| import { | ||
| Dialog, | ||
| DialogContent, | ||
| DialogDescription, | ||
| DialogFooter, | ||
| DialogHeader, | ||
| DialogTitle, | ||
| } from '@/components/ui/dialog'; | ||
| import { | ||
| parseExternalLink, | ||
| readTrustedDomains, | ||
| trustDomain, | ||
| writeTrustedDomains, | ||
| type ExternalLink, | ||
| } from '@/lib/external-links'; | ||
|
|
||
| function trustedStorage(): Storage | undefined { | ||
| if (typeof window === 'undefined') { | ||
| return undefined; | ||
| } | ||
|
|
||
| try { | ||
| return window.localStorage; | ||
| } catch { | ||
| // Blocked storage must not break the warning flow. | ||
| return undefined; | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Warns before following external links, since labels and shorteners can disguise where a link | ||
| * lands. Trusted domains are remembered in local storage and open without asking. | ||
| */ | ||
| export function ExternalLinkGuard() { | ||
| const [pending, setPending] = useState<{ | ||
| link: ExternalLink; | ||
| anchor: HTMLAnchorElement; | ||
| } | null>(null); | ||
| const [shownLink, setShownLink] = useState<ExternalLink | null>(null); | ||
| const [trustChecked, setTrustChecked] = useState(false); | ||
| // One-use pass for the anchor the visitor just confirmed, consumed on that click. | ||
| const confirmedAnchor = useRef<HTMLAnchorElement | null>(null); | ||
|
|
||
| useEffect(() => { | ||
| const onClick = (event: MouseEvent): void => { | ||
| if ( | ||
| event.defaultPrevented || | ||
| event.button !== 0 || | ||
| event.metaKey || | ||
| event.ctrlKey || | ||
| event.shiftKey || | ||
| event.altKey | ||
| ) { | ||
| return; | ||
| } | ||
|
|
||
| if (!(event.target instanceof Element)) { | ||
| return; | ||
| } | ||
|
|
||
| const anchor = event.target.closest('a[href]'); | ||
|
|
||
| if (!(anchor instanceof HTMLAnchorElement)) { | ||
| return; | ||
| } | ||
|
|
||
| if (confirmedAnchor.current === anchor) { | ||
| confirmedAnchor.current = null; | ||
|
|
||
| return; | ||
| } | ||
|
|
||
| const external = parseExternalLink( | ||
| anchor.getAttribute('href') ?? '', | ||
| window.location.href, | ||
| ); | ||
|
|
||
| if (external === null) { | ||
| return; | ||
| } | ||
|
|
||
| const trusted = readTrustedDomains(trustedStorage()).some( | ||
| (domain) => | ||
| domain.toLowerCase() === external.domain.toLowerCase(), | ||
| ); | ||
|
|
||
| if (trusted) { | ||
| return; | ||
| } | ||
|
|
||
| event.preventDefault(); | ||
| setTrustChecked(false); | ||
| setShownLink(external); | ||
| setPending({ link: external, anchor }); | ||
| }; | ||
|
|
||
| document.addEventListener('click', onClick, true); | ||
|
|
||
| return () => document.removeEventListener('click', onClick, true); | ||
| }, []); | ||
|
|
||
| const stay = (): void => setPending(null); | ||
|
|
||
| const leave = (): void => { | ||
| if (pending === null) { | ||
| return; | ||
| } | ||
|
|
||
| if (trustChecked) { | ||
| writeTrustedDomains( | ||
| trustedStorage(), | ||
| trustDomain( | ||
| readTrustedDomains(trustedStorage()), | ||
| pending.link.domain, | ||
| ), | ||
| ); | ||
| } | ||
|
|
||
| const { link, anchor } = pending; | ||
| setPending(null); | ||
| confirmedAnchor.current = anchor; | ||
|
|
||
| if (anchor.isConnected) { | ||
| anchor.click(); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Allow the confirmed click through the guard exactly once.
When the trust checkbox is unchecked, this second click finds the same untrusted domain. The listener prevents navigation and restores Add a one-use exemption for the confirmed anchor activation. Do not require persistent trust to complete a single visit.
|
||
| } else { | ||
| confirmedAnchor.current = null; | ||
| window.open(link.url, '_blank', 'noopener,noreferrer'); | ||
| } | ||
| }; | ||
|
|
||
| return ( | ||
| <Dialog | ||
| open={pending !== null} | ||
| onOpenChange={(open) => { | ||
| if (!open) { | ||
| stay(); | ||
| } | ||
| }} | ||
| > | ||
| <DialogContent data-test="external-link-guard"> | ||
| <DialogHeader> | ||
| <DialogTitle>Head to {shownLink?.domain}?</DialogTitle> | ||
| <DialogDescription> | ||
| This link takes you to an external site. Addresses can | ||
| be disguised, so check it before you continue. | ||
| </DialogDescription> | ||
| </DialogHeader> | ||
| <p className="rounded-md bg-muted px-3 py-2 font-mono text-xs wrap-anywhere"> | ||
| {shownLink?.url} | ||
| </p> | ||
| <label className="flex cursor-pointer items-center gap-2 text-sm"> | ||
| <Checkbox | ||
| checked={trustChecked} | ||
| onCheckedChange={(checked) => | ||
| setTrustChecked(checked === true) | ||
| } | ||
| data-test="external-link-trust" | ||
| /> | ||
| Don't warn me about links to {shownLink?.domain} again | ||
| </label> | ||
| <DialogFooter> | ||
| <Button | ||
| variant="outline" | ||
| onClick={stay} | ||
| data-test="external-link-stay" | ||
| > | ||
| Stay here | ||
| </Button> | ||
| <Button onClick={leave} data-test="external-link-leave"> | ||
| Visit site | ||
| </Button> | ||
| </DialogFooter> | ||
| </DialogContent> | ||
| </Dialog> | ||
| ); | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,84 @@ | ||
| // External links open a leave-site warning unless their domain is trusted. | ||
|
|
||
| export type ExternalLink = { | ||
| url: string; | ||
| domain: string; | ||
| }; | ||
|
|
||
| /** | ||
| * The link details when href points outside the current site, null for internal, relative and | ||
| * non-HTTP(S) links. Protocol-relative links resolve against the page, so //evil.example counts. | ||
| */ | ||
| export function parseExternalLink( | ||
| href: string, | ||
| base: string, | ||
| ): ExternalLink | null { | ||
| let url: URL; | ||
|
|
||
| try { | ||
| url = new URL(href, base); | ||
| } catch { | ||
| return null; | ||
| } | ||
|
|
||
| if (url.protocol !== 'http:' && url.protocol !== 'https:') { | ||
| return null; | ||
| } | ||
|
|
||
| let host: string; | ||
|
|
||
| try { | ||
| host = new URL(base).host; | ||
| } catch { | ||
| return null; | ||
| } | ||
|
|
||
| if (url.host.toLowerCase() === host.toLowerCase()) { | ||
| return null; | ||
| } | ||
|
|
||
| return { url: url.href, domain: url.host }; | ||
| } | ||
|
|
||
| const trustedDomainsKey = 'trusted-external-domains'; | ||
|
|
||
| export function readTrustedDomains( | ||
| storage: Pick<Storage, 'getItem'> | undefined, | ||
| ): string[] { | ||
| try { | ||
| const raw = storage?.getItem(trustedDomainsKey); | ||
|
|
||
| if (!raw) { | ||
| return []; | ||
| } | ||
|
|
||
| const parsed: unknown = JSON.parse(raw); | ||
|
|
||
| return Array.isArray(parsed) | ||
| ? parsed.filter( | ||
| (domain): domain is string => typeof domain === 'string', | ||
| ) | ||
| : []; | ||
| } catch { | ||
| return []; | ||
| } | ||
| } | ||
|
|
||
| export function trustDomain(domains: string[], domain: string): string[] { | ||
| const normalized = domain.toLowerCase(); | ||
|
|
||
| return domains.some((existing) => existing.toLowerCase() === normalized) | ||
| ? domains | ||
| : [...domains, domain]; | ||
| } | ||
|
|
||
| export function writeTrustedDomains( | ||
| storage: Pick<Storage, 'setItem'> | undefined, | ||
| domains: string[], | ||
| ): void { | ||
| try { | ||
| storage?.setItem(trustedDomainsKey, JSON.stringify(domains)); | ||
| } catch { | ||
| // Private browsing and disabled storage just skip persisting. | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| import assert from 'node:assert/strict'; | ||
| import { renderToStaticMarkup } from 'react-dom/server'; | ||
| import { test } from 'vitest'; | ||
| import { ExternalLinkGuard } from '../../resources/js/components/external-link-guard'; | ||
|
|
||
| test('renders nothing until an external link is clicked', () => { | ||
| assert.equal(renderToStaticMarkup(<ExternalLinkGuard />), ''); | ||
| }); |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,73 @@ | ||
| import assert from 'node:assert/strict'; | ||
| import { test } from 'node:test'; | ||
| import { | ||
| parseExternalLink, | ||
| readTrustedDomains, | ||
| trustDomain, | ||
| writeTrustedDomains, | ||
| } from '../../resources/js/lib/external-links.ts'; | ||
|
|
||
| function memoryStorage(initial: Record<string, string> = {}): Storage { | ||
| const store = new Map(Object.entries(initial)); | ||
|
|
||
| return { | ||
| getItem: (key: string) => store.get(key) ?? null, | ||
| setItem: (key: string, value: string) => { | ||
| store.set(key, value); | ||
| }, | ||
| } as Storage; | ||
| } | ||
|
|
||
| await test('flags outside links and passes internal, relative and invalid ones', () => { | ||
| const base = 'https://dev-null.sh/commits?page=2'; | ||
|
|
||
| assert.deepEqual(parseExternalLink('https://evil.example/x', base), { | ||
| url: 'https://evil.example/x', | ||
| domain: 'evil.example', | ||
| }); | ||
| assert.equal(parseExternalLink('https://dev-null.sh/commits', base), null); | ||
| assert.equal( | ||
| parseExternalLink('https://dev-null.sh.evil.example/', base)?.domain, | ||
| 'dev-null.sh.evil.example', | ||
| ); | ||
| assert.equal(parseExternalLink('/commits', base), null); | ||
| assert.equal( | ||
| parseExternalLink('//evil.example/x', base)?.domain, | ||
| 'evil.example', | ||
| ); | ||
| assert.equal(parseExternalLink('//dev-null.sh/x', base), null); | ||
| assert.equal(parseExternalLink('mailto:someone@example.com', base), null); | ||
| assert.equal(parseExternalLink('https://', base), null); | ||
| assert.equal(parseExternalLink('javascript:alert(1)', base), null); | ||
| assert.equal( | ||
| parseExternalLink(' HTTPS://EXAMPLE.COM/x ', base)?.domain, | ||
| 'example.com', | ||
| ); | ||
| }); | ||
|
|
||
| await test('trusts a domain once and remembers the list', () => { | ||
| assert.deepEqual(trustDomain([], 'Example.com'), ['Example.com']); | ||
| assert.deepEqual(trustDomain(['example.com'], 'EXAMPLE.COM'), [ | ||
| 'example.com', | ||
| ]); | ||
| assert.deepEqual(trustDomain(['a.example'], 'b.example'), [ | ||
| 'a.example', | ||
| 'b.example', | ||
| ]); | ||
| }); | ||
|
|
||
| await test('round-trips trusted domains and ignores corrupt storage', () => { | ||
| const storage = memoryStorage(); | ||
|
|
||
| assert.deepEqual(readTrustedDomains(storage), []); | ||
|
|
||
| writeTrustedDomains(storage, ['example.com']); | ||
| assert.deepEqual(readTrustedDomains(storage), ['example.com']); | ||
| assert.deepEqual( | ||
| readTrustedDomains( | ||
| memoryStorage({ 'trusted-external-domains': 'nope[' }), | ||
| ), | ||
| [], | ||
| ); | ||
| assert.deepEqual(readTrustedDomains(undefined), []); | ||
| }); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Script executed:
Repository: dev-null-sh/dev-null.sh
Length of output: 41490
Script executed:
Repository: dev-null-sh/dev-null.sh
Length of output: 16887
Script executed:
Repository: dev-null-sh/dev-null.sh
Length of output: 16502
Script executed:
Repository: dev-null-sh/dev-null.sh
Length of output: 15700
Script executed:
Repository: dev-null-sh/dev-null.sh
Length of output: 23093
Script executed:
Repository: dev-null-sh/dev-null.sh
Length of output: 8958
Script executed:
Repository: dev-null-sh/dev-null.sh
Length of output: 2580
Script executed:
Repository: dev-null-sh/dev-null.sh
Length of output: 8560
Script executed:
Repository: dev-null-sh/dev-null.sh
Length of output: 4056
Script executed:
Repository: dev-null-sh/dev-null.sh
Length of output: 7267
Recheck the destination before navigation.
A live stream update can change the anchor from YouTube to Twitch while the dialog still shows YouTube. The identity-only pass then opens Twitch without showing its warning. Bind the pass to the confirmed URL and recheck the anchor before navigation.