diff --git a/.changeset/nasty-spies-repair.md b/.changeset/nasty-spies-repair.md new file mode 100644 index 0000000..0aba6bd --- /dev/null +++ b/.changeset/nasty-spies-repair.md @@ -0,0 +1,5 @@ +--- +"@urami/core": minor +--- + +added `defaultDomain` config as a way to define domain to fetch an image as a relative path diff --git a/apps/docs/src/core/configuration.md b/apps/docs/src/core/configuration.md index 8bdc7e5..05f803e 100644 --- a/apps/docs/src/core/configuration.md +++ b/apps/docs/src/core/configuration.md @@ -50,6 +50,12 @@ List of domains that allowed to use the API, this will be checked via header `Re Only applied when `process.env.NODE_ENV` is set to `production`. Unset this option will allow anywhere to request image from this API. +## defaultDomain + +`string | undefined` + +Default domain to use when domain is not specified in URL. Defaults to undefined + ## ttl `number` diff --git a/packages/core/src/@types/Config.ts b/packages/core/src/@types/Config.ts index 896a9d2..4e9fa14 100644 --- a/packages/core/src/@types/Config.ts +++ b/packages/core/src/@types/Config.ts @@ -5,6 +5,9 @@ export interface Config { // lists of allowed domain to use this API (will check via header `Referer`), not specifying anything will allow all domains to use this API allowedDomains?: string[] + // default domain to use if no domain is specified + defaultDomain?: string + // directory to temporary store optimized images (default to .svelte-kit/images), paths will be relative to process.cwd() storePath: string diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 5612713..c7da350 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -42,18 +42,18 @@ export const createRequestHandler = const width = Number(fullRequestUrl.searchParams.get('w') ?? '') const quality = Number(fullRequestUrl.searchParams.get('q') ?? '') + // Check if the URL is valid. If not, try to construct a new URL using defaultDomain or referer header. try { // attempt to construct a URL, a relative URL will throw an error url = new URL(url).toString() } catch (e) { - // if relative URL does not have a referer header, throw an error - const referer = request.headers.get('referer') - if (referer === null) { - throw error(400, 'missing url') - } + // if default domain is specified, construct a new URL using the default domain + const targetDomain = + mergedConfig.defaultDomain ?? request.headers.get('referer') + + if (targetDomain === null) throw error(400, 'missing url') - // construct a new URL using the referer header - url = new URL(url, referer).toString() + url = new URL(url, mergedConfig.defaultDomain).toString() } // make sure that this url is allowed to optimize