Stuck with Cloudflare workers bulk origin proxy please - cdn

I need some help with Cloudflare workers. I'm not a dev by any stretch of the imagination and use Webflow so no code, but I've got a Webflow project where I need to squeeze every ounce of speed out of the site and I'm trying it on my domain first.
I've got a Pro Cloudflare account set up for the project, but my problem is that Webflow keeps all the assets like css, fonts and most importantly images on assets.website-files.com (their CDN) and not my actual domain, so Cloudflare is not caching or applying any performance enhancements on the images, etc... as assets.website-files.com is not part of my domain as you can see from the screenshot:
Dr.Falre
I contacted Cloudflare and they sent me this Cloudflare Workers script, but like I said, no code experience here, so would anyone here be able to help me out with this script from Cloudflare:
/**
* An object with different URLs to fetch
* #param {Object} ORIGINS
*/
const ORIGINS = {
"starwarsapi.yourdomain.com": "swapi.dev",
"google.yourdomain.com": "www.google.com",
}
async function handleRequest(request) {
const url = new URL(request.url)
// Check if incoming hostname is a key in the ORIGINS object
if (url.hostname in ORIGINS) {
const target = ORIGINS[url.hostname]
url.hostname = target
// If it is, proxy request to that third party origin
return await fetch(url.toString(), request)
}
// Otherwise, process request as normal
return await fetch(request)
}
addEventListener("fetch", event => {
event.respondWith(handleRequest(event.request))
})
Any help would be much appreciated.

Related

Confirmation of why cross-origin problems occur when using signInWithRedirect are resolved

I know that the signInWithRedirect() flow in Firebase does not behave correctly in some browsers because it uses cross-origin.
https://github.com/firebase/firebase-js-sdk/issues/6716
When using signInWithRedirect(), the following article is a best practice.
https://firebase.google.com/docs/auth/web/redirect-best-practices
I have an app created in Next.js with authentication using signInWithRedirect() and deployed it to Vercel.
If I do nothing, it will not work in Safari as described in the above issue.
So I took the following 3 actions and confirmed that it works correctly.
Reverse proxy settings(next.config.js)
/** #type {import('next').NextConfig} */
module.exports = {
reactStrictMode: true,
async rewrites() {
return [
{
source: '/__/auth/:path*',
destination: `https://${process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN}/__/auth/:path*`,
},
]
},
}
Changed authDomain when initializing FirebaseApp to the app's domain
In GCP, change approved redirect URI to https://<the-domain-that-serves-my-app>/__/auth/handler.
These are the third method in Best practices.
I do not fully understand why this setup solves the problem, and I would like to correct my understanding.
My understanding is as follows
authDomain = a.com (domain of the app)
An authentication request is generated from the browser and redirected to authDomain (a.com)
The request is forwarded to https://<project>.firebaseapp.com/__/auth/ because a reverse proxy is set up
Host the login helper code to the identity provider at <project>.firebaseapp.com.
Return to a.com
Access login helper storage from browser
Authenticated redirect URI is set to the app domain, so the information is stored in the browser's storage in the app domain. And since the authDomain is the same as the app's, the authentication iFrame is referenced to it.
Is this understanding correct?

CORS issue when calling API via Office Scripts Fetch

I am trying to make an API call via Office Scripts (fetch) to a publicly available Azure Function-based API I created. By policy we need to have CORS on for our Azure Functions. I've tried every domain I could think of, but I can't get the call to work unless I allow all origins. I've tried:
https://ourcompanydoamin.sharepoint.com
https://usc-excel.officeapps.live.com
https://browser.pipe.aria.microsoft.com
https://browser.events.data.microsoft.com
The first is the Excel Online domain I'm trying to execute from, and the rest came up during the script run in Chrome's Network tab. The error message in office Scripts doesn't tell me the domain the request is coming from like it does from Chrome's console. What host do I need to allow for Office Scripts to be able to make calls to my API?
The expected CORS settings for this is: https://*.officescripts.microsoftusercontent.com.
However, Azure Functions CORS doesn't support wildcard subdomains at the moment. If you try to set an origin with wildcard subdomains, you will get the following error:
One possible workaround is to explicitly maintain an "allow-list" in your Azure Functions code. Here is a proof-of-concept implementation (assuming you use node.js for your Azure Functions):
module.exports = async function (context, req) {
// List your allowed hosts here. Escape special characters for the regular expressions.
const allowedHosts = [
/https\:\/\/www\.myserver\.com/,
/https\:\/\/[^\.]+\.officescripts\.microsoftusercontent\.com/
];
if (!allowedHosts.some(host => host.test(req.headers.origin))) {
context.res = {
status: 403, /* Forbidden */
body: "Not allowed!"
};
return;
}
// Handle the normal request and generate the expected response.
context.res = {
status: 200,
body: "Allowed!"
};
}
Please note:
Regular expressions are needed to match the dynamic subdomains.
In order to do the origin check within the code, you'll need to set * as the Allowed Origins on your Functions CORS settings page.
Or if you want to build you service with ASP.NET Core, you can do something like this: https://stackoverflow.com/a/49943569/6656547.

Getting storage item without CORS configured

I fetched an item from my Firebase storage bucket via this technique (generally):
const url = await firebase.storage().ref('my/ref').getDownloadURL();
const filename = 'filename.ext';
const a = document.getElementById('link');
a.href = url;
a.download = filename;
a.click();
I did it the above way prior to trying the example from the docs:
storageRef.child('images/stars.jpg').getDownloadURL().then(function(url) {
// `url` is the download URL for 'images/stars.jpg'
// This can be downloaded directly:
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function(event) {
var blob = xhr.response;
};
xhr.open('GET', url);
xhr.send();
});
When trying it this way, I hit the CORS error. After adding the CORS config to my bucket, it then worked as expected. However, I cannot determine why I was able to successfully fetch it via the first technique prior to configuring CORS.
I tested it again by removing the GET method from my CORS config and uploading the config file again via gsutil. I was still able to successfully obtain the file via the first technique described above.
If this is possible to do without configuring CORS, how can I prevent it to restrict access? Odds are no one will be able to figure out the required ref to build the link, anyways, because the actual ref has multiple unique IDs that will be all but impossible to figure out. This is mainly a question out of curiosity.
I cannot determine why I was able to successfully fetch it via the first technique prior to configuring CORS.
Because same-origin policy doesn't apply when the Javascript can't access the data. In your first example, the JS tweaks the document and the document accesses the data. In the second example, the JS accesses the cross-origin data, and the absence of CORS prevents such access.
If this is possible to do without configuring CORS, how can I prevent it to restrict access?
CORS isn't designed to restrict access. (Wait, what?) CORS is designed to permit access that would otherwise be assumed to be something the user would not want -- for scripts on one page to have access to data from another origin, including, potentially, handing over use of the user's credentials to scripts on the current page when accessing the foreign site. CORS allows site B to tell the browser that it expects to be contacted by scripts from site A, and therefore such access should not be unexpected or assumed unauthorized. It has no impact on requests that don't fall under the same origin policy.
The solution -- and I apologize if I am stating the patently obvious -- is that getDownloadUrl() should not be able to fetch a usable URL for the object, if the object should not in fact be accessible. You can't trust code running on the browser, so whatever credentials are in play here should not be able to be used in this way, if the object is not intended to be accessible... otherwise you have a misconfiguration that is allowing access that should not be allowed.

Service worker caches files but doesn't load offline

This is my first time experimenting with service workers, and I'm sure I'm doing something stupid.
I have a service worker set up for a WordPress theme I'm working on. It's located at /public_html/wp-content/themes/framework/assets/scripts/service-worker.js.
I have set the header Servie-Worker-Allowed: "/" via the .htaccess file.
I'm using sw-toolbox to make things easier. My script is below.
Script:
toolbox.precache(["/", "../media/logo.svg", "../media/spritesheet.svg", "../scripts/modern.js", "../styles/modern.css"]);
toolbox.router.get("../media/*", toolbox.cacheFirst);
toolbox.router.get("/wp-content/uploads/*", toolbox.cacheFirst);
toolbox.router.get("/*", toolbox.networkFirst, {NetworkTimeoutSeconds: 5});
The service worker properly registers, and no errors are thrown. All files set to precache show up under Cache > Cache Storage in Chrome's developer tools correctly. For some reason these cached files aren't being served when offline.
I know there's issues with the scope of the service worker, but the Service-Worker-Allowed header should correct for that. Given that the files do in fact show up in cache without issue, I'd think that this is all working correctly.
What am I missing?
Note: I'd like to keep service-worker.js and the files I'm caching where they are and with relative paths; it becomes problematic moving them to the root or giving them absolute paths because this WordPress theme gets re-used on builds and has its name changed every time, making absolute paths a pain. I tested out rewriting to the root with .htaccess, which did work, but had it's own issues. I don't understand why that would work but what I'm currently trying wouldn't.
I think I was going about this wrong. There doesn't appear to be a need to manually specify to cache my theme assets as long as I've enabled caching in general. To that end, I've instead set up a rewrite rule so that service-worker.js lives at the root (i.e. https://www.example.com/service-worker.js), thus giving it correct scope. This has enabled my project to work offline. Code for this is below.
((global) => {
// disable the service worker for post previews
global.addEventListener("fetch", (event) => {
if (event.request.url.match(/preview=true/)) {
return;
}
});
// ensure the service worker takes over as soon as possible
global.addEventListener("install", event => event.waitUntil(global.skipWaiting()));
global.addEventListener("activate", event => event.waitUntil(global.clients.claim()));
// set up the cache
global.toolbox.precache(["/", "/offline/"]);
global.toolbox.router.get("/wp-content/uploads/*", toolbox.cacheFirst);
global.toolbox.router.get("/*", toolbox.networkFirst, {NetworkTimeoutSeconds: 5});
// redirect offline queries to offline page
self.toolbox.router.get("/(.*)", function (req, vals, opts) {
return toolbox.networkFirst(req, vals, opts).catch((error) => {
if (req.method === "GET" && req.headers.get("accept").includes("text/html")) {
return toolbox.cacheOnly(new Request("/offline/"), vals, opts);
}
throw error;
});
});
})(self);

Detecting a redirect in Flash/Actionscript?

I have a flash video player which requests a flv file from a central server. That server might redirect the request to a server from the user's country if possible, a lot like a CDN.
This video player also reports usage stats. One thing I'd like to report is the true server/location from which the player is streaming the video from. So basically, if it gets redirected I want to know about it.
It seems that you can't extract the url from a URLLoader, you can only keep a copy of the URLRequest that you constructed it with.
I notice that you can listen for HTTP status events, which would include a 302 or similar. But unfortunately, the HTTPStatusEvent object doesn't show the redirected location.
Any ideas about how to monitor for a redirect, and get the redirected location?
I'm a bit surprised Flash allows you to redirect a video request at all. I did a bit of digging and it looks like you can get the info:
Handling Crossdomain.xml and 302 Redirects Using NetStream
His post specifically talks about the trouble of security issues that arise because of the fact some operations fail if data is from an untrusted server. Since he doesn't know where his video is coming from (302 redirect) the Flash Player doesn't trust it and prevents some operations on the loaded content.
How he gets the server the content was actually loaded from is to do an operation on the file that should not be allowed and he parses the domain information from the error message:
try
{
var bit:BitmapData = new BitmapData(progressiveVideoPlayer.measuredWidth, progressiveVideoPlayer.measuredHeight, false, 0x000000);
bit.draw(progressiveVideoPlayer);
}
catch(error:SecurityError)
{
var list:Array = error.toString().split(" ");
var swfURL:String = list[7] as String;
var domain:String = list[10] as String;
domain = domain.substring(0, domain.length - 1);
var domainList:Array = domain.split("/");
var protocol:String = domainList[0] as String;
var address:String = domainList[2];
var policyFileURL:String = protocol + "//" + address + "/crossdomain.xml";
Security.loadPolicyFile(policyFileURL);
}
Notice he is doing it so that he can load the policy file (to allow the security restricted operations on the file). I'm not sure it will be helpful to you but at least read the article and have a think about it. You may contact the blog author directly too - he is pretty active in the general Flash community.

Resources