55 lines
1.3 KiB
TypeScript

// Utilities for postMessage origin validation and ACK helpers
export function getAllowedOriginsFromEnv(): string[] {
const allowed = new Set<string>();
try {
const raw = (import.meta.env.VITE_STUDIO_ALLOWED_ORIGINS as string) || "";
if (raw) {
raw
.split(",")
.map((s) => s.trim())
.filter(Boolean)
.forEach((o) => allowed.add(o));
}
} catch (e) {
/* ignore */
}
try {
const studioUrl = (import.meta.env.VITE_STUDIO_URL as string) || "";
if (studioUrl) {
try {
const u = new URL(studioUrl);
allowed.add(u.origin);
} catch (e) {
/* ignore */
}
}
} catch (e) {
/* ignore */
}
try {
allowed.add(window.location.origin);
} catch (e) {}
return Array.from(allowed);
}
export function isAllowedOrigin(origin: string | null | undefined): boolean {
if (!origin) return false;
const list = getAllowedOriginsFromEnv();
return list.includes(origin);
}
export function safePostMessage(
target: Window | null | undefined,
message: any,
targetOrigin: string,
) {
if (!target) return false;
try {
target.postMessage(message, targetOrigin);
return true;
} catch (e) {
// some window proxies can throw when cross-origin; ignore
return false;
}
}