Skip to content

Commit

Permalink
fix: avoid window.ipfs in non-HTML context
Browse files Browse the repository at this point in the history
Injecting proxy into application/xml produced malformed XML and SVG files.
This adds some sanity-checks and ensures injection happens only in HTML
contexts. It also improves performance by avoiding unnecessary port creation.
  • Loading branch information
lidel committed Jun 14, 2018
1 parent 4c77644 commit 4482b40
Showing 1 changed file with 25 additions and 5 deletions.
30 changes: 25 additions & 5 deletions add-on/src/contentScripts/ipfs-proxy/content.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,12 @@ const injectScript = require('./inject-script')

function init () {
const port = browser.runtime.connect({ name: 'ipfs-proxy' })

// Forward on messages from background to the page and vice versa
port.onMessage.addListener((data) => {
if (data && data.sender && data.sender.startsWith('postmsg-rpc/')) {
window.postMessage(data, '*')
}
})

window.addEventListener('message', (msg) => {
if (msg.data && msg.data.sender && msg.data.sender.startsWith('postmsg-rpc/')) {
port.postMessage(msg.data)
Expand All @@ -24,8 +22,30 @@ function init () {
injectScript(rawCode)
}

// Restricting window.ipfs to Secure Context
// See: https://github.com/ipfs-shipyard/ipfs-companion/issues/476
if (window.isSecureContext) {
function injectIpfsProxy () {
// Skip if proxy is already present
if (window.ipfs) {
return false
}
// Restricting window.ipfs to Secure Context
// See: https://github.com/ipfs-shipyard/ipfs-companion/issues/476
if (!window.isSecureContext) {
return false
}
// Skip if not in HTML context
// Check 1/2
const doctype = window.document.doctype
if (doctype && doctype.name !== 'html') {
return false
}
// Check 2/2
if (document.documentElement.nodeName !== 'HTML') {
return false
}
// Should be ok by now
return true
}

if (injectIpfsProxy()) {
init()
}

0 comments on commit 4482b40

Please sign in to comment.