Visualize Your Ideas With Code
feat(vite-plugin): add CORS Proxy (#357)
Waldemar Lehnera3c58228b7d3
diff --git a/package-lock.json b/package-lock.jsonindex d8caa83e..a0b7fcf3 100644--- a/package-lock.json+++ b/package-lock.json@@ -5755,6 +5755,15 @@"@types/range-parser": "*"}},+ "node_modules/@types/follow-redirects": {+ "version": "1.14.1",+ "resolved": "https://registry.npmjs.org/@types/follow-redirects/-/follow-redirects-1.14.1.tgz",+ "integrity": "sha512-THBEFwqsLuU/K62B5JRwab9NW97cFmL4Iy34NTMX0bMycQVzq2q7PKOkhfivIwxdpa/J72RppgC42vCHfwKJ0Q==",+ "dev": true,+ "dependencies": {+ "@types/node": "*"+ }+ },"node_modules/@types/graceful-fs": {"version": "4.1.5","license": "MIT",@@ -5844,8 +5853,9 @@"license": "MIT"},"node_modules/@types/node": {- "version": "18.13.0",- "license": "MIT"+ "version": "18.14.0",+ "resolved": "https://registry.npmjs.org/@types/node/-/node-18.14.0.tgz",+ "integrity": "sha512-5EWrvLmglK+imbCJY0+INViFWUHg1AHel1sq4ZVSfdcNqGy9Edv3UB9IIzzg+xPaUcAgZYcfVs2fBcwDeZzU0A=="},"node_modules/@types/normalize-package-data": {"version": "2.4.1",@@ -11085,14 +11095,15 @@}},"node_modules/follow-redirects": {- "version": "1.15.1",+ "version": "1.15.2",+ "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.2.tgz",+ "integrity": "sha512-VQLG33o04KaQ8uYi2tVNbdrWp1QWxNNea+nmIB4EVM28v0hmP17z7aG1+wAkNzVq4KeXTq3221ye5qTJP91JwA==","funding": [{"type": "individual","url": "https://github.com/sponsors/RubenVerborgh"}],- "license": "MIT","engines": {"node": ">=4.0"},@@ -21679,11 +21690,14 @@"version": "2.4.0","license": "MIT","dependencies": {+ "follow-redirects": "^1.15.2","mime-types": "^2.1.35"},"devDependencies": {"@motion-canvas/internal": "0.0.0",- "@types/mime-types": "^2.1.1"+ "@types/follow-redirects": "^1.14.1",+ "@types/mime-types": "^2.1.1",+ "@types/node": "^18.14.0"},"peerDependencies": {"vite": "3.x"@@ -25021,7 +25035,10 @@"version": "file:packages/vite-plugin","requires": {"@motion-canvas/internal": "0.0.0",+ "@types/follow-redirects": "^1.14.1","@types/mime-types": "^2.1.1",+ "@types/node": "*",+ "follow-redirects": "^1.15.2","mime-types": "^2.1.35"}},@@ -25686,6 +25703,15 @@"@types/range-parser": "*"}},+ "@types/follow-redirects": {+ "version": "1.14.1",+ "resolved": "https://registry.npmjs.org/@types/follow-redirects/-/follow-redirects-1.14.1.tgz",+ "integrity": "sha512-THBEFwqsLuU/K62B5JRwab9NW97cFmL4Iy34NTMX0bMycQVzq2q7PKOkhfivIwxdpa/J72RppgC42vCHfwKJ0Q==",+ "dev": true,+ "requires": {+ "@types/node": "*"+ }+ },"@types/graceful-fs": {"version": "4.1.5","peer": true,@@ -25762,7 +25788,9 @@"dev": true},"@types/node": {- "version": "18.13.0"+ "version": "18.14.0",+ "resolved": "https://registry.npmjs.org/@types/node/-/node-18.14.0.tgz",+ "integrity": "sha512-5EWrvLmglK+imbCJY0+INViFWUHg1AHel1sq4ZVSfdcNqGy9Edv3UB9IIzzg+xPaUcAgZYcfVs2fBcwDeZzU0A=="},"@types/normalize-package-data": {"version": "2.4.1",@@ -29022,7 +29050,9 @@}},"follow-redirects": {- "version": "1.15.1"+ "version": "1.15.2",+ "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.2.tgz",+ "integrity": "sha512-VQLG33o04KaQ8uYi2tVNbdrWp1QWxNNea+nmIB4EVM28v0hmP17z7aG1+wAkNzVq4KeXTq3221ye5qTJP91JwA=="},"fork-ts-checker-webpack-plugin": {"version": "6.5.2",diff --git a/packages/2d/src/components/Image.ts b/packages/2d/src/components/Image.tsindex e0f52775..5de7b9f2 100644--- a/packages/2d/src/components/Image.ts+++ b/packages/2d/src/components/Image.ts@@ -14,6 +14,7 @@ import {SignalValue,SimpleSignal,} from '@motion-canvas/core/lib/signals';+import {viaProxy} from '@motion-canvas/core/lib/utils';export interface ImageProps extends RectProps {src?: SignalValue<string>;@@ -54,12 +55,13 @@ export class Image extends Rect {@computed()protected image(): HTMLImageElement {- const src = this.src();+ const src = viaProxy(this.src());if (Image.pool[src]) {return Image.pool[src];}const image = document.createElement('img');+ image.crossOrigin = 'anonymous';image.src = src;if (!image.complete) {DependencyContext.collectPromise(diff --git a/packages/core/src/utils/index.ts b/packages/core/src/utils/index.tsindex 3ae44ec1..c016688a 100644--- a/packages/core/src/utils/index.ts+++ b/packages/core/src/utils/index.ts@@ -19,3 +19,4 @@ export * from './useThread';export * from './useTime';export * from './useContext';export * from './useDuration';+export * from './proxyUtils';diff --git a/packages/core/src/utils/proxyUtils.test.ts b/packages/core/src/utils/proxyUtils.test.tsnew file mode 100644index 00000000..e7257fb9--- /dev/null+++ b/packages/core/src/utils/proxyUtils.test.ts@@ -0,0 +1,104 @@+import {beforeEach, describe, expect, it, vi} from 'vitest';+import {isProxyEnabled, viaProxy} from './proxyUtils';+const windowMock = {+ location: {+ toString: () => 'https://mockhostname:1234',+ },+};++function proxy(str: string) {+ return '/cors-proxy/' + encodeURIComponent(str);+}++describe('proxyUtils', () => {+ describe('isProxyEnabled()', () => {+ it('should default to false without import.meta set', () => {+ import.meta.env['VITE_MC_PROXY_ENABLED'] = undefined;+ expect(isProxyEnabled()).toStrictEqual(false);+ }),+ it("should return true if 'true' is set for VITE_MC_PROXY_ENABLED", () => {+ import.meta.env['VITE_MC_PROXY_ENABLED'] = 'true';+ expect(isProxyEnabled()).toStrictEqual(true);+ }),+ it("should return false if 'false' is set for VITE_MC_PROXY_ENABLED", () => {+ import.meta.env['VITE_MC_PROXY_ENABLED'] = 'false';+ expect(isProxyEnabled()).toStrictEqual(false);+ });+ });++ describe('viaProxy()', () => {+ it('should not Proxy if VITE_MC_PROXY_ENABLED is not set', () => {+ import.meta.env['VITE_MC_PROXY_ENABLED'] = undefined;+ const input = 'https://via.placeholder.com/300.png/09f/fff';+ expect(viaProxy(input)).toStrictEqual(input);+ }),+ it("should not Proxy if VITE_MC_PROXY_ENABLED is set to 'false'", () => {+ import.meta.env['VITE_MC_PROXY_ENABLED'] = 'false';+ const input = 'https://via.placeholder.com/300.png/09f/fff';+ expect(viaProxy(input)).toStrictEqual(input);+ }),+ describe('VITE_MC_PROXY_ENABLED is enabled', () => {+ beforeEach(() => {+ import.meta.env.VITE_MC_PROXY_ENABLED = 'true';+ import.meta.env.VITE_MC_PROXY_ALLOW_LIST = undefined;+ vi.stubGlobal('window', windowMock);+ });+ const input = 'https://via.placeholder.com/300.png/09f/fff';+ const proxiedInput = proxy(input);++ it('should proxy if VITE_MC_PROXY_ALLOW_LIST is not set', () => {+ delete import.meta.env['VITE_MC_PROXY_ALLOW_LIST'];+ expect(viaProxy(input)).toStrictEqual(proxiedInput);+ });+ it('should not proxy if the host is not in the allow list', () => {+ import.meta.env['VITE_MC_PROXY_ALLOW_LIST'] = JSON.stringify([+ 'google.com',+ ]);+ const x = viaProxy(input);+ expect(x).toStrictEqual(input);+ });+ it('should proxy if VITE_MC_PROXY_ALLOW_LIST is an empty list', () => {+ import.meta.env['VITE_MC_PROXY_ALLOW_LIST'] = JSON.stringify([]);+ expect(viaProxy(input)).toStrictEqual(proxiedInput);+ });+ it('should proxy if the host is on the allow list', () => {+ (import.meta.env['VITE_MC_PROXY_ALLOW_LIST'] = JSON.stringify([+ 'via.placeholder.com',+ ])),+ expect(viaProxy(input)).toStrictEqual(proxiedInput);+ });+ it('should not proxy if the host is the same as the server', () => {+ import.meta.env['VITE_MC_PROXY_ALLOW_LIST'] = JSON.stringify([]);+ const input = windowMock.location.toString() + '/some/example.png';+ expect(viaProxy(input)).toStrictEqual(input);+ });+ }),+ describe('Protocols', () => {+ beforeEach(() => {+ import.meta.env.VITE_MC_PROXY_ENABLED = 'true';+ import.meta.env.VITE_MC_PROXY_ALLOW_LIST = JSON.stringify([]);+ vi.stubGlobal('window', windowMock);+ });++ it('should proxy if the request protocol is http and https', () => {+ const suffix = '://via.placeholder.com/300.png/09f/fff';+ const httpReq = 'http' + suffix;+ const httpsReq = 'https' + suffix;++ expect(viaProxy(httpReq)).toStrictEqual(proxy(httpReq));+ expect(viaProxy(httpsReq)).toStrictEqual(proxy(httpsReq));+ });+ it('should not proxy other protocols like data:', () => {+ const dataBlob =+ 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQIW2PYOO36fwAHOAMeASY22QAAAABJRU5ErkJggg==';+ expect(viaProxy(dataBlob)).toStrictEqual(dataBlob);+ });+ }),+ it('should not rewrite an already proxied request', () => {+ const raw = 'https://via.placeholder.com/300.png/09f/fff';++ expect(viaProxy(raw)).not.toStrictEqual(raw);+ expect(viaProxy(viaProxy(raw))).toStrictEqual(viaProxy(raw));+ });+ });+});diff --git a/packages/core/src/utils/proxyUtils.ts b/packages/core/src/utils/proxyUtils.tsnew file mode 100644index 00000000..35239de2--- /dev/null+++ b/packages/core/src/utils/proxyUtils.ts@@ -0,0 +1,149 @@+/**+ * Utility to redirect remote sources via Proxy+ *+ * This utility is used to rewrite a request to be routed through+ * the Proxy instead.+ */++import {useLogger} from './useProject';++/**+ * Route the given url through a local proxy.+ *+ * @example+ * This rewrites a remote url like `https://via.placeholder.com/300.png/09f/fff`+ * into a URI-Component-Encoded string like+ * `/cors-proxy/https%3A%2F%2Fvia.placeholder.com%2F300.png%2F09f%2Ffff`+ */+export function viaProxy(url: string) {+ if (!isProxyEnabled()) {+ // Proxy is disabled, so we just pass as-is.+ return url;+ }++ if (url.startsWith('/cors-proxy/')) {+ // Already proxied, return as-is+ return url;+ }++ // window.location.hostname is being passed here to ensure that+ // this does not throw an Error for same-origin requests+ // e.g. /some/image -> localhost:9000/some/image+ const selfUrl = new URL(window.location.toString());+ // inside a try-catch in case the URL cannot be understood+ try {+ const expandedUrl = new URL(url, selfUrl);+ if (!expandedUrl.protocol.startsWith('http')) {+ // this is probably some embedded image (e.g. image/png;base64).+ // don't touch and pass as is+ return url;+ }+ if (selfUrl.host === expandedUrl.host) {+ // This is a request to a "local" resource.+ // No need to rewrite+ return url;+ }++ // Check if the host matches the Allow List.+ // if not, no rewrite takes place.+ // will fail in the Editor if the+ // remote host does not accept anonymous+ if (!isInsideAllowList(expandedUrl.host)) {+ return url;+ }+ } catch (_) {+ // in case of error just silently pass as-is+ return url;+ }++ // Everything else is a "remote" resource and requires a rewrite.+ return `/cors-proxy/${encodeURIComponent(url)}`;+}++/**+ * Check the provided host is allowed to be routed+ * to the Proxy.+ */+function isInsideAllowList(host: string) {+ const allowList = getAllowList();+ if (allowList.length === 0) {+ // Allow List defaults to allow all if empty+ return true;+ }+ for (const entry of allowList) {+ if (entry.toLowerCase().trim() === host) {+ return true;+ }+ }+ return false;+}++/**+ * Check if the proxy is enabled via the plugin by checking+ * for `import.meta.env.VITE_MC_PROXY_ENABLED`+ *+ * @remarks The value can either be 'true' of 'false'+ * (as strings) if present, or be undefined if not run+ * from a vite context or run without the MC Plugin.+ */+export function isProxyEnabled() {+ if (import.meta.env) {+ return import.meta.env.VITE_MC_PROXY_ENABLED === 'true';+ }+ return false;+}++/**+ * Cached value so getAllowList does not+ * try to parse the Env var on every call,+ * spamming the console in the process+ */+let getAllowListCache: string[] | undefined = undefined;+/**+ * Return the list of allowed hosts+ * from the Plugin Config+ */+function getAllowList() {+ // Condition should get optimized away for Prod+ if (import.meta.env.VITEST !== 'true') {+ if (getAllowListCache) {+ return [...getAllowListCache];+ }+ }++ // Inline function gets immediately invoked+ // and the result stored in getAllowListCache.+ // The cached value is used on subsequent requests.+ const result = (function () {+ if (!isProxyEnabled() || !import.meta.env) {+ return [];+ }++ // This value is encoded as a JSON String.+ const valueJson = import.meta.env.VITE_MC_PROXY_ALLOW_LIST ?? '[]';+ const parsedJson = JSON.parse(valueJson);+ // Do an additional check that only strings are present,+ // create a warning and ignore the value+ if (!Array.isArray(parsedJson)) {+ useLogger().error(+ 'Parsed Allow List expected to be an Array, but is ' ++ typeof parsedJson,+ );+ }+ const validatedEntries = [];+ for (const entry of parsedJson) {+ if (typeof entry !== 'string') {+ useLogger().warn(+ 'Unexpected Value in Allow List: ' ++ entry ++ '. Expected a String. Skipping.',+ );+ continue;+ }+ validatedEntries.push(entry);+ }+ return validatedEntries;+ })();+ getAllowListCache = result;+ return [...getAllowListCache];+}diff --git a/packages/vite-plugin/package.json b/packages/vite-plugin/package.jsonindex 2c327d48..200e9375 100644--- a/packages/vite-plugin/package.json+++ b/packages/vite-plugin/package.json@@ -23,9 +23,12 @@},"devDependencies": {"@motion-canvas/internal": "0.0.0",- "@types/mime-types": "^2.1.1"+ "@types/follow-redirects": "^1.14.1",+ "@types/mime-types": "^2.1.1",+ "@types/node": "^18.14.0"},"dependencies": {+ "follow-redirects": "^1.15.2","mime-types": "^2.1.35"}}diff --git a/packages/vite-plugin/src/main.ts b/packages/vite-plugin/src/main.tsindex c0170d78..723fdc86 100644--- a/packages/vite-plugin/src/main.ts+++ b/packages/vite-plugin/src/main.ts@@ -4,6 +4,11 @@ import fs from 'fs';import {Readable} from 'stream';import mime from 'mime-types';import projectInstance from './__logs__/project-instance.md';+import {+ motionCanvasCorsProxy,+ MotionCanvasCorsProxyOptions,+ setupEnvVarsForProxy,+} from './proxy-middleware';export interface MotionCanvasPluginConfig {/**@@ -67,6 +72,16 @@ export interface MotionCanvasPluginConfig {* @default '\@motion-canvas/ui'*/editor?: string;+ /**+ * Configuration of the Proxy used for remote sources+ *+ * @remarks+ * This passes configuration to Motion Canvas' proxy.+ * Note that the proxy is disabled by default.+ * You can either pass `true` and a config object+ * to enable it.+ **/+ proxy?: boolean | MotionCanvasCorsProxyOptions;}interface ProjectData {@@ -79,6 +94,7 @@ export default ({output = './output',bufferedAssets = /\.(wav|ogg)$/,editor = '@motion-canvas/ui',+ proxy,}: MotionCanvasPluginConfig = {}): Plugin => {const editorPath = path.dirname(require.resolve(editor));const editorFile = fs.readFileSync(path.resolve(editorPath, 'editor.html'));@@ -89,6 +105,7 @@ export default ({const createHtml = (src: string) => htmlParts[0] + src + htmlParts[1];const resolvedEditorId = '\0virtual:editor';+const timeStamps: Record<string, number> = {};const outputPath = path.resolve(output);const projects: ProjectData[] = [];@@ -116,6 +133,9 @@ export default ({}}+ // Initialize the Proxy Module+ setupEnvVarsForProxy(proxy);+return {name: 'motion-canvas',async configResolved(resolvedConfig) {@@ -314,6 +334,14 @@ export default ({next();});++ // if proxy is unset (undefined), or set to false,+ // it will not register its middleware — as a result, no+ // proxy is started.+ if (proxy !== false && proxy !== undefined) {+ motionCanvasCorsProxy(server.middlewares, proxy === true ? {} : proxy);+ }+server.ws.on('motion-canvas:meta', async ({source, data}, client) => {timeStamps[source] = Date.now();await fs.promises.writeFile(diff --git a/packages/vite-plugin/src/proxy-middleware.ts b/packages/vite-plugin/src/proxy-middleware.tsnew file mode 100644index 00000000..d51dd6ae--- /dev/null+++ b/packages/vite-plugin/src/proxy-middleware.ts@@ -0,0 +1,291 @@+/**+ * This module provides the proxy located at+ * /cors-proxy/...+ *+ * It is needed when accessing remote resources.+ * Trying to access remote resources works while+ * in preview, but will fail when you try to+ * output the image (= "read" the canvas)+ *+ * See https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image+ * for reasons+ *+ * Using the proxy circumvents CORS-issues because+ * this way all remote resources are served from the+ * same host as the main app.+ */++import {Connect} from 'vite';+import {ServerResponse, IncomingMessage} from 'http';+import {http, https} from 'follow-redirects';++/**+ * Configuration used by the Proxy plugin+ */+export interface MotionCanvasCorsProxyOptions {+ /**+ * Set which types of resources are allowed by default.+ *+ * @remarks+ * Catchall on the right side is supported.+ * Pass an empty Array to allow all types of resources, although this is not+ * recommended.+ *+ * @default ["image/*", "video/*"]+ */+ allowedMimeTypes?: string[];+ /**+ * Set which hosts are allowed+ *+ * @remarks+ * Note that the host is everything to the left of the first `/`, and to the+ * right of the protocol `https://`. AllowList is not used by default,+ * although you should consider setting up just the relevant hosts.+ */+ allowListHosts?: string[];+}++export function setupEnvVarsForProxy(+ config: MotionCanvasCorsProxyOptions | undefined | boolean,+) {+ // Define Keys for Env Var+ const prefix = 'VITE_MC_PROXY_';+ const isEnabledKey = prefix + 'ENABLED';+ const allowList = prefix + 'ALLOW_LIST';++ if (config === true) {+ config = {}; // Use Default values+ }++ process.env[isEnabledKey] = String(!!config); // 'true' or 'false'++ if (config) {+ // These values are only configured if the Proxy is enabled+ // You cannot access them via import.meta.env if the Proxy+ // is set to false+ process.env[allowList] = JSON.stringify(config.allowListHosts ?? []);+ }+}++export function motionCanvasCorsProxy(+ middleware: Connect.Server,+ config: MotionCanvasCorsProxyOptions,+) {+ // Set the default config if no config was provided+ config.allowedMimeTypes ??= ['image/*', 'video/*'];+ config.allowListHosts ??= [];++ // Check the Mime Types to have a correct structure (left/right)+ // not having them in the correct format would crash the Middleware+ // further down below+ if ((config.allowedMimeTypes ?? []).some(e => e.split('/').length !== 2)) {+ throw new Error(+ "Invalid config for Proxy:\nAll Entries must have the following format:\n 'left/right' where left may be '*'",+ );+ }++ middleware.use((req, res, next) => {+ if (!req.url || !req.url.startsWith('/cors-proxy/')) {+ // url does not start with /cors-proxy/, so this+ // middleware does not care about it+ return next();+ }++ // For now, only allow GET Requests+ if (req.method !== 'GET') {+ return writeError('Only GET Requests are allowed', res, 405);+ }++ let sourceUrl: URL;+ try {+ sourceUrl = extractDestination(req.url);+ } catch (err) {+ return writeError(err as any, res);+ }++ if (+ !isReceivedUrlInAllowedHosts(sourceUrl.hostname, config.allowListHosts)+ ) {+ return writeError(+ `Blocked by Proxy: ${sourceUrl.hostname} is not on Hosts Allowlist`,+ res,+ );+ }++ // Get the resource, do some checks. Throws an Error+ // if the checks fail. The catch then writes an Error+ return tryGetResource(res, sourceUrl, config).catch(error => {+ writeError(error, res);+ });+ });+}++/**+ * Unwrap the destination from the URL.+ *+ * @remarks+ * Throws an Error if the value could not be unwrapped.+ *+ * @param url - the entire URL with the `/cors-proxy/` prefix and containing the+ * url-Encoded Path.+ *+ * @returns The URL that needs to be called.+ */+function extractDestination(url: string): URL {+ const withoutPrefix = url.replace('/cors-proxy/', '');+ const asUrl = new URL(decodeURIComponent(withoutPrefix));+ if (asUrl.protocol !== 'http:' && asUrl.protocol !== 'https:') {+ throw new Error('Only supported protocols are http and https');+ }+ return asUrl;+}++/**+ * A simple Error Helper that will write an Error and close the response.+ */+function writeError(+ message: string,+ res: ServerResponse<IncomingMessage>,+ statusCode = 400,+) {+ res.writeHead(statusCode, message);+ res.end();+}++/**+ * Check if the Proxy is allowed to get the requested resource based on the+ * host.+ */+function isReceivedUrlInAllowedHosts(+ hostname: string,+ allowListHosts: string[] | undefined,+) {+ if (!allowListHosts || allowListHosts.length == 0) {+ // if the allowListHosts is just the predefinedAllowlist, the user has not+ // set any additional hosts. In this case, allow any hostname+ return true;+ }+ // Check if the hostname is any of the values set in allowListHosts+ return allowListHosts.some(+ e => e.toLowerCase().trim() === hostname.toLowerCase().trim(),+ );+}++/**+ * Check if the Proxy is allowed to get the requested resource based on the+ * MIME-Type.+ *+ * @remarks+ * Also handles catch-All Declarations like `image/*`.+ */+function isResultOfAllowedResourceType(+ foundMimeType: string,+ allowedMimeTypes: string[],+) {+ if (!allowedMimeTypes || allowedMimeTypes.length === 0) {+ return true; // no filters set+ }++ if (foundMimeType.split('/').length !== 2) {+ return false; // invalid mime structure+ }++ const [leftSegment, rightSegment] = foundMimeType+ .split('/')+ .map(e => e.trim().toLowerCase());++ // Get all Segments where the left Part is identical between foundMimeType and+ // allowedMimeType.+ const leftSegmentMatches = allowedMimeTypes.filter(+ e => e.trim().toLowerCase().split('/')[0] === leftSegment,+ );+ if (leftSegmentMatches.length === 0) {+ // No matches at all, not even catchall - resource is rejected.+ return false;+ }++ // This just gets the right part of the MIME Types from the+ // configured allowList, e.g. "image/png" -> png+ const rightSegmentOfLeftSegmentMatches = leftSegmentMatches.map(+ e => e.split('/')[1],+ );++ // if an exact match or a catchall is found, the resource is allowed to be+ // proxied.+ return rightSegmentOfLeftSegmentMatches.some(+ e => e === '*' || e === rightSegment,+ );+}++/**+ * Requests a remote resource with the help of axios+ * May throw a string in case of a bad mime-type or missing headers+ */+async function tryGetResource(+ res: ServerResponse<IncomingMessage>,+ sourceUrl: URL,+ config: MotionCanvasCorsProxyOptions,+): Promise<void> {+ // Turn this callback into a Promise to avoid additional nesting+ const result: IncomingMessage = await new Promise((res, rej) => {+ try {+ // We check what protocol was used and decide if we use http or https+ const request = (+ sourceUrl.protocol.startsWith('https') ? https : http+ ).get(sourceUrl, data => {+ res(data);+ });+ request.on('error', (err: any) => {+ if (err.code && err.code == 'ENOTFOUND') {+ // This is a bit hacky, but this basically returns as a+ // 404 instead of crashing the Node Server with ENOTFOUND+ res({statusCode: 404} as any);+ } else {+ rej(err);+ }+ });+ } catch (err) {+ rej(err);+ }+ });++ if (!result.statusCode || result.statusCode >= 300) {+ throw 'Unexpected Status: ' + result.statusCode ?? 'NO_STATUS';+ }++ const contentType = result.headers['content-type'];+ const contentLength = result.headers['content-length'];++ if (!contentType) {+ throw 'Proxied Response does not contain a Content Type';+ }+ if (!contentLength) {+ throw 'Proxied Response does not contain a Content Length';+ }++ if (+ !isResultOfAllowedResourceType(+ contentType.toString(),+ config.allowedMimeTypes ?? [],+ )+ ) {+ throw 'Proxied response has blocked content-type: ' + contentType;+ }++ // Prepare Response+ for (const key in result.headers) {+ const header = result.headers[key];+ if (header === undefined) {+ console.warn('Proxy: Received Header is empty. Skipping…');+ continue;+ }+ res.setHeader(key, header);+ }+ res.addListener('error', () => {+ console.log('Proxy: Connection Reset');+ });+ res.setHeader('x-proxy-destination', sourceUrl.toString());+ // Don't store on the server, just immediately pass on the+ // received chunks+ result.pipe(res);+}