Skip to content

Instantly share code, notes, and snippets.

@lilianalillyy
Created March 19, 2024 12:52
Show Gist options
  • Save lilianalillyy/5d85c8e3a944ed9b70eb2674c82f410b to your computer and use it in GitHub Desktop.
Save lilianalillyy/5d85c8e3a944ed9b70eb2674c82f410b to your computer and use it in GitHub Desktop.
Cross-origin data
// debugging element to see data
const filesEl = document.createElement("pre");
filesEl.textContent = "waiting for files...";
filesEl.setAttribute("style", "z-index: 9999;background-color: #fff;")
document.body.prepend(filesEl);
const popup = window.open("https://fileserver.com/shared/handshake-files", 'popupWindowName', 'width=200,height=200');
setTimeout(() => {
console.log("fileserver is ready, sending request for files");
window.addEventListener("message", (e) => {
if (e.origin !== "https://fileserver.com") {
console.log("not file server", e.origin);
return;
}
const data = e.data;
if (data.message === "files") {
console.log("got files from fileserver", data.files);
filesEl && (filesEl.textContent = JSON.stringify(data.files, null, 2));
popup.close();
return;
}
});
popup.postMessage("request-files", "https://fileserver.com");
}, 1000); // this would be replaced by check if the fileserver.com loaded
window.addEventListener("message", (e) => {
if (e.origin !== "https://fileclient.com") {
console.log("not file client", e.origin);
return;
}
if (e.data === "request-files") {
console.log("requested files, fetching from api");
fetch("/allowed-files").then(res => res.json()).then(({files}) => {
// send files to file client
e.source.postMessage({ message: "files", files }, e.origin);
});
}
})
/**
* Target: We want allowed files for fileserver.com user session from fileclient.com.
* In our real usecase, instead of allowed files we'd want a SAT (to make auth handshake with Tony).
*
* In this example, we use two domains:
*
* a) fileclient.com
* b) fileserver.com
* - this domain has correct CORS headers to allow popups
* - user has a samesite session cookie for that origin fileclient.com cannot normally access
*
* What do we do:
* 1) fileclient.com creates a popup for an endpoint at fileserver.com which has a script eg. (/shared/handshake-files)
* 2) then fileclient.com posts message "request-files" to fileserver.com
* 3) fileserver.com receives the request message,
* - fetches the allowed files from it's side (as the popup *has* access to cookies)
* - sends back { message: "files", files: array of files[] } to fileclient.com
* 4) fileclient.com happily handles the received files
*
* What to consider in production
* a) fileserver.com should know which origins can access this data
* - Correct CORS headers
* - make the endpoint only work with allowed origins (eg. accessing from google.com would send 404 instead)
*
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment