Skip to content

Commit 57edf5c

Browse files
feat: validate origins based on hostnames
close #223
1 parent e650dad commit 57edf5c

1 file changed

Lines changed: 16 additions & 1 deletion

File tree

src/events/event.ts

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,9 @@ function on<T extends EventType>(
1515
} = {},
1616
) {
1717
const { eventOptions, allowedOrigins = [] } = options;
18+
const allowedHostnames = new Set(
19+
allowedOrigins.map(getHostName).filter(Boolean),
20+
);
1821

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

30-
if (!skipOriginCheck && !allowedOrigins.includes(url.origin)) {
33+
if (!skipOriginCheck && !allowedHostnames.has(getHostName(url.origin))) {
3134
throw new Error(`Invalid Origin ${origin}`);
3235
}
3336

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

46+
function getHostName(origin: string) {
47+
try {
48+
const { hostname } = new URL(origin);
49+
return hostname;
50+
} catch (error) {
51+
// eslint-disable-next-line no-console
52+
console.log(error);
53+
// return null If the URL is invalid
54+
return null;
55+
}
56+
}
57+
4358
export default { trigger, on };

0 commit comments

Comments
 (0)