Skip to content

Commit

Permalink
Merge pull request #224 from NFDI4Chem/orgins-validation
Browse files Browse the repository at this point in the history
feat: validate origins based on hostnames
  • Loading branch information
CS76 authored Aug 14, 2024
2 parents e650dad + 5d32319 commit 2767263
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
2 changes: 1 addition & 1 deletion src/allowed-origins.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
"https://chemotion-t-02.zdv.uni-mainz.de",
"https://pregl.ac.rwth-aachen.de",
"https://schindler-ag.rwth-aachen.de",
"10.195.9.248",
"http://10.195.9.248",
"https://dev1.zit.ph.tum.de",
"https://org2619.chemie.uni-leipzig.de",
"https://chemotion.ac.chemie.intern.uni-leipzig.de",
Expand Down
17 changes: 16 additions & 1 deletion src/events/event.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ function on<T extends EventType>(
} = {},
) {
const { eventOptions, allowedOrigins = [] } = options;
const allowedHostnames = new Set(
allowedOrigins.map(getHostName).filter(Boolean),
);

function listener(event: MessageEvent) {
const {
Expand All @@ -27,7 +30,7 @@ function on<T extends EventType>(
const skipOriginCheck =
allowedOrigins.length === 0 || allowedOrigins.includes('*');

if (!skipOriginCheck && !allowedOrigins.includes(url.origin)) {
if (!skipOriginCheck && !allowedHostnames.has(getHostName(url.origin))) {
throw new Error(`Invalid Origin ${origin}`);
}

Expand All @@ -40,4 +43,16 @@ function on<T extends EventType>(
return () => window.removeEventListener(`message`, listener);
}

function getHostName(origin: string) {
try {
const { hostname } = new URL(origin);
return hostname;
} catch (error) {
// eslint-disable-next-line no-console
console.log(error);
// return null If the URL is invalid
return null;
}
}

export default { trigger, on };

0 comments on commit 2767263

Please sign in to comment.