| 1 | // check if a link can be displayed in an iframe |
| 2 | export const isIframeable = async ({ |
| 3 | url, |
| 4 | requestDomain, |
| 5 | }: { |
| 6 | url: string; |
| 7 | requestDomain: string; |
| 8 | }) => { |
| 9 | const res = await fetch(url); |
| 10 | |
| 11 | const cspHeader = res.headers.get("content-security-policy"); |
| 12 | if (cspHeader) { |
| 13 | const frameAncestorsMatch = cspHeader.match( |
| 14 | /frame-ancestors\s+([\s\S]+?)(?=;|$)/i, |
| 15 | ); |
| 16 | if (frameAncestorsMatch) { |
| 17 | if (frameAncestorsMatch[1] === "*") { |
| 18 | return true; |
| 19 | } |
| 20 | const allowedOrigins = frameAncestorsMatch[1].split(/\s+/); |
| 21 | if (allowedOrigins.includes(requestDomain)) { |
| 22 | return true; |
| 23 | } |
| 24 | } |
| 25 | } |
| 26 | |
| 27 | const xFrameOptions = res.headers.get("X-Frame-Options"); |
| 28 | if (xFrameOptions === "DENY" || xFrameOptions === "SAMEORIGIN") { |
| 29 | return false; |
| 30 | } |
| 31 | |
| 32 | return true; |
| 33 | }; |