export type RemotePattern = { hostname?: string; pathname?: string; protocol?: string; port?: string; }; /** * Evaluates whether a given URL matches the specified remote pattern based on protocol, hostname, port, and pathname. * * @param {URL} url - The URL object to be matched against the remote pattern. * @param {RemotePattern} remotePattern - The remote pattern object containing the protocol, hostname, port, and pathname to match. * @return {boolean} Returns `true` if the URL matches the given remote pattern; otherwise, `false`. */ export function matchPattern(url: URL, remotePattern: RemotePattern): boolean { return matchOrigin(url, remotePattern) && matchPathname(url, remotePattern.pathname, true); } /** * Evaluates whether a URL's protocol, hostname and port match a pattern. This is the single * place these rules live: image `remotePatterns` and `domains`, and `security.allowedDomains`, * all match through it. * * @param url - The protocol (with trailing colon), hostname and port to match. * @param pattern - The pattern to match against. Its `pathname` is ignored. * @return `true` if the protocol, hostname and port all match; otherwise, `false`. */ export function matchOrigin( url: Pick, pattern: RemotePattern, ): boolean { return ( matchProtocol(url, pattern.protocol) && matchHostname(url, pattern.hostname, true) && matchPort(url, pattern.port) ); } const DEFAULT_PORTS: Record = { http: '80', https: '443' }; /** * Checks if the given URL's port matches the specified port. A URL without a port is compared * using its protocol's default port, so `443` matches `https://example.com`. * * @param url - The URL whose port will be checked. * @param [port] - The port to match against the URL's port. If not provided, any port matches. * @return `true` if the URL's port matches the specified port or if no port is provided; otherwise, `false`. */ export function matchPort(url: Pick, port?: string): boolean { return !port || port === (url.port || DEFAULT_PORTS[url.protocol.slice(0, -1)]); } /** * Compares the protocol of the provided URL with a specified protocol. * * @param url - The URL whose protocol needs to be checked. * @param [protocol] - The protocol to compare against, without the trailing colon. If not * provided, only `http` and `https` match. Any other protocol, such as `data`, must be * listed explicitly. * @return `true` if the protocol matches; otherwise, `false`. */ export function matchProtocol(url: Pick, protocol?: string): boolean { const urlProtocol = url.protocol.slice(0, -1).toLowerCase(); if (!protocol) return urlProtocol === 'http' || urlProtocol === 'https'; return protocol.toLowerCase() === urlProtocol; } /** * Matches a given URL's hostname against a specified hostname, with optional support for wildcard patterns. * * @param {URL} url - The URL object whose hostname is to be matched. * @param {string} [hostname] - The hostname to match against. Supports wildcard patterns if `allowWildcard` is `true`. * @param {boolean} [allowWildcard=false] - Indicates whether wildcard patterns in the `hostname` parameter are allowed. * @return {boolean} - Returns `true` if the URL's hostname matches the given hostname criteria; otherwise, `false`. */ export function matchHostname( url: Pick, hostname?: string, allowWildcard = false, ): boolean { if (!hostname) { return true; } else if (!allowWildcard || !hostname.startsWith('*')) { return hostname === url.hostname; } else if (hostname.startsWith('**.')) { const slicedHostname = hostname.slice(2); // ** length return slicedHostname !== url.hostname && url.hostname.endsWith(slicedHostname); } else if (hostname.startsWith('*.')) { const slicedHostname = hostname.slice(1); // * length // Check if url hostname ends with the base domain if (!url.hostname.endsWith(slicedHostname)) { return false; } // Extract the subdomain part (before the base domain, excluding the dot) const subdomainWithDot = url.hostname.slice(0, -(slicedHostname.length - 1)); // Should be exactly one subdomain part followed by a dot return subdomainWithDot.endsWith('.') && !subdomainWithDot.slice(0, -1).includes('.'); } return false; } /** * Matches a given URL's pathname against a specified pattern, with optional support for wildcards. * * @param {URL} url - The URL object containing the pathname to be matched. * @param {string} [pathname] - The pathname pattern to match the URL against. * @param {boolean} [allowWildcard=false] - Determines whether wildcard matching is allowed. * @return {boolean} - Returns `true` if the URL's pathname matches the specified pattern; otherwise, `false`. */ export function matchPathname(url: URL, pathname?: string, allowWildcard = false): boolean { if (!pathname) { return true; } else if (!allowWildcard || !pathname.endsWith('*')) { return pathname === url.pathname; } else if (pathname.endsWith('/**')) { const slicedPathname = pathname.slice(0, -2); // ** length return slicedPathname !== url.pathname && url.pathname.startsWith(slicedPathname); } else if (pathname.endsWith('/*')) { const slicedPathname = pathname.slice(0, -1); // * length if (!url.pathname.startsWith(slicedPathname)) { return false; } const additionalPathChunks = url.pathname .slice(slicedPathname.length) .split('/') .filter(Boolean); return additionalPathChunks.length === 1; } return false; } /** * Determines whether a given remote resource, identified by its source URL, * is allowed based on specified domains and remote patterns. * * @param {string} src - The source URL of the remote resource to be validated. * @param {Object} options - The configuration options for domain and pattern matching. * @param {string[]} options.domains - A list of allowed domain names. * @param {RemotePattern[]} options.remotePatterns - A list of allowed remote patterns for matching. * @return {boolean} Returns `true` if the source URL matches any of the specified domains or remote patterns; otherwise, `false`. */ export function isRemoteAllowed( src: string, { domains, remotePatterns, }: { domains: string[]; remotePatterns: RemotePattern[]; }, ): boolean { if (!URL.canParse(src)) { return false; } const url = new URL(src); // Non-http(s) protocols are never allowed if (!['http:', 'https:', 'data:'].includes(url.protocol)) { return false; } return ( domains.some((domain) => matchProtocol(url) && matchHostname(url, domain)) || remotePatterns.some((remotePattern) => matchPattern(url, remotePattern)) ); }