3 namespace BookStack\Util;
5 use BookStack\Exceptions\HttpFetchException;
8 * Validate the host we're connecting to when making a server-side-request.
9 * Will use the given hosts config if given during construction otherwise
10 * will look to the app configured config.
14 protected string $config;
16 public function __construct(?string $config = null)
18 $this->config = $config ?? config('app.ssr_hosts') ?? '';
22 * @throws HttpFetchException
24 public function ensureAllowed(string $url): void
26 if (!$this->allowed($url)) {
27 throw new HttpFetchException(trans('errors.http_ssr_url_no_match'));
32 * Check if the given URL is allowed by the configured SSR host values.
34 public function allowed(string $url): bool
36 $allowed = $this->getHostPatterns();
38 foreach ($allowed as $pattern) {
39 if ($this->urlMatchesPattern($url, $pattern)) {
47 protected function urlMatchesPattern($url, $pattern): bool
49 $pattern = rtrim(trim($pattern), '/');
52 if (empty($pattern) || empty($url)) {
56 $quoted = preg_quote($pattern, '/');
57 $regexPattern = str_replace('\*', '.*', $quoted);
59 return preg_match('/^' . $regexPattern . '($|\/.*$|#.*$)/i', $url);
65 protected function getHostPatterns(): array
67 return explode(' ', strtolower($this->config));