diff --git a/app/common/gristUrls.ts b/app/common/gristUrls.ts index 048e3504..deb3bfc9 100644 --- a/app/common/gristUrls.ts +++ b/app/common/gristUrls.ts @@ -185,18 +185,24 @@ export interface OrgUrlInfo { orgInPath?: string; // If /o/{orgInPath} should be used to access the requested org. } -function isInternalUrl(host: string, envValue?: string) { - if (!envValue) { return false; } - const internalUrl = new URL('/', envValue); - return internalUrl.host === host; +export function hostMatchesUrl(host?: string, url?: string) { + return host !== undefined && url !== undefined && new URL(url).host === host; } -function isDocInternalUrl(host: string) { - return isInternalUrl(host, process.env.APP_DOC_INTERNAL_URL); -} - -function isHomeInternalUrl(host: string) { - return isInternalUrl(host, process.env.APP_HOME_INTERNAL_URL); +/** + * Returns true if: + * - the server is a home worker and the host matches APP_HOME_INTERNAL_URL; + * - or the server is a doc worker and the host matches APP_DOC_INTERNAL_URL; + * + * @param {string?} host The host to check + */ +export function isOwnInternalUrlHost(host?: string) { + if (process.env.APP_HOME_INTERNAL_URL) { + return hostMatchesUrl(host, process.env.APP_HOME_INTERNAL_URL); + } else if (process.env.APP_DOC_INTERNAL_URL) { + return hostMatchesUrl(host, process.env.APP_DOC_INTERNAL_URL); + } + return false; } /** @@ -218,9 +224,8 @@ export function getHostType(host: string, options: { if (!options.baseDomain) { return 'native'; } if ( hostname === 'localhost' || - isDocInternalUrl(host) || - hostname.endsWith(options.baseDomain) || - isHomeInternalUrl(host) + isOwnInternalUrlHost(host) || + hostname.endsWith(options.baseDomain) ) { return 'native'; } diff --git a/app/server/lib/requestUtils.ts b/app/server/lib/requestUtils.ts index 3f0f5cf5..8216830b 100644 --- a/app/server/lib/requestUtils.ts +++ b/app/server/lib/requestUtils.ts @@ -1,5 +1,7 @@ import {ApiError} from 'app/common/ApiError'; -import {DEFAULT_HOME_SUBDOMAIN, isOrgInPathOnly, parseSubdomain, sanitizePathTail} from 'app/common/gristUrls'; +import { + DEFAULT_HOME_SUBDOMAIN, isOrgInPathOnly, isOwnInternalUrlHost, parseSubdomain, sanitizePathTail +} from 'app/common/gristUrls'; import * as gutil from 'app/common/gutil'; import {DocScope, QueryResult, Scope} from 'app/gen-server/lib/HomeDBManager'; import {getUserId, RequestWithLogin} from 'app/server/lib/Authorizer'; @@ -88,12 +90,7 @@ export function trustOrigin(req: IncomingMessage, resp?: Response): boolean { const origin = req.headers.origin; if (!origin) { return true; } // Not a CORS request. - if ( - (process.env.APP_HOME_INTERNAL_URL && req.hostname === new URL(process.env.APP_HOME_INTERNAL_URL).hostname) || - (process.env.APP_DOC_INTERNAL_URL && req.hostname === new URL(process.env.APP_DOC_INTERNAL_URL).hostname) - ) { - return true; - } + if (isOwnInternalUrlHost(req.get('Host'))) { return true; } if (!allowHost(req, new URL(origin))) { return false; }